1
0

test.cc 438 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. const int PORT = 1234;
  53. const string LONG_QUERY_VALUE = string(25000, '@');
  54. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  55. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  56. const string TOO_LONG_QUERY_URL =
  57. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  58. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  59. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  60. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  61. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  62. return file.name == key;
  63. });
  64. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  65. return *it;
  66. #else
  67. if (it != items.end()) { return *it; }
  68. throw std::runtime_error("invalid multipart form data name error");
  69. #endif
  70. }
  71. static void read_file(const std::string &path, std::string &out) {
  72. std::ifstream fs(path, std::ios_base::binary);
  73. if (!fs) throw std::runtime_error("File not found: " + path);
  74. fs.seekg(0, std::ios_base::end);
  75. auto size = fs.tellg();
  76. fs.seekg(0);
  77. out.resize(static_cast<size_t>(size));
  78. fs.read(&out[0], static_cast<std::streamsize>(size));
  79. }
  80. void performance_test(const char *host) {
  81. Server svr;
  82. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  83. res.set_content("Benchmark Response", "text/plain");
  84. });
  85. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  86. auto se = detail::scope_exit([&] {
  87. svr.stop();
  88. listen_thread.join();
  89. ASSERT_FALSE(svr.is_running());
  90. });
  91. svr.wait_until_ready();
  92. Client cli(host, PORT);
  93. // Warm-up request to establish connection and resolve DNS
  94. auto warmup_res = cli.Get("/benchmark");
  95. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  96. // Run multiple trials and collect timings
  97. const int num_trials = 20;
  98. std::vector<int64_t> timings;
  99. timings.reserve(num_trials);
  100. for (int i = 0; i < num_trials; i++) {
  101. auto start = std::chrono::high_resolution_clock::now();
  102. auto res = cli.Get("/benchmark");
  103. auto end = std::chrono::high_resolution_clock::now();
  104. auto elapsed =
  105. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  106. .count();
  107. // Assertions after timing measurement to avoid overhead
  108. ASSERT_TRUE(res);
  109. EXPECT_EQ(StatusCode::OK_200, res->status);
  110. timings.push_back(elapsed);
  111. }
  112. // Calculate 25th percentile (lower quartile)
  113. std::sort(timings.begin(), timings.end());
  114. auto p25 = timings[num_trials / 4];
  115. // Format timings for output
  116. std::ostringstream timings_str;
  117. timings_str << "[";
  118. for (size_t i = 0; i < timings.size(); i++) {
  119. if (i > 0) timings_str << ", ";
  120. timings_str << timings[i];
  121. }
  122. timings_str << "]";
  123. // Localhost HTTP GET should be fast even in CI environments
  124. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  125. << "ms (Issue #1777). Timings: " << timings_str.str();
  126. }
  127. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  128. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  129. class UnixSocketTest : public ::testing::Test {
  130. protected:
  131. void TearDown() override { std::remove(pathname_.c_str()); }
  132. void client_GET(const std::string &addr) {
  133. httplib::Client cli{addr};
  134. cli.set_address_family(AF_UNIX);
  135. ASSERT_TRUE(cli.is_valid());
  136. const auto &result = cli.Get(pattern_);
  137. ASSERT_TRUE(result) << "error: " << result.error();
  138. const auto &resp = result.value();
  139. EXPECT_EQ(resp.status, StatusCode::OK_200);
  140. EXPECT_EQ(resp.body, content_);
  141. }
  142. const std::string pathname_{"./httplib-server.sock"};
  143. const std::string pattern_{"/hi"};
  144. const std::string content_{"Hello World!"};
  145. };
  146. TEST_F(UnixSocketTest, pathname) {
  147. httplib::Server svr;
  148. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  149. res.set_content(content_, "text/plain");
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. }
  163. #if defined(__linux__) || \
  164. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  165. TEST_F(UnixSocketTest, PeerPid) {
  166. httplib::Server svr;
  167. std::string remote_port_val;
  168. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. remote_port_val = std::to_string(req.remote_port);
  171. });
  172. std::thread t{[&] {
  173. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  174. }};
  175. auto se = detail::scope_exit([&] {
  176. svr.stop();
  177. t.join();
  178. ASSERT_FALSE(svr.is_running());
  179. });
  180. svr.wait_until_ready();
  181. ASSERT_TRUE(svr.is_running());
  182. client_GET(pathname_);
  183. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  184. }
  185. #endif
  186. #ifdef __linux__
  187. TEST_F(UnixSocketTest, abstract) {
  188. constexpr char svr_path[]{"\x00httplib-server.sock"};
  189. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  190. httplib::Server svr;
  191. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  192. res.set_content(content_, "text/plain");
  193. });
  194. std::thread t{[&] {
  195. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  196. }};
  197. auto se = detail::scope_exit([&] {
  198. svr.stop();
  199. t.join();
  200. ASSERT_FALSE(svr.is_running());
  201. });
  202. svr.wait_until_ready();
  203. ASSERT_TRUE(svr.is_running());
  204. client_GET(abstract_addr);
  205. }
  206. #endif
  207. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  208. httplib::Server svr;
  209. std::string received_host_header;
  210. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  211. // Capture the Host header sent by the client
  212. auto host_iter = req.headers.find("Host");
  213. if (host_iter != req.headers.end()) {
  214. received_host_header = host_iter->second;
  215. }
  216. res.set_content(content_, "text/plain");
  217. });
  218. std::thread t{[&] {
  219. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  220. }};
  221. auto se = detail::scope_exit([&] {
  222. svr.stop();
  223. t.join();
  224. ASSERT_FALSE(svr.is_running());
  225. });
  226. svr.wait_until_ready();
  227. ASSERT_TRUE(svr.is_running());
  228. // Test that Host header is automatically set to "localhost" for Unix socket
  229. // connections
  230. httplib::Client cli{pathname_};
  231. cli.set_address_family(AF_UNIX);
  232. ASSERT_TRUE(cli.is_valid());
  233. const auto &result = cli.Get(pattern_);
  234. ASSERT_TRUE(result) << "error: " << result.error();
  235. const auto &resp = result.value();
  236. EXPECT_EQ(resp.status, StatusCode::OK_200);
  237. EXPECT_EQ(resp.body, content_);
  238. // Verify that Host header was automatically set to "localhost"
  239. EXPECT_EQ(received_host_header, "localhost");
  240. }
  241. #ifndef _WIN32
  242. TEST(SocketStream, wait_writable_UNIX) {
  243. int fds[2];
  244. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  245. const auto asSocketStream = [&](socket_t fd,
  246. std::function<bool(Stream &)> func) {
  247. return detail::process_client_socket(
  248. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  249. };
  250. asSocketStream(fds[0], [&](Stream &s0) {
  251. EXPECT_EQ(s0.socket(), fds[0]);
  252. EXPECT_TRUE(s0.wait_writable());
  253. EXPECT_EQ(0, close(fds[1]));
  254. EXPECT_FALSE(s0.wait_writable());
  255. return true;
  256. });
  257. EXPECT_EQ(0, close(fds[0]));
  258. }
  259. TEST(SocketStream, wait_writable_INET) {
  260. sockaddr_in addr;
  261. memset(&addr, 0, sizeof(addr));
  262. addr.sin_family = AF_INET;
  263. addr.sin_port = htons(PORT + 1);
  264. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  265. int disconnected_svr_sock = -1;
  266. std::thread svr{[&] {
  267. const int s = socket(AF_INET, SOCK_STREAM, 0);
  268. ASSERT_LE(0, s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. EXPECT_FALSE(ss.wait_writable());
  292. return true;
  293. });
  294. ASSERT_EQ(0, close(disconnected_svr_sock));
  295. }
  296. #endif // #ifndef _WIN32
  297. TEST(ClientTest, MoveConstructible) {
  298. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  299. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  300. }
  301. TEST(ClientTest, MoveAssignable) {
  302. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  303. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  304. }
  305. #ifdef _WIN32
  306. TEST(StartupTest, WSAStartup) {
  307. WSADATA wsaData;
  308. int ret = WSAStartup(0x0002, &wsaData);
  309. ASSERT_EQ(0, ret);
  310. }
  311. #endif
  312. TEST(DecodePathTest, PercentCharacter) {
  313. EXPECT_EQ(
  314. decode_path_component(
  315. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  316. U8("descrip=Gastos áéíóúñÑ 6"));
  317. }
  318. TEST(DecodePathTest, PercentCharacterNUL) {
  319. string expected;
  320. expected.push_back('x');
  321. expected.push_back('\0');
  322. expected.push_back('x');
  323. EXPECT_EQ(decode_path_component("x%00x"), expected);
  324. }
  325. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  326. string unescapedCharacters = "-_.!~*'()";
  327. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  328. }
  329. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  330. string reservedCharacters = ";,/?:@&=+$";
  331. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  332. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  333. }
  334. TEST(ClientQueryOrder, PreserveOrder) {
  335. // This test reproduces Issue #2259: client may reorder query parameters
  336. // when sending a GET request. The expected behavior is that the client
  337. // preserves the original query string order when the caller supplied it
  338. // as part of the path.
  339. Server svr;
  340. svr.Get("/", [&](const Request &req, Response &res) {
  341. // Echo back the raw target so the test can assert ordering
  342. res.set_content(req.target, "text/plain");
  343. });
  344. std::thread t{[&] { svr.listen(HOST, PORT); }};
  345. auto se = detail::scope_exit([&] {
  346. svr.stop();
  347. t.join();
  348. ASSERT_FALSE(svr.is_running());
  349. });
  350. svr.wait_until_ready();
  351. Client cli(HOST, PORT);
  352. ASSERT_TRUE(cli.is_valid());
  353. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  354. auto res = cli.Get(original);
  355. ASSERT_TRUE(res);
  356. // Expect the echoed target to exactly match the original path (order
  357. // preserved)
  358. EXPECT_EQ(res->body, original);
  359. }
  360. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  361. string chineseCharacters = U8("中国語");
  362. string russianCharacters = U8("дом");
  363. string brazilianCharacters = U8("óculos");
  364. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  365. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  366. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  367. "%D0%B4%D0%BE%D0%BC");
  368. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  369. }
  370. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  371. string unescapedCharacters = "-_.!~*'()";
  372. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  373. }
  374. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  375. string reservedCharacters = ";,/?:@&=+$";
  376. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  377. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  378. }
  379. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  380. string chineseCharacters = U8("中国語");
  381. string russianCharacters = U8("дом");
  382. string brazilianCharacters = U8("óculos");
  383. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  384. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  385. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  386. "%D0%B4%D0%BE%D0%BC");
  387. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  388. }
  389. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  390. // Issue #2082 use case: encoding path component with ampersand
  391. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  392. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  393. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  394. }
  395. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  396. string unescapedCharacters = "-_.!~*'()";
  397. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  398. }
  399. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  400. string reservedCharacters = ";,/?:@&=+$#";
  401. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  402. }
  403. TEST(EncodeUriTest, TestUTF8Characters) {
  404. string chineseCharacters = U8("中国語");
  405. string russianCharacters = U8("дом");
  406. string brazilianCharacters = U8("óculos");
  407. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  408. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  409. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  410. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  411. }
  412. TEST(EncodeUriTest, TestCompleteUri) {
  413. string uri =
  414. "https://example.com/path/to/resource?query=value&param=test#fragment";
  415. EXPECT_EQ(
  416. httplib::encode_uri(uri),
  417. "https://example.com/path/to/resource?query=value&param=test#fragment");
  418. }
  419. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  420. string uri =
  421. "https://example.com/path with spaces/file name.html?q=hello world";
  422. EXPECT_EQ(httplib::encode_uri(uri),
  423. "https://example.com/path%20with%20spaces/"
  424. "file%20name.html?q=hello%20world");
  425. }
  426. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  427. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  428. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  429. }
  430. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  431. string unescapedCharacters = "-_.!~*'()";
  432. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  433. }
  434. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  435. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  436. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  437. string encodedBrazilian = "%C3%B3culos";
  438. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  439. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  440. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  441. }
  442. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  443. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  444. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  445. "Piri Tommy Villiers - on & on");
  446. }
  447. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  448. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  449. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  450. }
  451. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  452. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  453. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  454. }
  455. TEST(DecodeUriTest, TestUTF8Characters) {
  456. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  457. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  458. string encodedBrazilian = "%C3%B3culos";
  459. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  460. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  461. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  462. }
  463. TEST(DecodeUriTest, TestCompleteUri) {
  464. string encodedUri = "https://example.com/path%20with%20spaces/"
  465. "file%20name.html?q=hello%20world";
  466. EXPECT_EQ(
  467. httplib::decode_uri(encodedUri),
  468. "https://example.com/path with spaces/file name.html?q=hello world");
  469. }
  470. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  471. string original =
  472. "https://example.com/path with spaces/file name.html?q=hello world";
  473. string encoded = httplib::encode_uri(original);
  474. string decoded = httplib::decode_uri(encoded);
  475. EXPECT_EQ(decoded, original);
  476. }
  477. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  478. string original = "Piri Tommy Villiers - on & on";
  479. string encoded = httplib::encode_uri_component(original);
  480. string decoded = httplib::decode_uri_component(encoded);
  481. EXPECT_EQ(decoded, original);
  482. }
  483. TEST(TrimTests, TrimStringTests) {
  484. EXPECT_EQ("abc", detail::trim_copy("abc"));
  485. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  486. EXPECT_TRUE(detail::trim_copy("").empty());
  487. }
  488. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  489. // Simple case without quality values
  490. std::vector<std::string> result1;
  491. EXPECT_TRUE(detail::parse_accept_header(
  492. "text/html,application/json,text/plain", result1));
  493. EXPECT_EQ(result1.size(), 3U);
  494. EXPECT_EQ(result1[0], "text/html");
  495. EXPECT_EQ(result1[1], "application/json");
  496. EXPECT_EQ(result1[2], "text/plain");
  497. // With quality values
  498. std::vector<std::string> result2;
  499. EXPECT_TRUE(detail::parse_accept_header(
  500. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  501. EXPECT_EQ(result2.size(), 3U);
  502. EXPECT_EQ(result2[0], "application/json"); // highest q value
  503. EXPECT_EQ(result2[1], "text/html");
  504. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  505. }
  506. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  507. // Mixed with and without quality values
  508. std::vector<std::string> result;
  509. EXPECT_TRUE(detail::parse_accept_header(
  510. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  511. EXPECT_EQ(result.size(), 3U);
  512. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  513. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  514. EXPECT_EQ(result[2], "application/json"); // q=0.5
  515. }
  516. TEST(ParseAcceptHeaderTest, EdgeCases) {
  517. // Empty header
  518. std::vector<std::string> empty_result;
  519. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  520. EXPECT_TRUE(empty_result.empty());
  521. // Single type
  522. std::vector<std::string> single_result;
  523. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  524. EXPECT_EQ(single_result.size(), 1U);
  525. EXPECT_EQ(single_result[0], "application/json");
  526. // Wildcard types
  527. std::vector<std::string> wildcard_result;
  528. EXPECT_TRUE(detail::parse_accept_header(
  529. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  530. EXPECT_EQ(wildcard_result.size(), 3U);
  531. EXPECT_EQ(wildcard_result[0], "application/json");
  532. EXPECT_EQ(wildcard_result[1], "text/*");
  533. EXPECT_EQ(wildcard_result[2], "*/*");
  534. }
  535. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  536. // Common browser Accept header
  537. std::vector<std::string> browser_result;
  538. EXPECT_TRUE(
  539. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  540. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  541. browser_result));
  542. EXPECT_EQ(browser_result.size(), 6U);
  543. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  544. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  547. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  548. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  549. // API client header
  550. std::vector<std::string> api_result;
  551. EXPECT_TRUE(detail::parse_accept_header(
  552. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  553. api_result));
  554. EXPECT_EQ(api_result.size(), 3U);
  555. EXPECT_EQ(api_result[0], "application/json");
  556. EXPECT_EQ(api_result[1], "application/xml");
  557. EXPECT_EQ(api_result[2], "text/plain");
  558. }
  559. TEST(ParseAcceptHeaderTest, SpecialCases) {
  560. // Quality value with 3 decimal places
  561. std::vector<std::string> decimal_result;
  562. EXPECT_TRUE(detail::parse_accept_header(
  563. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  564. EXPECT_EQ(decimal_result.size(), 2U);
  565. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  566. EXPECT_EQ(decimal_result[1], "text/html");
  567. // Zero quality (should still be included but with lowest priority)
  568. std::vector<std::string> zero_q_result;
  569. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  570. zero_q_result));
  571. EXPECT_EQ(zero_q_result.size(), 2U);
  572. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  573. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  574. // No spaces around commas
  575. std::vector<std::string> no_space_result;
  576. EXPECT_TRUE(detail::parse_accept_header(
  577. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  578. no_space_result));
  579. EXPECT_EQ(no_space_result.size(), 3U);
  580. EXPECT_EQ(no_space_result[0], "text/html");
  581. EXPECT_EQ(no_space_result[1], "application/json");
  582. EXPECT_EQ(no_space_result[2], "text/plain");
  583. }
  584. TEST(ParseAcceptHeaderTest, InvalidCases) {
  585. std::vector<std::string> result;
  586. // Invalid quality value (> 1.0)
  587. EXPECT_FALSE(
  588. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  589. // Invalid quality value (< 0.0)
  590. EXPECT_FALSE(
  591. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  592. // Invalid quality value (not a number)
  593. EXPECT_FALSE(detail::parse_accept_header(
  594. "text/html;q=invalid,application/json", result));
  595. // Empty quality value
  596. EXPECT_FALSE(
  597. detail::parse_accept_header("text/html;q=,application/json", result));
  598. // Invalid media type format (no slash and not wildcard)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("invalidtype,application/json", result));
  601. // Empty media type
  602. result.clear();
  603. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  604. // Only commas
  605. result.clear();
  606. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  607. // Valid cases should still work
  608. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  609. EXPECT_EQ(result.size(), 1U);
  610. EXPECT_EQ(result[0], "*/*");
  611. EXPECT_TRUE(detail::parse_accept_header("*", result));
  612. EXPECT_EQ(result.size(), 1U);
  613. EXPECT_EQ(result[0], "*");
  614. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  615. EXPECT_EQ(result.size(), 1U);
  616. EXPECT_EQ(result[0], "text/*");
  617. }
  618. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  619. Server svr;
  620. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  621. EXPECT_EQ(req.accept_content_types.size(), 3U);
  622. EXPECT_EQ(req.accept_content_types[0], "application/json");
  623. EXPECT_EQ(req.accept_content_types[1], "text/html");
  624. EXPECT_EQ(req.accept_content_types[2], "*/*");
  625. res.set_content("ok", "text/plain");
  626. });
  627. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  628. EXPECT_TRUE(false);
  629. res.set_content("bad request", "text/plain");
  630. });
  631. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  632. auto se = detail::scope_exit([&] {
  633. svr.stop();
  634. listen_thread.join();
  635. ASSERT_FALSE(svr.is_running());
  636. });
  637. svr.wait_until_ready();
  638. Client cli("localhost", PORT);
  639. {
  640. auto res =
  641. cli.Get("/accept_ok",
  642. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  643. ASSERT_TRUE(res);
  644. EXPECT_EQ(StatusCode::OK_200, res->status);
  645. }
  646. {
  647. auto res = cli.Get("/accept_bad_request",
  648. {{"Accept", "text/html;q=abc,application/json"}});
  649. ASSERT_TRUE(res);
  650. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  651. }
  652. }
  653. TEST(DivideTest, DivideStringTests) {
  654. auto divide = [](const std::string &str, char d) {
  655. std::string lhs;
  656. std::string rhs;
  657. detail::divide(str, d,
  658. [&](const char *lhs_data, std::size_t lhs_size,
  659. const char *rhs_data, std::size_t rhs_size) {
  660. lhs.assign(lhs_data, lhs_size);
  661. rhs.assign(rhs_data, rhs_size);
  662. });
  663. return std::make_pair(std::move(lhs), std::move(rhs));
  664. };
  665. {
  666. const auto res = divide("", '=');
  667. EXPECT_EQ(res.first, "");
  668. EXPECT_EQ(res.second, "");
  669. }
  670. {
  671. const auto res = divide("=", '=');
  672. EXPECT_EQ(res.first, "");
  673. EXPECT_EQ(res.second, "");
  674. }
  675. {
  676. const auto res = divide(" ", '=');
  677. EXPECT_EQ(res.first, " ");
  678. EXPECT_EQ(res.second, "");
  679. }
  680. {
  681. const auto res = divide("a", '=');
  682. EXPECT_EQ(res.first, "a");
  683. EXPECT_EQ(res.second, "");
  684. }
  685. {
  686. const auto res = divide("a=", '=');
  687. EXPECT_EQ(res.first, "a");
  688. EXPECT_EQ(res.second, "");
  689. }
  690. {
  691. const auto res = divide("=b", '=');
  692. EXPECT_EQ(res.first, "");
  693. EXPECT_EQ(res.second, "b");
  694. }
  695. {
  696. const auto res = divide("a=b", '=');
  697. EXPECT_EQ(res.first, "a");
  698. EXPECT_EQ(res.second, "b");
  699. }
  700. {
  701. const auto res = divide("a=b=", '=');
  702. EXPECT_EQ(res.first, "a");
  703. EXPECT_EQ(res.second, "b=");
  704. }
  705. {
  706. const auto res = divide("a=b=c", '=');
  707. EXPECT_EQ(res.first, "a");
  708. EXPECT_EQ(res.second, "b=c");
  709. }
  710. }
  711. TEST(SplitTest, ParseQueryString) {
  712. string s = "key1=val1&key2=val2&key3=val3";
  713. Params dic;
  714. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  715. [&](const char *b, const char *e) {
  716. string key, val;
  717. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  718. if (key.empty()) {
  719. key.assign(b2, e2);
  720. } else {
  721. val.assign(b2, e2);
  722. }
  723. });
  724. dic.emplace(key, val);
  725. });
  726. EXPECT_EQ("val1", dic.find("key1")->second);
  727. EXPECT_EQ("val2", dic.find("key2")->second);
  728. EXPECT_EQ("val3", dic.find("key3")->second);
  729. }
  730. TEST(SplitTest, ParseInvalidQueryTests) {
  731. {
  732. string s = " ";
  733. Params dict;
  734. detail::parse_query_text(s, dict);
  735. EXPECT_TRUE(dict.empty());
  736. }
  737. {
  738. string s = " = =";
  739. Params dict;
  740. detail::parse_query_text(s, dict);
  741. EXPECT_TRUE(dict.empty());
  742. }
  743. }
  744. TEST(ParseQueryTest, ParseQueryString) {
  745. {
  746. std::string s = "key1=val1&key2=val2&key3=val3";
  747. Params dic;
  748. detail::parse_query_text(s, dic);
  749. EXPECT_EQ("val1", dic.find("key1")->second);
  750. EXPECT_EQ("val2", dic.find("key2")->second);
  751. EXPECT_EQ("val3", dic.find("key3")->second);
  752. }
  753. {
  754. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  755. Params dic;
  756. detail::parse_query_text(s, dic);
  757. EXPECT_EQ("", dic.find("key1")->second);
  758. EXPECT_EQ("val1", dic.find("key2")->second);
  759. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  760. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  761. }
  762. }
  763. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  764. Params dic;
  765. EXPECT_EQ(detail::params_to_query_str(dic), "");
  766. dic.emplace("key1", "val1");
  767. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  768. dic.emplace("key2", "val2");
  769. dic.emplace("key3", "val3");
  770. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  771. }
  772. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  773. string content_type = "multipart/form-data; boundary=something";
  774. string boundary;
  775. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  776. EXPECT_TRUE(ret);
  777. EXPECT_EQ(boundary, "something");
  778. }
  779. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  780. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  781. string boundary;
  782. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  783. EXPECT_TRUE(ret);
  784. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  785. }
  786. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  787. string content_type =
  788. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  793. }
  794. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  795. string content_type =
  796. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  797. string boundary;
  798. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  799. EXPECT_TRUE(ret);
  800. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  801. }
  802. TEST(GetHeaderValueTest, DefaultValue) {
  803. Headers headers = {{"Dummy", "Dummy"}};
  804. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  805. EXPECT_STREQ("text/plain", val);
  806. }
  807. TEST(GetHeaderValueTest, DefaultValueInt) {
  808. Headers headers = {{"Dummy", "Dummy"}};
  809. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  810. EXPECT_EQ(100ull, val);
  811. }
  812. TEST(GetHeaderValueTest, RegularValue) {
  813. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  814. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  815. EXPECT_STREQ("text/html", val);
  816. }
  817. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  818. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  819. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  820. EXPECT_STREQ("text/html", val);
  821. }
  822. TEST(GetHeaderValueTest, SetContent) {
  823. Response res;
  824. res.set_content("html", "text/html");
  825. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  826. res.set_content("text", "text/plain");
  827. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  828. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  829. }
  830. TEST(GetHeaderValueTest, RegularValueInt) {
  831. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  832. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  833. EXPECT_EQ(100ull, val);
  834. }
  835. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  836. Headers headers = {{"Content-Length", "x"}};
  837. auto is_invalid_value = false;
  838. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  839. is_invalid_value);
  840. EXPECT_EQ(0ull, val);
  841. EXPECT_TRUE(is_invalid_value);
  842. }
  843. TEST(GetHeaderValueTest, Range) {
  844. {
  845. Headers headers = {make_range_header({{1, -1}})};
  846. auto val = detail::get_header_value(headers, "Range", 0, 0);
  847. EXPECT_STREQ("bytes=1-", val);
  848. }
  849. {
  850. Headers headers = {make_range_header({{-1, 1}})};
  851. auto val = detail::get_header_value(headers, "Range", 0, 0);
  852. EXPECT_STREQ("bytes=-1", val);
  853. }
  854. {
  855. Headers headers = {make_range_header({{1, 10}})};
  856. auto val = detail::get_header_value(headers, "Range", 0, 0);
  857. EXPECT_STREQ("bytes=1-10", val);
  858. }
  859. {
  860. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  861. auto val = detail::get_header_value(headers, "Range", 0, 0);
  862. EXPECT_STREQ("bytes=1-10, 100-", val);
  863. }
  864. {
  865. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  866. auto val = detail::get_header_value(headers, "Range", 0, 0);
  867. EXPECT_STREQ("bytes=1-10, 100-200", val);
  868. }
  869. {
  870. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  871. auto val = detail::get_header_value(headers, "Range", 0, 0);
  872. EXPECT_STREQ("bytes=0-0, -1", val);
  873. }
  874. }
  875. TEST(ParseHeaderValueTest, Range) {
  876. {
  877. Ranges ranges;
  878. auto ret = detail::parse_range_header("bytes=1-", ranges);
  879. EXPECT_TRUE(ret);
  880. EXPECT_EQ(1u, ranges.size());
  881. EXPECT_EQ(1u, ranges[0].first);
  882. EXPECT_EQ(-1, ranges[0].second);
  883. }
  884. {
  885. Ranges ranges;
  886. auto ret = detail::parse_range_header("bytes=-1", ranges);
  887. EXPECT_TRUE(ret);
  888. EXPECT_EQ(1u, ranges.size());
  889. EXPECT_EQ(-1, ranges[0].first);
  890. EXPECT_EQ(1u, ranges[0].second);
  891. }
  892. {
  893. Ranges ranges;
  894. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  895. EXPECT_TRUE(ret);
  896. EXPECT_EQ(1u, ranges.size());
  897. EXPECT_EQ(1u, ranges[0].first);
  898. EXPECT_EQ(10u, ranges[0].second);
  899. }
  900. {
  901. Ranges ranges;
  902. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  903. EXPECT_FALSE(ret);
  904. }
  905. {
  906. Ranges ranges;
  907. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  908. EXPECT_TRUE(ret);
  909. EXPECT_EQ(2u, ranges.size());
  910. EXPECT_EQ(1u, ranges[0].first);
  911. EXPECT_EQ(10u, ranges[0].second);
  912. EXPECT_EQ(100u, ranges[1].first);
  913. EXPECT_EQ(-1, ranges[1].second);
  914. }
  915. {
  916. Ranges ranges;
  917. auto ret =
  918. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  919. EXPECT_TRUE(ret);
  920. EXPECT_EQ(3u, ranges.size());
  921. EXPECT_EQ(1u, ranges[0].first);
  922. EXPECT_EQ(10u, ranges[0].second);
  923. EXPECT_EQ(100u, ranges[1].first);
  924. EXPECT_EQ(200u, ranges[1].second);
  925. EXPECT_EQ(300u, ranges[2].first);
  926. EXPECT_EQ(400u, ranges[2].second);
  927. }
  928. {
  929. Ranges ranges;
  930. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  936. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  943. EXPECT_TRUE(ranges.empty());
  944. }
  945. }
  946. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  947. Request req;
  948. req.set_header("Accept-Encoding", "gzip");
  949. Response res;
  950. res.set_header("Content-Type", "text/plain");
  951. auto ret = detail::encoding_type(req, res);
  952. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  953. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  954. #else
  955. EXPECT_TRUE(ret == detail::EncodingType::None);
  956. #endif
  957. }
  958. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  966. #elif CPPHTTPLIB_ZLIB_SUPPORT
  967. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  968. #elif CPPHTTPLIB_ZSTD_SUPPORT
  969. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  970. #else
  971. EXPECT_TRUE(ret == detail::EncodingType::None);
  972. #endif
  973. }
  974. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  975. Request req;
  976. req.set_header("Accept-Encoding",
  977. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  978. Response res;
  979. res.set_header("Content-Type", "text/plain");
  980. auto ret = detail::encoding_type(req, res);
  981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  982. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  983. #elif CPPHTTPLIB_ZLIB_SUPPORT
  984. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  985. #elif CPPHTTPLIB_ZSTD_SUPPORT
  986. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  987. #else
  988. EXPECT_TRUE(ret == detail::EncodingType::None);
  989. #endif
  990. }
  991. TEST(BufferStreamTest, read) {
  992. detail::BufferStream strm1;
  993. Stream &strm = strm1;
  994. EXPECT_EQ(5, strm.write("hello"));
  995. char buf[512];
  996. EXPECT_EQ(2, strm.read(buf, 2));
  997. EXPECT_EQ('h', buf[0]);
  998. EXPECT_EQ('e', buf[1]);
  999. EXPECT_EQ(2, strm.read(buf, 2));
  1000. EXPECT_EQ('l', buf[0]);
  1001. EXPECT_EQ('l', buf[1]);
  1002. EXPECT_EQ(1, strm.read(buf, 1));
  1003. EXPECT_EQ('o', buf[0]);
  1004. EXPECT_EQ(0, strm.read(buf, 1));
  1005. }
  1006. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1007. auto host = "www.httpwatch.com";
  1008. auto ip = hosted_at(host);
  1009. EXPECT_EQ("23.96.13.243", ip);
  1010. std::vector<std::string> addrs;
  1011. hosted_at(host, addrs);
  1012. EXPECT_EQ(1u, addrs.size());
  1013. }
  1014. #if 0 // It depends on each test environment...
  1015. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1016. auto host = "www.youtube.com";
  1017. std::vector<std::string> addrs;
  1018. hosted_at(host, addrs);
  1019. EXPECT_EQ(20u, addrs.size());
  1020. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1021. EXPECT_TRUE(it != addrs.end());
  1022. }
  1023. #endif
  1024. class ChunkedEncodingTest : public ::testing::Test {
  1025. protected:
  1026. ChunkedEncodingTest()
  1027. : cli_(HOST, PORT)
  1028. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1029. ,
  1030. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1031. #endif
  1032. {
  1033. cli_.set_connection_timeout(2);
  1034. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1035. cli_.enable_server_certificate_verification(false);
  1036. #endif
  1037. }
  1038. virtual void SetUp() {
  1039. read_file("./image.jpg", image_data_);
  1040. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1041. res.set_content("Hello World!", "text/plain");
  1042. });
  1043. svr_.Get(
  1044. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1045. res.set_chunked_content_provider(
  1046. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1047. size_t remaining = image_data_.size() - offset;
  1048. if (remaining == 0) {
  1049. sink.done();
  1050. } else {
  1051. constexpr size_t CHUNK_SIZE = 1024;
  1052. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1053. sink.write(&image_data_[offset], send_size);
  1054. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1055. }
  1056. return true;
  1057. });
  1058. });
  1059. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1060. svr_.wait_until_ready();
  1061. }
  1062. virtual void TearDown() {
  1063. svr_.stop();
  1064. if (!request_threads_.empty()) {
  1065. std::this_thread::sleep_for(std::chrono::seconds(1));
  1066. for (auto &t : request_threads_) {
  1067. t.join();
  1068. }
  1069. }
  1070. t_.join();
  1071. }
  1072. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1073. SSLClient cli_;
  1074. SSLServer svr_;
  1075. #else
  1076. Client cli_;
  1077. Server svr_;
  1078. #endif
  1079. thread t_;
  1080. std::vector<thread> request_threads_;
  1081. std::string image_data_;
  1082. };
  1083. TEST_F(ChunkedEncodingTest, NormalGet) {
  1084. auto res = cli_.Get("/chunked");
  1085. ASSERT_TRUE(res);
  1086. std::string out;
  1087. read_file("./image.jpg", out);
  1088. EXPECT_EQ(StatusCode::OK_200, res->status);
  1089. EXPECT_EQ(out, res->body);
  1090. }
  1091. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1092. std::string body;
  1093. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1094. body.append(data, data_length);
  1095. return true;
  1096. });
  1097. ASSERT_TRUE(res);
  1098. std::string out;
  1099. read_file("./image.jpg", out);
  1100. EXPECT_EQ(StatusCode::OK_200, res->status);
  1101. EXPECT_EQ(out, body);
  1102. }
  1103. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1104. std::string body;
  1105. auto res = cli_.Get(
  1106. "/chunked",
  1107. [&](const Response &response) {
  1108. EXPECT_EQ(StatusCode::OK_200, response.status);
  1109. return true;
  1110. },
  1111. [&](const char *data, size_t data_length) {
  1112. body.append(data, data_length);
  1113. return true;
  1114. });
  1115. ASSERT_TRUE(res);
  1116. std::string out;
  1117. read_file("./image.jpg", out);
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. EXPECT_EQ(out, body);
  1120. }
  1121. TEST(RangeTest, FromHTTPBin_Online) {
  1122. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1123. auto host = "httpcan.org";
  1124. auto path = std::string{"/range/32"};
  1125. #else
  1126. auto host = "nghttp2.org";
  1127. auto path = std::string{"/httpbin/range/32"};
  1128. #endif
  1129. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1130. auto port = 443;
  1131. SSLClient cli(host, port);
  1132. #else
  1133. auto port = 80;
  1134. Client cli(host, port);
  1135. #endif
  1136. cli.set_connection_timeout(5);
  1137. {
  1138. auto res = cli.Get(path);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1141. EXPECT_EQ(StatusCode::OK_200, res->status);
  1142. }
  1143. {
  1144. Headers headers = {make_range_header({{1, -1}})};
  1145. auto res = cli.Get(path, headers);
  1146. ASSERT_TRUE(res);
  1147. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1149. }
  1150. {
  1151. Headers headers = {make_range_header({{1, 10}})};
  1152. auto res = cli.Get(path, headers);
  1153. ASSERT_TRUE(res);
  1154. EXPECT_EQ("bcdefghijk", res->body);
  1155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1156. }
  1157. {
  1158. Headers headers = {make_range_header({{0, 31}})};
  1159. auto res = cli.Get(path, headers);
  1160. ASSERT_TRUE(res);
  1161. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1162. EXPECT_EQ(StatusCode::OK_200, res->status);
  1163. }
  1164. {
  1165. Headers headers = {make_range_header({{0, -1}})};
  1166. auto res = cli.Get(path, headers);
  1167. ASSERT_TRUE(res);
  1168. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1169. EXPECT_EQ(StatusCode::OK_200, res->status);
  1170. }
  1171. {
  1172. Headers headers = {make_range_header({{0, 32}})};
  1173. auto res = cli.Get(path, headers);
  1174. ASSERT_TRUE(res);
  1175. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1176. }
  1177. }
  1178. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1179. auto host = "unresolvableaddress.local";
  1180. auto path = std::string{"/"};
  1181. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1182. auto port = 443;
  1183. SSLClient cli(host, port);
  1184. #else
  1185. auto port = 80;
  1186. Client cli(host, port);
  1187. #endif
  1188. cli.set_connection_timeout(1);
  1189. {
  1190. auto res = cli.Get(path);
  1191. ASSERT_FALSE(res);
  1192. }
  1193. std::this_thread::sleep_for(std::chrono::seconds(8));
  1194. }
  1195. TEST(ConnectionErrorTest, InvalidHost) {
  1196. auto host = "-abcde.com";
  1197. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1198. auto port = 443;
  1199. SSLClient cli(host, port);
  1200. #else
  1201. auto port = 80;
  1202. Client cli(host, port);
  1203. #endif
  1204. cli.set_connection_timeout(std::chrono::seconds(2));
  1205. auto res = cli.Get("/");
  1206. ASSERT_TRUE(!res);
  1207. EXPECT_EQ(Error::Connection, res.error());
  1208. }
  1209. TEST(ConnectionErrorTest, InvalidHost2) {
  1210. auto host = "httpcan.org/";
  1211. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1212. SSLClient cli(host);
  1213. #else
  1214. Client cli(host);
  1215. #endif
  1216. cli.set_connection_timeout(std::chrono::seconds(2));
  1217. auto res = cli.Get("/");
  1218. ASSERT_TRUE(!res);
  1219. EXPECT_EQ(Error::Connection, res.error());
  1220. }
  1221. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1222. auto host = "httpcan.org/";
  1223. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1224. SSLClient cli(host);
  1225. #else
  1226. Client cli(host);
  1227. #endif
  1228. cli.set_connection_timeout(std::chrono::seconds(2));
  1229. auto res = cli.Get("/");
  1230. ASSERT_TRUE(!res);
  1231. stringstream s;
  1232. s << "error code: " << res.error();
  1233. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1234. }
  1235. TEST(ConnectionErrorTest, InvalidPort) {
  1236. auto host = "localhost";
  1237. auto port = 44380;
  1238. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1239. SSLClient cli(host, port);
  1240. #else
  1241. Client cli(host, port);
  1242. #endif
  1243. cli.set_connection_timeout(std::chrono::seconds(2));
  1244. auto res = cli.Get("/");
  1245. ASSERT_TRUE(!res);
  1246. EXPECT_TRUE(Error::Connection == res.error() ||
  1247. Error::ConnectionTimeout == res.error());
  1248. }
  1249. TEST(ConnectionErrorTest, Timeout_Online) {
  1250. auto host = "google.com";
  1251. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1252. auto port = 44380;
  1253. SSLClient cli(host, port);
  1254. #else
  1255. auto port = 8080;
  1256. Client cli(host, port);
  1257. #endif
  1258. cli.set_connection_timeout(std::chrono::seconds(2));
  1259. // only probe one address type so that the error reason
  1260. // correlates to the timed-out IPv4, not the unsupported
  1261. // IPv6 connection attempt
  1262. cli.set_address_family(AF_INET);
  1263. auto res = cli.Get("/");
  1264. ASSERT_TRUE(!res);
  1265. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1266. }
  1267. TEST(CancelTest, NoCancel_Online) {
  1268. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1269. auto host = "httpcan.org";
  1270. auto path = std::string{"/range/32"};
  1271. #else
  1272. auto host = "nghttp2.org";
  1273. auto path = std::string{"/httpbin/range/32"};
  1274. #endif
  1275. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1276. auto port = 443;
  1277. SSLClient cli(host, port);
  1278. #else
  1279. auto port = 80;
  1280. Client cli(host, port);
  1281. #endif
  1282. cli.set_connection_timeout(std::chrono::seconds(5));
  1283. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1284. ASSERT_TRUE(res);
  1285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1286. EXPECT_EQ(StatusCode::OK_200, res->status);
  1287. }
  1288. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1289. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1290. auto host = "httpcan.org";
  1291. auto path = std::string{"/range/32"};
  1292. #else
  1293. auto host = "nghttp2.org";
  1294. auto path = std::string{"/httpbin/range/32"};
  1295. #endif
  1296. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1297. auto port = 443;
  1298. SSLClient cli(host, port);
  1299. #else
  1300. auto port = 80;
  1301. Client cli(host, port);
  1302. #endif
  1303. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1304. cli.set_connection_timeout(std::chrono::seconds(5));
  1305. ASSERT_TRUE(!res);
  1306. EXPECT_EQ(Error::Canceled, res.error());
  1307. }
  1308. TEST(CancelTest, WithCancelLargePayload_Online) {
  1309. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1310. auto host = "httpcan.org";
  1311. auto path = std::string{"/range/65536"};
  1312. #else
  1313. auto host = "nghttp2.org";
  1314. auto path = std::string{"/httpbin/range/65536"};
  1315. #endif
  1316. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1317. auto port = 443;
  1318. SSLClient cli(host, port);
  1319. #else
  1320. auto port = 80;
  1321. Client cli(host, port);
  1322. #endif
  1323. cli.set_connection_timeout(std::chrono::seconds(5));
  1324. uint32_t count = 0;
  1325. auto res =
  1326. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1327. ASSERT_TRUE(!res);
  1328. EXPECT_EQ(Error::Canceled, res.error());
  1329. }
  1330. TEST(CancelTest, NoCancelPost) {
  1331. Server svr;
  1332. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1333. res.set_content("Hello World!", "text/plain");
  1334. });
  1335. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1336. auto se = detail::scope_exit([&] {
  1337. svr.stop();
  1338. thread.join();
  1339. ASSERT_FALSE(svr.is_running());
  1340. });
  1341. svr.wait_until_ready();
  1342. Client cli(HOST, PORT);
  1343. cli.set_connection_timeout(std::chrono::seconds(5));
  1344. auto res =
  1345. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1346. "application/json", [](uint64_t, uint64_t) { return true; });
  1347. ASSERT_TRUE(res);
  1348. EXPECT_EQ("Hello World!", res->body);
  1349. EXPECT_EQ(StatusCode::OK_200, res->status);
  1350. }
  1351. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1352. Server svr;
  1353. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1354. res.set_content("Hello World!", "text/plain");
  1355. });
  1356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1357. auto se = detail::scope_exit([&] {
  1358. svr.stop();
  1359. thread.join();
  1360. ASSERT_FALSE(svr.is_running());
  1361. });
  1362. svr.wait_until_ready();
  1363. Client cli(HOST, PORT);
  1364. cli.set_connection_timeout(std::chrono::seconds(5));
  1365. auto res =
  1366. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1367. "application/json", [](uint64_t, uint64_t) { return false; });
  1368. ASSERT_TRUE(!res);
  1369. EXPECT_EQ(Error::Canceled, res.error());
  1370. }
  1371. TEST(CancelTest, WithCancelLargePayloadPost) {
  1372. Server svr;
  1373. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1374. res.set_content(LARGE_DATA, "text/plain");
  1375. });
  1376. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1377. auto se = detail::scope_exit([&] {
  1378. svr.stop();
  1379. thread.join();
  1380. ASSERT_FALSE(svr.is_running());
  1381. });
  1382. svr.wait_until_ready();
  1383. Client cli(HOST, PORT);
  1384. cli.set_connection_timeout(std::chrono::seconds(5));
  1385. auto res =
  1386. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1387. "application/json", [](uint64_t, uint64_t) { return false; });
  1388. ASSERT_TRUE(!res);
  1389. EXPECT_EQ(Error::Canceled, res.error());
  1390. }
  1391. TEST(CancelTest, NoCancelPut) {
  1392. Server svr;
  1393. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1394. res.set_content("Hello World!", "text/plain");
  1395. });
  1396. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1397. auto se = detail::scope_exit([&] {
  1398. svr.stop();
  1399. thread.join();
  1400. ASSERT_FALSE(svr.is_running());
  1401. });
  1402. svr.wait_until_ready();
  1403. Client cli(HOST, PORT);
  1404. cli.set_connection_timeout(std::chrono::seconds(5));
  1405. auto res =
  1406. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1407. "application/json", [](uint64_t, uint64_t) { return true; });
  1408. ASSERT_TRUE(res);
  1409. EXPECT_EQ("Hello World!", res->body);
  1410. EXPECT_EQ(StatusCode::OK_200, res->status);
  1411. }
  1412. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1413. Server svr;
  1414. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1415. res.set_content("Hello World!", "text/plain");
  1416. });
  1417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1418. auto se = detail::scope_exit([&] {
  1419. svr.stop();
  1420. thread.join();
  1421. ASSERT_FALSE(svr.is_running());
  1422. });
  1423. svr.wait_until_ready();
  1424. Client cli(HOST, PORT);
  1425. cli.set_connection_timeout(std::chrono::seconds(5));
  1426. auto res =
  1427. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1428. "application/json", [](uint64_t, uint64_t) { return false; });
  1429. ASSERT_TRUE(!res);
  1430. EXPECT_EQ(Error::Canceled, res.error());
  1431. }
  1432. TEST(CancelTest, WithCancelLargePayloadPut) {
  1433. Server svr;
  1434. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1435. res.set_content(LARGE_DATA, "text/plain");
  1436. });
  1437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1438. auto se = detail::scope_exit([&] {
  1439. svr.stop();
  1440. thread.join();
  1441. ASSERT_FALSE(svr.is_running());
  1442. });
  1443. svr.wait_until_ready();
  1444. Client cli(HOST, PORT);
  1445. cli.set_connection_timeout(std::chrono::seconds(5));
  1446. auto res =
  1447. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1448. "application/json", [](uint64_t, uint64_t) { return false; });
  1449. ASSERT_TRUE(!res);
  1450. EXPECT_EQ(Error::Canceled, res.error());
  1451. }
  1452. TEST(CancelTest, NoCancelPatch) {
  1453. Server svr;
  1454. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1455. res.set_content("Hello World!", "text/plain");
  1456. });
  1457. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1458. auto se = detail::scope_exit([&] {
  1459. svr.stop();
  1460. thread.join();
  1461. ASSERT_FALSE(svr.is_running());
  1462. });
  1463. svr.wait_until_ready();
  1464. Client cli(HOST, PORT);
  1465. cli.set_connection_timeout(std::chrono::seconds(5));
  1466. auto res =
  1467. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1468. "application/json", [](uint64_t, uint64_t) { return true; });
  1469. ASSERT_TRUE(res);
  1470. EXPECT_EQ("Hello World!", res->body);
  1471. EXPECT_EQ(StatusCode::OK_200, res->status);
  1472. }
  1473. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1474. Server svr;
  1475. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1476. res.set_content("Hello World!", "text/plain");
  1477. });
  1478. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1479. auto se = detail::scope_exit([&] {
  1480. svr.stop();
  1481. thread.join();
  1482. ASSERT_FALSE(svr.is_running());
  1483. });
  1484. svr.wait_until_ready();
  1485. Client cli(HOST, PORT);
  1486. cli.set_connection_timeout(std::chrono::seconds(5));
  1487. auto res =
  1488. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1489. "application/json", [](uint64_t, uint64_t) { return false; });
  1490. ASSERT_TRUE(!res);
  1491. EXPECT_EQ(Error::Canceled, res.error());
  1492. }
  1493. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1494. Server svr;
  1495. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1496. res.set_content(LARGE_DATA, "text/plain");
  1497. });
  1498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1499. auto se = detail::scope_exit([&] {
  1500. svr.stop();
  1501. thread.join();
  1502. ASSERT_FALSE(svr.is_running());
  1503. });
  1504. svr.wait_until_ready();
  1505. Client cli(HOST, PORT);
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. auto res =
  1508. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1509. "application/json", [](uint64_t, uint64_t) { return false; });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelDelete) {
  1514. Server svr;
  1515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1535. Server svr;
  1536. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1555. Server svr;
  1556. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1557. res.set_content(LARGE_DATA, "text/plain");
  1558. });
  1559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. thread.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. Client cli(HOST, PORT);
  1567. cli.set_connection_timeout(std::chrono::seconds(5));
  1568. auto res =
  1569. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1570. "application/json", [](uint64_t, uint64_t) { return false; });
  1571. ASSERT_TRUE(!res);
  1572. EXPECT_EQ(Error::Canceled, res.error());
  1573. }
  1574. static std::string remove_whitespace(const std::string &input) {
  1575. std::string output;
  1576. output.reserve(input.size());
  1577. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1578. [](unsigned char c) { return !std::isspace(c); });
  1579. return output;
  1580. }
  1581. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1582. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1583. auto host = "httpcan.org";
  1584. auto path = std::string{"/basic-auth/hello/world"};
  1585. #else
  1586. auto host = "nghttp2.org";
  1587. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1588. #endif
  1589. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1590. auto port = 443;
  1591. SSLClient cli(host, port);
  1592. #else
  1593. auto port = 80;
  1594. Client cli(host, port);
  1595. #endif
  1596. {
  1597. auto res = cli.Get(path);
  1598. ASSERT_TRUE(res);
  1599. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1600. }
  1601. {
  1602. auto res =
  1603. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1604. ASSERT_TRUE(res);
  1605. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1606. remove_whitespace(res->body));
  1607. EXPECT_EQ(StatusCode::OK_200, res->status);
  1608. }
  1609. {
  1610. cli.set_basic_auth("hello", "world");
  1611. auto res = cli.Get(path);
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1614. remove_whitespace(res->body));
  1615. EXPECT_EQ(StatusCode::OK_200, res->status);
  1616. }
  1617. {
  1618. cli.set_basic_auth("hello", "bad");
  1619. auto res = cli.Get(path);
  1620. ASSERT_TRUE(res);
  1621. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1622. }
  1623. {
  1624. cli.set_basic_auth("bad", "world");
  1625. auto res = cli.Get(path);
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1628. }
  1629. }
  1630. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1631. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1632. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1633. auto host = "httpcan.org";
  1634. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1635. auto paths = std::vector<std::string>{
  1636. "/digest-auth/auth/hello/world/MD5",
  1637. "/digest-auth/auth/hello/world/SHA-256",
  1638. "/digest-auth/auth/hello/world/SHA-512",
  1639. };
  1640. #else
  1641. auto host = "nghttp2.org";
  1642. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1643. auto paths = std::vector<std::string>{
  1644. "/httpbin/digest-auth/auth/hello/world/MD5",
  1645. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1646. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1647. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1648. };
  1649. #endif
  1650. auto port = 443;
  1651. SSLClient cli(host, port);
  1652. {
  1653. auto res = cli.Get(unauth_path);
  1654. ASSERT_TRUE(res);
  1655. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1656. }
  1657. {
  1658. cli.set_digest_auth("hello", "world");
  1659. for (const auto &path : paths) {
  1660. auto res = cli.Get(path.c_str());
  1661. ASSERT_TRUE(res);
  1662. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1663. std::string algo(path.substr(path.rfind('/') + 1));
  1664. EXPECT_EQ(
  1665. remove_whitespace("{\"algorithm\":\"" + algo +
  1666. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1667. remove_whitespace(res->body));
  1668. #else
  1669. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1670. remove_whitespace(res->body));
  1671. #endif
  1672. EXPECT_EQ(StatusCode::OK_200, res->status);
  1673. }
  1674. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1675. cli.set_digest_auth("hello", "bad");
  1676. for (const auto &path : paths) {
  1677. auto res = cli.Get(path.c_str());
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1680. }
  1681. #endif
  1682. }
  1683. }
  1684. #endif
  1685. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1686. auto host = "google.com";
  1687. auto another_host = "example.com";
  1688. auto wrong_ip = "0.0.0.0";
  1689. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1690. SSLClient cli(host);
  1691. #else
  1692. Client cli(host);
  1693. #endif
  1694. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1695. auto res = cli.Get("/");
  1696. ASSERT_TRUE(res);
  1697. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1698. }
  1699. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1700. auto host = "google.com";
  1701. auto wrong_ip = "0.0.0.0";
  1702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1703. SSLClient cli(host);
  1704. #else
  1705. Client cli(host);
  1706. #endif
  1707. cli.set_hostname_addr_map({{host, wrong_ip}});
  1708. auto res = cli.Get("/");
  1709. ASSERT_TRUE(!res);
  1710. EXPECT_EQ(Error::Connection, res.error());
  1711. }
  1712. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1713. auto host = "nghttp2.org";
  1714. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1715. SSLClient cli(host);
  1716. #else
  1717. Client cli(host);
  1718. #endif
  1719. cli.set_follow_location(true);
  1720. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1721. ASSERT_TRUE(res);
  1722. EXPECT_EQ(StatusCode::OK_200, res->status);
  1723. }
  1724. TEST(RedirectTest, Redirect_Online) {
  1725. auto host = "nghttp2.org";
  1726. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1727. SSLClient cli(host);
  1728. #else
  1729. Client cli(host);
  1730. #endif
  1731. cli.set_follow_location(true);
  1732. auto res = cli.Get("/httpbin/redirect/3");
  1733. ASSERT_TRUE(res);
  1734. EXPECT_EQ(StatusCode::OK_200, res->status);
  1735. }
  1736. TEST(RelativeRedirectTest, Redirect_Online) {
  1737. auto host = "nghttp2.org";
  1738. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_follow_location(true);
  1744. auto res = cli.Get("/httpbin/relative-redirect/3");
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::OK_200, res->status);
  1747. }
  1748. TEST(TooManyRedirectTest, Redirect_Online) {
  1749. auto host = "nghttp2.org";
  1750. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1751. SSLClient cli(host);
  1752. #else
  1753. Client cli(host);
  1754. #endif
  1755. cli.set_follow_location(true);
  1756. auto res = cli.Get("/httpbin/redirect/21");
  1757. ASSERT_TRUE(!res);
  1758. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1759. }
  1760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1761. TEST(YahooRedirectTest, Redirect_Online) {
  1762. Client cli("yahoo.com");
  1763. auto res = cli.Get("/");
  1764. ASSERT_TRUE(res);
  1765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1766. cli.set_follow_location(true);
  1767. res = cli.Get("/");
  1768. ASSERT_TRUE(res);
  1769. EXPECT_EQ(StatusCode::OK_200, res->status);
  1770. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1771. }
  1772. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1773. #define REDIR_HOST "httpbingo.org"
  1774. #define REDIR_PATH "/redirect-to"
  1775. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1776. SSLClient cli(REDIR_HOST);
  1777. cli.set_follow_location(true);
  1778. auto res =
  1779. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1780. ASSERT_TRUE(res);
  1781. EXPECT_EQ(StatusCode::OK_200, res->status);
  1782. }
  1783. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1784. SSLClient cli(REDIR_HOST);
  1785. cli.set_follow_location(true);
  1786. Params params;
  1787. params.emplace("url", "http://example.com");
  1788. params.emplace("status_code", "302");
  1789. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1790. ASSERT_TRUE(res);
  1791. EXPECT_EQ(StatusCode::OK_200, res->status);
  1792. }
  1793. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1794. SSLClient cli(REDIR_HOST);
  1795. cli.set_follow_location(true);
  1796. Params params;
  1797. params.emplace("url", "http://example.com");
  1798. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1799. ASSERT_TRUE(res);
  1800. EXPECT_EQ(StatusCode::OK_200, res->status);
  1801. }
  1802. TEST(UrlWithSpace, Redirect_Online) {
  1803. SSLClient cli("edge.forgecdn.net");
  1804. cli.set_follow_location(true);
  1805. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1806. ASSERT_TRUE(res);
  1807. EXPECT_EQ(StatusCode::OK_200, res->status);
  1808. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1809. }
  1810. #endif
  1811. #if !defined(_WIN32) && !defined(_WIN64)
  1812. TEST(ReceiveSignals, Signal) {
  1813. auto setupSignalHandlers = []() {
  1814. struct sigaction act;
  1815. sigemptyset(&act.sa_mask);
  1816. act.sa_flags = SA_SIGINFO;
  1817. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1818. switch (sig) {
  1819. case SIGINT:
  1820. default: break;
  1821. }
  1822. };
  1823. ::sigaction(SIGINT, &act, nullptr);
  1824. };
  1825. Server svr;
  1826. int port = 0;
  1827. auto thread = std::thread([&]() {
  1828. setupSignalHandlers();
  1829. port = svr.bind_to_any_port(HOST);
  1830. svr.listen_after_bind();
  1831. });
  1832. auto se = detail::scope_exit([&] {
  1833. svr.stop();
  1834. thread.join();
  1835. ASSERT_FALSE(svr.is_running());
  1836. });
  1837. svr.wait_until_ready();
  1838. ASSERT_TRUE(svr.is_running());
  1839. pthread_kill(thread.native_handle(), SIGINT);
  1840. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1841. ASSERT_TRUE(svr.is_running());
  1842. }
  1843. #endif
  1844. TEST(RedirectToDifferentPort, Redirect) {
  1845. Server svr1;
  1846. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("Hello World!", "text/plain");
  1848. });
  1849. int svr1_port = 0;
  1850. auto thread1 = std::thread([&]() {
  1851. svr1_port = svr1.bind_to_any_port(HOST);
  1852. svr1.listen_after_bind();
  1853. });
  1854. Server svr2;
  1855. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1856. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1857. });
  1858. int svr2_port = 0;
  1859. auto thread2 = std::thread([&]() {
  1860. svr2_port = svr2.bind_to_any_port(HOST);
  1861. svr2.listen_after_bind();
  1862. });
  1863. auto se = detail::scope_exit([&] {
  1864. svr2.stop();
  1865. thread2.join();
  1866. svr1.stop();
  1867. thread1.join();
  1868. ASSERT_FALSE(svr2.is_running());
  1869. ASSERT_FALSE(svr1.is_running());
  1870. });
  1871. svr1.wait_until_ready();
  1872. svr2.wait_until_ready();
  1873. Client cli("localhost", svr2_port);
  1874. cli.set_follow_location(true);
  1875. auto res = cli.Get("/2");
  1876. ASSERT_TRUE(res);
  1877. EXPECT_EQ(StatusCode::OK_200, res->status);
  1878. EXPECT_EQ("Hello World!", res->body);
  1879. }
  1880. TEST(RedirectFromPageWithContent, Redirect) {
  1881. Server svr;
  1882. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1883. res.set_content("___", "text/plain");
  1884. res.set_redirect("/2");
  1885. });
  1886. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1887. res.set_content("Hello World!", "text/plain");
  1888. });
  1889. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1890. auto se = detail::scope_exit([&] {
  1891. svr.stop();
  1892. th.join();
  1893. ASSERT_FALSE(svr.is_running());
  1894. });
  1895. svr.wait_until_ready();
  1896. {
  1897. Client cli("localhost", PORT);
  1898. cli.set_follow_location(true);
  1899. std::string body;
  1900. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1901. body.append(data, data_length);
  1902. return true;
  1903. });
  1904. ASSERT_TRUE(res);
  1905. EXPECT_EQ(StatusCode::OK_200, res->status);
  1906. EXPECT_EQ("Hello World!", body);
  1907. }
  1908. {
  1909. Client cli("localhost", PORT);
  1910. std::string body;
  1911. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1912. body.append(data, data_length);
  1913. return true;
  1914. });
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(StatusCode::Found_302, res->status);
  1917. EXPECT_EQ("___", body);
  1918. }
  1919. }
  1920. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1921. Server svr;
  1922. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1923. res.set_content("___", "text/plain");
  1924. // res.set_redirect("/2");
  1925. res.set_redirect("http://[::1]:1234/2");
  1926. });
  1927. svr.Get("/2", [&](const Request &req, Response &res) {
  1928. auto host_header = req.headers.find("Host");
  1929. ASSERT_TRUE(host_header != req.headers.end());
  1930. EXPECT_EQ("[::1]:1234", host_header->second);
  1931. res.set_content("Hello World!", "text/plain");
  1932. });
  1933. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1934. auto se = detail::scope_exit([&] {
  1935. svr.stop();
  1936. th.join();
  1937. ASSERT_FALSE(svr.is_running());
  1938. });
  1939. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1940. // actually starts anything, so the condition !svr.is_running() will
  1941. // always remain true, and the loop never stops.
  1942. // This basically counts how many milliseconds have passed since the
  1943. // call to svr.listen(), and if after 5 seconds nothing started yet
  1944. // aborts the test.
  1945. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1946. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1947. ASSERT_LT(milliseconds, 5000U);
  1948. }
  1949. {
  1950. Client cli("http://[::1]:1234");
  1951. cli.set_follow_location(true);
  1952. std::string body;
  1953. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1954. body.append(data, data_length);
  1955. return true;
  1956. });
  1957. ASSERT_TRUE(res);
  1958. EXPECT_EQ(StatusCode::OK_200, res->status);
  1959. EXPECT_EQ("Hello World!", body);
  1960. }
  1961. {
  1962. Client cli("http://[::1]:1234");
  1963. std::string body;
  1964. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1965. body.append(data, data_length);
  1966. return true;
  1967. });
  1968. ASSERT_TRUE(res);
  1969. EXPECT_EQ(StatusCode::Found_302, res->status);
  1970. EXPECT_EQ("___", body);
  1971. }
  1972. }
  1973. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1974. Server svr;
  1975. svr.Get("/foo", [](const Request &req, Response &res) {
  1976. auto a = req.params.find("a");
  1977. if (a != req.params.end()) {
  1978. res.set_content((*a).second, "text/plain");
  1979. res.status = StatusCode::OK_200;
  1980. } else {
  1981. res.status = StatusCode::BadRequest_400;
  1982. }
  1983. });
  1984. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1985. auto se = detail::scope_exit([&] {
  1986. svr.stop();
  1987. thread.join();
  1988. ASSERT_FALSE(svr.is_running());
  1989. });
  1990. svr.wait_until_ready();
  1991. {
  1992. Client cli(HOST, PORT);
  1993. cli.set_path_encode(false);
  1994. auto res = cli.Get("/foo?a=explicitly+encoded");
  1995. ASSERT_TRUE(res);
  1996. EXPECT_EQ(StatusCode::OK_200, res->status);
  1997. // This expects it back with a space, as the `+` won't have been
  1998. // url-encoded, and server-side the params get decoded turning `+`
  1999. // into spaces.
  2000. EXPECT_EQ("explicitly encoded", res->body);
  2001. }
  2002. }
  2003. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2004. Server svr;
  2005. svr.Get("/", [](const Request &req, Response &) {
  2006. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2007. });
  2008. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2009. auto se = detail::scope_exit([&] {
  2010. svr.stop();
  2011. thread.join();
  2012. ASSERT_FALSE(svr.is_running());
  2013. });
  2014. svr.wait_until_ready();
  2015. {
  2016. Client cli(HOST, PORT);
  2017. cli.set_path_encode(false);
  2018. auto res = cli.Get("/?something=%0A");
  2019. ASSERT_TRUE(res);
  2020. EXPECT_EQ(StatusCode::OK_200, res->status);
  2021. }
  2022. }
  2023. TEST(BindServerTest, DISABLED_BindDualStack) {
  2024. Server svr;
  2025. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2026. res.set_content("Hello World!", "text/plain");
  2027. });
  2028. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2029. auto se = detail::scope_exit([&] {
  2030. svr.stop();
  2031. thread.join();
  2032. ASSERT_FALSE(svr.is_running());
  2033. });
  2034. svr.wait_until_ready();
  2035. {
  2036. Client cli("127.0.0.1", PORT);
  2037. auto res = cli.Get("/1");
  2038. ASSERT_TRUE(res);
  2039. EXPECT_EQ(StatusCode::OK_200, res->status);
  2040. EXPECT_EQ("Hello World!", res->body);
  2041. }
  2042. {
  2043. Client cli("::1", PORT);
  2044. auto res = cli.Get("/1");
  2045. ASSERT_TRUE(res);
  2046. EXPECT_EQ(StatusCode::OK_200, res->status);
  2047. EXPECT_EQ("Hello World!", res->body);
  2048. }
  2049. }
  2050. TEST(BindServerTest, BindAndListenSeparately) {
  2051. Server svr;
  2052. int port = svr.bind_to_any_port("0.0.0.0");
  2053. ASSERT_TRUE(svr.is_valid());
  2054. ASSERT_TRUE(port > 0);
  2055. svr.stop();
  2056. }
  2057. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2058. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2060. CLIENT_CA_CERT_DIR);
  2061. int port = svr.bind_to_any_port("0.0.0.0");
  2062. ASSERT_TRUE(svr.is_valid());
  2063. ASSERT_TRUE(port > 0);
  2064. svr.stop();
  2065. }
  2066. #endif
  2067. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2068. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2069. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2070. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2071. int port = svr.bind_to_any_port("0.0.0.0");
  2072. ASSERT_TRUE(svr.is_valid());
  2073. ASSERT_TRUE(port > 0);
  2074. svr.stop();
  2075. }
  2076. #endif
  2077. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2078. X509 *readCertificate(const std::string &strFileName) {
  2079. std::ifstream inStream(strFileName);
  2080. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2081. std::istreambuf_iterator<char>());
  2082. if (strCertPEM.empty()) return (nullptr);
  2083. BIO *pbCert = BIO_new(BIO_s_mem());
  2084. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2085. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2086. BIO_free(pbCert);
  2087. return (pCert);
  2088. }
  2089. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2090. std::ifstream inStream(strFileName);
  2091. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2092. std::istreambuf_iterator<char>());
  2093. if (strPrivateKeyPEM.empty()) return (nullptr);
  2094. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2095. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2096. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2097. BIO_free(pbPrivKey);
  2098. return (pPrivateKey);
  2099. }
  2100. TEST(BindServerTest, UpdateCerts) {
  2101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2102. int port = svr.bind_to_any_port("0.0.0.0");
  2103. ASSERT_TRUE(svr.is_valid());
  2104. ASSERT_TRUE(port > 0);
  2105. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2106. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2107. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2108. ASSERT_TRUE(cert != nullptr);
  2109. ASSERT_TRUE(ca_cert != nullptr);
  2110. ASSERT_TRUE(key != nullptr);
  2111. X509_STORE *cert_store = X509_STORE_new();
  2112. X509_STORE_add_cert(cert_store, ca_cert);
  2113. svr.update_certs(cert, key, cert_store);
  2114. ASSERT_TRUE(svr.is_valid());
  2115. svr.stop();
  2116. X509_free(cert);
  2117. X509_free(ca_cert);
  2118. EVP_PKEY_free(key);
  2119. }
  2120. #endif
  2121. TEST(ErrorHandlerTest, ContentLength) {
  2122. Server svr;
  2123. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2124. res.status = StatusCode::OK_200;
  2125. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2126. "text/html"); // <= Content-Length still 13
  2127. });
  2128. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2129. res.set_content("Hello World!\n", "text/plain");
  2130. res.status = 524;
  2131. });
  2132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2133. auto se = detail::scope_exit([&] {
  2134. svr.stop();
  2135. thread.join();
  2136. ASSERT_FALSE(svr.is_running());
  2137. });
  2138. svr.wait_until_ready();
  2139. {
  2140. Client cli(HOST, PORT);
  2141. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2142. ASSERT_TRUE(res);
  2143. EXPECT_EQ(StatusCode::OK_200, res->status);
  2144. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2145. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2146. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2147. }
  2148. }
  2149. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2150. TEST(ExceptionTest, WithoutExceptionHandler) {
  2151. Server svr;
  2152. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2153. throw std::runtime_error("exception...");
  2154. });
  2155. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2156. throw std::runtime_error("exception\r\n...");
  2157. });
  2158. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2159. auto se = detail::scope_exit([&] {
  2160. svr.stop();
  2161. listen_thread.join();
  2162. ASSERT_FALSE(svr.is_running());
  2163. });
  2164. svr.wait_until_ready();
  2165. Client cli("localhost", PORT);
  2166. {
  2167. auto res = cli.Get("/exception");
  2168. ASSERT_TRUE(res);
  2169. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2170. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2171. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2172. }
  2173. {
  2174. auto res = cli.Get("/unknown");
  2175. ASSERT_TRUE(res);
  2176. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2177. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2178. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2179. }
  2180. }
  2181. TEST(ExceptionTest, WithExceptionHandler) {
  2182. Server svr;
  2183. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2184. std::exception_ptr ep) {
  2185. EXPECT_FALSE(ep == nullptr);
  2186. try {
  2187. std::rethrow_exception(ep);
  2188. } catch (std::exception &e) {
  2189. EXPECT_EQ("abc", std::string(e.what()));
  2190. } catch (...) {}
  2191. res.status = StatusCode::InternalServerError_500;
  2192. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2193. "text/html"); // <= Content-Length still 13 at this point
  2194. });
  2195. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2196. res.set_content("Hello World!\n", "text/plain");
  2197. throw std::runtime_error("abc");
  2198. });
  2199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2200. auto se = detail::scope_exit([&] {
  2201. svr.stop();
  2202. thread.join();
  2203. ASSERT_FALSE(svr.is_running());
  2204. });
  2205. svr.wait_until_ready();
  2206. for (size_t i = 0; i < 10; i++) {
  2207. Client cli(HOST, PORT);
  2208. for (size_t j = 0; j < 100; j++) {
  2209. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2210. ASSERT_TRUE(res);
  2211. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2213. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2214. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2215. }
  2216. cli.set_keep_alive(true);
  2217. for (size_t j = 0; j < 100; j++) {
  2218. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2219. ASSERT_TRUE(res);
  2220. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2221. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2222. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2223. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2224. }
  2225. }
  2226. }
  2227. TEST(ExceptionTest, AndErrorHandler) {
  2228. Server svr;
  2229. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2230. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2231. });
  2232. svr.set_exception_handler(
  2233. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2234. EXPECT_FALSE(ep == nullptr);
  2235. try {
  2236. std::rethrow_exception(ep);
  2237. } catch (std::exception &e) {
  2238. res.set_content(e.what(), "text/html");
  2239. } catch (...) {}
  2240. res.status = StatusCode::InternalServerError_500;
  2241. });
  2242. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2243. throw std::runtime_error("EXCEPTION");
  2244. });
  2245. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2246. res.set_content("ERROR", "text/html");
  2247. res.status = StatusCode::InternalServerError_500;
  2248. });
  2249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2250. auto se = detail::scope_exit([&] {
  2251. svr.stop();
  2252. thread.join();
  2253. ASSERT_FALSE(svr.is_running());
  2254. });
  2255. svr.wait_until_ready();
  2256. Client cli(HOST, PORT);
  2257. {
  2258. auto res = cli.Get("/exception");
  2259. ASSERT_TRUE(res);
  2260. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2261. EXPECT_EQ("EXCEPTION", res->body);
  2262. }
  2263. {
  2264. auto res = cli.Get("/error");
  2265. ASSERT_TRUE(res);
  2266. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2267. EXPECT_EQ("ERROR", res->body);
  2268. }
  2269. {
  2270. auto res = cli.Get("/invalid");
  2271. ASSERT_TRUE(res);
  2272. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2273. EXPECT_EQ("NOT_FOUND", res->body);
  2274. }
  2275. }
  2276. #endif
  2277. TEST(NoContentTest, ContentLength) {
  2278. Server svr;
  2279. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2280. res.status = StatusCode::NoContent_204;
  2281. });
  2282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2283. auto se = detail::scope_exit([&] {
  2284. svr.stop();
  2285. thread.join();
  2286. ASSERT_FALSE(svr.is_running());
  2287. });
  2288. svr.wait_until_ready();
  2289. {
  2290. Client cli(HOST, PORT);
  2291. auto res = cli.Get("/hi");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2294. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2295. }
  2296. }
  2297. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2298. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2299. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2300. ASSERT_TRUE(svr.is_valid());
  2301. #else
  2302. Server svr;
  2303. #endif
  2304. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2305. if (req.path == "/routing_handler") {
  2306. res.set_header("PRE_ROUTING", "on");
  2307. res.set_content("Routing Handler", "text/plain");
  2308. return httplib::Server::HandlerResponse::Handled;
  2309. }
  2310. return httplib::Server::HandlerResponse::Unhandled;
  2311. });
  2312. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2313. res.set_content("Error", "text/html");
  2314. });
  2315. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2316. if (req.path == "/routing_handler") {
  2317. res.set_header("POST_ROUTING", "on");
  2318. }
  2319. });
  2320. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2321. res.set_content("Hello World!\n", "text/plain");
  2322. });
  2323. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2324. auto se = detail::scope_exit([&] {
  2325. svr.stop();
  2326. thread.join();
  2327. ASSERT_FALSE(svr.is_running());
  2328. });
  2329. svr.wait_until_ready();
  2330. {
  2331. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2332. SSLClient cli(HOST, PORT);
  2333. cli.enable_server_certificate_verification(false);
  2334. #else
  2335. Client cli(HOST, PORT);
  2336. #endif
  2337. auto res = cli.Get("/routing_handler");
  2338. ASSERT_TRUE(res);
  2339. EXPECT_EQ(StatusCode::OK_200, res->status);
  2340. EXPECT_EQ("Routing Handler", res->body);
  2341. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2342. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2343. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2344. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2345. }
  2346. {
  2347. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2348. SSLClient cli(HOST, PORT);
  2349. cli.enable_server_certificate_verification(false);
  2350. #else
  2351. Client cli(HOST, PORT);
  2352. #endif
  2353. auto res = cli.Get("/hi");
  2354. ASSERT_TRUE(res);
  2355. EXPECT_EQ(StatusCode::OK_200, res->status);
  2356. EXPECT_EQ("Hello World!\n", res->body);
  2357. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2358. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2359. }
  2360. {
  2361. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2362. SSLClient cli(HOST, PORT);
  2363. cli.enable_server_certificate_verification(false);
  2364. #else
  2365. Client cli(HOST, PORT);
  2366. #endif
  2367. auto res = cli.Get("/aaa");
  2368. ASSERT_TRUE(res);
  2369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2370. EXPECT_EQ("Error", res->body);
  2371. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2372. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2373. }
  2374. }
  2375. TEST(RequestHandlerTest, PreRequestHandler) {
  2376. auto route_path = "/user/:user";
  2377. Server svr;
  2378. svr.Get("/hi", [](const Request &, Response &res) {
  2379. res.set_content("hi", "text/plain");
  2380. });
  2381. svr.Get(route_path, [](const Request &req, Response &res) {
  2382. res.set_content(req.path_params.at("user"), "text/plain");
  2383. });
  2384. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2385. if (req.matched_route == route_path) {
  2386. auto user = req.path_params.at("user");
  2387. if (user != "john") {
  2388. res.status = StatusCode::Forbidden_403;
  2389. res.set_content("error", "text/html");
  2390. return Server::HandlerResponse::Handled;
  2391. }
  2392. }
  2393. return Server::HandlerResponse::Unhandled;
  2394. });
  2395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2396. auto se = detail::scope_exit([&] {
  2397. svr.stop();
  2398. thread.join();
  2399. ASSERT_FALSE(svr.is_running());
  2400. });
  2401. svr.wait_until_ready();
  2402. Client cli(HOST, PORT);
  2403. {
  2404. auto res = cli.Get("/hi");
  2405. ASSERT_TRUE(res);
  2406. EXPECT_EQ(StatusCode::OK_200, res->status);
  2407. EXPECT_EQ("hi", res->body);
  2408. }
  2409. {
  2410. auto res = cli.Get("/user/john");
  2411. ASSERT_TRUE(res);
  2412. EXPECT_EQ(StatusCode::OK_200, res->status);
  2413. EXPECT_EQ("john", res->body);
  2414. }
  2415. {
  2416. auto res = cli.Get("/user/invalid-user");
  2417. ASSERT_TRUE(res);
  2418. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2419. EXPECT_EQ("error", res->body);
  2420. }
  2421. }
  2422. TEST(InvalidFormatTest, StatusCode) {
  2423. Server svr;
  2424. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2425. res.set_content("Hello World!\n", "text/plain");
  2426. res.status = 9999; // Status should be a three-digit code...
  2427. });
  2428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2429. auto se = detail::scope_exit([&] {
  2430. svr.stop();
  2431. thread.join();
  2432. ASSERT_FALSE(svr.is_running());
  2433. });
  2434. svr.wait_until_ready();
  2435. {
  2436. Client cli(HOST, PORT);
  2437. auto res = cli.Get("/hi");
  2438. ASSERT_FALSE(res);
  2439. }
  2440. }
  2441. TEST(URLFragmentTest, WithFragment) {
  2442. Server svr;
  2443. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2444. EXPECT_TRUE(req.target == "/hi");
  2445. });
  2446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2447. auto se = detail::scope_exit([&] {
  2448. svr.stop();
  2449. thread.join();
  2450. ASSERT_FALSE(svr.is_running());
  2451. });
  2452. svr.wait_until_ready();
  2453. {
  2454. Client cli(HOST, PORT);
  2455. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2456. EXPECT_TRUE(res);
  2457. EXPECT_EQ(StatusCode::OK_200, res->status);
  2458. res = cli.Get("/hi%23key1=val1=key2=val2");
  2459. EXPECT_TRUE(res);
  2460. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2461. }
  2462. }
  2463. TEST(HeaderWriter, SetHeaderWriter) {
  2464. Server svr;
  2465. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2466. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2467. return detail::write_headers(strm, hdrs);
  2468. });
  2469. svr.Get("/hi", [](const Request &req, Response &res) {
  2470. auto it = req.headers.find("CustomClientHeader");
  2471. EXPECT_TRUE(it != req.headers.end());
  2472. EXPECT_EQ(it->second, "CustomClientValue");
  2473. res.set_content("Hello World!\n", "text/plain");
  2474. });
  2475. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2476. auto se = detail::scope_exit([&] {
  2477. svr.stop();
  2478. thread.join();
  2479. ASSERT_FALSE(svr.is_running());
  2480. });
  2481. svr.wait_until_ready();
  2482. {
  2483. Client cli(HOST, PORT);
  2484. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2485. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2486. return detail::write_headers(strm, hdrs);
  2487. });
  2488. auto res = cli.Get("/hi");
  2489. EXPECT_TRUE(res);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. auto it = res->headers.find("CustomServerHeader");
  2492. EXPECT_TRUE(it != res->headers.end());
  2493. EXPECT_EQ(it->second, "CustomServerValue");
  2494. }
  2495. }
  2496. class ServerTest : public ::testing::Test {
  2497. protected:
  2498. ServerTest()
  2499. : cli_(HOST, PORT)
  2500. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2501. ,
  2502. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2503. #endif
  2504. {
  2505. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2506. cli_.enable_server_certificate_verification(false);
  2507. #endif
  2508. }
  2509. virtual void SetUp() {
  2510. svr_.set_mount_point("/", "./www");
  2511. svr_.set_mount_point("/mount", "./www2");
  2512. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2513. svr_.Get("/hi",
  2514. [&](const Request & /*req*/, Response &res) {
  2515. res.set_content("Hello World!", "text/plain");
  2516. })
  2517. .Get("/file_content",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. res.set_file_content("./www/dir/test.html");
  2520. })
  2521. .Get("/file_content_with_content_type",
  2522. [&](const Request & /*req*/, Response &res) {
  2523. res.set_file_content("./www/file", "text/plain");
  2524. })
  2525. .Get("/invalid_file_content",
  2526. [&](const Request & /*req*/, Response &res) {
  2527. res.set_file_content("./www/dir/invalid_file_path");
  2528. })
  2529. .Get("/http_response_splitting",
  2530. [&](const Request & /*req*/, Response &res) {
  2531. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2532. EXPECT_EQ(0U, res.headers.size());
  2533. EXPECT_FALSE(res.has_header("a"));
  2534. res.set_header("a", "1\nSet-Cookie: a=1");
  2535. EXPECT_EQ(0U, res.headers.size());
  2536. EXPECT_FALSE(res.has_header("a"));
  2537. res.set_header("a", "1\rSet-Cookie: a=1");
  2538. EXPECT_EQ(0U, res.headers.size());
  2539. EXPECT_FALSE(res.has_header("a"));
  2540. res.set_header("a\r\nb", "0");
  2541. EXPECT_EQ(0U, res.headers.size());
  2542. EXPECT_FALSE(res.has_header("a"));
  2543. res.set_header("a\rb", "0");
  2544. EXPECT_EQ(0U, res.headers.size());
  2545. EXPECT_FALSE(res.has_header("a"));
  2546. res.set_header("a\nb", "0");
  2547. EXPECT_EQ(0U, res.headers.size());
  2548. EXPECT_FALSE(res.has_header("a"));
  2549. res.set_redirect("1\r\nSet-Cookie: a=1");
  2550. EXPECT_EQ(0U, res.headers.size());
  2551. EXPECT_FALSE(res.has_header("Location"));
  2552. })
  2553. .Get("/slow",
  2554. [&](const Request & /*req*/, Response &res) {
  2555. std::this_thread::sleep_for(std::chrono::seconds(2));
  2556. res.set_content("slow", "text/plain");
  2557. })
  2558. #if 0
  2559. .Post("/slowpost",
  2560. [&](const Request & /*req*/, Response &res) {
  2561. std::this_thread::sleep_for(std::chrono::seconds(2));
  2562. res.set_content("slow", "text/plain");
  2563. })
  2564. #endif
  2565. .Get("/remote_addr",
  2566. [&](const Request &req, Response &res) {
  2567. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2568. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2569. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2570. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2571. res.set_content(req.remote_addr, "text/plain");
  2572. })
  2573. .Get("/local_addr",
  2574. [&](const Request &req, Response &res) {
  2575. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2576. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2577. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2578. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2579. auto local_addr = req.local_addr;
  2580. auto local_port = std::to_string(req.local_port);
  2581. res.set_content(local_addr.append(":").append(local_port),
  2582. "text/plain");
  2583. })
  2584. .Get("/endwith%",
  2585. [&](const Request & /*req*/, Response &res) {
  2586. res.set_content("Hello World!", "text/plain");
  2587. })
  2588. .Get("/a\\+\\+b",
  2589. [&](const Request &req, Response &res) {
  2590. ASSERT_TRUE(req.has_param("a +b"));
  2591. auto val = req.get_param_value("a +b");
  2592. res.set_content(val, "text/plain");
  2593. })
  2594. .Get("/", [&](const Request & /*req*/,
  2595. Response &res) { res.set_redirect("/hi"); })
  2596. .Post("/1",
  2597. [](const Request & /*req*/, Response &res) {
  2598. res.set_redirect("/2", StatusCode::SeeOther_303);
  2599. })
  2600. .Get("/2",
  2601. [](const Request & /*req*/, Response &res) {
  2602. res.set_content("redirected.", "text/plain");
  2603. res.status = StatusCode::OK_200;
  2604. })
  2605. .Post("/person",
  2606. [&](const Request &req, Response &res) {
  2607. if (req.has_param("name") && req.has_param("note")) {
  2608. persons_[req.get_param_value("name")] =
  2609. req.get_param_value("note");
  2610. } else {
  2611. res.status = StatusCode::BadRequest_400;
  2612. }
  2613. })
  2614. .Put("/person",
  2615. [&](const Request &req, Response &res) {
  2616. if (req.has_param("name") && req.has_param("note")) {
  2617. persons_[req.get_param_value("name")] =
  2618. req.get_param_value("note");
  2619. } else {
  2620. res.status = StatusCode::BadRequest_400;
  2621. }
  2622. })
  2623. .Get("/person/(.*)",
  2624. [&](const Request &req, Response &res) {
  2625. string name = req.matches[1];
  2626. if (persons_.find(name) != persons_.end()) {
  2627. auto note = persons_[name];
  2628. res.set_content(note, "text/plain");
  2629. } else {
  2630. res.status = StatusCode::NotFound_404;
  2631. }
  2632. })
  2633. .Delete("/person",
  2634. [&](const Request &req, Response &res) {
  2635. if (req.has_param("name")) {
  2636. string name = req.get_param_value("name");
  2637. if (persons_.find(name) != persons_.end()) {
  2638. persons_.erase(name);
  2639. res.set_content("DELETED", "text/plain");
  2640. } else {
  2641. res.status = StatusCode::NotFound_404;
  2642. }
  2643. } else {
  2644. res.status = StatusCode::BadRequest_400;
  2645. }
  2646. })
  2647. .Post("/x-www-form-urlencoded-json",
  2648. [&](const Request &req, Response &res) {
  2649. auto json = req.get_param_value("json");
  2650. ASSERT_EQ(JSON_DATA, json);
  2651. res.set_content(json, "appliation/json");
  2652. res.status = StatusCode::OK_200;
  2653. })
  2654. .Get("/streamed-chunked",
  2655. [&](const Request & /*req*/, Response &res) {
  2656. res.set_chunked_content_provider(
  2657. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2658. sink.os << "123";
  2659. sink.os << "456";
  2660. sink.os << "789";
  2661. sink.done();
  2662. return true;
  2663. });
  2664. })
  2665. .Get("/streamed-chunked-with-prohibited-trailer",
  2666. [&](const Request & /*req*/, Response &res) {
  2667. auto i = new int(0);
  2668. // Declare both a prohibited trailer (Content-Length) and an
  2669. // allowed one
  2670. res.set_header("Trailer", "Content-Length, X-Allowed");
  2671. res.set_chunked_content_provider(
  2672. "text/plain",
  2673. [i](size_t /*offset*/, DataSink &sink) {
  2674. switch (*i) {
  2675. case 0: sink.os << "123"; break;
  2676. case 1: sink.os << "456"; break;
  2677. case 2: sink.os << "789"; break;
  2678. case 3: {
  2679. sink.done_with_trailer(
  2680. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2681. } break;
  2682. }
  2683. (*i)++;
  2684. return true;
  2685. },
  2686. [i](bool success) {
  2687. EXPECT_TRUE(success);
  2688. delete i;
  2689. });
  2690. })
  2691. .Get("/streamed-chunked2",
  2692. [&](const Request & /*req*/, Response &res) {
  2693. auto i = new int(0);
  2694. res.set_chunked_content_provider(
  2695. "text/plain",
  2696. [i](size_t /*offset*/, DataSink &sink) {
  2697. switch (*i) {
  2698. case 0: sink.os << "123"; break;
  2699. case 1: sink.os << "456"; break;
  2700. case 2: sink.os << "789"; break;
  2701. case 3: sink.done(); break;
  2702. }
  2703. (*i)++;
  2704. return true;
  2705. },
  2706. [i](bool success) {
  2707. EXPECT_TRUE(success);
  2708. delete i;
  2709. });
  2710. })
  2711. .Get("/streamed-chunked-with-trailer",
  2712. [&](const Request & /*req*/, Response &res) {
  2713. auto i = new int(0);
  2714. res.set_header("Trailer", "Dummy1, Dummy2");
  2715. res.set_chunked_content_provider(
  2716. "text/plain",
  2717. [i](size_t /*offset*/, DataSink &sink) {
  2718. switch (*i) {
  2719. case 0: sink.os << "123"; break;
  2720. case 1: sink.os << "456"; break;
  2721. case 2: sink.os << "789"; break;
  2722. case 3: {
  2723. sink.done_with_trailer(
  2724. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2725. } break;
  2726. }
  2727. (*i)++;
  2728. return true;
  2729. },
  2730. [i](bool success) {
  2731. EXPECT_TRUE(success);
  2732. delete i;
  2733. });
  2734. })
  2735. .Get("/streamed",
  2736. [&](const Request & /*req*/, Response &res) {
  2737. res.set_content_provider(
  2738. 6, "text/plain",
  2739. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2740. sink.os << (offset < 3 ? "a" : "b");
  2741. return true;
  2742. });
  2743. })
  2744. .Get("/streamed-with-range",
  2745. [&](const Request &req, Response &res) {
  2746. auto data = new std::string("abcdefg");
  2747. res.set_content_provider(
  2748. data->size(), "text/plain",
  2749. [data](size_t offset, size_t length, DataSink &sink) {
  2750. size_t DATA_CHUNK_SIZE = 4;
  2751. const auto &d = *data;
  2752. auto out_len =
  2753. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2754. auto ret =
  2755. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2756. EXPECT_TRUE(ret);
  2757. return true;
  2758. },
  2759. [data, &req](bool success) {
  2760. EXPECT_EQ(success, !req.has_param("error"));
  2761. delete data;
  2762. });
  2763. })
  2764. .Get("/streamed-cancel",
  2765. [&](const Request & /*req*/, Response &res) {
  2766. res.set_content_provider(
  2767. size_t(-1), "text/plain",
  2768. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2769. sink.os << "data_chunk";
  2770. return true;
  2771. });
  2772. })
  2773. .Get("/regex-with-delimiter",
  2774. [&](const Request &req, Response & /*res*/) {
  2775. ASSERT_TRUE(req.has_param("key"));
  2776. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2777. })
  2778. .Get("/with-range",
  2779. [&](const Request & /*req*/, Response &res) {
  2780. res.set_content("abcdefg", "text/plain");
  2781. })
  2782. .Get("/test-start-time",
  2783. [&](const Request &req, Response & /*res*/) {
  2784. EXPECT_NE(req.start_time_,
  2785. std::chrono::steady_clock::time_point::min());
  2786. })
  2787. .Get("/with-range-customized-response",
  2788. [&](const Request & /*req*/, Response &res) {
  2789. res.status = StatusCode::BadRequest_400;
  2790. res.set_content(JSON_DATA, "application/json");
  2791. })
  2792. .Post("/chunked",
  2793. [&](const Request &req, Response & /*res*/) {
  2794. EXPECT_EQ(req.body, "dechunked post body");
  2795. })
  2796. .Post("/large-chunked",
  2797. [&](const Request &req, Response & /*res*/) {
  2798. std::string expected(6 * 30 * 1024u, 'a');
  2799. EXPECT_EQ(req.body, expected);
  2800. })
  2801. .Post("/multipart",
  2802. [&](const Request &req, Response & /*res*/) {
  2803. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2804. req.form.get_field_count("text2") +
  2805. req.form.get_field_count("file3") +
  2806. req.form.get_field_count("file4"));
  2807. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2808. req.form.get_file_count("file2"));
  2809. ASSERT_TRUE(!req.form.has_file("???"));
  2810. ASSERT_TRUE(!req.form.has_field("???"));
  2811. ASSERT_TRUE(req.body.empty());
  2812. {
  2813. const auto &text = req.form.get_field("text1");
  2814. EXPECT_EQ("text default", text);
  2815. }
  2816. {
  2817. const auto &text = req.form.get_field("text2");
  2818. EXPECT_EQ("aωb", text);
  2819. }
  2820. {
  2821. const auto &file = req.form.get_file("file1");
  2822. EXPECT_EQ("hello.txt", file.filename);
  2823. EXPECT_EQ("text/plain", file.content_type);
  2824. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2825. }
  2826. {
  2827. const auto &file = req.form.get_file("file2");
  2828. EXPECT_EQ("world.json", file.filename);
  2829. EXPECT_EQ("application/json", file.content_type);
  2830. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2831. }
  2832. {
  2833. const auto &text = req.form.get_field("file3");
  2834. EXPECT_EQ(0u, text.size());
  2835. }
  2836. {
  2837. const auto &text = req.form.get_field("file4");
  2838. EXPECT_EQ(0u, text.size());
  2839. }
  2840. })
  2841. .Post("/multipart/multi_file_values",
  2842. [&](const Request &req, Response & /*res*/) {
  2843. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2844. req.form.get_field_count("multi_text1"));
  2845. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2846. ASSERT_TRUE(!req.form.has_file("???"));
  2847. ASSERT_TRUE(!req.form.has_field("???"));
  2848. ASSERT_TRUE(req.body.empty());
  2849. {
  2850. const auto &text = req.form.get_field("text");
  2851. EXPECT_EQ("default text", text);
  2852. }
  2853. {
  2854. const auto &text1_values = req.form.get_fields("multi_text1");
  2855. EXPECT_EQ(2u, text1_values.size());
  2856. EXPECT_EQ("aaaaa", text1_values[0]);
  2857. EXPECT_EQ("bbbbb", text1_values[1]);
  2858. }
  2859. {
  2860. const auto &file1_values = req.form.get_files("multi_file1");
  2861. EXPECT_EQ(2u, file1_values.size());
  2862. auto file1 = file1_values[0];
  2863. EXPECT_EQ(file1.filename, "hello.txt");
  2864. EXPECT_EQ(file1.content_type, "text/plain");
  2865. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2866. auto file2 = file1_values[1];
  2867. EXPECT_EQ(file2.filename, "world.json");
  2868. EXPECT_EQ(file2.content_type, "application/json");
  2869. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2870. }
  2871. })
  2872. .Post("/empty",
  2873. [&](const Request &req, Response &res) {
  2874. EXPECT_EQ(req.body, "");
  2875. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2876. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2877. res.set_content("empty", "text/plain");
  2878. })
  2879. .Post("/empty-no-content-type",
  2880. [&](const Request &req, Response &res) {
  2881. EXPECT_EQ(req.body, "");
  2882. EXPECT_FALSE(req.has_header("Content-Type"));
  2883. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2884. res.set_content("empty-no-content-type", "text/plain");
  2885. })
  2886. .Post("/path-only",
  2887. [&](const Request &req, Response &res) {
  2888. EXPECT_EQ(req.body, "");
  2889. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2890. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2891. res.set_content("path-only", "text/plain");
  2892. })
  2893. .Post("/path-headers-only",
  2894. [&](const Request &req, Response &res) {
  2895. EXPECT_EQ(req.body, "");
  2896. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2897. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2898. EXPECT_EQ("world", req.get_header_value("hello"));
  2899. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2900. res.set_content("path-headers-only", "text/plain");
  2901. })
  2902. .Post("/post-large",
  2903. [&](const Request &req, Response &res) {
  2904. EXPECT_EQ(req.body, LARGE_DATA);
  2905. res.set_content(req.body, "text/plain");
  2906. })
  2907. .Post("/post-loopback",
  2908. [&](const Request &, Response &res,
  2909. ContentReader const &content_reader) {
  2910. std::string body;
  2911. content_reader([&](const char *data, size_t data_length) {
  2912. body.append(data, data_length);
  2913. return true;
  2914. });
  2915. res.set_content(body, "text/plain");
  2916. })
  2917. .Put("/put-loopback",
  2918. [&](const Request &, Response &res,
  2919. ContentReader const &content_reader) {
  2920. std::string body;
  2921. content_reader([&](const char *data, size_t data_length) {
  2922. body.append(data, data_length);
  2923. return true;
  2924. });
  2925. res.set_content(body, "text/plain");
  2926. })
  2927. .Patch("/patch-loopback",
  2928. [&](const Request &, Response &res,
  2929. ContentReader const &content_reader) {
  2930. std::string body;
  2931. content_reader([&](const char *data, size_t data_length) {
  2932. body.append(data, data_length);
  2933. return true;
  2934. });
  2935. res.set_content(body, "text/plain");
  2936. })
  2937. .Put("/empty-no-content-type",
  2938. [&](const Request &req, Response &res) {
  2939. EXPECT_EQ(req.body, "");
  2940. EXPECT_FALSE(req.has_header("Content-Type"));
  2941. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2942. res.set_content("empty-no-content-type", "text/plain");
  2943. })
  2944. .Put("/put",
  2945. [&](const Request &req, Response &res) {
  2946. EXPECT_EQ(req.body, "PUT");
  2947. res.set_content(req.body, "text/plain");
  2948. })
  2949. .Put("/put-large",
  2950. [&](const Request &req, Response &res) {
  2951. EXPECT_EQ(req.body, LARGE_DATA);
  2952. res.set_content(req.body, "text/plain");
  2953. })
  2954. .Patch("/patch",
  2955. [&](const Request &req, Response &res) {
  2956. EXPECT_EQ(req.body, "PATCH");
  2957. res.set_content(req.body, "text/plain");
  2958. })
  2959. .Delete("/delete",
  2960. [&](const Request & /*req*/, Response &res) {
  2961. res.set_content("DELETE", "text/plain");
  2962. })
  2963. .Delete("/delete-body",
  2964. [&](const Request &req, Response &res) {
  2965. EXPECT_EQ(req.body, "content");
  2966. res.set_content(req.body, "text/plain");
  2967. })
  2968. .Options(R"(\*)",
  2969. [&](const Request & /*req*/, Response &res) {
  2970. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2971. })
  2972. .Get("/request-target",
  2973. [&](const Request &req, Response & /*res*/) {
  2974. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2975. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2976. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2977. })
  2978. .Get("/long-query-value",
  2979. [&](const Request &req, Response & /*res*/) {
  2980. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2981. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2982. })
  2983. .Get("/too-long-query-value",
  2984. [&](const Request &req, Response & /*res*/) {
  2985. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2986. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2987. })
  2988. .Get("/array-param",
  2989. [&](const Request &req, Response & /*res*/) {
  2990. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2991. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2992. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2993. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2994. })
  2995. .Post("/validate-no-multiple-headers",
  2996. [&](const Request &req, Response & /*res*/) {
  2997. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2998. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2999. })
  3000. .Post("/content_receiver",
  3001. [&](const Request &req, Response &res,
  3002. const ContentReader &content_reader) {
  3003. if (req.is_multipart_form_data()) {
  3004. std::vector<FormData> items;
  3005. content_reader(
  3006. [&](const FormData &file) {
  3007. items.push_back(file);
  3008. return true;
  3009. },
  3010. [&](const char *data, size_t data_length) {
  3011. items.back().content.append(data, data_length);
  3012. return true;
  3013. });
  3014. EXPECT_EQ(5u, items.size());
  3015. {
  3016. const auto &file = get_file_value(items, "text1");
  3017. EXPECT_TRUE(file.filename.empty());
  3018. EXPECT_EQ("text default", file.content);
  3019. }
  3020. {
  3021. const auto &file = get_file_value(items, "text2");
  3022. EXPECT_TRUE(file.filename.empty());
  3023. EXPECT_EQ("aωb", file.content);
  3024. }
  3025. {
  3026. const auto &file = get_file_value(items, "file1");
  3027. EXPECT_EQ("hello.txt", file.filename);
  3028. EXPECT_EQ("text/plain", file.content_type);
  3029. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3030. }
  3031. {
  3032. const auto &file = get_file_value(items, "file2");
  3033. EXPECT_EQ("world.json", file.filename);
  3034. EXPECT_EQ("application/json", file.content_type);
  3035. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3036. }
  3037. {
  3038. const auto &file = get_file_value(items, "file3");
  3039. EXPECT_TRUE(file.filename.empty());
  3040. EXPECT_EQ("application/octet-stream", file.content_type);
  3041. EXPECT_EQ(0u, file.content.size());
  3042. }
  3043. } else {
  3044. std::string body;
  3045. content_reader([&](const char *data, size_t data_length) {
  3046. EXPECT_EQ(7U, data_length);
  3047. body.append(data, data_length);
  3048. return true;
  3049. });
  3050. EXPECT_EQ(body, "content");
  3051. res.set_content(body, "text/plain");
  3052. }
  3053. })
  3054. .Put("/content_receiver",
  3055. [&](const Request & /*req*/, Response &res,
  3056. const ContentReader &content_reader) {
  3057. std::string body;
  3058. content_reader([&](const char *data, size_t data_length) {
  3059. body.append(data, data_length);
  3060. return true;
  3061. });
  3062. EXPECT_EQ(body, "content");
  3063. res.set_content(body, "text/plain");
  3064. })
  3065. .Patch("/content_receiver",
  3066. [&](const Request & /*req*/, Response &res,
  3067. const ContentReader &content_reader) {
  3068. std::string body;
  3069. content_reader([&](const char *data, size_t data_length) {
  3070. body.append(data, data_length);
  3071. return true;
  3072. });
  3073. EXPECT_EQ(body, "content");
  3074. res.set_content(body, "text/plain");
  3075. })
  3076. .Post("/query-string-and-body",
  3077. [&](const Request &req, Response & /*res*/) {
  3078. ASSERT_TRUE(req.has_param("key"));
  3079. EXPECT_EQ(req.get_param_value("key"), "value");
  3080. EXPECT_EQ(req.body, "content");
  3081. })
  3082. .Get("/last-request",
  3083. [&](const Request &req, Response & /*res*/) {
  3084. EXPECT_EQ("close", req.get_header_value("Connection"));
  3085. })
  3086. .Get(R"(/redirect/(\d+))",
  3087. [&](const Request &req, Response &res) {
  3088. auto num = std::stoi(req.matches[1]) + 1;
  3089. std::string url = "/redirect/" + std::to_string(num);
  3090. res.set_redirect(url);
  3091. })
  3092. .Post("/binary",
  3093. [&](const Request &req, Response &res) {
  3094. EXPECT_EQ(4U, req.body.size());
  3095. EXPECT_EQ("application/octet-stream",
  3096. req.get_header_value("Content-Type"));
  3097. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3098. res.set_content(req.body, "application/octet-stream");
  3099. })
  3100. .Put("/binary",
  3101. [&](const Request &req, Response &res) {
  3102. EXPECT_EQ(4U, req.body.size());
  3103. EXPECT_EQ("application/octet-stream",
  3104. req.get_header_value("Content-Type"));
  3105. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3106. res.set_content(req.body, "application/octet-stream");
  3107. })
  3108. .Patch("/binary",
  3109. [&](const Request &req, Response &res) {
  3110. EXPECT_EQ(4U, req.body.size());
  3111. EXPECT_EQ("application/octet-stream",
  3112. req.get_header_value("Content-Type"));
  3113. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3114. res.set_content(req.body, "application/octet-stream");
  3115. })
  3116. .Delete("/binary",
  3117. [&](const Request &req, Response &res) {
  3118. EXPECT_EQ(4U, req.body.size());
  3119. EXPECT_EQ("application/octet-stream",
  3120. req.get_header_value("Content-Type"));
  3121. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3122. res.set_content(req.body, "application/octet-stream");
  3123. })
  3124. .Get("/issue1772",
  3125. [&](const Request & /*req*/, Response &res) {
  3126. res.status = 401;
  3127. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3128. })
  3129. .Delete("/issue609",
  3130. [](const httplib::Request &, httplib::Response &res,
  3131. const httplib::ContentReader &) {
  3132. res.set_content("ok", "text/plain");
  3133. })
  3134. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3135. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3136. .Get("/compress",
  3137. [&](const Request & /*req*/, Response &res) {
  3138. res.set_content(
  3139. "12345678901234567890123456789012345678901234567890123456789"
  3140. "01234567890123456789012345678901234567890",
  3141. "text/plain");
  3142. })
  3143. .Get("/nocompress",
  3144. [&](const Request & /*req*/, Response &res) {
  3145. res.set_content(
  3146. "12345678901234567890123456789012345678901234567890123456789"
  3147. "01234567890123456789012345678901234567890",
  3148. "application/octet-stream");
  3149. })
  3150. .Post("/compress-multipart",
  3151. [&](const Request &req, Response & /*res*/) {
  3152. EXPECT_EQ(2u, req.form.fields.size());
  3153. ASSERT_TRUE(!req.form.has_field("???"));
  3154. {
  3155. const auto &text = req.form.get_field("key1");
  3156. EXPECT_EQ("test", text);
  3157. }
  3158. {
  3159. const auto &text = req.form.get_field("key2");
  3160. EXPECT_EQ("--abcdefg123", text);
  3161. }
  3162. })
  3163. #endif
  3164. ;
  3165. persons_["john"] = "programmer";
  3166. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3167. svr_.wait_until_ready();
  3168. }
  3169. virtual void TearDown() {
  3170. svr_.stop();
  3171. if (!request_threads_.empty()) {
  3172. std::this_thread::sleep_for(std::chrono::seconds(1));
  3173. for (auto &t : request_threads_) {
  3174. t.join();
  3175. }
  3176. }
  3177. t_.join();
  3178. }
  3179. map<string, string> persons_;
  3180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3181. SSLClient cli_;
  3182. SSLServer svr_;
  3183. #else
  3184. Client cli_;
  3185. Server svr_;
  3186. #endif
  3187. thread t_;
  3188. std::vector<thread> request_threads_;
  3189. };
  3190. TEST_F(ServerTest, GetMethod200) {
  3191. auto res = cli_.Get("/hi");
  3192. ASSERT_TRUE(res);
  3193. EXPECT_EQ("HTTP/1.1", res->version);
  3194. EXPECT_EQ(StatusCode::OK_200, res->status);
  3195. EXPECT_EQ("OK", res->reason);
  3196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3197. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3198. EXPECT_EQ("Hello World!", res->body);
  3199. }
  3200. TEST_F(ServerTest, GetEmptyFile) {
  3201. auto res = cli_.Get("/empty_file");
  3202. ASSERT_TRUE(res);
  3203. EXPECT_EQ(StatusCode::OK_200, res->status);
  3204. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3205. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3206. EXPECT_EQ("", res->body);
  3207. }
  3208. TEST_F(ServerTest, GetFileContent) {
  3209. auto res = cli_.Get("/file_content");
  3210. ASSERT_TRUE(res);
  3211. EXPECT_EQ(StatusCode::OK_200, res->status);
  3212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3213. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3214. EXPECT_EQ("test.html", res->body);
  3215. }
  3216. TEST_F(ServerTest, GetFileContentWithRange) {
  3217. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3218. ASSERT_TRUE(res);
  3219. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3220. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3221. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3222. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3223. EXPECT_EQ("est", res->body);
  3224. }
  3225. TEST_F(ServerTest, GetFileContentWithContentType) {
  3226. auto res = cli_.Get("/file_content_with_content_type");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3230. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3231. EXPECT_EQ("file\n", res->body);
  3232. }
  3233. TEST_F(ServerTest, GetInvalidFileContent) {
  3234. auto res = cli_.Get("/invalid_file_content");
  3235. ASSERT_TRUE(res);
  3236. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3237. }
  3238. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3239. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3240. ASSERT_TRUE(res);
  3241. EXPECT_EQ("HTTP/1.1", res->version);
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3244. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3245. EXPECT_EQ("Hello World!", res->body);
  3246. }
  3247. TEST_F(ServerTest, GetMethod302) {
  3248. auto res = cli_.Get("/");
  3249. ASSERT_TRUE(res);
  3250. EXPECT_EQ(StatusCode::Found_302, res->status);
  3251. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3252. }
  3253. TEST_F(ServerTest, GetMethod302Redirect) {
  3254. cli_.set_follow_location(true);
  3255. auto res = cli_.Get("/");
  3256. ASSERT_TRUE(res);
  3257. EXPECT_EQ(StatusCode::OK_200, res->status);
  3258. EXPECT_EQ("Hello World!", res->body);
  3259. EXPECT_EQ("/hi", res->location);
  3260. }
  3261. TEST_F(ServerTest, GetMethod404) {
  3262. auto res = cli_.Get("/invalid");
  3263. ASSERT_TRUE(res);
  3264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3265. }
  3266. TEST_F(ServerTest, HeadMethod200) {
  3267. auto res = cli_.Head("/hi");
  3268. ASSERT_TRUE(res);
  3269. EXPECT_EQ(StatusCode::OK_200, res->status);
  3270. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3271. EXPECT_TRUE(res->body.empty());
  3272. }
  3273. TEST_F(ServerTest, HeadMethod200Static) {
  3274. auto res = cli_.Head("/mount/dir/index.html");
  3275. ASSERT_TRUE(res);
  3276. EXPECT_EQ(StatusCode::OK_200, res->status);
  3277. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3278. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3279. EXPECT_TRUE(res->body.empty());
  3280. }
  3281. TEST_F(ServerTest, HeadMethod404) {
  3282. auto res = cli_.Head("/invalid");
  3283. ASSERT_TRUE(res);
  3284. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3285. EXPECT_TRUE(res->body.empty());
  3286. }
  3287. TEST_F(ServerTest, GetMethodPersonJohn) {
  3288. auto res = cli_.Get("/person/john");
  3289. ASSERT_TRUE(res);
  3290. EXPECT_EQ(StatusCode::OK_200, res->status);
  3291. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3292. EXPECT_EQ("programmer", res->body);
  3293. }
  3294. TEST_F(ServerTest, PostMethod1) {
  3295. auto res = cli_.Get("/person/john1");
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3298. res = cli_.Post("/person", "name=john1&note=coder",
  3299. "application/x-www-form-urlencoded");
  3300. ASSERT_TRUE(res);
  3301. ASSERT_EQ(StatusCode::OK_200, res->status);
  3302. res = cli_.Get("/person/john1");
  3303. ASSERT_TRUE(res);
  3304. ASSERT_EQ(StatusCode::OK_200, res->status);
  3305. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3306. ASSERT_EQ("coder", res->body);
  3307. }
  3308. TEST_F(ServerTest, PostMethod2) {
  3309. auto res = cli_.Get("/person/john2");
  3310. ASSERT_TRUE(res);
  3311. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3312. Params params;
  3313. params.emplace("name", "john2");
  3314. params.emplace("note", "coder");
  3315. res = cli_.Post("/person", params);
  3316. ASSERT_TRUE(res);
  3317. ASSERT_EQ(StatusCode::OK_200, res->status);
  3318. res = cli_.Get("/person/john2");
  3319. ASSERT_TRUE(res);
  3320. ASSERT_EQ(StatusCode::OK_200, res->status);
  3321. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3322. ASSERT_EQ("coder", res->body);
  3323. }
  3324. TEST_F(ServerTest, PutMethod3) {
  3325. auto res = cli_.Get("/person/john3");
  3326. ASSERT_TRUE(res);
  3327. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3328. Params params;
  3329. params.emplace("name", "john3");
  3330. params.emplace("note", "coder");
  3331. res = cli_.Put("/person", params);
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::OK_200, res->status);
  3334. res = cli_.Get("/person/john3");
  3335. ASSERT_TRUE(res);
  3336. ASSERT_EQ(StatusCode::OK_200, res->status);
  3337. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3338. ASSERT_EQ("coder", res->body);
  3339. }
  3340. TEST_F(ServerTest, DeleteMethod1) {
  3341. auto res = cli_.Get("/person/john4");
  3342. ASSERT_TRUE(res);
  3343. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3344. Params params;
  3345. params.emplace("name", "john4");
  3346. params.emplace("note", "coder");
  3347. res = cli_.Post("/person", params);
  3348. ASSERT_TRUE(res);
  3349. ASSERT_EQ(StatusCode::OK_200, res->status);
  3350. res = cli_.Get("/person/john4");
  3351. ASSERT_TRUE(res);
  3352. ASSERT_EQ(StatusCode::OK_200, res->status);
  3353. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3354. ASSERT_EQ("coder", res->body);
  3355. Params delete_params;
  3356. delete_params.emplace("name", "john4");
  3357. res = cli_.Delete("/person", delete_params);
  3358. ASSERT_TRUE(res);
  3359. ASSERT_EQ(StatusCode::OK_200, res->status);
  3360. ASSERT_EQ("DELETED", res->body);
  3361. res = cli_.Get("/person/john4");
  3362. ASSERT_TRUE(res);
  3363. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3364. }
  3365. TEST_F(ServerTest, DeleteMethod2) {
  3366. auto res = cli_.Get("/person/john5");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3369. Params params;
  3370. params.emplace("name", "john5");
  3371. params.emplace("note", "developer");
  3372. res = cli_.Post("/person", params);
  3373. ASSERT_TRUE(res);
  3374. ASSERT_EQ(StatusCode::OK_200, res->status);
  3375. res = cli_.Get("/person/john5");
  3376. ASSERT_TRUE(res);
  3377. ASSERT_EQ(StatusCode::OK_200, res->status);
  3378. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3379. ASSERT_EQ("developer", res->body);
  3380. Params delete_params;
  3381. delete_params.emplace("name", "john5");
  3382. Headers headers;
  3383. headers.emplace("Custom-Header", "test-value");
  3384. res = cli_.Delete("/person", headers, delete_params);
  3385. ASSERT_TRUE(res);
  3386. ASSERT_EQ(StatusCode::OK_200, res->status);
  3387. ASSERT_EQ("DELETED", res->body);
  3388. res = cli_.Get("/person/john5");
  3389. ASSERT_TRUE(res);
  3390. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3391. }
  3392. TEST_F(ServerTest, DeleteMethod3) {
  3393. auto res = cli_.Get("/person/john6");
  3394. ASSERT_TRUE(res);
  3395. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3396. Params params;
  3397. params.emplace("name", "john6");
  3398. params.emplace("note", "tester");
  3399. res = cli_.Post("/person", params);
  3400. ASSERT_TRUE(res);
  3401. ASSERT_EQ(StatusCode::OK_200, res->status);
  3402. res = cli_.Get("/person/john6");
  3403. ASSERT_TRUE(res);
  3404. ASSERT_EQ(StatusCode::OK_200, res->status);
  3405. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3406. ASSERT_EQ("tester", res->body);
  3407. Params delete_params;
  3408. delete_params.emplace("name", "john6");
  3409. Headers headers;
  3410. headers.emplace("Custom-Header", "test-value");
  3411. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3412. ASSERT_TRUE(res);
  3413. ASSERT_EQ(StatusCode::OK_200, res->status);
  3414. ASSERT_EQ("DELETED", res->body);
  3415. res = cli_.Get("/person/john6");
  3416. ASSERT_TRUE(res);
  3417. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3418. }
  3419. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3420. Params params;
  3421. params.emplace("json", JSON_DATA);
  3422. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3423. ASSERT_TRUE(res);
  3424. ASSERT_EQ(StatusCode::OK_200, res->status);
  3425. ASSERT_EQ(JSON_DATA, res->body);
  3426. }
  3427. TEST_F(ServerTest, PostEmptyContent) {
  3428. auto res = cli_.Post("/empty", "", "text/plain");
  3429. ASSERT_TRUE(res);
  3430. ASSERT_EQ(StatusCode::OK_200, res->status);
  3431. ASSERT_EQ("empty", res->body);
  3432. }
  3433. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3434. auto res = cli_.Post("/empty-no-content-type");
  3435. ASSERT_TRUE(res);
  3436. ASSERT_EQ(StatusCode::OK_200, res->status);
  3437. ASSERT_EQ("empty-no-content-type", res->body);
  3438. }
  3439. TEST_F(ServerTest, PostPathOnly) {
  3440. auto res = cli_.Post("/path-only");
  3441. ASSERT_TRUE(res);
  3442. ASSERT_EQ(StatusCode::OK_200, res->status);
  3443. ASSERT_EQ("path-only", res->body);
  3444. }
  3445. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3446. auto res = cli_.Post("/path-headers-only",
  3447. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3448. ASSERT_TRUE(res);
  3449. ASSERT_EQ(StatusCode::OK_200, res->status);
  3450. ASSERT_EQ("path-headers-only", res->body);
  3451. }
  3452. TEST_F(ServerTest, PostLarge) {
  3453. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3454. ASSERT_TRUE(res);
  3455. ASSERT_EQ(StatusCode::OK_200, res->status);
  3456. EXPECT_EQ(LARGE_DATA, res->body);
  3457. }
  3458. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3459. auto res = cli_.Put("/empty-no-content-type");
  3460. ASSERT_TRUE(res);
  3461. ASSERT_EQ(StatusCode::OK_200, res->status);
  3462. ASSERT_EQ("empty-no-content-type", res->body);
  3463. }
  3464. TEST_F(ServerTest, GetMethodDir) {
  3465. auto res = cli_.Get("/dir/");
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::OK_200, res->status);
  3468. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3469. auto body = R"(<html>
  3470. <head>
  3471. </head>
  3472. <body>
  3473. <a href="/dir/test.html">Test</a>
  3474. <a href="/hi">hi</a>
  3475. </body>
  3476. </html>
  3477. )";
  3478. EXPECT_EQ(body, res->body);
  3479. }
  3480. TEST_F(ServerTest, GetMethodDirTest) {
  3481. auto res = cli_.Get("/dir/test.html");
  3482. ASSERT_TRUE(res);
  3483. EXPECT_EQ(StatusCode::OK_200, res->status);
  3484. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3485. EXPECT_EQ("test.html", res->body);
  3486. }
  3487. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3488. auto res = cli_.Get("/dir/../dir/test.html");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(StatusCode::OK_200, res->status);
  3491. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3492. EXPECT_EQ("test.html", res->body);
  3493. }
  3494. TEST_F(ServerTest, GetMethodInvalidPath) {
  3495. auto res = cli_.Get("/dir/../test.html");
  3496. ASSERT_TRUE(res);
  3497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3498. }
  3499. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3500. auto res = cli_.Get("/../www/dir/test.html");
  3501. ASSERT_TRUE(res);
  3502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3503. }
  3504. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3505. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3508. }
  3509. TEST_F(ServerTest, GetMethodDirMountTest) {
  3510. auto res = cli_.Get("/mount/dir/test.html");
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::OK_200, res->status);
  3513. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3514. EXPECT_EQ("test.html", res->body);
  3515. }
  3516. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3517. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3518. ASSERT_TRUE(res);
  3519. EXPECT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3521. EXPECT_EQ("test.html", res->body);
  3522. }
  3523. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3524. auto res = cli_.Get("/mount/dir/../test.html");
  3525. ASSERT_TRUE(res);
  3526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3527. }
  3528. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3529. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3532. }
  3533. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3534. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3535. ASSERT_TRUE(res);
  3536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3537. }
  3538. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3539. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3540. ASSERT_TRUE(res);
  3541. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3542. }
  3543. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3544. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3545. ASSERT_TRUE(res);
  3546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3547. }
  3548. TEST_F(ServerTest, PostMethod303) {
  3549. auto res = cli_.Post("/1", "body", "text/plain");
  3550. ASSERT_TRUE(res);
  3551. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3552. EXPECT_EQ("/2", res->get_header_value("Location"));
  3553. }
  3554. TEST_F(ServerTest, PostMethod303Redirect) {
  3555. cli_.set_follow_location(true);
  3556. auto res = cli_.Post("/1", "body", "text/plain");
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. EXPECT_EQ("redirected.", res->body);
  3560. EXPECT_EQ("/2", res->location);
  3561. }
  3562. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3563. auto res = cli_.Get("/dir/test.abcde");
  3564. ASSERT_TRUE(res);
  3565. EXPECT_EQ(StatusCode::OK_200, res->status);
  3566. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3567. EXPECT_EQ("abcde", res->body);
  3568. }
  3569. TEST_F(ServerTest, StaticFileRange) {
  3570. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3571. ASSERT_TRUE(res);
  3572. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3573. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3574. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3575. EXPECT_EQ(true, res->has_header("Content-Range"));
  3576. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3577. EXPECT_EQ(std::string("cd"), res->body);
  3578. }
  3579. TEST_F(ServerTest, StaticFileRanges) {
  3580. auto res =
  3581. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3582. ASSERT_TRUE(res);
  3583. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3584. EXPECT_TRUE(
  3585. res->get_header_value("Content-Type")
  3586. .find(
  3587. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3588. 0);
  3589. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3590. }
  3591. TEST_F(ServerTest, StaticFileRangeHead) {
  3592. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3593. ASSERT_TRUE(res);
  3594. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3595. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3596. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3597. EXPECT_EQ(true, res->has_header("Content-Range"));
  3598. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3599. }
  3600. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3601. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3602. ASSERT_TRUE(res);
  3603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3604. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3605. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3606. EXPECT_EQ(true, res->has_header("Content-Range"));
  3607. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3608. res->get_header_value("Content-Range"));
  3609. EXPECT_EQ("LAST\n", res->body);
  3610. }
  3611. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3612. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3615. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3616. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3617. EXPECT_EQ(true, res->has_header("Content-Range"));
  3618. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3619. }
  3620. TEST_F(ServerTest, StaticFileBigFile) {
  3621. auto res = cli_.Get("/dir/1MB.txt");
  3622. ASSERT_TRUE(res);
  3623. EXPECT_EQ(StatusCode::OK_200, res->status);
  3624. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3625. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3626. }
  3627. TEST_F(ServerTest, InvalidBaseDirMount) {
  3628. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3629. }
  3630. TEST_F(ServerTest, Binary) {
  3631. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3632. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3633. "application/octet-stream");
  3634. ASSERT_TRUE(res);
  3635. ASSERT_EQ(StatusCode::OK_200, res->status);
  3636. ASSERT_EQ(4U, res->body.size());
  3637. res = cli_.Put("/binary", binary.data(), binary.size(),
  3638. "application/octet-stream");
  3639. ASSERT_TRUE(res);
  3640. ASSERT_EQ(StatusCode::OK_200, res->status);
  3641. ASSERT_EQ(4U, res->body.size());
  3642. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3643. "application/octet-stream");
  3644. ASSERT_TRUE(res);
  3645. ASSERT_EQ(StatusCode::OK_200, res->status);
  3646. ASSERT_EQ(4U, res->body.size());
  3647. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3648. "application/octet-stream");
  3649. ASSERT_TRUE(res);
  3650. ASSERT_EQ(StatusCode::OK_200, res->status);
  3651. ASSERT_EQ(4U, res->body.size());
  3652. }
  3653. TEST_F(ServerTest, BinaryString) {
  3654. auto binary = std::string("\x00\x01\x02\x03", 4);
  3655. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3656. ASSERT_TRUE(res);
  3657. ASSERT_EQ(StatusCode::OK_200, res->status);
  3658. ASSERT_EQ(4U, res->body.size());
  3659. res = cli_.Put("/binary", binary, "application/octet-stream");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ(4U, res->body.size());
  3663. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3664. ASSERT_TRUE(res);
  3665. ASSERT_EQ(StatusCode::OK_200, res->status);
  3666. ASSERT_EQ(4U, res->body.size());
  3667. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3668. ASSERT_TRUE(res);
  3669. ASSERT_EQ(StatusCode::OK_200, res->status);
  3670. ASSERT_EQ(4U, res->body.size());
  3671. }
  3672. TEST_F(ServerTest, EmptyRequest) {
  3673. auto res = cli_.Get("");
  3674. ASSERT_TRUE(!res);
  3675. EXPECT_EQ(Error::Connection, res.error());
  3676. }
  3677. TEST_F(ServerTest, LongRequest) {
  3678. std::string request;
  3679. for (size_t i = 0; i < 545; i++) {
  3680. request += "/TooLongRequest";
  3681. }
  3682. request += "OK";
  3683. auto res = cli_.Get(request.c_str());
  3684. ASSERT_TRUE(res);
  3685. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3686. }
  3687. TEST_F(ServerTest, TooLongRequest) {
  3688. std::string request;
  3689. for (size_t i = 0; i < 546; i++) {
  3690. request += "/TooLongRequest";
  3691. }
  3692. request += "_NG";
  3693. auto start = std::chrono::high_resolution_clock::now();
  3694. cli_.set_keep_alive(true);
  3695. auto res = cli_.Get(request.c_str());
  3696. auto end = std::chrono::high_resolution_clock::now();
  3697. auto elapsed =
  3698. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3699. .count();
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3702. EXPECT_LE(elapsed, 100);
  3703. EXPECT_EQ("close", res->get_header_value("Connection"));
  3704. EXPECT_FALSE(cli_.is_socket_open());
  3705. }
  3706. TEST_F(ServerTest, AlmostTooLongRequest) {
  3707. // test for #2046 - URI length check shouldn't include other content on req
  3708. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3709. // leading /, space, HTTP/1.1)
  3710. std::string request =
  3711. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3712. auto res = cli_.Get(request.c_str());
  3713. ASSERT_TRUE(res);
  3714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3715. }
  3716. TEST_F(ServerTest, LongHeader) {
  3717. Request req;
  3718. req.method = "GET";
  3719. req.path = "/hi";
  3720. std::string host_and_port;
  3721. host_and_port += HOST;
  3722. host_and_port += ":";
  3723. host_and_port += std::to_string(PORT);
  3724. req.headers.emplace("Host", host_and_port.c_str());
  3725. req.headers.emplace("Accept", "*/*");
  3726. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3727. req.headers.emplace(
  3728. "Header-Name",
  3729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3757. "@@@@@@@@@@@@@@@@");
  3758. auto res = std::make_shared<Response>();
  3759. auto error = Error::Success;
  3760. auto ret = cli_.send(req, *res, error);
  3761. ASSERT_TRUE(ret);
  3762. EXPECT_EQ(StatusCode::OK_200, res->status);
  3763. }
  3764. TEST_F(ServerTest, LongQueryValue) {
  3765. auto start = std::chrono::high_resolution_clock::now();
  3766. cli_.set_keep_alive(true);
  3767. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3768. auto end = std::chrono::high_resolution_clock::now();
  3769. auto elapsed =
  3770. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3771. .count();
  3772. ASSERT_TRUE(res);
  3773. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3774. EXPECT_LE(elapsed, 100);
  3775. EXPECT_EQ("close", res->get_header_value("Connection"));
  3776. EXPECT_FALSE(cli_.is_socket_open());
  3777. }
  3778. TEST_F(ServerTest, TooLongQueryValue) {
  3779. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3780. ASSERT_FALSE(res);
  3781. EXPECT_EQ(Error::Read, res.error());
  3782. }
  3783. TEST_F(ServerTest, TooLongHeader) {
  3784. Request req;
  3785. req.method = "GET";
  3786. req.path = "/hi";
  3787. std::string host_and_port;
  3788. host_and_port += HOST;
  3789. host_and_port += ":";
  3790. host_and_port += std::to_string(PORT);
  3791. req.headers.emplace("Host", host_and_port.c_str());
  3792. req.headers.emplace("Accept", "*/*");
  3793. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3794. req.headers.emplace(
  3795. "Header-Name",
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3823. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3824. "@@@@@@@@@@@@@@@@@");
  3825. auto res = std::make_shared<Response>();
  3826. auto error = Error::Success;
  3827. auto ret = cli_.send(req, *res, error);
  3828. ASSERT_TRUE(ret);
  3829. EXPECT_EQ(StatusCode::OK_200, res->status);
  3830. }
  3831. TEST_F(ServerTest, HeaderCountAtLimit) {
  3832. // Test with headers just under the 100 limit
  3833. httplib::Headers headers;
  3834. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3835. // This should keep us just under the 100 header limit
  3836. for (int i = 0; i < 95; i++) {
  3837. std::string name = "X-Test-Header-" + std::to_string(i);
  3838. std::string value = "value" + std::to_string(i);
  3839. headers.emplace(name, value);
  3840. }
  3841. // This should work fine as we're under the limit
  3842. auto res = cli_.Get("/hi", headers);
  3843. EXPECT_TRUE(res);
  3844. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3845. }
  3846. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3847. // Test with many headers to exceed the 100 limit
  3848. httplib::Headers headers;
  3849. // Add 150 headers to definitely exceed the 100 limit
  3850. for (int i = 0; i < 150; i++) {
  3851. std::string name = "X-Test-Header-" + std::to_string(i);
  3852. std::string value = "value" + std::to_string(i);
  3853. headers.emplace(name, value);
  3854. }
  3855. // This should fail due to exceeding header count limit
  3856. cli_.set_keep_alive(true);
  3857. auto res = cli_.Get("/hi", headers);
  3858. // The request should either fail or return 400 Bad Request
  3859. if (res) {
  3860. // If we get a response, it should be 400 Bad Request
  3861. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3862. } else {
  3863. // Or the request should fail entirely
  3864. EXPECT_FALSE(res);
  3865. }
  3866. EXPECT_EQ("close", res->get_header_value("Connection"));
  3867. EXPECT_FALSE(cli_.is_socket_open());
  3868. }
  3869. TEST_F(ServerTest, PercentEncoding) {
  3870. auto res = cli_.Get("/e%6edwith%");
  3871. ASSERT_TRUE(res);
  3872. EXPECT_EQ(StatusCode::OK_200, res->status);
  3873. }
  3874. TEST_F(ServerTest, PercentEncodingUnicode) {
  3875. auto res = cli_.Get("/e%u006edwith%");
  3876. ASSERT_TRUE(res);
  3877. EXPECT_EQ(StatusCode::OK_200, res->status);
  3878. }
  3879. TEST_F(ServerTest, InvalidPercentEncoding) {
  3880. auto res = cli_.Get("/%endwith%");
  3881. ASSERT_TRUE(res);
  3882. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3883. }
  3884. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3885. auto res = cli_.Get("/%uendwith%");
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3888. }
  3889. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3890. auto res = cli_.Get("/hello?aaa=bbb%");
  3891. ASSERT_TRUE(res);
  3892. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3893. }
  3894. TEST_F(ServerTest, PlusSignEncoding) {
  3895. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3896. ASSERT_TRUE(res);
  3897. EXPECT_EQ(StatusCode::OK_200, res->status);
  3898. EXPECT_EQ("a +b", res->body);
  3899. }
  3900. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3901. // This test simulates a potential DoS attack using many headers
  3902. // to verify our security fix prevents memory exhaustion
  3903. httplib::Headers attack_headers;
  3904. // Attempt to add many headers like an attacker would (200 headers to far
  3905. // exceed limit)
  3906. for (int i = 0; i < 200; i++) {
  3907. std::string name = "X-Attack-Header-" + std::to_string(i);
  3908. std::string value = "attack_payload_" + std::to_string(i);
  3909. attack_headers.emplace(name, value);
  3910. }
  3911. // Try to POST with excessive headers
  3912. cli_.set_keep_alive(true);
  3913. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3914. // Should either fail or return 400 Bad Request due to security limit
  3915. if (res) {
  3916. // If we get a response, it should be 400 Bad Request
  3917. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3918. } else {
  3919. // Request failed, which is the expected behavior for DoS protection
  3920. EXPECT_FALSE(res);
  3921. }
  3922. EXPECT_EQ("close", res->get_header_value("Connection"));
  3923. EXPECT_FALSE(cli_.is_socket_open());
  3924. }
  3925. TEST_F(ServerTest, MultipartFormData) {
  3926. UploadFormDataItems items = {
  3927. {"text1", "text default", "", ""},
  3928. {"text2", "aωb", "", ""},
  3929. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3930. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3931. {"file3", "", "", "application/octet-stream"},
  3932. {"file4", "", "", " application/json tmp-string "}};
  3933. auto res = cli_.Post("/multipart", items);
  3934. ASSERT_TRUE(res);
  3935. EXPECT_EQ(StatusCode::OK_200, res->status);
  3936. }
  3937. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3938. UploadFormDataItems items = {
  3939. {"text", "default text", "", ""},
  3940. {"multi_text1", "aaaaa", "", ""},
  3941. {"multi_text1", "bbbbb", "", ""},
  3942. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3943. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3944. "application/json"},
  3945. };
  3946. auto res = cli_.Post("/multipart/multi_file_values", items);
  3947. ASSERT_TRUE(res);
  3948. EXPECT_EQ(StatusCode::OK_200, res->status);
  3949. }
  3950. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3951. auto res = cli_.Get("/hi");
  3952. ASSERT_TRUE(res);
  3953. EXPECT_EQ(StatusCode::OK_200, res->status);
  3954. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3958. Request req;
  3959. req.method = "POST";
  3960. req.path = "/chunked";
  3961. std::string host_and_port;
  3962. host_and_port += HOST;
  3963. host_and_port += ":";
  3964. host_and_port += std::to_string(PORT);
  3965. req.headers.emplace("Host", host_and_port.c_str());
  3966. req.headers.emplace("Accept", "*/*");
  3967. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3968. req.headers.emplace("Content-Type", "text/plain");
  3969. req.headers.emplace("Content-Length", "0");
  3970. req.headers.emplace(
  3971. "Transfer-Encoding",
  3972. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3973. // Client does not chunk, so make a chunked body manually.
  3974. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3975. auto res = std::make_shared<Response>();
  3976. auto error = Error::Success;
  3977. auto ret = cli_.send(req, *res, error);
  3978. ASSERT_TRUE(ret);
  3979. EXPECT_EQ(StatusCode::OK_200, res->status);
  3980. }
  3981. TEST_F(ServerTest, GetStreamed2) {
  3982. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3985. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3986. EXPECT_EQ(true, res->has_header("Content-Range"));
  3987. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3988. EXPECT_EQ(std::string("ab"), res->body);
  3989. }
  3990. TEST_F(ServerTest, GetStreamed) {
  3991. auto res = cli_.Get("/streamed");
  3992. ASSERT_TRUE(res);
  3993. EXPECT_EQ(StatusCode::OK_200, res->status);
  3994. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3995. EXPECT_EQ(std::string("aaabbb"), res->body);
  3996. }
  3997. TEST_F(ServerTest, GetStreamedWithRange1) {
  3998. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3999. ASSERT_TRUE(res);
  4000. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4001. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4002. EXPECT_EQ(true, res->has_header("Content-Range"));
  4003. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4004. EXPECT_EQ(std::string("def"), res->body);
  4005. }
  4006. TEST_F(ServerTest, GetStreamedWithRange2) {
  4007. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4010. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4011. EXPECT_EQ(true, res->has_header("Content-Range"));
  4012. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4013. EXPECT_EQ(std::string("bcdefg"), res->body);
  4014. }
  4015. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4016. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4017. ASSERT_TRUE(res);
  4018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4019. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4020. EXPECT_EQ(true, res->has_header("Content-Range"));
  4021. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4022. EXPECT_EQ(std::string("efg"), res->body);
  4023. }
  4024. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4025. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4026. ASSERT_TRUE(res);
  4027. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4028. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4029. EXPECT_EQ(false, res->has_header("Content-Range"));
  4030. EXPECT_EQ(0U, res->body.size());
  4031. }
  4032. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4033. auto res = cli_.Get("/streamed-with-range",
  4034. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4035. "92233720368547758079223372036854775807"}});
  4036. ASSERT_TRUE(res);
  4037. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4038. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4039. EXPECT_EQ(false, res->has_header("Content-Range"));
  4040. EXPECT_EQ(0U, res->body.size());
  4041. }
  4042. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4043. auto res = cli_.Get(
  4044. "/with-range",
  4045. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4046. {"Accept-Encoding", ""}});
  4047. ASSERT_TRUE(res);
  4048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4049. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4050. EXPECT_EQ(true, res->has_header("Content-Range"));
  4051. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4052. EXPECT_EQ(std::string("abcdefg"), res->body);
  4053. }
  4054. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4055. auto res = cli_.Get("/with-range", {
  4056. {"Range", "bytes=0-"},
  4057. {"Accept-Encoding", ""},
  4058. });
  4059. ASSERT_TRUE(res);
  4060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4061. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4062. EXPECT_EQ(true, res->has_header("Content-Range"));
  4063. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4064. EXPECT_EQ(std::string("abcdefg"), res->body);
  4065. }
  4066. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4067. auto res =
  4068. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4069. ASSERT_TRUE(res);
  4070. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4071. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4072. EXPECT_EQ(false, res->has_header("Content-Range"));
  4073. EXPECT_EQ(267U, res->body.size());
  4074. // Check that both range contents are present
  4075. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4076. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4077. // Check that Content-Range headers are present for both ranges
  4078. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4079. std::string::npos);
  4080. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4081. std::string::npos);
  4082. }
  4083. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4084. Ranges ranges;
  4085. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4086. ranges.emplace_back(0, -1);
  4087. }
  4088. auto res =
  4089. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4090. ASSERT_TRUE(res);
  4091. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4092. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4093. EXPECT_EQ(false, res->has_header("Content-Range"));
  4094. EXPECT_EQ(0U, res->body.size());
  4095. }
  4096. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4097. auto res =
  4098. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4101. EXPECT_EQ(5U, res->body.size());
  4102. // Check that overlapping ranges are coalesced into a single range
  4103. EXPECT_EQ("bcdef", res->body);
  4104. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4105. // Should be single range, not multipart
  4106. EXPECT_TRUE(res->has_header("Content-Range"));
  4107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4108. }
  4109. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4110. auto res =
  4111. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4112. ASSERT_TRUE(res);
  4113. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4114. EXPECT_EQ(268U, res->body.size());
  4115. // Check that both range contents are present
  4116. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4117. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4118. // Check that Content-Range headers are present for both ranges
  4119. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4120. std::string::npos);
  4121. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4122. std::string::npos);
  4123. }
  4124. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4125. auto res =
  4126. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4127. ASSERT_TRUE(res);
  4128. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4129. EXPECT_EQ(269U, res->body.size());
  4130. // Check that both duplicate range contents are present
  4131. size_t first_abc = res->body.find("abc\r\n");
  4132. EXPECT_TRUE(first_abc != std::string::npos);
  4133. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4134. EXPECT_TRUE(second_abc != std::string::npos);
  4135. // Check that Content-Range headers are present for both ranges
  4136. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4137. EXPECT_TRUE(first_range != std::string::npos);
  4138. size_t second_range =
  4139. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4140. EXPECT_TRUE(second_range != std::string::npos);
  4141. }
  4142. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4143. auto res = cli_.Get("/streamed-with-range?error",
  4144. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4147. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4148. EXPECT_EQ(false, res->has_header("Content-Range"));
  4149. EXPECT_EQ(0U, res->body.size());
  4150. }
  4151. TEST_F(ServerTest, GetStreamedEndless) {
  4152. uint64_t offset = 0;
  4153. auto res = cli_.Get("/streamed-cancel",
  4154. [&](const char * /*data*/, uint64_t data_length) {
  4155. if (offset < 100) {
  4156. offset += data_length;
  4157. return true;
  4158. }
  4159. return false;
  4160. });
  4161. ASSERT_TRUE(!res);
  4162. EXPECT_EQ(Error::Canceled, res.error());
  4163. }
  4164. TEST_F(ServerTest, ClientStop) {
  4165. std::atomic_size_t count{4};
  4166. std::vector<std::thread> threads;
  4167. for (auto i = count.load(); i != 0; --i) {
  4168. threads.emplace_back([&]() {
  4169. auto res = cli_.Get("/streamed-cancel",
  4170. [&](const char *, uint64_t) { return true; });
  4171. --count;
  4172. ASSERT_TRUE(!res);
  4173. EXPECT_TRUE(res.error() == Error::Canceled ||
  4174. res.error() == Error::Read || res.error() == Error::Write);
  4175. });
  4176. }
  4177. std::this_thread::sleep_for(std::chrono::seconds(2));
  4178. while (count != 0) {
  4179. cli_.stop();
  4180. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4181. }
  4182. for (auto &t : threads) {
  4183. t.join();
  4184. }
  4185. }
  4186. TEST_F(ServerTest, GetWithRange1) {
  4187. auto res = cli_.Get("/with-range", {
  4188. make_range_header({{3, 5}}),
  4189. {"Accept-Encoding", ""},
  4190. });
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(true, res->has_header("Content-Range"));
  4195. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4196. EXPECT_EQ(std::string("def"), res->body);
  4197. }
  4198. TEST_F(ServerTest, GetWithRange2) {
  4199. auto res = cli_.Get("/with-range", {
  4200. make_range_header({{1, -1}}),
  4201. {"Accept-Encoding", ""},
  4202. });
  4203. ASSERT_TRUE(res);
  4204. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4205. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4206. EXPECT_EQ(true, res->has_header("Content-Range"));
  4207. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4208. EXPECT_EQ(std::string("bcdefg"), res->body);
  4209. }
  4210. TEST_F(ServerTest, GetWithRange3) {
  4211. auto res = cli_.Get("/with-range", {
  4212. make_range_header({{0, 0}}),
  4213. {"Accept-Encoding", ""},
  4214. });
  4215. ASSERT_TRUE(res);
  4216. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4217. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4218. EXPECT_EQ(true, res->has_header("Content-Range"));
  4219. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4220. EXPECT_EQ(std::string("a"), res->body);
  4221. }
  4222. TEST_F(ServerTest, GetWithRange4) {
  4223. auto res = cli_.Get("/with-range", {
  4224. make_range_header({{-1, 2}}),
  4225. {"Accept-Encoding", ""},
  4226. });
  4227. ASSERT_TRUE(res);
  4228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4229. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4230. EXPECT_EQ(true, res->has_header("Content-Range"));
  4231. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4232. EXPECT_EQ(std::string("fg"), res->body);
  4233. }
  4234. TEST_F(ServerTest, GetWithRange5) {
  4235. auto res = cli_.Get("/with-range", {
  4236. make_range_header({{0, 5}}),
  4237. {"Accept-Encoding", ""},
  4238. });
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(true, res->has_header("Content-Range"));
  4243. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4244. EXPECT_EQ(std::string("abcdef"), res->body);
  4245. }
  4246. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4247. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4250. }
  4251. TEST_F(ServerTest, GetWithRangeMultipart) {
  4252. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4253. ASSERT_TRUE(res);
  4254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4255. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4256. EXPECT_EQ(false, res->has_header("Content-Range"));
  4257. EXPECT_EQ(267U, res->body.size());
  4258. }
  4259. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4260. auto res =
  4261. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4264. }
  4265. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4266. auto res = cli_.Get("/with-range-customized-response",
  4267. {{make_range_header({{1, 2}})}});
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4270. EXPECT_EQ(true, res->has_header("Content-Length"));
  4271. EXPECT_EQ(false, res->has_header("Content-Range"));
  4272. EXPECT_EQ(JSON_DATA, res->body);
  4273. }
  4274. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4275. auto res = cli_.Get("/with-range-customized-response",
  4276. {{make_range_header({{1, 2}, {4, 5}})}});
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4279. EXPECT_EQ(true, res->has_header("Content-Length"));
  4280. EXPECT_EQ(false, res->has_header("Content-Range"));
  4281. EXPECT_EQ(JSON_DATA, res->body);
  4282. }
  4283. TEST_F(ServerTest, Issue1772) {
  4284. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4285. ASSERT_TRUE(res);
  4286. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4287. }
  4288. TEST_F(ServerTest, Issue609) {
  4289. auto res = cli_.Delete("/issue609");
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::OK_200, res->status);
  4292. EXPECT_EQ(std::string("ok"), res->body);
  4293. }
  4294. TEST_F(ServerTest, GetStreamedChunked) {
  4295. auto res = cli_.Get("/streamed-chunked");
  4296. ASSERT_TRUE(res);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. EXPECT_EQ(std::string("123456789"), res->body);
  4299. }
  4300. TEST_F(ServerTest, GetStreamedChunked2) {
  4301. auto res = cli_.Get("/streamed-chunked2");
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. EXPECT_EQ(std::string("123456789"), res->body);
  4305. }
  4306. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4307. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4308. ASSERT_TRUE(res);
  4309. EXPECT_EQ(StatusCode::OK_200, res->status);
  4310. EXPECT_EQ(std::string("123456789"), res->body);
  4311. EXPECT_TRUE(res->has_header("Trailer"));
  4312. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4313. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4314. // Trailers are now stored separately from headers (security fix)
  4315. EXPECT_EQ(2U, res->trailers.size());
  4316. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4317. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4318. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4319. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4320. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4321. // Verify trailers are NOT in headers (security verification)
  4322. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4323. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4324. }
  4325. TEST_F(ServerTest, LargeChunkedPost) {
  4326. Request req;
  4327. req.method = "POST";
  4328. req.path = "/large-chunked";
  4329. std::string host_and_port;
  4330. host_and_port += HOST;
  4331. host_and_port += ":";
  4332. host_and_port += std::to_string(PORT);
  4333. req.headers.emplace("Host", host_and_port.c_str());
  4334. req.headers.emplace("Accept", "*/*");
  4335. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4336. req.headers.emplace("Content-Type", "text/plain");
  4337. req.headers.emplace("Content-Length", "0");
  4338. req.headers.emplace("Transfer-Encoding", "chunked");
  4339. std::string long_string(30 * 1024u, 'a');
  4340. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4341. // Attempt to make a large enough post to exceed OS buffers, to test that
  4342. // the server handles short reads if the full chunk data isn't available.
  4343. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4344. auto res = std::make_shared<Response>();
  4345. auto error = Error::Success;
  4346. auto ret = cli_.send(req, *res, error);
  4347. ASSERT_TRUE(ret);
  4348. EXPECT_EQ(StatusCode::OK_200, res->status);
  4349. }
  4350. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4351. auto res = cli_.Get("/remote_addr");
  4352. ASSERT_TRUE(res);
  4353. EXPECT_EQ(StatusCode::OK_200, res->status);
  4354. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4355. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4356. }
  4357. TEST_F(ServerTest, GetMethodLocalAddr) {
  4358. auto res = cli_.Get("/local_addr");
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4362. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4363. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4364. }
  4365. TEST_F(ServerTest, HTTPResponseSplitting) {
  4366. auto res = cli_.Get("/http_response_splitting");
  4367. ASSERT_TRUE(res);
  4368. EXPECT_EQ(StatusCode::OK_200, res->status);
  4369. }
  4370. TEST_F(ServerTest, SlowRequest) {
  4371. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4372. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4373. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4374. }
  4375. #if 0
  4376. TEST_F(ServerTest, SlowPost) {
  4377. char buffer[64 * 1024];
  4378. memset(buffer, 0x42, sizeof(buffer));
  4379. auto res = cli_.Post(
  4380. "/slowpost", 64 * 1024 * 1024,
  4381. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4382. auto ret = sink.write(buffer, sizeof(buffer));
  4383. EXPECT_TRUE(ret);
  4384. return true;
  4385. },
  4386. "text/plain");
  4387. ASSERT_TRUE(res);
  4388. EXPECT_EQ(StatusCode::OK_200, res->status);
  4389. }
  4390. TEST_F(ServerTest, SlowPostFail) {
  4391. char buffer[64 * 1024];
  4392. memset(buffer, 0x42, sizeof(buffer));
  4393. cli_.set_write_timeout(std::chrono::seconds(0));
  4394. auto res = cli_.Post(
  4395. "/slowpost", 64 * 1024 * 1024,
  4396. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4397. sink.write(buffer, sizeof(buffer));
  4398. return true;
  4399. },
  4400. "text/plain");
  4401. ASSERT_TRUE(!res);
  4402. EXPECT_EQ(Error::Write, res.error());
  4403. }
  4404. #endif
  4405. TEST_F(ServerTest, Put) {
  4406. auto res = cli_.Put("/put", "PUT", "text/plain");
  4407. ASSERT_TRUE(res);
  4408. EXPECT_EQ(StatusCode::OK_200, res->status);
  4409. EXPECT_EQ("PUT", res->body);
  4410. }
  4411. TEST_F(ServerTest, PutWithContentProvider) {
  4412. auto res = cli_.Put(
  4413. "/put", 3,
  4414. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4415. sink.os << "PUT";
  4416. return true;
  4417. },
  4418. "text/plain");
  4419. ASSERT_TRUE(res);
  4420. EXPECT_EQ(StatusCode::OK_200, res->status);
  4421. EXPECT_EQ("PUT", res->body);
  4422. }
  4423. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4424. auto res = cli_.Post(
  4425. "/post", 42,
  4426. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4427. return false;
  4428. },
  4429. "text/plain");
  4430. ASSERT_TRUE(!res);
  4431. EXPECT_EQ(Error::Canceled, res.error());
  4432. }
  4433. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4434. auto res = cli_.Put(
  4435. "/put",
  4436. [](size_t /*offset*/, DataSink &sink) {
  4437. sink.os << "PUT";
  4438. sink.done();
  4439. return true;
  4440. },
  4441. "text/plain");
  4442. ASSERT_TRUE(res);
  4443. EXPECT_EQ(StatusCode::OK_200, res->status);
  4444. EXPECT_EQ("PUT", res->body);
  4445. }
  4446. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4447. auto res = cli_.Post(
  4448. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4449. "text/plain");
  4450. ASSERT_TRUE(!res);
  4451. EXPECT_EQ(Error::Canceled, res.error());
  4452. }
  4453. TEST_F(ServerTest, PostLoopBack) {
  4454. std::string body;
  4455. auto res = cli_.Post(
  4456. "/post-loopback", 9,
  4457. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4458. EXPECT_EQ(9u, length);
  4459. sink.write("123", 3);
  4460. sink.write("456", 3);
  4461. sink.write("789", 3);
  4462. return true;
  4463. },
  4464. "text/plain",
  4465. [&body](const char *data, size_t data_length) {
  4466. body.append(data, data_length);
  4467. return true;
  4468. });
  4469. ASSERT_TRUE(res);
  4470. EXPECT_EQ(StatusCode::OK_200, res->status);
  4471. EXPECT_EQ("123456789", body);
  4472. }
  4473. TEST_F(ServerTest, PutLoopBack) {
  4474. std::string body;
  4475. auto res = cli_.Put(
  4476. "/put-loopback", 9,
  4477. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4478. EXPECT_EQ(9u, length);
  4479. sink.write("123", 3);
  4480. sink.write("456", 3);
  4481. sink.write("789", 3);
  4482. return true;
  4483. },
  4484. "text/plain",
  4485. [&body](const char *data, size_t data_length) {
  4486. body.append(data, data_length);
  4487. return true;
  4488. });
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. EXPECT_EQ("123456789", body);
  4492. }
  4493. TEST_F(ServerTest, PatchLoopBack) {
  4494. std::string body;
  4495. auto res = cli_.Patch(
  4496. "/patch-loopback", 9,
  4497. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4498. EXPECT_EQ(9u, length);
  4499. sink.write("123", 3);
  4500. sink.write("456", 3);
  4501. sink.write("789", 3);
  4502. return true;
  4503. },
  4504. "text/plain",
  4505. [&body](const char *data, size_t data_length) {
  4506. body.append(data, data_length);
  4507. return true;
  4508. });
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. EXPECT_EQ("123456789", body);
  4512. }
  4513. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4514. std::string body;
  4515. auto res = cli_.Post(
  4516. "/post-loopback",
  4517. [](size_t /*offset*/, DataSink &sink) {
  4518. sink.write("123", 3);
  4519. sink.write("456", 3);
  4520. sink.write("789", 3);
  4521. sink.done();
  4522. return true;
  4523. },
  4524. "text/plain",
  4525. [&body](const char *data, size_t data_length) {
  4526. body.append(data, data_length);
  4527. return true;
  4528. });
  4529. ASSERT_TRUE(res);
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ("123456789", body);
  4532. }
  4533. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4534. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4535. cli_.set_compress(true);
  4536. auto res = cli_.Put(
  4537. "/put", 3,
  4538. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4539. sink.os << "PUT";
  4540. return true;
  4541. },
  4542. "text/plain");
  4543. ASSERT_TRUE(res);
  4544. EXPECT_EQ(StatusCode::OK_200, res->status);
  4545. EXPECT_EQ("PUT", res->body);
  4546. }
  4547. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4548. cli_.set_compress(true);
  4549. auto res = cli_.Post(
  4550. "/post", 42,
  4551. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4552. return false;
  4553. },
  4554. "text/plain");
  4555. ASSERT_TRUE(!res);
  4556. EXPECT_EQ(Error::Canceled, res.error());
  4557. }
  4558. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4559. cli_.set_compress(true);
  4560. auto res = cli_.Put(
  4561. "/put",
  4562. [](size_t /*offset*/, DataSink &sink) {
  4563. sink.os << "PUT";
  4564. sink.done();
  4565. return true;
  4566. },
  4567. "text/plain");
  4568. ASSERT_TRUE(res);
  4569. EXPECT_EQ(StatusCode::OK_200, res->status);
  4570. EXPECT_EQ("PUT", res->body);
  4571. }
  4572. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4573. cli_.set_compress(true);
  4574. auto res = cli_.Post(
  4575. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4576. "text/plain");
  4577. ASSERT_TRUE(!res);
  4578. EXPECT_EQ(Error::Canceled, res.error());
  4579. }
  4580. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4581. cli_.set_compress(true);
  4582. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4583. ASSERT_TRUE(res);
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ(LARGE_DATA, res->body);
  4586. }
  4587. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4588. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4589. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4590. Client cli(s.c_str());
  4591. cli.enable_server_certificate_verification(false);
  4592. #else
  4593. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4594. Client cli(s.c_str());
  4595. #endif
  4596. cli.set_compress(true);
  4597. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4598. ASSERT_TRUE(res);
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. EXPECT_EQ(LARGE_DATA, res->body);
  4601. // The compressed size should be less than a 10th of the original. May vary
  4602. // depending on the zlib library.
  4603. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4604. static_cast<uint64_t>(10 * 1024 * 1024));
  4605. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4606. }
  4607. TEST_F(ServerTest, PutContentWithDeflate) {
  4608. cli_.set_compress(false);
  4609. Headers headers;
  4610. headers.emplace("Content-Encoding", "deflate");
  4611. // PUT in deflate format:
  4612. auto res = cli_.Put("/put", headers,
  4613. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4614. ASSERT_TRUE(res);
  4615. EXPECT_EQ(StatusCode::OK_200, res->status);
  4616. EXPECT_EQ("PUT", res->body);
  4617. }
  4618. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4619. Headers headers;
  4620. headers.emplace("Accept-Encoding", "gzip, deflate");
  4621. auto res = cli_.Get("/streamed-chunked", headers);
  4622. ASSERT_TRUE(res);
  4623. EXPECT_EQ(StatusCode::OK_200, res->status);
  4624. EXPECT_EQ(std::string("123456789"), res->body);
  4625. }
  4626. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4627. Headers headers;
  4628. headers.emplace("Accept-Encoding", "gzip, deflate");
  4629. auto res = cli_.Get("/streamed-chunked2", headers);
  4630. ASSERT_TRUE(res);
  4631. EXPECT_EQ(StatusCode::OK_200, res->status);
  4632. EXPECT_EQ(std::string("123456789"), res->body);
  4633. }
  4634. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4635. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. }
  4639. TEST(GzipDecompressor, ChunkedDecompression) {
  4640. std::string data;
  4641. for (size_t i = 0; i < 32 * 1024; ++i) {
  4642. data.push_back(static_cast<char>('a' + i % 26));
  4643. }
  4644. std::string compressed_data;
  4645. {
  4646. httplib::detail::gzip_compressor compressor;
  4647. bool result = compressor.compress(
  4648. data.data(), data.size(),
  4649. /*last=*/true,
  4650. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4651. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4652. compressed_data_size);
  4653. return true;
  4654. });
  4655. ASSERT_TRUE(result);
  4656. }
  4657. std::string decompressed_data;
  4658. {
  4659. httplib::detail::gzip_decompressor decompressor;
  4660. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4661. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4662. size_t chunk_size = 130;
  4663. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4664. chunk_begin += chunk_size) {
  4665. size_t current_chunk_size =
  4666. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4667. bool result = decompressor.decompress(
  4668. compressed_data.data() + chunk_begin, current_chunk_size,
  4669. [&](const char *decompressed_data_chunk,
  4670. size_t decompressed_data_chunk_size) {
  4671. decompressed_data.insert(decompressed_data.size(),
  4672. decompressed_data_chunk,
  4673. decompressed_data_chunk_size);
  4674. return true;
  4675. });
  4676. ASSERT_TRUE(result);
  4677. }
  4678. }
  4679. ASSERT_EQ(data, decompressed_data);
  4680. }
  4681. TEST(GzipDecompressor, DeflateDecompression) {
  4682. std::string original_text = "Raw deflate without gzip";
  4683. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4684. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4685. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4686. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4687. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4688. std::string decompressed_data;
  4689. {
  4690. httplib::detail::gzip_decompressor decompressor;
  4691. bool result = decompressor.decompress(
  4692. compressed_data.data(), compressed_data.size(),
  4693. [&](const char *decompressed_data_chunk,
  4694. size_t decompressed_data_chunk_size) {
  4695. decompressed_data.insert(decompressed_data.size(),
  4696. decompressed_data_chunk,
  4697. decompressed_data_chunk_size);
  4698. return true;
  4699. });
  4700. ASSERT_TRUE(result);
  4701. }
  4702. ASSERT_EQ(original_text, decompressed_data);
  4703. }
  4704. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4705. std::string original_text = "Raw deflate without gzip";
  4706. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4707. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4708. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4709. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4710. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4711. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4712. std::string decompressed_data;
  4713. {
  4714. httplib::detail::gzip_decompressor decompressor;
  4715. bool result = decompressor.decompress(
  4716. compressed_data.data(), compressed_data.size(),
  4717. [&](const char *decompressed_data_chunk,
  4718. size_t decompressed_data_chunk_size) {
  4719. decompressed_data.insert(decompressed_data.size(),
  4720. decompressed_data_chunk,
  4721. decompressed_data_chunk_size);
  4722. return true;
  4723. });
  4724. ASSERT_TRUE(result);
  4725. }
  4726. ASSERT_EQ(original_text, decompressed_data);
  4727. }
  4728. #ifdef _WIN32
  4729. TEST(GzipDecompressor, LargeRandomData) {
  4730. // prepare large random data that is difficult to be compressed and is
  4731. // expected to have large size even when compressed
  4732. std::random_device seed_gen;
  4733. std::mt19937 random(seed_gen());
  4734. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4735. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4736. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4737. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4738. // compress data over 4GiB
  4739. std::string compressed_data;
  4740. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4741. httplib::detail::gzip_compressor compressor;
  4742. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4743. data.size() * sizeof(std::uint32_t), true,
  4744. [&](const char *data, size_t size) {
  4745. compressed_data.insert(
  4746. compressed_data.size(), data, size);
  4747. return true;
  4748. });
  4749. ASSERT_TRUE(result);
  4750. // FIXME: compressed data size is expected to be greater than 4GiB,
  4751. // but there is no guarantee
  4752. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4753. // decompress data over 4GiB
  4754. std::string decompressed_data;
  4755. decompressed_data.reserve(data_size);
  4756. httplib::detail::gzip_decompressor decompressor;
  4757. result = decompressor.decompress(
  4758. compressed_data.data(), compressed_data.size(),
  4759. [&](const char *data, size_t size) {
  4760. decompressed_data.insert(decompressed_data.size(), data, size);
  4761. return true;
  4762. });
  4763. ASSERT_TRUE(result);
  4764. // compare
  4765. ASSERT_EQ(data_size, decompressed_data.size());
  4766. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4767. 0);
  4768. }
  4769. #endif
  4770. #endif
  4771. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4772. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4773. Headers headers;
  4774. headers.emplace("Accept-Encoding", "br");
  4775. auto res = cli_.Get("/streamed-chunked", headers);
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ(std::string("123456789"), res->body);
  4779. }
  4780. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4781. Headers headers;
  4782. headers.emplace("Accept-Encoding", "br");
  4783. auto res = cli_.Get("/streamed-chunked2", headers);
  4784. ASSERT_TRUE(res);
  4785. EXPECT_EQ(StatusCode::OK_200, res->status);
  4786. EXPECT_EQ(std::string("123456789"), res->body);
  4787. }
  4788. #endif
  4789. TEST_F(ServerTest, Patch) {
  4790. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ("PATCH", res->body);
  4794. }
  4795. TEST_F(ServerTest, Delete) {
  4796. auto res = cli_.Delete("/delete");
  4797. ASSERT_TRUE(res);
  4798. EXPECT_EQ(StatusCode::OK_200, res->status);
  4799. EXPECT_EQ("DELETE", res->body);
  4800. }
  4801. TEST_F(ServerTest, DeleteContentReceiver) {
  4802. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4803. ASSERT_TRUE(res);
  4804. EXPECT_EQ(StatusCode::OK_200, res->status);
  4805. EXPECT_EQ("content", res->body);
  4806. }
  4807. TEST_F(ServerTest, Options) {
  4808. auto res = cli_.Options("*");
  4809. ASSERT_TRUE(res);
  4810. EXPECT_EQ(StatusCode::OK_200, res->status);
  4811. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4812. EXPECT_TRUE(res->body.empty());
  4813. }
  4814. TEST_F(ServerTest, URL) {
  4815. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4816. ASSERT_TRUE(res);
  4817. EXPECT_EQ(StatusCode::OK_200, res->status);
  4818. }
  4819. TEST_F(ServerTest, ArrayParam) {
  4820. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4821. ASSERT_TRUE(res);
  4822. EXPECT_EQ(StatusCode::OK_200, res->status);
  4823. }
  4824. TEST_F(ServerTest, NoMultipleHeaders) {
  4825. Headers headers = {{"Content-Length", "5"}};
  4826. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4827. "text/plain");
  4828. ASSERT_TRUE(res);
  4829. EXPECT_EQ(StatusCode::OK_200, res->status);
  4830. }
  4831. TEST_F(ServerTest, PostContentReceiver) {
  4832. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4833. ASSERT_TRUE(res);
  4834. ASSERT_EQ(StatusCode::OK_200, res->status);
  4835. ASSERT_EQ("content", res->body);
  4836. }
  4837. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4838. UploadFormDataItems items = {
  4839. {"text1", "text default", "", ""},
  4840. {"text2", "aωb", "", ""},
  4841. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4842. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4843. {"file3", "", "", "application/octet-stream"},
  4844. };
  4845. auto res = cli_.Post("/content_receiver", items);
  4846. ASSERT_TRUE(res);
  4847. EXPECT_EQ(StatusCode::OK_200, res->status);
  4848. }
  4849. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4850. UploadFormDataItems items = {
  4851. {"text1", "text default", "", ""},
  4852. {"text2", "aωb", "", ""},
  4853. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4854. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4855. {"file3", "", "", "application/octet-stream"},
  4856. };
  4857. auto boundary = std::string("+++++");
  4858. std::string body;
  4859. for (const auto &item : items) {
  4860. body += "--" + boundary + "\r\n";
  4861. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4862. if (!item.filename.empty()) {
  4863. body += "; filename=\"" + item.filename + "\"";
  4864. }
  4865. body += "\r\n";
  4866. if (!item.content_type.empty()) {
  4867. body += "Content-Type: " + item.content_type + "\r\n";
  4868. }
  4869. body += "\r\n";
  4870. body += item.content + "\r\n";
  4871. }
  4872. body += "--" + boundary + "--\r\n";
  4873. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4874. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4875. ASSERT_TRUE(res);
  4876. EXPECT_EQ(StatusCode::OK_200, res->status);
  4877. }
  4878. TEST_F(ServerTest, PostContentReceiverGzip) {
  4879. cli_.set_compress(true);
  4880. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4881. ASSERT_TRUE(res);
  4882. ASSERT_EQ(StatusCode::OK_200, res->status);
  4883. ASSERT_EQ("content", res->body);
  4884. }
  4885. TEST_F(ServerTest, PutContentReceiver) {
  4886. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4887. ASSERT_TRUE(res);
  4888. ASSERT_EQ(StatusCode::OK_200, res->status);
  4889. ASSERT_EQ("content", res->body);
  4890. }
  4891. TEST_F(ServerTest, PatchContentReceiver) {
  4892. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4893. ASSERT_TRUE(res);
  4894. ASSERT_EQ(StatusCode::OK_200, res->status);
  4895. ASSERT_EQ("content", res->body);
  4896. }
  4897. template <typename ClientType>
  4898. void TestWithHeadersAndContentReceiver(
  4899. ClientType &cli,
  4900. std::function<Result(ClientType &, const std::string &, const Headers &,
  4901. const std::string &, const std::string &,
  4902. ContentReceiver, DownloadProgress)>
  4903. request_func) {
  4904. Headers headers;
  4905. headers.emplace("X-Custom-Header", "test-value");
  4906. std::string received_body;
  4907. auto res = request_func(
  4908. cli, "/content_receiver", headers, "content", "application/json",
  4909. [&](const char *data, size_t data_length) {
  4910. received_body.append(data, data_length);
  4911. return true;
  4912. },
  4913. nullptr);
  4914. ASSERT_TRUE(res);
  4915. EXPECT_EQ(StatusCode::OK_200, res->status);
  4916. EXPECT_EQ("content", received_body);
  4917. }
  4918. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4920. using ClientT = SSLClient;
  4921. #else
  4922. using ClientT = Client;
  4923. #endif
  4924. TestWithHeadersAndContentReceiver<ClientT>(
  4925. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4926. const std::string &body, const std::string &content_type,
  4927. ContentReceiver receiver, DownloadProgress progress) {
  4928. return cli.Post(path, headers, body, content_type, receiver, progress);
  4929. });
  4930. }
  4931. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4932. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4933. using ClientT = SSLClient;
  4934. #else
  4935. using ClientT = Client;
  4936. #endif
  4937. TestWithHeadersAndContentReceiver<ClientT>(
  4938. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4939. const std::string &body, const std::string &content_type,
  4940. ContentReceiver receiver, DownloadProgress progress) {
  4941. return cli.Put(path, headers, body, content_type, receiver, progress);
  4942. });
  4943. }
  4944. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4945. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4946. using ClientT = SSLClient;
  4947. #else
  4948. using ClientT = Client;
  4949. #endif
  4950. TestWithHeadersAndContentReceiver<ClientT>(
  4951. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4952. const std::string &body, const std::string &content_type,
  4953. ContentReceiver receiver, DownloadProgress progress) {
  4954. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4955. });
  4956. }
  4957. template <typename ClientType>
  4958. void TestWithHeadersAndContentReceiverWithProgress(
  4959. ClientType &cli,
  4960. std::function<Result(ClientType &, const std::string &, const Headers &,
  4961. const std::string &, const std::string &,
  4962. ContentReceiver, DownloadProgress)>
  4963. request_func) {
  4964. Headers headers;
  4965. headers.emplace("X-Test-Header", "progress-test");
  4966. std::string received_body;
  4967. auto progress_called = false;
  4968. auto res = request_func(
  4969. cli, "/content_receiver", headers, "content", "text/plain",
  4970. [&](const char *data, size_t data_length) {
  4971. received_body.append(data, data_length);
  4972. return true;
  4973. },
  4974. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4975. progress_called = true;
  4976. return true;
  4977. });
  4978. ASSERT_TRUE(res);
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. EXPECT_EQ("content", received_body);
  4981. EXPECT_TRUE(progress_called);
  4982. }
  4983. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4985. using ClientT = SSLClient;
  4986. #else
  4987. using ClientT = Client;
  4988. #endif
  4989. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4990. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4991. const std::string &body, const std::string &content_type,
  4992. ContentReceiver receiver, DownloadProgress progress) {
  4993. return cli.Post(path, headers, body, content_type, receiver, progress);
  4994. });
  4995. }
  4996. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4997. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4998. using ClientT = SSLClient;
  4999. #else
  5000. using ClientT = Client;
  5001. #endif
  5002. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5003. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5004. const std::string &body, const std::string &content_type,
  5005. ContentReceiver receiver, DownloadProgress progress) {
  5006. return cli.Put(path, headers, body, content_type, receiver, progress);
  5007. });
  5008. }
  5009. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5010. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5011. using ClientT = SSLClient;
  5012. #else
  5013. using ClientT = Client;
  5014. #endif
  5015. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5016. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5017. const std::string &body, const std::string &content_type,
  5018. ContentReceiver receiver, DownloadProgress progress) {
  5019. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5020. });
  5021. }
  5022. template <typename ClientType>
  5023. void TestWithHeadersAndContentReceiverError(
  5024. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5025. const Headers &, const std::string &,
  5026. const std::string &, ContentReceiver)>
  5027. request_func) {
  5028. Headers headers;
  5029. headers.emplace("X-Error-Test", "true");
  5030. std::string received_body;
  5031. auto receiver_failed = false;
  5032. auto res =
  5033. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5034. [&](const char *data, size_t data_length) {
  5035. received_body.append(data, data_length);
  5036. receiver_failed = true;
  5037. return false;
  5038. });
  5039. ASSERT_FALSE(res);
  5040. EXPECT_TRUE(receiver_failed);
  5041. }
  5042. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5043. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5044. using ClientT = SSLClient;
  5045. #else
  5046. using ClientT = Client;
  5047. #endif
  5048. TestWithHeadersAndContentReceiverError<ClientT>(
  5049. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5050. const std::string &body, const std::string &content_type,
  5051. ContentReceiver receiver) {
  5052. return cli.Post(path, headers, body, content_type, receiver);
  5053. });
  5054. }
  5055. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5056. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5057. using ClientT = SSLClient;
  5058. #else
  5059. using ClientT = Client;
  5060. #endif
  5061. TestWithHeadersAndContentReceiverError<ClientT>(
  5062. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5063. const std::string &body, const std::string &content_type,
  5064. ContentReceiver receiver) {
  5065. return cli.Put(path, headers, body, content_type, receiver);
  5066. });
  5067. }
  5068. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5069. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5070. using ClientT = SSLClient;
  5071. #else
  5072. using ClientT = Client;
  5073. #endif
  5074. TestWithHeadersAndContentReceiverError<ClientT>(
  5075. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5076. const std::string &body, const std::string &content_type,
  5077. ContentReceiver receiver) {
  5078. return cli.Patch(path, headers, body, content_type, receiver);
  5079. });
  5080. }
  5081. TEST_F(ServerTest, PostQueryStringAndBody) {
  5082. auto res =
  5083. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5084. ASSERT_TRUE(res);
  5085. ASSERT_EQ(StatusCode::OK_200, res->status);
  5086. }
  5087. TEST_F(ServerTest, HTTP2Magic) {
  5088. Request req;
  5089. req.method = "PRI";
  5090. req.path = "*";
  5091. req.body = "SM";
  5092. auto res = std::make_shared<Response>();
  5093. auto error = Error::Success;
  5094. auto ret = cli_.send(req, *res, error);
  5095. ASSERT_TRUE(ret);
  5096. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5097. }
  5098. TEST_F(ServerTest, KeepAlive) {
  5099. auto res = cli_.Get("/hi");
  5100. ASSERT_TRUE(res);
  5101. EXPECT_EQ(StatusCode::OK_200, res->status);
  5102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5103. EXPECT_EQ("Hello World!", res->body);
  5104. res = cli_.Get("/hi");
  5105. ASSERT_TRUE(res);
  5106. EXPECT_EQ(StatusCode::OK_200, res->status);
  5107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5108. EXPECT_EQ("Hello World!", res->body);
  5109. res = cli_.Get("/hi");
  5110. ASSERT_TRUE(res);
  5111. EXPECT_EQ(StatusCode::OK_200, res->status);
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("Hello World!", res->body);
  5114. res = cli_.Get("/not-exist");
  5115. ASSERT_TRUE(res);
  5116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5117. res = cli_.Post("/empty", "", "text/plain");
  5118. ASSERT_TRUE(res);
  5119. EXPECT_EQ(StatusCode::OK_200, res->status);
  5120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5121. EXPECT_EQ("empty", res->body);
  5122. EXPECT_EQ("close", res->get_header_value("Connection"));
  5123. res = cli_.Post(
  5124. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5125. "text/plain");
  5126. ASSERT_TRUE(res);
  5127. EXPECT_EQ(StatusCode::OK_200, res->status);
  5128. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5129. EXPECT_EQ("empty", res->body);
  5130. cli_.set_keep_alive(false);
  5131. res = cli_.Get("/last-request");
  5132. ASSERT_TRUE(res);
  5133. EXPECT_EQ(StatusCode::OK_200, res->status);
  5134. EXPECT_EQ("close", res->get_header_value("Connection"));
  5135. }
  5136. TEST_F(ServerTest, TooManyRedirect) {
  5137. cli_.set_follow_location(true);
  5138. auto res = cli_.Get("/redirect/0");
  5139. ASSERT_TRUE(!res);
  5140. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5141. }
  5142. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5143. Request req;
  5144. req.method = "FOOBAR";
  5145. req.path = "/hi";
  5146. cli_.set_keep_alive(true);
  5147. auto res = cli_.send(req);
  5148. ASSERT_TRUE(res);
  5149. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5150. EXPECT_EQ("close", res->get_header_value("Connection"));
  5151. EXPECT_FALSE(cli_.is_socket_open());
  5152. }
  5153. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5154. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5155. TEST_F(ServerTest, Gzip) {
  5156. Headers headers;
  5157. headers.emplace("Accept-Encoding", "gzip, deflate");
  5158. auto res = cli_.Get("/compress", headers);
  5159. ASSERT_TRUE(res);
  5160. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5162. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5163. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5164. "7890123456789012345678901234567890",
  5165. res->body);
  5166. EXPECT_EQ(StatusCode::OK_200, res->status);
  5167. }
  5168. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5169. Headers headers;
  5170. headers.emplace("Accept-Encoding", "");
  5171. auto res = cli_.Get("/compress", headers);
  5172. ASSERT_TRUE(res);
  5173. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5175. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5176. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5177. "7890123456789012345678901234567890",
  5178. res->body);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. }
  5181. TEST_F(ServerTest, GzipWithContentReceiver) {
  5182. Headers headers;
  5183. headers.emplace("Accept-Encoding", "gzip, deflate");
  5184. std::string body;
  5185. auto res = cli_.Get("/compress", headers,
  5186. [&](const char *data, uint64_t data_length) {
  5187. EXPECT_EQ(100U, data_length);
  5188. body.append(data, data_length);
  5189. return true;
  5190. });
  5191. ASSERT_TRUE(res);
  5192. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5193. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5194. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5195. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5196. "7890123456789012345678901234567890",
  5197. body);
  5198. EXPECT_EQ(StatusCode::OK_200, res->status);
  5199. }
  5200. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5201. Headers headers;
  5202. headers.emplace("Accept-Encoding", "gzip, deflate");
  5203. cli_.set_decompress(false);
  5204. auto res = cli_.Get("/compress", headers);
  5205. ASSERT_TRUE(res);
  5206. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5207. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5208. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5209. EXPECT_EQ(33U, res->body.size());
  5210. EXPECT_EQ(StatusCode::OK_200, res->status);
  5211. }
  5212. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5213. Headers headers;
  5214. headers.emplace("Accept-Encoding", "");
  5215. std::string body;
  5216. auto res = cli_.Get("/compress", headers,
  5217. [&](const char *data, uint64_t data_length) {
  5218. EXPECT_EQ(100U, data_length);
  5219. body.append(data, data_length);
  5220. return true;
  5221. });
  5222. ASSERT_TRUE(res);
  5223. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5225. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5226. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5227. "7890123456789012345678901234567890",
  5228. body);
  5229. EXPECT_EQ(StatusCode::OK_200, res->status);
  5230. }
  5231. TEST_F(ServerTest, NoGzip) {
  5232. Headers headers;
  5233. headers.emplace("Accept-Encoding", "gzip, deflate");
  5234. auto res = cli_.Get("/nocompress", headers);
  5235. ASSERT_TRUE(res);
  5236. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5237. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5238. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5239. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5240. "7890123456789012345678901234567890",
  5241. res->body);
  5242. EXPECT_EQ(StatusCode::OK_200, res->status);
  5243. }
  5244. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5245. Headers headers;
  5246. headers.emplace("Accept-Encoding", "gzip, deflate");
  5247. std::string body;
  5248. auto res = cli_.Get("/nocompress", headers,
  5249. [&](const char *data, uint64_t data_length) {
  5250. EXPECT_EQ(100U, data_length);
  5251. body.append(data, data_length);
  5252. return true;
  5253. });
  5254. ASSERT_TRUE(res);
  5255. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5256. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5257. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5258. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5259. "7890123456789012345678901234567890",
  5260. body);
  5261. EXPECT_EQ(StatusCode::OK_200, res->status);
  5262. }
  5263. TEST_F(ServerTest, MultipartFormDataGzip) {
  5264. UploadFormDataItems items = {
  5265. {"key1", "test", "", ""},
  5266. {"key2", "--abcdefg123", "", ""},
  5267. };
  5268. cli_.set_compress(true);
  5269. auto res = cli_.Post("/compress-multipart", items);
  5270. ASSERT_TRUE(res);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. }
  5273. #endif
  5274. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5275. TEST_F(ServerTest, Brotli) {
  5276. Headers headers;
  5277. headers.emplace("Accept-Encoding", "br");
  5278. auto res = cli_.Get("/compress", headers);
  5279. ASSERT_TRUE(res);
  5280. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5282. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5283. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5284. "7890123456789012345678901234567890",
  5285. res->body);
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. }
  5288. #endif
  5289. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5290. TEST_F(ServerTest, Zstd) {
  5291. Headers headers;
  5292. headers.emplace("Accept-Encoding", "zstd");
  5293. auto res = cli_.Get("/compress", headers);
  5294. ASSERT_TRUE(res);
  5295. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5297. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5298. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5299. "7890123456789012345678901234567890",
  5300. res->body);
  5301. EXPECT_EQ(StatusCode::OK_200, res->status);
  5302. }
  5303. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5304. Headers headers;
  5305. headers.emplace("Accept-Encoding", "");
  5306. auto res = cli_.Get("/compress", headers);
  5307. ASSERT_TRUE(res);
  5308. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5309. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5310. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5311. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5312. "7890123456789012345678901234567890",
  5313. res->body);
  5314. EXPECT_EQ(StatusCode::OK_200, res->status);
  5315. }
  5316. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5317. Headers headers;
  5318. headers.emplace("Accept-Encoding", "zstd");
  5319. std::string body;
  5320. auto res = cli_.Get("/compress", headers,
  5321. [&](const char *data, uint64_t data_length) {
  5322. EXPECT_EQ(100U, data_length);
  5323. body.append(data, data_length);
  5324. return true;
  5325. });
  5326. ASSERT_TRUE(res);
  5327. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5329. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5330. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5331. "7890123456789012345678901234567890",
  5332. body);
  5333. EXPECT_EQ(StatusCode::OK_200, res->status);
  5334. }
  5335. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5336. Headers headers;
  5337. headers.emplace("Accept-Encoding", "zstd");
  5338. cli_.set_decompress(false);
  5339. auto res = cli_.Get("/compress", headers);
  5340. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5341. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5342. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5343. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5344. ASSERT_TRUE(res);
  5345. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5347. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5348. EXPECT_EQ(StatusCode::OK_200, res->status);
  5349. ASSERT_EQ(26U, res->body.size());
  5350. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5351. 0);
  5352. }
  5353. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5354. Headers headers;
  5355. headers.emplace("Accept-Encoding", "");
  5356. std::string body;
  5357. auto res = cli_.Get("/compress", headers,
  5358. [&](const char *data, uint64_t data_length) {
  5359. EXPECT_EQ(100U, data_length);
  5360. body.append(data, data_length);
  5361. return true;
  5362. });
  5363. ASSERT_TRUE(res);
  5364. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5365. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5366. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5367. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5368. "7890123456789012345678901234567890",
  5369. body);
  5370. EXPECT_EQ(StatusCode::OK_200, res->status);
  5371. }
  5372. TEST_F(ServerTest, NoZstd) {
  5373. Headers headers;
  5374. headers.emplace("Accept-Encoding", "zstd");
  5375. auto res = cli_.Get("/nocompress", headers);
  5376. ASSERT_TRUE(res);
  5377. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5378. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5379. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5380. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5381. "7890123456789012345678901234567890",
  5382. res->body);
  5383. EXPECT_EQ(StatusCode::OK_200, res->status);
  5384. }
  5385. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5386. Headers headers;
  5387. headers.emplace("Accept-Encoding", "zstd");
  5388. std::string body;
  5389. auto res = cli_.Get("/nocompress", headers,
  5390. [&](const char *data, uint64_t data_length) {
  5391. EXPECT_EQ(100U, data_length);
  5392. body.append(data, data_length);
  5393. return true;
  5394. });
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5397. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5399. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5400. "7890123456789012345678901234567890",
  5401. body);
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. }
  5404. // TODO: How to enable zstd ??
  5405. TEST_F(ServerTest, MultipartFormDataZstd) {
  5406. UploadFormDataItems items = {
  5407. {"key1", "test", "", ""},
  5408. {"key2", "--abcdefg123", "", ""},
  5409. };
  5410. Headers headers;
  5411. headers.emplace("Accept-Encoding", "zstd");
  5412. cli_.set_compress(true);
  5413. auto res = cli_.Post("/compress-multipart", headers, items);
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. }
  5417. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "zstd");
  5420. cli_.set_compress(true);
  5421. auto res = cli_.Put(
  5422. "/put", headers, 3,
  5423. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5424. sink.os << "PUT";
  5425. return true;
  5426. },
  5427. "text/plain");
  5428. ASSERT_TRUE(res);
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ("PUT", res->body);
  5431. }
  5432. // Pre-compression logging tests
  5433. TEST_F(ServerTest, PreCompressionLogging) {
  5434. // Test data for compression (matches the actual /compress endpoint content)
  5435. const std::string test_content =
  5436. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5437. "3456789012345678901234567890";
  5438. // Variables to capture logging data
  5439. std::string pre_compression_body;
  5440. std::string pre_compression_content_type;
  5441. std::string pre_compression_content_encoding;
  5442. std::string post_compression_body;
  5443. std::string post_compression_content_type;
  5444. std::string post_compression_content_encoding;
  5445. // Set up pre-compression logger
  5446. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5447. const Response &res) {
  5448. pre_compression_body = res.body;
  5449. pre_compression_content_type = res.get_header_value("Content-Type");
  5450. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5451. });
  5452. // Set up post-compression logger
  5453. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5454. post_compression_body = res.body;
  5455. post_compression_content_type = res.get_header_value("Content-Type");
  5456. post_compression_content_encoding =
  5457. res.get_header_value("Content-Encoding");
  5458. });
  5459. // Test with gzip compression
  5460. Headers headers;
  5461. headers.emplace("Accept-Encoding", "gzip");
  5462. auto res = cli_.Get("/compress", headers);
  5463. // Verify response was compressed
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5467. // Verify pre-compression logger captured uncompressed content
  5468. EXPECT_EQ(test_content, pre_compression_body);
  5469. EXPECT_EQ("text/plain", pre_compression_content_type);
  5470. EXPECT_TRUE(pre_compression_content_encoding
  5471. .empty()); // No encoding header before compression
  5472. // Verify post-compression logger captured compressed content
  5473. EXPECT_NE(test_content,
  5474. post_compression_body); // Should be different after compression
  5475. EXPECT_EQ("text/plain", post_compression_content_type);
  5476. EXPECT_EQ("gzip", post_compression_content_encoding);
  5477. // Verify compressed content is smaller
  5478. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5479. }
  5480. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5481. const std::string test_content =
  5482. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5483. "3456789012345678901234567890";
  5484. std::string pre_compression_body;
  5485. std::string post_compression_body;
  5486. svr_.set_pre_compression_logger(
  5487. [&](const Request & /*req*/, const Response &res) {
  5488. pre_compression_body = res.body;
  5489. });
  5490. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5491. post_compression_body = res.body;
  5492. });
  5493. Headers headers;
  5494. headers.emplace("Accept-Encoding", "br");
  5495. auto res = cli_.Get("/compress", headers);
  5496. ASSERT_TRUE(res);
  5497. EXPECT_EQ(StatusCode::OK_200, res->status);
  5498. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5499. // Verify pre-compression content is uncompressed
  5500. EXPECT_EQ(test_content, pre_compression_body);
  5501. // Verify post-compression content is compressed
  5502. EXPECT_NE(test_content, post_compression_body);
  5503. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5504. }
  5505. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5506. const std::string test_content =
  5507. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5508. "3456789012345678901234567890";
  5509. std::string pre_compression_body;
  5510. std::string post_compression_body;
  5511. svr_.set_pre_compression_logger(
  5512. [&](const Request & /*req*/, const Response &res) {
  5513. pre_compression_body = res.body;
  5514. });
  5515. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5516. post_compression_body = res.body;
  5517. });
  5518. // Request without compression (use /nocompress endpoint)
  5519. Headers headers;
  5520. auto res = cli_.Get("/nocompress", headers);
  5521. ASSERT_TRUE(res);
  5522. EXPECT_EQ(StatusCode::OK_200, res->status);
  5523. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5524. // Pre-compression logger should not be called when no compression is applied
  5525. EXPECT_TRUE(
  5526. pre_compression_body.empty()); // Pre-compression logger not called
  5527. EXPECT_EQ(
  5528. test_content,
  5529. post_compression_body); // Post-compression logger captures final content
  5530. }
  5531. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5532. const std::string test_content =
  5533. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5534. "3456789012345678901234567890";
  5535. std::string pre_compression_body;
  5536. bool pre_logger_called = false;
  5537. // Set only pre-compression logger
  5538. svr_.set_pre_compression_logger(
  5539. [&](const Request & /*req*/, const Response &res) {
  5540. pre_compression_body = res.body;
  5541. pre_logger_called = true;
  5542. });
  5543. Headers headers;
  5544. headers.emplace("Accept-Encoding", "gzip");
  5545. auto res = cli_.Get("/compress", headers);
  5546. ASSERT_TRUE(res);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5549. // Verify pre-compression logger was called
  5550. EXPECT_TRUE(pre_logger_called);
  5551. EXPECT_EQ(test_content, pre_compression_body);
  5552. }
  5553. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5554. {
  5555. // Test with Expect: 100-continue header - success case
  5556. // Server returns 100 Continue, client sends body, server returns 200 OK
  5557. Request req;
  5558. req.method = "POST";
  5559. req.path = "/post-large";
  5560. req.set_header("Expect", "100-continue");
  5561. req.body = LARGE_DATA;
  5562. Response res;
  5563. auto error = Error::Success;
  5564. cli_.set_keep_alive(true);
  5565. auto ret = cli_.send(req, res, error);
  5566. EXPECT_TRUE(ret);
  5567. EXPECT_EQ(StatusCode::OK_200, res.status);
  5568. EXPECT_EQ(LARGE_DATA, res.body);
  5569. }
  5570. {
  5571. // Test with Expect: 100-continue header - error case
  5572. // Client should not send the body when server returns an error
  5573. Request req;
  5574. req.method = "POST";
  5575. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5576. req.set_header("Expect", "100-continue");
  5577. req.body = LARGE_DATA;
  5578. Response res;
  5579. auto error = Error::Success;
  5580. auto start = std::chrono::high_resolution_clock::now();
  5581. cli_.set_keep_alive(true);
  5582. auto ret = cli_.send(req, res, error);
  5583. auto end = std::chrono::high_resolution_clock::now();
  5584. auto elapsed =
  5585. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5586. .count();
  5587. // With Expect: 100-continue, request completes successfully but with error
  5588. EXPECT_TRUE(ret);
  5589. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5590. EXPECT_EQ("close", res.get_header_value("Connection"));
  5591. EXPECT_FALSE(cli_.is_socket_open());
  5592. EXPECT_LE(elapsed, 200);
  5593. }
  5594. {
  5595. // Send an extra GET request to ensure error recovery without hanging
  5596. Request req;
  5597. req.method = "GET";
  5598. req.path = "/hi";
  5599. auto start = std::chrono::high_resolution_clock::now();
  5600. auto res = cli_.send(req);
  5601. auto end = std::chrono::high_resolution_clock::now();
  5602. auto elapsed =
  5603. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5604. .count();
  5605. ASSERT_TRUE(res);
  5606. EXPECT_EQ(StatusCode::OK_200, res->status);
  5607. EXPECT_EQ("Hello World!", res->body);
  5608. EXPECT_LE(elapsed, 100);
  5609. }
  5610. }
  5611. TEST(ZstdDecompressor, ChunkedDecompression) {
  5612. std::string data;
  5613. for (size_t i = 0; i < 32 * 1024; ++i) {
  5614. data.push_back(static_cast<char>('a' + i % 26));
  5615. }
  5616. std::string compressed_data;
  5617. {
  5618. httplib::detail::zstd_compressor compressor;
  5619. bool result = compressor.compress(
  5620. data.data(), data.size(),
  5621. /*last=*/true,
  5622. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5623. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5624. compressed_data_size);
  5625. return true;
  5626. });
  5627. ASSERT_TRUE(result);
  5628. }
  5629. std::string decompressed_data;
  5630. {
  5631. httplib::detail::zstd_decompressor decompressor;
  5632. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5633. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5634. size_t chunk_size = 130;
  5635. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5636. chunk_begin += chunk_size) {
  5637. size_t current_chunk_size =
  5638. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5639. bool result = decompressor.decompress(
  5640. compressed_data.data() + chunk_begin, current_chunk_size,
  5641. [&](const char *decompressed_data_chunk,
  5642. size_t decompressed_data_chunk_size) {
  5643. decompressed_data.insert(decompressed_data.size(),
  5644. decompressed_data_chunk,
  5645. decompressed_data_chunk_size);
  5646. return true;
  5647. });
  5648. ASSERT_TRUE(result);
  5649. }
  5650. }
  5651. ASSERT_EQ(data, decompressed_data);
  5652. }
  5653. TEST(ZstdDecompressor, Decompress) {
  5654. std::string original_text = "Compressed with ZSTD";
  5655. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5656. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5657. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5658. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5659. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5660. std::string decompressed_data;
  5661. {
  5662. httplib::detail::zstd_decompressor decompressor;
  5663. bool result = decompressor.decompress(
  5664. compressed_data.data(), compressed_data.size(),
  5665. [&](const char *decompressed_data_chunk,
  5666. size_t decompressed_data_chunk_size) {
  5667. decompressed_data.insert(decompressed_data.size(),
  5668. decompressed_data_chunk,
  5669. decompressed_data_chunk_size);
  5670. return true;
  5671. });
  5672. ASSERT_TRUE(result);
  5673. }
  5674. ASSERT_EQ(original_text, decompressed_data);
  5675. }
  5676. #endif
  5677. // Sends a raw request to a server listening at HOST:PORT.
  5678. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5679. std::string *resp = nullptr) {
  5680. auto error = Error::Success;
  5681. auto client_sock = detail::create_client_socket(
  5682. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5683. /*connection_timeout_sec=*/5, 0,
  5684. /*read_timeout_sec=*/5, 0,
  5685. /*write_timeout_sec=*/5, 0, std::string(), error);
  5686. if (client_sock == INVALID_SOCKET) { return false; }
  5687. auto ret = detail::process_client_socket(
  5688. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5689. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5690. if (req.size() !=
  5691. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5692. return false;
  5693. }
  5694. char buf[512];
  5695. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5696. while (line_reader.getline()) {
  5697. if (resp) { *resp += line_reader.ptr(); }
  5698. }
  5699. return true;
  5700. });
  5701. detail::close_socket(client_sock);
  5702. return ret;
  5703. }
  5704. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5705. Server svr;
  5706. std::string header_value;
  5707. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5708. header_value = req.get_header_value("foo");
  5709. res.set_content("ok", "text/plain");
  5710. });
  5711. thread t = thread([&] { svr.listen(HOST, PORT); });
  5712. auto se = detail::scope_exit([&] {
  5713. svr.stop();
  5714. t.join();
  5715. ASSERT_FALSE(svr.is_running());
  5716. });
  5717. svr.wait_until_ready();
  5718. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5719. // like characters are not treated the same - use vertical tab and escape.
  5720. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5721. "foo: \t \v bar \x1B\t \r\n"
  5722. "Connection: close\r\n"
  5723. "\r\n";
  5724. std::string res;
  5725. ASSERT_TRUE(send_request(5, req, &res));
  5726. EXPECT_EQ(header_value, "");
  5727. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5728. }
  5729. // Sends a raw request and verifies that there isn't a crash or exception.
  5730. static void test_raw_request(const std::string &req,
  5731. std::string *out = nullptr) {
  5732. Server svr;
  5733. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5734. res.set_content("ok", "text/plain");
  5735. });
  5736. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5737. res.set_content("ok", "text/plain");
  5738. });
  5739. svr.Get("/header_field_value_check",
  5740. [&](const Request & /*req*/, Response &res) {
  5741. res.set_content("ok", "text/plain");
  5742. });
  5743. // Server read timeout must be longer than the client read timeout for the
  5744. // bug to reproduce, probably to force the server to process a request
  5745. // without a trailing blank line.
  5746. const time_t client_read_timeout_sec = 1;
  5747. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5748. bool listen_thread_ok = false;
  5749. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5750. auto se = detail::scope_exit([&] {
  5751. svr.stop();
  5752. t.join();
  5753. ASSERT_FALSE(svr.is_running());
  5754. EXPECT_TRUE(listen_thread_ok);
  5755. });
  5756. svr.wait_until_ready();
  5757. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5758. }
  5759. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5760. // A certain header line causes an exception if the header property is parsed
  5761. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5762. test_raw_request(
  5763. "GET /hi HTTP/1.1\r\n"
  5764. " : "
  5765. " "
  5766. " ");
  5767. }
  5768. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5769. // A certain header line causes an exception if the header property *name* is
  5770. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5771. // greedy matcher and requires backtracking when there are a lot of ":"
  5772. // characters.
  5773. // This occurs with libc++ but not libstdc++.
  5774. test_raw_request(
  5775. "GET /hi HTTP/1.1\r\n"
  5776. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5777. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5778. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5779. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5780. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5781. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5782. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5783. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5784. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5785. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5786. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5787. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5788. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5789. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5790. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5791. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5792. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5793. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5794. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5795. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5796. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5797. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5798. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5799. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5800. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5801. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5802. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5803. "&&&%%%");
  5804. }
  5805. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5806. // Make sure this doesn't crash the server.
  5807. // In a previous version of the header line regex, the "\r" rendered the line
  5808. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5809. // a new position where the leading white space ended and the field value
  5810. // began.
  5811. // The crash occurs with libc++ but not libstdc++.
  5812. test_raw_request("GET /hi HTTP/1.1\r\n"
  5813. "a:" +
  5814. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5815. "\r\n"
  5816. "\r\n");
  5817. }
  5818. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5819. std::string out;
  5820. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5821. "Content-Type: text/plain\r\n"
  5822. "Transfer-Encoding: chunked\r\n"
  5823. "\r\n"
  5824. "nothex\r\n",
  5825. &out);
  5826. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5827. }
  5828. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5829. std::string out;
  5830. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5831. "Content-Type: text/plain\r\n"
  5832. "Transfer-Encoding: chunked\r\n"
  5833. "\r\n"
  5834. "3\r\n"
  5835. "xyz\r\n"
  5836. "NaN\r\n",
  5837. &out);
  5838. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5839. }
  5840. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5841. std::string out;
  5842. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5843. "Content-Type: text/plain\r\n"
  5844. "Transfer-Encoding: chunked\r\n"
  5845. "\r\n"
  5846. // Length is too large for 64 bits.
  5847. "1ffffffffffffffff\r\n"
  5848. "xyz\r\n",
  5849. &out);
  5850. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5851. }
  5852. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5853. test_raw_request("GET /hi HTTP/1.1\r\n"
  5854. "Content-Type: text/plain\r\n\r");
  5855. }
  5856. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5857. std::string out;
  5858. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5859. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5860. }
  5861. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5862. Server svr;
  5863. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5864. EXPECT_TRUE(!req.remote_addr.empty());
  5865. });
  5866. thread t = thread([&] { svr.listen(HOST, PORT); });
  5867. auto se = detail::scope_exit([&] {
  5868. svr.stop();
  5869. t.join();
  5870. ASSERT_FALSE(svr.is_running());
  5871. });
  5872. svr.wait_until_ready();
  5873. // Send an invalid request line to trigger Bad Request
  5874. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5875. std::string out;
  5876. ASSERT_TRUE(send_request(5, bad_req, &out));
  5877. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5878. }
  5879. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5880. std::string out;
  5881. std::string request(
  5882. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5883. test_raw_request(request, &out);
  5884. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5885. }
  5886. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5887. std::string out;
  5888. std::string request(
  5889. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5890. test_raw_request(request, &out);
  5891. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5892. }
  5893. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5894. std::string out;
  5895. std::string request(
  5896. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5897. test_raw_request(request, &out);
  5898. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5899. }
  5900. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5901. std::string out;
  5902. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5903. "Test: \r\n\r\n",
  5904. &out);
  5905. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5906. }
  5907. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5908. Server svr;
  5909. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5910. res.set_header("Cache-Control", "no-cache");
  5911. res.set_chunked_content_provider(
  5912. "text/event-stream", [](size_t offset, DataSink &sink) {
  5913. std::string s = "data:";
  5914. s += std::to_string(offset);
  5915. s += "\n\n";
  5916. auto ret = sink.write(s.data(), s.size());
  5917. EXPECT_TRUE(ret);
  5918. std::this_thread::sleep_for(std::chrono::seconds(1));
  5919. return true;
  5920. });
  5921. });
  5922. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5923. svr.wait_until_ready();
  5924. Client client(HOST, PORT);
  5925. const Headers headers = {{"Accept", "text/event-stream"}};
  5926. auto get_thread = std::thread([&client, &headers]() {
  5927. auto res = client.Get(
  5928. "/events", headers,
  5929. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5930. });
  5931. auto se = detail::scope_exit([&] {
  5932. svr.stop();
  5933. get_thread.join();
  5934. listen_thread.join();
  5935. ASSERT_FALSE(svr.is_running());
  5936. });
  5937. // Give GET time to get a few messages.
  5938. std::this_thread::sleep_for(std::chrono::seconds(2));
  5939. }
  5940. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5941. httplib::Server svr;
  5942. svr.Post("/hi",
  5943. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5944. res.status = StatusCode::OK_200;
  5945. });
  5946. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5947. svr.wait_until_ready();
  5948. Client cli(HOST, PORT);
  5949. auto res = cli.Post("/hi", "data", "text/plain");
  5950. ASSERT_TRUE(res);
  5951. EXPECT_EQ(StatusCode::OK_200, res->status);
  5952. svr.stop();
  5953. thread.join();
  5954. ASSERT_FALSE(svr.is_running());
  5955. res = cli.Post("/hi", "data", "text/plain");
  5956. ASSERT_FALSE(res);
  5957. }
  5958. TEST(ServerStopTest, ListenFailure) {
  5959. Server svr;
  5960. auto t = thread([&]() {
  5961. auto ret = svr.listen("????", PORT);
  5962. EXPECT_FALSE(ret);
  5963. });
  5964. svr.wait_until_ready();
  5965. svr.stop();
  5966. t.join();
  5967. }
  5968. TEST(ServerStopTest, Decommision) {
  5969. Server svr;
  5970. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5971. for (int i = 0; i < 4; i++) {
  5972. auto is_even = !(i % 2);
  5973. std::thread t{[&] {
  5974. try {
  5975. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5976. if (is_even) {
  5977. throw std::runtime_error("Some thing that happens to go wrong.");
  5978. }
  5979. svr.listen(HOST, PORT);
  5980. } catch (...) { svr.decommission(); }
  5981. }};
  5982. svr.wait_until_ready();
  5983. // Server is up
  5984. {
  5985. Client cli(HOST, PORT);
  5986. auto res = cli.Get("/hi");
  5987. if (is_even) {
  5988. EXPECT_FALSE(res);
  5989. } else {
  5990. EXPECT_TRUE(res);
  5991. EXPECT_EQ("hi...", res->body);
  5992. }
  5993. }
  5994. svr.stop();
  5995. t.join();
  5996. // Server is down...
  5997. {
  5998. Client cli(HOST, PORT);
  5999. auto res = cli.Get("/hi");
  6000. EXPECT_FALSE(res);
  6001. }
  6002. }
  6003. }
  6004. // Helper function for string body upload progress tests
  6005. template <typename SetupHandler, typename ClientCall>
  6006. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6007. ClientCall &&client_call,
  6008. const string &body) {
  6009. Server svr;
  6010. setup_handler(svr);
  6011. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6012. auto se = detail::scope_exit([&] {
  6013. svr.stop();
  6014. t.join();
  6015. });
  6016. svr.wait_until_ready();
  6017. Client cli(HOST, PORT);
  6018. vector<uint64_t> progress_values;
  6019. bool progress_called = false;
  6020. auto res =
  6021. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6022. progress_values.push_back(current);
  6023. progress_called = true;
  6024. return true;
  6025. });
  6026. ASSERT_TRUE(res);
  6027. EXPECT_EQ(200, res->status);
  6028. EXPECT_TRUE(progress_called);
  6029. }
  6030. TEST(UploadProgressTest, PostStringBodyBasic) {
  6031. TestStringBodyUploadProgress(
  6032. [](Server &svr) {
  6033. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6034. res.set_content("received", "text/plain");
  6035. });
  6036. },
  6037. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6038. return cli.Post("/test", body, "text/plain", progress_callback);
  6039. },
  6040. "test data for upload progress");
  6041. }
  6042. TEST(UploadProgressTest, PutStringBodyBasic) {
  6043. TestStringBodyUploadProgress(
  6044. [](Server &svr) {
  6045. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6046. res.set_content("put received", "text/plain");
  6047. });
  6048. },
  6049. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6050. return cli.Put("/test", body, "text/plain", progress_callback);
  6051. },
  6052. "put test data for upload progress");
  6053. }
  6054. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6055. TestStringBodyUploadProgress(
  6056. [](Server &svr) {
  6057. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6058. res.set_content("patch received", "text/plain");
  6059. });
  6060. },
  6061. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6062. return cli.Patch("/test", body, "text/plain", progress_callback);
  6063. },
  6064. "patch test data for upload progress");
  6065. }
  6066. // Helper function for content provider upload progress tests
  6067. template <typename SetupHandler, typename ClientCall>
  6068. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6069. ClientCall &&client_call) {
  6070. Server svr;
  6071. setup_handler(svr);
  6072. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6073. auto se = detail::scope_exit([&] {
  6074. svr.stop();
  6075. t.join();
  6076. });
  6077. svr.wait_until_ready();
  6078. Client cli(HOST, PORT);
  6079. vector<uint64_t> progress_values;
  6080. auto res =
  6081. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6082. progress_values.push_back(current);
  6083. return true;
  6084. });
  6085. ASSERT_TRUE(res);
  6086. EXPECT_EQ(200, res->status);
  6087. EXPECT_FALSE(progress_values.empty());
  6088. }
  6089. TEST(UploadProgressTest, PostContentProviderProgress) {
  6090. TestContentProviderUploadProgress(
  6091. [](Server &svr) {
  6092. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6093. res.set_content("provider received", "text/plain");
  6094. });
  6095. },
  6096. [](Client &cli, UploadProgress progress_callback) {
  6097. return cli.Post(
  6098. "/test", 10,
  6099. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6100. sink.os << "test data";
  6101. return true;
  6102. },
  6103. "text/plain", progress_callback);
  6104. });
  6105. }
  6106. // Helper function for multipart upload progress tests
  6107. template <typename SetupHandler, typename ClientCall>
  6108. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6109. ClientCall &&client_call,
  6110. const string &endpoint) {
  6111. Server svr;
  6112. setup_handler(svr);
  6113. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6114. auto se = detail::scope_exit([&] {
  6115. svr.stop();
  6116. t.join();
  6117. });
  6118. svr.wait_until_ready();
  6119. Client cli(HOST, PORT);
  6120. vector<uint64_t> progress_values;
  6121. UploadFormDataItems items = {
  6122. {"field1", "value1", "", ""},
  6123. {"field2", "longer value for progress tracking test", "", ""},
  6124. {"file1", "file content data for upload progress", "test.txt",
  6125. "text/plain"}};
  6126. auto res = client_call(cli, endpoint, items,
  6127. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6128. progress_values.push_back(current);
  6129. return true;
  6130. });
  6131. ASSERT_TRUE(res);
  6132. EXPECT_EQ(200, res->status);
  6133. EXPECT_FALSE(progress_values.empty());
  6134. }
  6135. TEST(UploadProgressTest, PostMultipartProgress) {
  6136. TestMultipartUploadProgress(
  6137. [](Server &svr) {
  6138. svr.Post("/multipart", [](const Request &req, Response &res) {
  6139. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6140. res.set_content("multipart received", "text/plain");
  6141. });
  6142. },
  6143. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6144. UploadProgress progress_callback) {
  6145. return cli.Post(endpoint, items, progress_callback);
  6146. },
  6147. "/multipart");
  6148. }
  6149. // Helper function for basic download progress tests
  6150. template <typename SetupHandler, typename ClientCall>
  6151. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6152. ClientCall &&client_call, const string &endpoint,
  6153. size_t expected_content_size) {
  6154. Server svr;
  6155. setup_handler(svr);
  6156. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6157. auto se = detail::scope_exit([&] {
  6158. svr.stop();
  6159. t.join();
  6160. });
  6161. svr.wait_until_ready();
  6162. Client cli(HOST, PORT);
  6163. vector<uint64_t> progress_values;
  6164. auto res = client_call(cli, endpoint,
  6165. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6166. progress_values.push_back(current);
  6167. return true;
  6168. });
  6169. ASSERT_TRUE(res);
  6170. EXPECT_EQ(200, res->status);
  6171. EXPECT_FALSE(progress_values.empty());
  6172. EXPECT_EQ(expected_content_size, res->body.size());
  6173. }
  6174. TEST(DownloadProgressTest, GetBasic) {
  6175. TestBasicDownloadProgress(
  6176. [](Server &svr) {
  6177. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6178. string content(1000, 'D');
  6179. res.set_content(content, "text/plain");
  6180. });
  6181. },
  6182. [](Client &cli, const string &endpoint,
  6183. DownloadProgress progress_callback) {
  6184. return cli.Get(endpoint, progress_callback);
  6185. },
  6186. "/download", 1000u);
  6187. }
  6188. // Helper function for content receiver download progress tests
  6189. template <typename SetupHandler, typename ClientCall>
  6190. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6191. ClientCall &&client_call,
  6192. const string &endpoint,
  6193. size_t expected_content_size) {
  6194. Server svr;
  6195. setup_handler(svr);
  6196. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6197. auto se = detail::scope_exit([&] {
  6198. svr.stop();
  6199. t.join();
  6200. });
  6201. svr.wait_until_ready();
  6202. Client cli(HOST, PORT);
  6203. vector<uint64_t> progress_values;
  6204. string received_body;
  6205. auto res = client_call(
  6206. cli, endpoint,
  6207. [&](const char *data, size_t data_length) -> bool {
  6208. received_body.append(data, data_length);
  6209. return true;
  6210. },
  6211. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6212. progress_values.push_back(current);
  6213. return true;
  6214. });
  6215. ASSERT_TRUE(res);
  6216. EXPECT_EQ(200, res->status);
  6217. EXPECT_FALSE(progress_values.empty());
  6218. EXPECT_EQ(expected_content_size, received_body.size());
  6219. EXPECT_TRUE(res->body.empty());
  6220. }
  6221. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6222. TestContentReceiverDownloadProgress(
  6223. [](Server &svr) {
  6224. svr.Get("/download-receiver",
  6225. [](const Request & /*req*/, Response &res) {
  6226. string content(2000, 'R');
  6227. res.set_content(content, "text/plain");
  6228. });
  6229. },
  6230. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6231. DownloadProgress progress_callback) {
  6232. return cli.Get(endpoint, content_receiver, progress_callback);
  6233. },
  6234. "/download-receiver", 2000u);
  6235. }
  6236. TEST(StreamingTest, NoContentLengthStreaming) {
  6237. Server svr;
  6238. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6239. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6240. if (offset < 6) {
  6241. sink.os << (offset < 3 ? "a" : "b");
  6242. } else {
  6243. sink.done();
  6244. }
  6245. return true;
  6246. });
  6247. });
  6248. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6249. auto listen_se = detail::scope_exit([&] {
  6250. svr.stop();
  6251. listen_thread.join();
  6252. ASSERT_FALSE(svr.is_running());
  6253. });
  6254. svr.wait_until_ready();
  6255. Client client(HOST, PORT);
  6256. auto get_thread = std::thread([&client]() {
  6257. std::string s;
  6258. auto res =
  6259. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6260. s += std::string(data, len);
  6261. return true;
  6262. });
  6263. ASSERT_TRUE(res);
  6264. EXPECT_EQ(StatusCode::OK_200, res->status);
  6265. EXPECT_EQ("aaabbb", s);
  6266. });
  6267. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6268. // Give GET time to get a few messages.
  6269. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6270. }
  6271. TEST(MountTest, Unmount) {
  6272. Server svr;
  6273. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6274. auto se = detail::scope_exit([&] {
  6275. svr.stop();
  6276. listen_thread.join();
  6277. ASSERT_FALSE(svr.is_running());
  6278. });
  6279. svr.wait_until_ready();
  6280. Client cli("localhost", PORT);
  6281. svr.set_mount_point("/mount2", "./www2");
  6282. auto res = cli.Get("/");
  6283. ASSERT_TRUE(res);
  6284. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6285. res = cli.Get("/mount2/dir/test.html");
  6286. ASSERT_TRUE(res);
  6287. EXPECT_EQ(StatusCode::OK_200, res->status);
  6288. svr.set_mount_point("/", "./www");
  6289. res = cli.Get("/dir/");
  6290. ASSERT_TRUE(res);
  6291. EXPECT_EQ(StatusCode::OK_200, res->status);
  6292. svr.remove_mount_point("/");
  6293. res = cli.Get("/dir/");
  6294. ASSERT_TRUE(res);
  6295. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6296. svr.remove_mount_point("/mount2");
  6297. res = cli.Get("/mount2/dir/test.html");
  6298. ASSERT_TRUE(res);
  6299. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6300. }
  6301. TEST(MountTest, Redicect) {
  6302. Server svr;
  6303. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6304. auto se = detail::scope_exit([&] {
  6305. svr.stop();
  6306. listen_thread.join();
  6307. ASSERT_FALSE(svr.is_running());
  6308. });
  6309. svr.set_mount_point("/", "./www");
  6310. svr.wait_until_ready();
  6311. Client cli("localhost", PORT);
  6312. auto res = cli.Get("/dir/");
  6313. ASSERT_TRUE(res);
  6314. EXPECT_EQ(StatusCode::OK_200, res->status);
  6315. res = cli.Get("/dir");
  6316. ASSERT_TRUE(res);
  6317. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6318. res = cli.Get("/file");
  6319. ASSERT_TRUE(res);
  6320. EXPECT_EQ(StatusCode::OK_200, res->status);
  6321. res = cli.Get("/file/");
  6322. ASSERT_TRUE(res);
  6323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6324. cli.set_follow_location(true);
  6325. res = cli.Get("/dir");
  6326. ASSERT_TRUE(res);
  6327. EXPECT_EQ(StatusCode::OK_200, res->status);
  6328. }
  6329. TEST(MountTest, MultibytesPathName) {
  6330. Server svr;
  6331. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6332. auto se = detail::scope_exit([&] {
  6333. svr.stop();
  6334. listen_thread.join();
  6335. ASSERT_FALSE(svr.is_running());
  6336. });
  6337. svr.set_mount_point("/", "./www");
  6338. svr.wait_until_ready();
  6339. Client cli("localhost", PORT);
  6340. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6341. ASSERT_TRUE(res);
  6342. EXPECT_EQ(StatusCode::OK_200, res->status);
  6343. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6344. }
  6345. TEST(KeepAliveTest, ReadTimeout) {
  6346. Server svr;
  6347. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6348. std::this_thread::sleep_for(std::chrono::seconds(2));
  6349. res.set_content("a", "text/plain");
  6350. });
  6351. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6352. res.set_content("b", "text/plain");
  6353. });
  6354. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6355. auto se = detail::scope_exit([&] {
  6356. svr.stop();
  6357. listen_thread.join();
  6358. ASSERT_FALSE(svr.is_running());
  6359. });
  6360. svr.wait_until_ready();
  6361. Client cli("localhost", PORT);
  6362. cli.set_keep_alive(true);
  6363. cli.set_read_timeout(std::chrono::seconds(1));
  6364. auto resa = cli.Get("/a");
  6365. ASSERT_FALSE(resa);
  6366. EXPECT_EQ(Error::Read, resa.error());
  6367. auto resb = cli.Get("/b");
  6368. ASSERT_TRUE(resb);
  6369. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6370. EXPECT_EQ("b", resb->body);
  6371. }
  6372. TEST(KeepAliveTest, MaxCount) {
  6373. size_t keep_alive_max_count = 3;
  6374. Server svr;
  6375. svr.set_keep_alive_max_count(keep_alive_max_count);
  6376. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6377. res.set_content("Hello World!", "text/plain");
  6378. });
  6379. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6380. auto se = detail::scope_exit([&] {
  6381. svr.stop();
  6382. listen_thread.join();
  6383. ASSERT_FALSE(svr.is_running());
  6384. });
  6385. svr.wait_until_ready();
  6386. Client cli(HOST, PORT);
  6387. cli.set_keep_alive(true);
  6388. for (size_t i = 0; i < 5; i++) {
  6389. auto result = cli.Get("/hi");
  6390. ASSERT_TRUE(result);
  6391. EXPECT_EQ(StatusCode::OK_200, result->status);
  6392. if (i == keep_alive_max_count - 1) {
  6393. EXPECT_EQ("close", result->get_header_value("Connection"));
  6394. } else {
  6395. EXPECT_FALSE(result->has_header("Connection"));
  6396. }
  6397. }
  6398. }
  6399. TEST(KeepAliveTest, Issue1041) {
  6400. Server svr;
  6401. svr.set_keep_alive_timeout(3);
  6402. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6403. res.set_content("Hello World!", "text/plain");
  6404. });
  6405. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6406. auto se = detail::scope_exit([&] {
  6407. svr.stop();
  6408. listen_thread.join();
  6409. ASSERT_FALSE(svr.is_running());
  6410. });
  6411. svr.wait_until_ready();
  6412. Client cli(HOST, PORT);
  6413. cli.set_keep_alive(true);
  6414. auto result = cli.Get("/hi");
  6415. ASSERT_TRUE(result);
  6416. EXPECT_EQ(StatusCode::OK_200, result->status);
  6417. std::this_thread::sleep_for(std::chrono::seconds(5));
  6418. result = cli.Get("/hi");
  6419. ASSERT_TRUE(result);
  6420. EXPECT_EQ(StatusCode::OK_200, result->status);
  6421. }
  6422. TEST(KeepAliveTest, Issue1959) {
  6423. Server svr;
  6424. svr.set_keep_alive_timeout(5);
  6425. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6426. res.set_content("a", "text/plain");
  6427. });
  6428. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6429. auto se = detail::scope_exit([&] {
  6430. if (!svr.is_running()) return;
  6431. svr.stop();
  6432. listen_thread.join();
  6433. ASSERT_FALSE(svr.is_running());
  6434. });
  6435. svr.wait_until_ready();
  6436. Client cli("localhost", PORT);
  6437. cli.set_keep_alive(true);
  6438. using namespace std::chrono;
  6439. auto start = steady_clock::now();
  6440. cli.Get("/a");
  6441. svr.stop();
  6442. listen_thread.join();
  6443. auto end = steady_clock::now();
  6444. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6445. EXPECT_LT(elapsed, 5000);
  6446. }
  6447. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6448. TEST(KeepAliveTest, SSLClientReconnection) {
  6449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6450. ASSERT_TRUE(svr.is_valid());
  6451. svr.set_keep_alive_timeout(1);
  6452. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6453. res.set_content("Hello World!", "text/plain");
  6454. });
  6455. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6456. auto se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. listen_thread.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. SSLClient cli(HOST, PORT);
  6463. cli.enable_server_certificate_verification(false);
  6464. cli.set_keep_alive(true);
  6465. auto result = cli.Get("/hi");
  6466. ASSERT_TRUE(result);
  6467. EXPECT_EQ(StatusCode::OK_200, result->status);
  6468. result = cli.Get("/hi");
  6469. ASSERT_TRUE(result);
  6470. EXPECT_EQ(StatusCode::OK_200, result->status);
  6471. std::this_thread::sleep_for(std::chrono::seconds(2));
  6472. // Recoonect
  6473. result = cli.Get("/hi");
  6474. ASSERT_TRUE(result);
  6475. EXPECT_EQ(StatusCode::OK_200, result->status);
  6476. result = cli.Get("/hi");
  6477. ASSERT_TRUE(result);
  6478. EXPECT_EQ(StatusCode::OK_200, result->status);
  6479. }
  6480. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6482. ASSERT_TRUE(svr.is_valid());
  6483. svr.set_keep_alive_timeout(1);
  6484. std::string content = "reconnect";
  6485. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6486. res.set_content("Hello World!", "text/plain");
  6487. });
  6488. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6489. auto se = detail::scope_exit([&] {
  6490. svr.stop();
  6491. listen_thread.join();
  6492. ASSERT_FALSE(svr.is_running());
  6493. });
  6494. svr.wait_until_ready();
  6495. SSLClient cli(HOST, PORT);
  6496. cli.enable_server_certificate_verification(false);
  6497. cli.set_keep_alive(true);
  6498. auto result = cli.Post(
  6499. "/hi", content.size(),
  6500. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6501. sink.write(content.c_str(), content.size());
  6502. return true;
  6503. },
  6504. "text/plain");
  6505. ASSERT_TRUE(result);
  6506. EXPECT_EQ(200, result->status);
  6507. std::this_thread::sleep_for(std::chrono::seconds(2));
  6508. // Recoonect
  6509. result = cli.Post(
  6510. "/hi", content.size(),
  6511. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6512. sink.write(content.c_str(), content.size());
  6513. return true;
  6514. },
  6515. "text/plain");
  6516. ASSERT_TRUE(result);
  6517. EXPECT_EQ(200, result->status);
  6518. result = cli.Post(
  6519. "/hi", content.size(),
  6520. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6521. sink.write(content.c_str(), content.size());
  6522. return true;
  6523. },
  6524. "text/plain");
  6525. ASSERT_TRUE(result);
  6526. EXPECT_EQ(200, result->status);
  6527. }
  6528. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6529. {
  6530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6531. ASSERT_TRUE(svr.is_valid());
  6532. svr.Get("/sni", [&](const Request &req, Response &res) {
  6533. std::string expected;
  6534. if (req.ssl) {
  6535. if (const char *sni =
  6536. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6537. expected = sni;
  6538. }
  6539. }
  6540. EXPECT_EQ(expected, req.get_param_value("expected"));
  6541. res.set_content("ok", "text/plain");
  6542. });
  6543. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6544. auto se = detail::scope_exit([&] {
  6545. svr.stop();
  6546. listen_thread.join();
  6547. ASSERT_FALSE(svr.is_running());
  6548. });
  6549. svr.wait_until_ready();
  6550. {
  6551. SSLClient cli("localhost", PORT);
  6552. cli.enable_server_certificate_verification(false);
  6553. auto res = cli.Get("/sni?expected=localhost");
  6554. ASSERT_TRUE(res);
  6555. }
  6556. {
  6557. SSLClient cli("::1", PORT);
  6558. cli.enable_server_certificate_verification(false);
  6559. auto res = cli.Get("/sni?expected=");
  6560. // NOTE: This may fail if the server is listening on IPv4 only
  6561. // (e.g., when localhost resolves to 127.0.0.1 only)
  6562. if (res) {
  6563. EXPECT_EQ(StatusCode::OK_200, res->status);
  6564. } else {
  6565. EXPECT_EQ(Error::Connection, res.error());
  6566. }
  6567. }
  6568. }
  6569. }
  6570. #endif
  6571. TEST(ClientProblemDetectionTest, ContentProvider) {
  6572. Server svr;
  6573. size_t content_length = 1024 * 1024;
  6574. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6575. res.set_content_provider(
  6576. content_length, "text/plain",
  6577. [&](size_t offset, size_t length, DataSink &sink) {
  6578. auto out_len = std::min(length, static_cast<size_t>(1024));
  6579. std::string out(out_len, '@');
  6580. sink.write(out.data(), out_len);
  6581. return offset < 4096;
  6582. },
  6583. [](bool success) { ASSERT_FALSE(success); });
  6584. });
  6585. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6586. res.set_content_provider(
  6587. 0, "text/plain",
  6588. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6589. EXPECT_TRUE(false);
  6590. return true;
  6591. },
  6592. [](bool success) { ASSERT_FALSE(success); });
  6593. });
  6594. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6595. auto se = detail::scope_exit([&] {
  6596. svr.stop();
  6597. listen_thread.join();
  6598. ASSERT_FALSE(svr.is_running());
  6599. });
  6600. svr.wait_until_ready();
  6601. Client cli("localhost", PORT);
  6602. {
  6603. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6604. size_t /*data_length*/) { return false; });
  6605. ASSERT_FALSE(res);
  6606. }
  6607. {
  6608. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6609. size_t /*data_length*/) { return false; });
  6610. ASSERT_TRUE(res);
  6611. }
  6612. }
  6613. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6614. Server svr;
  6615. svr.set_error_handler([](Request const &, Response &res) -> void {
  6616. res.set_chunked_content_provider(
  6617. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6618. sink.os << "hello";
  6619. sink.os << "world";
  6620. sink.done();
  6621. return true;
  6622. });
  6623. });
  6624. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6625. auto se = detail::scope_exit([&] {
  6626. svr.stop();
  6627. listen_thread.join();
  6628. ASSERT_FALSE(svr.is_running());
  6629. });
  6630. svr.wait_until_ready();
  6631. Client cli("localhost", PORT);
  6632. auto res = cli.Get("/");
  6633. ASSERT_TRUE(res);
  6634. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6635. EXPECT_EQ("helloworld", res->body);
  6636. }
  6637. TEST(LongPollingTest, ClientCloseDetection) {
  6638. Server svr;
  6639. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6640. res.set_chunked_content_provider(
  6641. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6642. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6643. sink.os << "hello";
  6644. auto count = 10;
  6645. while (count > 0 && sink.is_writable()) {
  6646. this_thread::sleep_for(chrono::milliseconds(10));
  6647. count--;
  6648. }
  6649. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6650. return true;
  6651. });
  6652. });
  6653. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6654. auto se = detail::scope_exit([&] {
  6655. svr.stop();
  6656. listen_thread.join();
  6657. ASSERT_FALSE(svr.is_running());
  6658. });
  6659. svr.wait_until_ready();
  6660. Client cli("localhost", PORT);
  6661. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6662. EXPECT_EQ("hello", string(data, data_length));
  6663. return false; // close the socket immediately.
  6664. });
  6665. ASSERT_FALSE(res);
  6666. }
  6667. TEST(GetWithParametersTest, GetWithParameters) {
  6668. Server svr;
  6669. svr.Get("/", [&](const Request &req, Response &) {
  6670. EXPECT_EQ("world", req.get_param_value("hello"));
  6671. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6672. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6673. });
  6674. svr.Get("/params", [&](const Request &req, Response &) {
  6675. EXPECT_EQ("world", req.get_param_value("hello"));
  6676. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6677. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6678. });
  6679. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6680. EXPECT_EQ("resource-id", req.matches[1]);
  6681. EXPECT_EQ("foo", req.get_param_value("param1"));
  6682. EXPECT_EQ("bar", req.get_param_value("param2"));
  6683. });
  6684. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6685. EXPECT_EQ("user-id", req.path_params.at("id"));
  6686. EXPECT_EQ("foo", req.get_param_value("param1"));
  6687. EXPECT_EQ("bar", req.get_param_value("param2"));
  6688. });
  6689. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6690. auto se = detail::scope_exit([&] {
  6691. svr.stop();
  6692. listen_thread.join();
  6693. ASSERT_FALSE(svr.is_running());
  6694. });
  6695. svr.wait_until_ready();
  6696. {
  6697. Client cli(HOST, PORT);
  6698. Params params;
  6699. params.emplace("hello", "world");
  6700. params.emplace("hello2", "world2");
  6701. params.emplace("hello3", "world3");
  6702. auto res = cli.Get("/", params, Headers{});
  6703. ASSERT_TRUE(res);
  6704. EXPECT_EQ(StatusCode::OK_200, res->status);
  6705. }
  6706. {
  6707. Client cli(HOST, PORT);
  6708. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6709. ASSERT_TRUE(res);
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. }
  6712. {
  6713. Client cli(HOST, PORT);
  6714. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6715. ASSERT_TRUE(res);
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. }
  6718. {
  6719. Client cli(HOST, PORT);
  6720. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6721. ASSERT_TRUE(res);
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. }
  6724. }
  6725. TEST(GetWithParametersTest, GetWithParameters2) {
  6726. Server svr;
  6727. svr.Get("/", [&](const Request &req, Response &res) {
  6728. auto text = req.get_param_value("hello");
  6729. res.set_content(text, "text/plain");
  6730. });
  6731. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6732. auto se = detail::scope_exit([&] {
  6733. svr.stop();
  6734. listen_thread.join();
  6735. ASSERT_FALSE(svr.is_running());
  6736. });
  6737. svr.wait_until_ready();
  6738. Client cli("localhost", PORT);
  6739. Params params;
  6740. params.emplace("hello", "world");
  6741. std::string body;
  6742. auto res = cli.Get("/", params, Headers{},
  6743. [&](const char *data, size_t data_length) {
  6744. body.append(data, data_length);
  6745. return true;
  6746. });
  6747. ASSERT_TRUE(res);
  6748. EXPECT_EQ(StatusCode::OK_200, res->status);
  6749. EXPECT_EQ("world", body);
  6750. }
  6751. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6752. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6753. auto host = "httpcan.org";
  6754. auto path = std::string{"/range/32"};
  6755. #else
  6756. auto host = "nghttp2.org";
  6757. auto path = std::string{"/httpbin/range/32"};
  6758. #endif
  6759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6760. SSLClient cli(host);
  6761. #else
  6762. Client cli(host);
  6763. #endif
  6764. cli.set_default_headers({make_range_header({{1, 10}})});
  6765. cli.set_connection_timeout(5);
  6766. {
  6767. auto res = cli.Get(path);
  6768. ASSERT_TRUE(res);
  6769. EXPECT_EQ("bcdefghijk", res->body);
  6770. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6771. }
  6772. {
  6773. auto res = cli.Get(path);
  6774. ASSERT_TRUE(res);
  6775. EXPECT_EQ("bcdefghijk", res->body);
  6776. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6777. }
  6778. }
  6779. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6780. Server svr;
  6781. svr.set_default_headers({{"Hello", "World"}});
  6782. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6783. res.set_content("ok", "text/plain");
  6784. });
  6785. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6786. auto se = detail::scope_exit([&] {
  6787. svr.stop();
  6788. listen_thread.join();
  6789. ASSERT_FALSE(svr.is_running());
  6790. });
  6791. svr.wait_until_ready();
  6792. Client cli("localhost", PORT);
  6793. auto res = cli.Get("/");
  6794. ASSERT_TRUE(res);
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. EXPECT_EQ("ok", res->body);
  6797. EXPECT_EQ("World", res->get_header_value("Hello"));
  6798. }
  6799. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6800. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6802. ASSERT_TRUE(svr.is_valid());
  6803. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6804. std::this_thread::sleep_for(std::chrono::seconds(2));
  6805. res.set_content("a", "text/plain");
  6806. });
  6807. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6808. res.set_content("b", "text/plain");
  6809. });
  6810. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6811. auto se = detail::scope_exit([&] {
  6812. svr.stop();
  6813. listen_thread.join();
  6814. ASSERT_FALSE(svr.is_running());
  6815. });
  6816. svr.wait_until_ready();
  6817. SSLClient cli("localhost", PORT);
  6818. cli.enable_server_certificate_verification(false);
  6819. cli.set_keep_alive(true);
  6820. cli.set_read_timeout(std::chrono::seconds(1));
  6821. auto resa = cli.Get("/a");
  6822. ASSERT_TRUE(!resa);
  6823. EXPECT_EQ(Error::Read, resa.error());
  6824. auto resb = cli.Get("/b");
  6825. ASSERT_TRUE(resb);
  6826. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6827. EXPECT_EQ("b", resb->body);
  6828. }
  6829. #endif
  6830. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6831. protected:
  6832. ServerTestWithAI_PASSIVE()
  6833. : cli_(HOST, PORT)
  6834. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6835. ,
  6836. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6837. #endif
  6838. {
  6839. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6840. cli_.enable_server_certificate_verification(false);
  6841. #endif
  6842. }
  6843. virtual void SetUp() {
  6844. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6845. res.set_content("Hello World!", "text/plain");
  6846. });
  6847. t_ = thread(
  6848. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6849. svr_.wait_until_ready();
  6850. }
  6851. virtual void TearDown() {
  6852. svr_.stop();
  6853. t_.join();
  6854. }
  6855. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6856. SSLClient cli_;
  6857. SSLServer svr_;
  6858. #else
  6859. Client cli_;
  6860. Server svr_;
  6861. #endif
  6862. thread t_;
  6863. };
  6864. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6865. auto res = cli_.Get("/hi");
  6866. ASSERT_TRUE(res);
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6869. EXPECT_EQ("Hello World!", res->body);
  6870. }
  6871. class ServerUpDownTest : public ::testing::Test {
  6872. protected:
  6873. ServerUpDownTest() : cli_(HOST, PORT) {}
  6874. virtual void SetUp() {
  6875. t_ = thread([&]() {
  6876. svr_.bind_to_any_port(HOST);
  6877. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6878. ASSERT_TRUE(svr_.listen_after_bind());
  6879. });
  6880. svr_.wait_until_ready();
  6881. }
  6882. virtual void TearDown() {
  6883. svr_.stop();
  6884. t_.join();
  6885. }
  6886. Client cli_;
  6887. Server svr_;
  6888. thread t_;
  6889. };
  6890. TEST_F(ServerUpDownTest, QuickStartStop) {
  6891. // Should not crash, especially when run with
  6892. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6893. }
  6894. class PayloadMaxLengthTest : public ::testing::Test {
  6895. protected:
  6896. PayloadMaxLengthTest()
  6897. : cli_(HOST, PORT)
  6898. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6899. ,
  6900. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6901. #endif
  6902. {
  6903. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6904. cli_.enable_server_certificate_verification(false);
  6905. #endif
  6906. }
  6907. virtual void SetUp() {
  6908. svr_.set_payload_max_length(8);
  6909. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6910. res.set_content("test", "text/plain");
  6911. });
  6912. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6913. svr_.wait_until_ready();
  6914. }
  6915. virtual void TearDown() {
  6916. svr_.stop();
  6917. t_.join();
  6918. }
  6919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6920. SSLClient cli_;
  6921. SSLServer svr_;
  6922. #else
  6923. Client cli_;
  6924. Server svr_;
  6925. #endif
  6926. thread t_;
  6927. };
  6928. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6929. auto res = cli_.Post("/test", "123456789", "text/plain");
  6930. ASSERT_TRUE(res);
  6931. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6932. res = cli_.Post("/test", "12345678", "text/plain");
  6933. ASSERT_TRUE(res);
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. }
  6936. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6937. // Test chunked encoding with payload exceeding the 8-byte limit
  6938. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6939. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6940. ASSERT_TRUE(res);
  6941. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6942. }
  6943. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6944. // Test chunked encoding with payload within the 8-byte limit
  6945. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6946. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6947. ASSERT_TRUE(res);
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. }
  6950. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6951. // Test using send_request to send chunked data exceeding payload limit
  6952. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6953. "Host: " +
  6954. std::string(HOST) + ":" + std::to_string(PORT) +
  6955. "\r\n"
  6956. "Transfer-Encoding: chunked\r\n"
  6957. "Connection: close\r\n"
  6958. "\r\n"
  6959. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6960. "0123456789\r\n"
  6961. "0\r\n" // End chunk
  6962. "\r\n";
  6963. std::string response;
  6964. bool result = send_request(1, chunked_request, &response);
  6965. if (!result) {
  6966. // If send_request fails, it might be because the server closed the
  6967. // connection due to payload limit enforcement, which is acceptable
  6968. SUCCEED()
  6969. << "Server rejected oversized chunked request (connection closed)";
  6970. } else {
  6971. // If we got a response, check if it's an error response or connection was
  6972. // closed early Short response length indicates connection was closed due to
  6973. // payload limit
  6974. if (response.length() <= 10) {
  6975. SUCCEED() << "Server closed connection for oversized chunked request";
  6976. } else {
  6977. // Check for error status codes
  6978. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6979. response.find("Payload Too Large") != std::string::npos ||
  6980. response.find("400") != std::string::npos);
  6981. }
  6982. }
  6983. }
  6984. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6985. // Test request without Content-Length header exceeding payload limit
  6986. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6987. "Host: " +
  6988. std::string(HOST) + ":" +
  6989. std::to_string(PORT) +
  6990. "\r\n"
  6991. "Connection: close\r\n"
  6992. "\r\n";
  6993. // Add payload exceeding the 8-byte limit
  6994. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6995. request_without_content_length += large_payload;
  6996. std::string response;
  6997. bool result = send_request(1, request_without_content_length, &response);
  6998. if (!result) {
  6999. // If send_request fails, server likely closed connection due to payload
  7000. // limit
  7001. SUCCEED() << "Server rejected oversized request without Content-Length "
  7002. "(connection closed)";
  7003. } else {
  7004. // Check if server responded with error or closed connection early
  7005. if (response.length() <= 10) {
  7006. SUCCEED() << "Server closed connection for oversized request without "
  7007. "Content-Length";
  7008. } else {
  7009. // Check for error status codes
  7010. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7011. response.find("Payload Too Large") != std::string::npos ||
  7012. response.find("400") != std::string::npos);
  7013. }
  7014. }
  7015. }
  7016. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7017. // Test request without Content-Length header within payload limit
  7018. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7019. "Host: " +
  7020. std::string(HOST) + ":" +
  7021. std::to_string(PORT) +
  7022. "\r\n"
  7023. "Connection: close\r\n"
  7024. "\r\n";
  7025. // Add payload within the 8-byte limit
  7026. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7027. request_without_content_length += small_payload;
  7028. std::string response;
  7029. bool result = send_request(1, request_without_content_length, &response);
  7030. // For requests without Content-Length, the server may have different behavior
  7031. // The key is that it should not reject due to payload limit for small
  7032. // payloads
  7033. if (result) {
  7034. // Check for any HTTP response (success or error, but not connection closed)
  7035. if (response.length() > 10) {
  7036. SUCCEED()
  7037. << "Server processed request without Content-Length within limit";
  7038. } else {
  7039. // Short response might indicate connection closed, which is acceptable
  7040. SUCCEED() << "Server closed connection for request without "
  7041. "Content-Length (acceptable behavior)";
  7042. }
  7043. } else {
  7044. // Connection failure might be due to protocol requirements
  7045. SUCCEED() << "Connection issue with request without Content-Length "
  7046. "(environment-specific)";
  7047. }
  7048. }
  7049. class LargePayloadMaxLengthTest : public ::testing::Test {
  7050. protected:
  7051. LargePayloadMaxLengthTest()
  7052. : cli_(HOST, PORT)
  7053. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7054. ,
  7055. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7056. #endif
  7057. {
  7058. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7059. cli_.enable_server_certificate_verification(false);
  7060. #endif
  7061. }
  7062. virtual void SetUp() {
  7063. // Set 10MB payload limit
  7064. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7065. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7066. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7067. res.set_content("Large payload test", "text/plain");
  7068. });
  7069. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7070. svr_.wait_until_ready();
  7071. }
  7072. virtual void TearDown() {
  7073. svr_.stop();
  7074. t_.join();
  7075. }
  7076. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7077. SSLClient cli_;
  7078. SSLServer svr_;
  7079. #else
  7080. Client cli_;
  7081. Server svr_;
  7082. #endif
  7083. thread t_;
  7084. };
  7085. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7086. // Test chunked encoding with payload within 10MB limit
  7087. std::string medium_payload(5 * 1024 * 1024,
  7088. 'A'); // 5MB payload, within 10MB limit
  7089. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7090. ASSERT_TRUE(res);
  7091. EXPECT_EQ(StatusCode::OK_200, res->status);
  7092. }
  7093. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7094. // Test chunked encoding with payload exceeding 10MB limit
  7095. std::string large_payload(12 * 1024 * 1024,
  7096. 'B'); // 12MB payload, exceeds 10MB limit
  7097. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7098. ASSERT_TRUE(res);
  7099. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7100. }
  7101. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7102. // Test request without Content-Length header within 10MB limit
  7103. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7104. "Host: " +
  7105. std::string(HOST) + ":" +
  7106. std::to_string(PORT) +
  7107. "\r\n"
  7108. "Connection: close\r\n"
  7109. "\r\n";
  7110. // Add 1MB payload (within 10MB limit)
  7111. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7112. request_without_content_length += medium_payload;
  7113. std::string response;
  7114. bool result = send_request(5, request_without_content_length, &response);
  7115. if (result) {
  7116. // Should get a proper HTTP response for payloads within limit
  7117. if (response.length() > 10) {
  7118. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7119. "10MB limit";
  7120. } else {
  7121. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7122. "Content-Length)";
  7123. }
  7124. } else {
  7125. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7126. }
  7127. }
  7128. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7129. // Test request without Content-Length header exceeding 10MB limit
  7130. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7131. "Host: " +
  7132. std::string(HOST) + ":" +
  7133. std::to_string(PORT) +
  7134. "\r\n"
  7135. "Connection: close\r\n"
  7136. "\r\n";
  7137. // Add 12MB payload (exceeds 10MB limit)
  7138. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7139. request_without_content_length += large_payload;
  7140. std::string response;
  7141. bool result = send_request(10, request_without_content_length, &response);
  7142. if (!result) {
  7143. // Server should close connection due to payload limit
  7144. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7145. "(connection closed)";
  7146. } else {
  7147. // Check for error response
  7148. if (response.length() <= 10) {
  7149. SUCCEED()
  7150. << "Server closed connection for 12MB request exceeding 10MB limit";
  7151. } else {
  7152. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7153. response.find("Payload Too Large") != std::string::npos ||
  7154. response.find("400") != std::string::npos);
  7155. }
  7156. }
  7157. }
  7158. TEST(HostAndPortPropertiesTest, NoSSL) {
  7159. httplib::Client cli("www.google.com", 1234);
  7160. ASSERT_EQ("www.google.com", cli.host());
  7161. ASSERT_EQ(1234, cli.port());
  7162. }
  7163. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7164. httplib::Client cli("www.google.com:1234");
  7165. ASSERT_EQ("www.google.com", cli.host());
  7166. ASSERT_EQ(1234, cli.port());
  7167. }
  7168. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7169. TEST(HostAndPortPropertiesTest, SSL) {
  7170. httplib::SSLClient cli("www.google.com");
  7171. ASSERT_EQ("www.google.com", cli.host());
  7172. ASSERT_EQ(443, cli.port());
  7173. }
  7174. #endif
  7175. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7176. TEST(SSLClientTest, UpdateCAStore) {
  7177. httplib::SSLClient httplib_client("www.google.com");
  7178. auto ca_store_1 = X509_STORE_new();
  7179. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7180. nullptr);
  7181. httplib_client.set_ca_cert_store(ca_store_1);
  7182. auto ca_store_2 = X509_STORE_new();
  7183. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7184. nullptr);
  7185. httplib_client.set_ca_cert_store(ca_store_2);
  7186. }
  7187. TEST(SSLClientTest, ServerNameIndication_Online) {
  7188. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7189. auto host = "httpcan.org";
  7190. auto path = std::string{"/get"};
  7191. #else
  7192. auto host = "nghttp2.org";
  7193. auto path = std::string{"/httpbin/get"};
  7194. #endif
  7195. SSLClient cli(host, 443);
  7196. auto res = cli.Get(path);
  7197. ASSERT_TRUE(res);
  7198. ASSERT_EQ(StatusCode::OK_200, res->status);
  7199. }
  7200. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7201. // Use a site that will cause SSL verification failure due to self-signed cert
  7202. SSLClient cli("self-signed.badssl.com", 443);
  7203. cli.enable_server_certificate_verification(true);
  7204. auto res = cli.Get("/");
  7205. ASSERT_TRUE(!res);
  7206. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7207. // For SSL server verification errors, ssl_error should be 0, only
  7208. // ssl_openssl_error should be set
  7209. EXPECT_EQ(0, res.ssl_error());
  7210. // Verify OpenSSL error is captured for SSLServerVerification
  7211. // This occurs when SSL_get_verify_result() returns a verification failure
  7212. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7213. res.ssl_openssl_error());
  7214. }
  7215. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7216. // Use a site where hostname doesn't match the certificate
  7217. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7218. SSLClient cli("wrong.host.badssl.com", 443);
  7219. cli.enable_server_certificate_verification(true);
  7220. cli.enable_server_hostname_verification(true);
  7221. auto res = cli.Get("/");
  7222. ASSERT_TRUE(!res);
  7223. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7224. // For SSL hostname verification errors, ssl_error should be 0, only
  7225. // ssl_openssl_error should be set
  7226. EXPECT_EQ(0, res.ssl_error());
  7227. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7228. // This occurs when verify_host() fails due to hostname mismatch
  7229. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7230. res.ssl_openssl_error());
  7231. }
  7232. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7233. Client cli("https://google.com");
  7234. auto res = cli.Get("/");
  7235. ASSERT_TRUE(res);
  7236. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7237. }
  7238. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7239. SSLClient cli("google.com");
  7240. cli.set_ca_cert_path(CA_CERT_FILE);
  7241. auto res = cli.Get("/");
  7242. ASSERT_TRUE(res);
  7243. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7244. }
  7245. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7246. SSLClient cli("google.com");
  7247. cli.enable_server_certificate_verification(true);
  7248. cli.set_ca_cert_path("hello");
  7249. auto res = cli.Get("/");
  7250. ASSERT_TRUE(!res);
  7251. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7252. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7253. // should be set
  7254. EXPECT_EQ(0, res.ssl_error());
  7255. // Verify OpenSSL error is captured for SSLLoadingCerts
  7256. // This error occurs when SSL_CTX_load_verify_locations() fails
  7257. // > openssl errstr 0x80000002
  7258. // error:80000002:system library::No such file or directory
  7259. // > openssl errstr 0xA000126
  7260. // error:0A000126:SSL routines::unexpected eof while reading
  7261. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7262. res.ssl_openssl_error() == 0xA000126);
  7263. }
  7264. TEST(SSLClientTest, ServerCertificateVerification4) {
  7265. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7266. ASSERT_TRUE(svr.is_valid());
  7267. svr.Get("/test", [&](const Request &, Response &res) {
  7268. res.set_content("test", "text/plain");
  7269. svr.stop();
  7270. ASSERT_TRUE(true);
  7271. });
  7272. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7273. auto se = detail::scope_exit([&] {
  7274. t.join();
  7275. ASSERT_FALSE(svr.is_running());
  7276. });
  7277. svr.wait_until_ready();
  7278. SSLClient cli("127.0.0.1", PORT);
  7279. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7280. cli.enable_server_certificate_verification(true);
  7281. cli.set_connection_timeout(30);
  7282. auto res = cli.Get("/test");
  7283. ASSERT_TRUE(res);
  7284. ASSERT_EQ(StatusCode::OK_200, res->status);
  7285. }
  7286. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7287. std::string cert;
  7288. read_file(CA_CERT_FILE, cert);
  7289. SSLClient cli("google.com");
  7290. cli.load_ca_cert_store(cert.data(), cert.size());
  7291. const auto res = cli.Get("/");
  7292. ASSERT_TRUE(res);
  7293. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7294. }
  7295. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7296. // clang-format off
  7297. static constexpr char cert[] =
  7298. "GlobalSign Root CA\n"
  7299. "==================\n"
  7300. "-----BEGIN CERTIFICATE-----\n"
  7301. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7302. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7303. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7304. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7305. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7306. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7307. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7308. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7309. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7310. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7311. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7312. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7313. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7314. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7315. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7316. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7317. "-----END CERTIFICATE-----\n";
  7318. // clang-format on
  7319. SSLClient cli("google.com");
  7320. cli.load_ca_cert_store(cert, sizeof(cert));
  7321. const auto res = cli.Get("/");
  7322. ASSERT_TRUE(res);
  7323. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7324. }
  7325. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7326. SSLClient cli("www.youtube.com");
  7327. cli.set_ca_cert_path(CA_CERT_FILE);
  7328. cli.enable_server_certificate_verification(true);
  7329. cli.set_follow_location(true);
  7330. auto res = cli.Get("/");
  7331. ASSERT_TRUE(res);
  7332. ASSERT_EQ(StatusCode::OK_200, res->status);
  7333. }
  7334. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  7335. SSLClient cli("wWw.YouTube.Com");
  7336. cli.set_ca_cert_path(CA_CERT_FILE);
  7337. cli.enable_server_certificate_verification(true);
  7338. cli.enable_server_hostname_verification(true);
  7339. cli.set_follow_location(true);
  7340. auto res = cli.Get("/");
  7341. ASSERT_TRUE(res);
  7342. ASSERT_EQ(StatusCode::OK_200, res->status);
  7343. }
  7344. TEST(SSLClientTest, HostNameMatchCase_Online) {
  7345. SSLClient cli("gOoGlE.COm");
  7346. cli.enable_server_certificate_verification(true);
  7347. cli.enable_server_hostname_verification(true);
  7348. cli.set_follow_location(true);
  7349. auto res = cli.Get("/");
  7350. ASSERT_TRUE(res);
  7351. ASSERT_EQ(StatusCode::OK_200, res->status);
  7352. }
  7353. TEST(SSLClientTest, Issue2004_Online) {
  7354. Client client("https://google.com");
  7355. client.set_follow_location(true);
  7356. auto res = client.Get("/");
  7357. ASSERT_TRUE(res);
  7358. ASSERT_EQ(StatusCode::OK_200, res->status);
  7359. auto body = res->body;
  7360. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7361. }
  7362. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7363. // Create SSLClient with invalid cert/key to make is_valid() return false
  7364. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7365. "nonexistent_key.pem");
  7366. // is_valid() should be false due to cert loading failure
  7367. ASSERT_FALSE(cli.is_valid());
  7368. auto res = cli.Get("/");
  7369. ASSERT_FALSE(res);
  7370. EXPECT_EQ(Error::SSLConnection, res.error());
  7371. }
  7372. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7373. // Test for Issue #2251: SSL error not properly reported when client cert
  7374. // and key paths are swapped or mismatched
  7375. // This simulates the scenario where user accidentally swaps the cert and key
  7376. // files
  7377. // Using client cert file as private key and vice versa (completely wrong)
  7378. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7379. // Should fail validation due to cert/key mismatch
  7380. ASSERT_FALSE(cli.is_valid());
  7381. // Attempt to make a request should fail with proper error
  7382. auto res = cli.Get("/");
  7383. ASSERT_FALSE(res);
  7384. EXPECT_EQ(Error::SSLConnection, res.error());
  7385. // SSL error should be recorded in the Result object (this is the key fix for
  7386. // Issue #2251)
  7387. auto openssl_error = res.ssl_openssl_error();
  7388. EXPECT_NE(0u, openssl_error);
  7389. }
  7390. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7391. // Another variant: using valid file paths but with mismatched cert/key pair
  7392. // This tests the case where files exist but contain incompatible key material
  7393. // Using client cert with wrong key (cert2 key)
  7394. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7395. // Should fail validation
  7396. ASSERT_FALSE(cli.is_valid());
  7397. auto res = cli.Get("/");
  7398. ASSERT_FALSE(res);
  7399. // Must report error properly, not appear as success
  7400. EXPECT_EQ(Error::SSLConnection, res.error());
  7401. // OpenSSL error should be captured in Result
  7402. EXPECT_NE(0u, res.ssl_openssl_error());
  7403. }
  7404. #if 0
  7405. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7406. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7407. ASSERT_TRUE(cli != nullptr);
  7408. cli->set_address_family(AF_INET6);
  7409. cli->set_interface("en0");
  7410. auto res = cli->Get("/get");
  7411. ASSERT_TRUE(res);
  7412. ASSERT_EQ(StatusCode::OK_200, res->status);
  7413. }
  7414. #endif
  7415. void ClientCertPresent(
  7416. const std::string &client_cert_file,
  7417. const std::string &client_private_key_file,
  7418. const std::string &client_encrypted_private_key_pass = std::string()) {
  7419. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7420. CLIENT_CA_CERT_DIR);
  7421. ASSERT_TRUE(svr.is_valid());
  7422. svr.Get("/test", [&](const Request &req, Response &res) {
  7423. res.set_content("test", "text/plain");
  7424. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7425. ASSERT_TRUE(peer_cert != nullptr);
  7426. auto subject_name = X509_get_subject_name(peer_cert);
  7427. ASSERT_TRUE(subject_name != nullptr);
  7428. std::string common_name;
  7429. {
  7430. char name[BUFSIZ];
  7431. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7432. name, sizeof(name));
  7433. common_name.assign(name, static_cast<size_t>(name_len));
  7434. }
  7435. EXPECT_EQ("Common Name", common_name);
  7436. X509_free(peer_cert);
  7437. });
  7438. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7439. auto se = detail::scope_exit([&] {
  7440. svr.stop();
  7441. t.join();
  7442. ASSERT_FALSE(svr.is_running());
  7443. });
  7444. svr.wait_until_ready();
  7445. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7446. client_encrypted_private_key_pass);
  7447. cli.enable_server_certificate_verification(false);
  7448. cli.set_connection_timeout(30);
  7449. auto res = cli.Get("/test");
  7450. ASSERT_TRUE(res);
  7451. ASSERT_EQ(StatusCode::OK_200, res->status);
  7452. }
  7453. TEST(SSLClientServerTest, ClientCertPresent) {
  7454. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7455. }
  7456. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7457. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7458. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7459. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7460. }
  7461. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7462. void MemoryClientCertPresent(
  7463. const std::string &client_cert_file,
  7464. const std::string &client_private_key_file,
  7465. const std::string &client_encrypted_private_key_pass = std::string()) {
  7466. auto f = fopen(SERVER_CERT_FILE, "r+");
  7467. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7468. fclose(f);
  7469. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7470. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7471. fclose(f);
  7472. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7473. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7474. auto client_ca_cert_store = X509_STORE_new();
  7475. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7476. X509_free(client_cert);
  7477. fclose(f);
  7478. f = fopen(client_cert_file.c_str(), "r+");
  7479. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7480. fclose(f);
  7481. f = fopen(client_private_key_file.c_str(), "r+");
  7482. auto client_private_key = PEM_read_PrivateKey(
  7483. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7484. fclose(f);
  7485. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7486. ASSERT_TRUE(svr.is_valid());
  7487. svr.Get("/test", [&](const Request &req, Response &res) {
  7488. res.set_content("test", "text/plain");
  7489. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7490. ASSERT_TRUE(peer_cert != nullptr);
  7491. auto subject_name = X509_get_subject_name(peer_cert);
  7492. ASSERT_TRUE(subject_name != nullptr);
  7493. std::string common_name;
  7494. {
  7495. char name[BUFSIZ];
  7496. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7497. name, sizeof(name));
  7498. common_name.assign(name, static_cast<size_t>(name_len));
  7499. }
  7500. EXPECT_EQ("Common Name", common_name);
  7501. X509_free(peer_cert);
  7502. });
  7503. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7504. auto se = detail::scope_exit([&] {
  7505. svr.stop();
  7506. t.join();
  7507. ASSERT_FALSE(svr.is_running());
  7508. });
  7509. svr.wait_until_ready();
  7510. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7511. client_encrypted_private_key_pass);
  7512. cli.enable_server_certificate_verification(false);
  7513. cli.set_connection_timeout(30);
  7514. auto res = cli.Get("/test");
  7515. ASSERT_TRUE(res);
  7516. ASSERT_EQ(StatusCode::OK_200, res->status);
  7517. X509_free(server_cert);
  7518. EVP_PKEY_free(server_private_key);
  7519. X509_free(client_cert);
  7520. EVP_PKEY_free(client_private_key);
  7521. }
  7522. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7523. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7524. }
  7525. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7526. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7527. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7528. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7529. }
  7530. #endif
  7531. TEST(SSLClientServerTest, ClientCertMissing) {
  7532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7533. CLIENT_CA_CERT_DIR);
  7534. ASSERT_TRUE(svr.is_valid());
  7535. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7536. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7537. auto se = detail::scope_exit([&] {
  7538. svr.stop();
  7539. t.join();
  7540. ASSERT_FALSE(svr.is_running());
  7541. });
  7542. svr.wait_until_ready();
  7543. SSLClient cli(HOST, PORT);
  7544. cli.set_connection_timeout(30);
  7545. auto res = cli.Get("/test");
  7546. ASSERT_TRUE(!res);
  7547. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7548. // For SSL server verification errors, ssl_error should be 0, only
  7549. // ssl_openssl_error should be set
  7550. EXPECT_EQ(0, res.ssl_error());
  7551. // Verify OpenSSL error is captured for SSLServerVerification
  7552. // Note: This test may have different error codes depending on the exact
  7553. // verification failure
  7554. EXPECT_NE(0UL, res.ssl_openssl_error());
  7555. }
  7556. TEST(SSLClientServerTest, TrustDirOptional) {
  7557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7558. ASSERT_TRUE(svr.is_valid());
  7559. svr.Get("/test", [&](const Request &, Response &res) {
  7560. res.set_content("test", "text/plain");
  7561. });
  7562. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7563. auto se = detail::scope_exit([&] {
  7564. svr.stop();
  7565. t.join();
  7566. ASSERT_FALSE(svr.is_running());
  7567. });
  7568. svr.wait_until_ready();
  7569. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7570. cli.enable_server_certificate_verification(false);
  7571. cli.set_connection_timeout(30);
  7572. auto res = cli.Get("/test");
  7573. ASSERT_TRUE(res);
  7574. ASSERT_EQ(StatusCode::OK_200, res->status);
  7575. }
  7576. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7577. class NoListenSSLServer : public SSLServer {
  7578. public:
  7579. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7580. const char *client_ca_cert_file_path,
  7581. const char *client_ca_cert_dir_path = nullptr)
  7582. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7583. client_ca_cert_dir_path),
  7584. stop_(false) {}
  7585. std::atomic_bool stop_;
  7586. private:
  7587. bool process_and_close_socket(socket_t /*sock*/) override {
  7588. // Don't create SSL context
  7589. while (!stop_.load()) {
  7590. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7591. }
  7592. return true;
  7593. }
  7594. };
  7595. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7596. CLIENT_CA_CERT_FILE);
  7597. ASSERT_TRUE(svr.is_valid());
  7598. svr.Get("/test", [&](const Request &, Response &res) {
  7599. res.set_content("test", "text/plain");
  7600. });
  7601. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7602. auto se = detail::scope_exit([&] {
  7603. svr.stop_ = true;
  7604. svr.stop();
  7605. t.join();
  7606. ASSERT_FALSE(svr.is_running());
  7607. });
  7608. svr.wait_until_ready();
  7609. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7610. cli.enable_server_certificate_verification(false);
  7611. cli.set_connection_timeout(1);
  7612. auto res = cli.Get("/test");
  7613. ASSERT_TRUE(!res);
  7614. EXPECT_EQ(Error::SSLConnection, res.error());
  7615. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7616. }
  7617. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7618. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7619. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7620. SSL_CTX_set_options(&ssl_ctx,
  7621. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7622. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7623. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7624. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7625. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7626. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7627. "ECDHE-DSS-AES128-SHA256:"
  7628. "ECDHE-RSA-AES256-SHA256:"
  7629. "ECDHE-DSS-AES256-SHA256:";
  7630. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7631. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7632. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7633. SSL_FILETYPE_PEM) != 1) {
  7634. return false;
  7635. }
  7636. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7637. CLIENT_CA_CERT_DIR);
  7638. SSL_CTX_set_verify(
  7639. &ssl_ctx,
  7640. SSL_VERIFY_PEER |
  7641. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7642. nullptr);
  7643. return true;
  7644. };
  7645. SSLServer svr(setup_ssl_ctx_callback);
  7646. ASSERT_TRUE(svr.is_valid());
  7647. svr.Get("/test", [&](const Request &req, Response &res) {
  7648. res.set_content("test", "text/plain");
  7649. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7650. ASSERT_TRUE(peer_cert != nullptr);
  7651. auto subject_name = X509_get_subject_name(peer_cert);
  7652. ASSERT_TRUE(subject_name != nullptr);
  7653. std::string common_name;
  7654. {
  7655. char name[BUFSIZ];
  7656. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7657. name, sizeof(name));
  7658. common_name.assign(name, static_cast<size_t>(name_len));
  7659. }
  7660. EXPECT_EQ("Common Name", common_name);
  7661. X509_free(peer_cert);
  7662. });
  7663. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7664. auto se = detail::scope_exit([&] {
  7665. svr.stop();
  7666. t.join();
  7667. ASSERT_FALSE(svr.is_running());
  7668. });
  7669. svr.wait_until_ready();
  7670. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7671. cli.enable_server_certificate_verification(false);
  7672. cli.set_connection_timeout(30);
  7673. auto res = cli.Get("/test");
  7674. ASSERT_TRUE(res);
  7675. ASSERT_EQ(StatusCode::OK_200, res->status);
  7676. }
  7677. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7678. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7679. ASSERT_TRUE(svr.is_valid());
  7680. // Set up a handler to verify client certificate is present
  7681. bool client_cert_verified = false;
  7682. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7683. // Verify that client certificate was provided
  7684. client_cert_verified = true;
  7685. res.set_content("success", "text/plain");
  7686. });
  7687. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7688. auto se = detail::scope_exit([&] {
  7689. svr.stop();
  7690. t.join();
  7691. ASSERT_FALSE(svr.is_running());
  7692. });
  7693. svr.wait_until_ready();
  7694. // Client with certificate
  7695. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7696. cli.enable_server_certificate_verification(false);
  7697. cli.set_connection_timeout(30);
  7698. auto res = cli.Get("/test");
  7699. ASSERT_TRUE(res);
  7700. ASSERT_EQ(StatusCode::OK_200, res->status);
  7701. ASSERT_TRUE(client_cert_verified);
  7702. EXPECT_EQ("success", res->body);
  7703. }
  7704. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7705. // Test that when client CA cert file is provided,
  7706. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7707. // Create a server with client authentication
  7708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7709. ASSERT_TRUE(svr.is_valid());
  7710. // We can't directly access the SSL_CTX from SSLServer to verify,
  7711. // but we can test that the server properly requests client certificates
  7712. // and accepts valid ones from the specified CA
  7713. bool handler_called = false;
  7714. svr.Get("/test", [&](const Request &req, Response &res) {
  7715. handler_called = true;
  7716. // Verify that a client certificate was provided
  7717. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7718. ASSERT_TRUE(peer_cert != nullptr);
  7719. // Get the issuer name
  7720. auto issuer_name = X509_get_issuer_name(peer_cert);
  7721. ASSERT_TRUE(issuer_name != nullptr);
  7722. char issuer_buf[256];
  7723. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7724. // The client certificate should be issued by our test CA
  7725. std::string issuer_str(issuer_buf);
  7726. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7727. X509_free(peer_cert);
  7728. res.set_content("authenticated", "text/plain");
  7729. });
  7730. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7731. auto se = detail::scope_exit([&] {
  7732. svr.stop();
  7733. t.join();
  7734. ASSERT_FALSE(svr.is_running());
  7735. });
  7736. svr.wait_until_ready();
  7737. // Connect with a client certificate issued by the CA
  7738. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7739. cli.enable_server_certificate_verification(false);
  7740. cli.set_connection_timeout(30);
  7741. auto res = cli.Get("/test");
  7742. ASSERT_TRUE(res);
  7743. ASSERT_EQ(StatusCode::OK_200, res->status);
  7744. ASSERT_TRUE(handler_called);
  7745. EXPECT_EQ("authenticated", res->body);
  7746. }
  7747. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7748. // Test 1: Valid CA file - no error should be recorded
  7749. {
  7750. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7751. CLIENT_CA_CERT_FILE);
  7752. ASSERT_TRUE(svr.is_valid());
  7753. // With valid setup, last_ssl_error should be 0
  7754. EXPECT_EQ(0, svr.ssl_last_error());
  7755. }
  7756. // Test 2: Invalid CA file content
  7757. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7758. {
  7759. // Create a temporary file with completely invalid content
  7760. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7761. {
  7762. std::ofstream ofs(temp_invalid_ca);
  7763. ofs << "This is not a certificate file at all\n";
  7764. ofs << "Just plain text content\n";
  7765. }
  7766. // Create server with invalid CA file
  7767. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7768. // Clean up temporary file
  7769. std::remove(temp_invalid_ca);
  7770. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7771. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7772. // Note: SSL_CTX_load_verify_locations typically fails first,
  7773. // but our error handling code path is still exercised
  7774. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7775. }
  7776. }
  7777. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7778. // Test SSL server using X509_STORE constructor with client CA certificates
  7779. // This test verifies that Phase 2 implementation correctly extracts CA names
  7780. // from an X509_STORE and sets them in the SSL context
  7781. // Load the CA certificate into memory
  7782. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7783. ASSERT_NE(nullptr, bio);
  7784. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7785. BIO_free(bio);
  7786. ASSERT_NE(nullptr, ca_cert);
  7787. // Create an X509_STORE and add the CA certificate
  7788. auto store = X509_STORE_new();
  7789. ASSERT_NE(nullptr, store);
  7790. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7791. // Load server certificate and private key
  7792. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7793. ASSERT_NE(nullptr, cert_bio);
  7794. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7795. BIO_free(cert_bio);
  7796. ASSERT_NE(nullptr, server_cert);
  7797. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7798. ASSERT_NE(nullptr, key_bio);
  7799. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7800. BIO_free(key_bio);
  7801. ASSERT_NE(nullptr, server_key);
  7802. // Create SSLServer with X509_STORE constructor
  7803. // Note: X509_STORE ownership is transferred to SSL_CTX
  7804. SSLServer svr(server_cert, server_key, store);
  7805. ASSERT_TRUE(svr.is_valid());
  7806. // No SSL error should be recorded for valid setup
  7807. EXPECT_EQ(0, svr.ssl_last_error());
  7808. // Set up server endpoints
  7809. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7810. res.set_content("ok", "text/plain");
  7811. });
  7812. // Start server in a thread
  7813. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7814. svr.wait_until_ready();
  7815. // Connect with client certificate (using constructor with paths)
  7816. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7817. cli.enable_server_certificate_verification(false);
  7818. auto res = cli.Get("/test-x509store");
  7819. ASSERT_TRUE(res);
  7820. EXPECT_EQ(200, res->status);
  7821. EXPECT_EQ("ok", res->body);
  7822. // Clean up
  7823. X509_free(server_cert);
  7824. EVP_PKEY_free(server_key);
  7825. X509_free(ca_cert);
  7826. svr.stop();
  7827. server_thread.join();
  7828. }
  7829. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7830. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7831. // prepare large data
  7832. std::random_device seed_gen;
  7833. std::mt19937 random(seed_gen());
  7834. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7835. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7836. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7837. // server
  7838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7839. ASSERT_TRUE(svr.is_valid());
  7840. svr.Post("/binary", [&](const Request &req, Response &res) {
  7841. EXPECT_EQ(large_size_byte, req.body.size());
  7842. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7843. res.set_content(req.body, "application/octet-stream");
  7844. });
  7845. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7846. auto se = detail::scope_exit([&] {
  7847. svr.stop();
  7848. listen_thread.join();
  7849. ASSERT_FALSE(svr.is_running());
  7850. });
  7851. svr.wait_until_ready();
  7852. // client POST
  7853. SSLClient cli("localhost", PORT);
  7854. cli.enable_server_certificate_verification(false);
  7855. cli.set_read_timeout(std::chrono::seconds(100));
  7856. cli.set_write_timeout(std::chrono::seconds(100));
  7857. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7858. large_size_byte, "application/octet-stream");
  7859. // compare
  7860. EXPECT_EQ(StatusCode::OK_200, res->status);
  7861. EXPECT_EQ(large_size_byte, res->body.size());
  7862. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7863. }
  7864. #endif
  7865. #ifdef _WIN32
  7866. TEST(CleanupTest, WSACleanup) {
  7867. int ret = WSACleanup();
  7868. ASSERT_EQ(0, ret);
  7869. }
  7870. #endif
  7871. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7872. TEST(NoSSLSupport, SimpleInterface) {
  7873. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7874. }
  7875. #endif
  7876. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7877. TEST(InvalidScheme, SimpleInterface) {
  7878. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7879. }
  7880. #endif
  7881. TEST(NoScheme, SimpleInterface) {
  7882. Client cli("yahoo.com:80");
  7883. ASSERT_TRUE(cli.is_valid());
  7884. }
  7885. TEST(SendAPI, SimpleInterface_Online) {
  7886. Client cli("http://yahoo.com");
  7887. Request req;
  7888. req.method = "GET";
  7889. req.path = "/";
  7890. auto res = cli.send(req);
  7891. ASSERT_TRUE(res);
  7892. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7893. }
  7894. TEST(SendAPI, WithParamsInRequest) {
  7895. Server svr;
  7896. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7897. EXPECT_TRUE(req.has_param("test"));
  7898. EXPECT_EQ("test_value", req.get_param_value("test"));
  7899. });
  7900. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7901. auto se = detail::scope_exit([&] {
  7902. svr.stop();
  7903. t.join();
  7904. ASSERT_FALSE(svr.is_running());
  7905. });
  7906. svr.wait_until_ready();
  7907. Client cli(HOST, PORT);
  7908. {
  7909. Request req;
  7910. req.method = "GET";
  7911. req.path = "/";
  7912. req.params.emplace("test", "test_value");
  7913. auto res = cli.send(req);
  7914. ASSERT_TRUE(res);
  7915. }
  7916. {
  7917. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7918. ASSERT_TRUE(res);
  7919. }
  7920. }
  7921. TEST(ClientImplMethods, GetSocketTest) {
  7922. httplib::Server svr;
  7923. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7924. res.status = StatusCode::OK_200;
  7925. });
  7926. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7927. auto se = detail::scope_exit([&] {
  7928. svr.stop();
  7929. thread.join();
  7930. ASSERT_FALSE(svr.is_running());
  7931. });
  7932. svr.wait_until_ready();
  7933. {
  7934. httplib::Client cli("http://127.0.0.1:3333");
  7935. cli.set_keep_alive(true);
  7936. // Use the behavior of cpp-httplib of opening the connection
  7937. // only when the first request happens. If that changes,
  7938. // this test would be obsolete.
  7939. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7940. // This also implicitly tests the server. But other tests would fail much
  7941. // earlier than this one to be considered.
  7942. auto res = cli.Get("/");
  7943. ASSERT_TRUE(res);
  7944. EXPECT_EQ(StatusCode::OK_200, res->status);
  7945. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7946. }
  7947. }
  7948. // Disabled due to out-of-memory problem on GitHub Actions
  7949. #ifdef _WIN64
  7950. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7951. // allocate content size larger than 2GB in memory
  7952. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7953. char *content = (char *)malloc(content_size);
  7954. ASSERT_TRUE(content);
  7955. Server svr;
  7956. svr.Get("/foo",
  7957. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7958. res.set_content(content, content_size, "application/octet-stream");
  7959. });
  7960. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7961. auto se = detail::scope_exit([&] {
  7962. svr.stop();
  7963. listen_thread.join();
  7964. if (content) free(content);
  7965. ASSERT_FALSE(svr.is_running());
  7966. });
  7967. svr.wait_until_ready();
  7968. Client cli(HOST, PORT);
  7969. auto res = cli.Get("/foo");
  7970. ASSERT_TRUE(res);
  7971. EXPECT_EQ(StatusCode::OK_200, res->status);
  7972. EXPECT_EQ(content_size, res->body.length());
  7973. }
  7974. #endif
  7975. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7976. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7977. Client cli("http://yahoo.com");
  7978. auto res = cli.Get("/");
  7979. ASSERT_TRUE(res);
  7980. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7981. cli.set_follow_location(true);
  7982. res = cli.Get("/");
  7983. ASSERT_TRUE(res);
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7986. }
  7987. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7988. Client cli("https://yahoo.com");
  7989. auto res = cli.Get("/");
  7990. ASSERT_TRUE(res);
  7991. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7992. cli.set_follow_location(true);
  7993. res = cli.Get("/");
  7994. ASSERT_TRUE(res);
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7997. }
  7998. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7999. Client cli("https://yahoo.com");
  8000. auto res = cli.Get("/");
  8001. ASSERT_TRUE(res);
  8002. ASSERT_FALSE(!res);
  8003. ASSERT_TRUE(res);
  8004. ASSERT_FALSE(res == nullptr);
  8005. ASSERT_TRUE(res != nullptr);
  8006. EXPECT_EQ(Error::Success, res.error());
  8007. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8008. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8009. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8010. cli.set_follow_location(true);
  8011. res = cli.Get("/");
  8012. ASSERT_TRUE(res);
  8013. EXPECT_EQ(Error::Success, res.error());
  8014. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8015. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8016. EXPECT_EQ(StatusCode::OK_200, res->status);
  8017. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8018. }
  8019. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8020. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8021. Client cli("https://cdnjs.cloudflare.com");
  8022. auto res =
  8023. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8024. ASSERT_TRUE(res);
  8025. EXPECT_EQ(StatusCode::OK_200, res->status);
  8026. EXPECT_EQ(287630U, res->body.size());
  8027. EXPECT_EQ("application/javascript; charset=utf-8",
  8028. res->get_header_value("Content-Type"));
  8029. }
  8030. #endif
  8031. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8032. #undef REDIR_HOST // Silence compiler warning
  8033. #define REDIR_HOST "https://httpbingo.org"
  8034. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8035. Client cli(REDIR_HOST);
  8036. cli.set_follow_location(true);
  8037. auto res =
  8038. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8039. ASSERT_TRUE(res);
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. }
  8042. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8043. Client cli(REDIR_HOST);
  8044. cli.set_follow_location(true);
  8045. Params params;
  8046. params.emplace("url", "http://example.com");
  8047. params.emplace("status_code", "302");
  8048. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8049. ASSERT_TRUE(res);
  8050. EXPECT_EQ(StatusCode::OK_200, res->status);
  8051. }
  8052. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8053. Client cli(REDIR_HOST);
  8054. cli.set_follow_location(true);
  8055. Params params;
  8056. params.emplace("url", "http://example.com");
  8057. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8058. ASSERT_TRUE(res);
  8059. EXPECT_EQ(StatusCode::OK_200, res->status);
  8060. }
  8061. TEST(HttpToHttpsRedirectTest, CertFile) {
  8062. Server svr;
  8063. ASSERT_TRUE(svr.is_valid());
  8064. svr.Get("/index", [&](const Request &, Response &res) {
  8065. res.set_redirect("https://127.0.0.1:1235/index");
  8066. svr.stop();
  8067. });
  8068. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8069. ASSERT_TRUE(ssl_svr.is_valid());
  8070. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8071. res.set_content("test", "text/plain");
  8072. ssl_svr.stop();
  8073. });
  8074. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8075. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8076. auto se = detail::scope_exit([&] {
  8077. t2.join();
  8078. t.join();
  8079. ASSERT_FALSE(svr.is_running());
  8080. });
  8081. svr.wait_until_ready();
  8082. ssl_svr.wait_until_ready();
  8083. Client cli("127.0.0.1", PORT);
  8084. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8085. cli.enable_server_certificate_verification(true);
  8086. cli.set_follow_location(true);
  8087. cli.set_connection_timeout(30);
  8088. auto res = cli.Get("/index");
  8089. ASSERT_TRUE(res);
  8090. ASSERT_EQ(StatusCode::OK_200, res->status);
  8091. }
  8092. TEST(SSLClientRedirectTest, CertFile) {
  8093. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8094. ASSERT_TRUE(ssl_svr1.is_valid());
  8095. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8096. res.set_redirect("https://127.0.0.1:1235/index");
  8097. ssl_svr1.stop();
  8098. });
  8099. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8100. ASSERT_TRUE(ssl_svr2.is_valid());
  8101. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8102. res.set_content("test", "text/plain");
  8103. ssl_svr2.stop();
  8104. });
  8105. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8106. thread t2 =
  8107. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8108. auto se = detail::scope_exit([&] {
  8109. t2.join();
  8110. t.join();
  8111. ASSERT_FALSE(ssl_svr1.is_running());
  8112. });
  8113. ssl_svr1.wait_until_ready();
  8114. ssl_svr2.wait_until_ready();
  8115. SSLClient cli("127.0.0.1", PORT);
  8116. std::string cert;
  8117. read_file(SERVER_CERT2_FILE, cert);
  8118. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8119. cli.enable_server_certificate_verification(true);
  8120. cli.set_follow_location(true);
  8121. cli.set_connection_timeout(30);
  8122. auto res = cli.Get("/index");
  8123. ASSERT_TRUE(res);
  8124. ASSERT_EQ(StatusCode::OK_200, res->status);
  8125. }
  8126. // Test that set_ca_cert_store() skips system certs (consistent with
  8127. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  8128. // should be trusted - system certs should NOT be loaded.
  8129. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  8130. // Load a specific cert that is NOT a system CA cert
  8131. std::string cert;
  8132. read_file(SERVER_CERT2_FILE, cert);
  8133. SSLClient cli("google.com");
  8134. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8135. cli.enable_server_certificate_verification(true);
  8136. // This should FAIL because:
  8137. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  8138. // 2. System certs should NOT be loaded when custom store is set
  8139. // If system certs WERE loaded, this would succeed
  8140. auto res = cli.Get("/");
  8141. ASSERT_FALSE(res);
  8142. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8143. }
  8144. TEST(MultipartFormDataTest, LargeData) {
  8145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8146. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8147. const ContentReader &content_reader) {
  8148. if (req.is_multipart_form_data()) {
  8149. std::vector<FormData> items;
  8150. content_reader(
  8151. [&](const FormData &file) {
  8152. items.push_back(file);
  8153. return true;
  8154. },
  8155. [&](const char *data, size_t data_length) {
  8156. items.back().content.append(data, data_length);
  8157. return true;
  8158. });
  8159. EXPECT_TRUE(std::string(items[0].name) == "document");
  8160. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8161. EXPECT_TRUE(items[0].filename == "2MB_data");
  8162. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8163. EXPECT_TRUE(items[1].name == "hello");
  8164. EXPECT_TRUE(items[1].content == "world");
  8165. EXPECT_TRUE(items[1].filename == "");
  8166. EXPECT_TRUE(items[1].content_type == "");
  8167. } else {
  8168. std::string body;
  8169. content_reader([&](const char *data, size_t data_length) {
  8170. body.append(data, data_length);
  8171. return true;
  8172. });
  8173. }
  8174. });
  8175. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8176. auto se = detail::scope_exit([&] {
  8177. svr.stop();
  8178. t.join();
  8179. ASSERT_FALSE(svr.is_running());
  8180. });
  8181. svr.wait_until_ready();
  8182. {
  8183. std::string data(1024 * 1024 * 2, '.');
  8184. std::stringstream buffer;
  8185. buffer << data;
  8186. Client cli("https://localhost:8080");
  8187. cli.enable_server_certificate_verification(false);
  8188. UploadFormDataItems items{
  8189. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8190. {"hello", "world", "", ""},
  8191. };
  8192. auto res = cli.Post("/post", items);
  8193. ASSERT_TRUE(res);
  8194. ASSERT_EQ(StatusCode::OK_200, res->status);
  8195. }
  8196. }
  8197. TEST(MultipartFormDataTest, DataProviderItems) {
  8198. std::random_device seed_gen;
  8199. std::mt19937 random(seed_gen());
  8200. std::string rand1;
  8201. rand1.resize(1000);
  8202. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8203. std::string rand2;
  8204. rand2.resize(3000);
  8205. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8207. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8208. const ContentReader &content_reader) {
  8209. ASSERT_FALSE(req.is_multipart_form_data());
  8210. std::string body;
  8211. content_reader([&](const char *data, size_t data_length) {
  8212. body.append(data, data_length);
  8213. return true;
  8214. });
  8215. EXPECT_EQ(body, "");
  8216. });
  8217. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8218. const ContentReader &content_reader) {
  8219. ASSERT_TRUE(req.is_multipart_form_data());
  8220. std::vector<FormData> items;
  8221. content_reader(
  8222. [&](const FormData &file) {
  8223. items.push_back(file);
  8224. return true;
  8225. },
  8226. [&](const char *data, size_t data_length) {
  8227. items.back().content.append(data, data_length);
  8228. return true;
  8229. });
  8230. ASSERT_TRUE(items.size() == 2);
  8231. EXPECT_EQ(std::string(items[0].name), "name1");
  8232. EXPECT_EQ(items[0].content, "Testing123");
  8233. EXPECT_EQ(items[0].filename, "filename1");
  8234. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8235. EXPECT_EQ(items[1].name, "name2");
  8236. EXPECT_EQ(items[1].content, "Testing456");
  8237. EXPECT_EQ(items[1].filename, "");
  8238. EXPECT_EQ(items[1].content_type, "");
  8239. });
  8240. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8241. const ContentReader &content_reader) {
  8242. ASSERT_TRUE(req.is_multipart_form_data());
  8243. std::vector<FormData> items;
  8244. content_reader(
  8245. [&](const FormData &file) {
  8246. items.push_back(file);
  8247. return true;
  8248. },
  8249. [&](const char *data, size_t data_length) {
  8250. items.back().content.append(data, data_length);
  8251. return true;
  8252. });
  8253. ASSERT_TRUE(items.size() == 2);
  8254. EXPECT_EQ(items[0].name, "name3");
  8255. EXPECT_EQ(items[0].content, rand1);
  8256. EXPECT_EQ(items[0].filename, "filename3");
  8257. EXPECT_EQ(items[0].content_type, "");
  8258. EXPECT_EQ(items[1].name, "name4");
  8259. EXPECT_EQ(items[1].content, rand2);
  8260. EXPECT_EQ(items[1].filename, "filename4");
  8261. EXPECT_EQ(items[1].content_type, "");
  8262. });
  8263. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8264. const ContentReader &content_reader) {
  8265. ASSERT_TRUE(req.is_multipart_form_data());
  8266. std::vector<FormData> items;
  8267. content_reader(
  8268. [&](const FormData &file) {
  8269. items.push_back(file);
  8270. return true;
  8271. },
  8272. [&](const char *data, size_t data_length) {
  8273. items.back().content.append(data, data_length);
  8274. return true;
  8275. });
  8276. ASSERT_TRUE(items.size() == 4);
  8277. EXPECT_EQ(std::string(items[0].name), "name1");
  8278. EXPECT_EQ(items[0].content, "Testing123");
  8279. EXPECT_EQ(items[0].filename, "filename1");
  8280. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8281. EXPECT_EQ(items[1].name, "name2");
  8282. EXPECT_EQ(items[1].content, "Testing456");
  8283. EXPECT_EQ(items[1].filename, "");
  8284. EXPECT_EQ(items[1].content_type, "");
  8285. EXPECT_EQ(items[2].name, "name3");
  8286. EXPECT_EQ(items[2].content, rand1);
  8287. EXPECT_EQ(items[2].filename, "filename3");
  8288. EXPECT_EQ(items[2].content_type, "");
  8289. EXPECT_EQ(items[3].name, "name4");
  8290. EXPECT_EQ(items[3].content, rand2);
  8291. EXPECT_EQ(items[3].filename, "filename4");
  8292. EXPECT_EQ(items[3].content_type, "");
  8293. });
  8294. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8295. auto se = detail::scope_exit([&] {
  8296. svr.stop();
  8297. t.join();
  8298. ASSERT_FALSE(svr.is_running());
  8299. });
  8300. svr.wait_until_ready();
  8301. {
  8302. Client cli("https://localhost:8080");
  8303. cli.enable_server_certificate_verification(false);
  8304. UploadFormDataItems items{
  8305. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8306. {"name2", "Testing456", "", ""}, // not a file
  8307. };
  8308. {
  8309. auto res = cli.Post("/post-none", {}, {}, {});
  8310. ASSERT_TRUE(res);
  8311. ASSERT_EQ(StatusCode::OK_200, res->status);
  8312. }
  8313. FormDataProviderItems providers;
  8314. {
  8315. auto res =
  8316. cli.Post("/post-items", {}, items, providers); // empty providers
  8317. ASSERT_TRUE(res);
  8318. ASSERT_EQ(StatusCode::OK_200, res->status);
  8319. }
  8320. providers.push_back({"name3",
  8321. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8322. // test the offset is given correctly at each step
  8323. if (!offset)
  8324. sink.os.write(rand1.data(), 30);
  8325. else if (offset == 30)
  8326. sink.os.write(rand1.data() + 30, 300);
  8327. else if (offset == 330)
  8328. sink.os.write(rand1.data() + 330, 670);
  8329. else if (offset == rand1.size())
  8330. sink.done();
  8331. return true;
  8332. },
  8333. "filename3",
  8334. {}});
  8335. providers.push_back({"name4",
  8336. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8337. // test the offset is given correctly at each step
  8338. if (!offset)
  8339. sink.os.write(rand2.data(), 2000);
  8340. else if (offset == 2000)
  8341. sink.os.write(rand2.data() + 2000, 1);
  8342. else if (offset == 2001)
  8343. sink.os.write(rand2.data() + 2001, 999);
  8344. else if (offset == rand2.size())
  8345. sink.done();
  8346. return true;
  8347. },
  8348. "filename4",
  8349. {}});
  8350. {
  8351. auto res = cli.Post("/post-providers", {}, {}, providers);
  8352. ASSERT_TRUE(res);
  8353. ASSERT_EQ(StatusCode::OK_200, res->status);
  8354. }
  8355. {
  8356. auto res = cli.Post("/post-both", {}, items, providers);
  8357. ASSERT_TRUE(res);
  8358. ASSERT_EQ(StatusCode::OK_200, res->status);
  8359. }
  8360. }
  8361. }
  8362. TEST(MultipartFormDataTest, BadHeader) {
  8363. Server svr;
  8364. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8365. res.set_content("ok", "text/plain");
  8366. });
  8367. thread t = thread([&] { svr.listen(HOST, PORT); });
  8368. auto se = detail::scope_exit([&] {
  8369. svr.stop();
  8370. t.join();
  8371. ASSERT_FALSE(svr.is_running());
  8372. });
  8373. svr.wait_until_ready();
  8374. const std::string body =
  8375. "This is the preamble. It is to be ignored, though it\r\n"
  8376. "is a handy place for composition agents to include an\r\n"
  8377. "explanatory note to non-MIME conformant readers.\r\n"
  8378. "\r\n"
  8379. "\r\n"
  8380. "--simple boundary\r\n"
  8381. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8382. ": BAD...\r\n"
  8383. "\r\n"
  8384. "value1\r\n"
  8385. "--simple boundary\r\n"
  8386. "Content-Disposition: form-data; name=\"field2\"; "
  8387. "filename=\"example.txt\"\r\n"
  8388. "\r\n"
  8389. "value2\r\n"
  8390. "--simple boundary--\r\n"
  8391. "This is the epilogue. It is also to be ignored.\r\n";
  8392. std::string content_type =
  8393. R"(multipart/form-data; boundary="simple boundary")";
  8394. Client cli(HOST, PORT);
  8395. auto res = cli.Post("/post", body, content_type.c_str());
  8396. ASSERT_TRUE(res);
  8397. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8398. }
  8399. TEST(MultipartFormDataTest, WithPreamble) {
  8400. Server svr;
  8401. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8402. res.set_content("ok", "text/plain");
  8403. });
  8404. thread t = thread([&] { svr.listen(HOST, PORT); });
  8405. auto se = detail::scope_exit([&] {
  8406. svr.stop();
  8407. t.join();
  8408. ASSERT_FALSE(svr.is_running());
  8409. });
  8410. svr.wait_until_ready();
  8411. const std::string body =
  8412. "This is the preamble. It is to be ignored, though it\r\n"
  8413. "is a handy place for composition agents to include an\r\n"
  8414. "explanatory note to non-MIME conformant readers.\r\n"
  8415. "\r\n"
  8416. "\r\n"
  8417. "--simple boundary\r\n"
  8418. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8419. "\r\n"
  8420. "value1\r\n"
  8421. "--simple boundary\r\n"
  8422. "Content-Disposition: form-data; name=\"field2\"; "
  8423. "filename=\"example.txt\"\r\n"
  8424. "\r\n"
  8425. "value2\r\n"
  8426. "--simple boundary--\r\n"
  8427. "This is the epilogue. It is also to be ignored.\r\n";
  8428. std::string content_type =
  8429. R"(multipart/form-data; boundary="simple boundary")";
  8430. Client cli(HOST, PORT);
  8431. auto res = cli.Post("/post", body, content_type.c_str());
  8432. ASSERT_TRUE(res);
  8433. EXPECT_EQ(StatusCode::OK_200, res->status);
  8434. }
  8435. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8437. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8438. const ContentReader &content_reader) {
  8439. if (req.is_multipart_form_data()) {
  8440. std::vector<FormData> items;
  8441. content_reader(
  8442. [&](const FormData &file) {
  8443. items.push_back(file);
  8444. return true;
  8445. },
  8446. [&](const char *data, size_t data_length) {
  8447. items.back().content.append(data, data_length);
  8448. return true;
  8449. });
  8450. EXPECT_TRUE(std::string(items[0].name) == "document");
  8451. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8452. EXPECT_TRUE(items[0].filename == "2MB_data");
  8453. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8454. EXPECT_TRUE(items[1].name == "hello");
  8455. EXPECT_TRUE(items[1].content == "world");
  8456. EXPECT_TRUE(items[1].filename == "");
  8457. EXPECT_TRUE(items[1].content_type == "");
  8458. } else {
  8459. std::string body;
  8460. content_reader([&](const char *data, size_t data_length) {
  8461. body.append(data, data_length);
  8462. return true;
  8463. });
  8464. }
  8465. });
  8466. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8467. auto se = detail::scope_exit([&] {
  8468. svr.stop();
  8469. t.join();
  8470. ASSERT_FALSE(svr.is_running());
  8471. });
  8472. svr.wait_until_ready();
  8473. {
  8474. std::string data(1024 * 1024 * 2, '.');
  8475. std::stringstream buffer;
  8476. buffer << data;
  8477. Client cli("https://localhost:8080");
  8478. cli.enable_server_certificate_verification(false);
  8479. UploadFormDataItems items{
  8480. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8481. {"hello", "world", "", ""},
  8482. };
  8483. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8484. ASSERT_TRUE(res);
  8485. ASSERT_EQ(StatusCode::OK_200, res->status);
  8486. }
  8487. }
  8488. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8489. std::string data(1024 * 1024 * 2, '&');
  8490. std::stringstream buffer;
  8491. buffer << data;
  8492. Client cli("https://localhost:8080");
  8493. UploadFormDataItems items{
  8494. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8495. {"hello", "world", "", ""},
  8496. };
  8497. for (const char &c : " \t\r\n") {
  8498. auto res =
  8499. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8500. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8501. ASSERT_FALSE(res);
  8502. }
  8503. }
  8504. TEST(MultipartFormDataTest, PutFormData) {
  8505. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8506. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8507. const ContentReader &content_reader) {
  8508. if (req.is_multipart_form_data()) {
  8509. std::vector<FormData> items;
  8510. content_reader(
  8511. [&](const FormData &file) {
  8512. items.push_back(file);
  8513. return true;
  8514. },
  8515. [&](const char *data, size_t data_length) {
  8516. items.back().content.append(data, data_length);
  8517. return true;
  8518. });
  8519. EXPECT_TRUE(std::string(items[0].name) == "document");
  8520. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8521. EXPECT_TRUE(items[0].filename == "2MB_data");
  8522. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8523. EXPECT_TRUE(items[1].name == "hello");
  8524. EXPECT_TRUE(items[1].content == "world");
  8525. EXPECT_TRUE(items[1].filename == "");
  8526. EXPECT_TRUE(items[1].content_type == "");
  8527. } else {
  8528. std::string body;
  8529. content_reader([&](const char *data, size_t data_length) {
  8530. body.append(data, data_length);
  8531. return true;
  8532. });
  8533. }
  8534. });
  8535. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8536. auto se = detail::scope_exit([&] {
  8537. svr.stop();
  8538. t.join();
  8539. ASSERT_FALSE(svr.is_running());
  8540. });
  8541. svr.wait_until_ready();
  8542. {
  8543. std::string data(1024 * 1024 * 2, '&');
  8544. std::stringstream buffer;
  8545. buffer << data;
  8546. Client cli("https://localhost:8080");
  8547. cli.enable_server_certificate_verification(false);
  8548. UploadFormDataItems items{
  8549. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8550. {"hello", "world", "", ""},
  8551. };
  8552. auto res = cli.Put("/put", items);
  8553. ASSERT_TRUE(res);
  8554. ASSERT_EQ(StatusCode::OK_200, res->status);
  8555. }
  8556. }
  8557. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8558. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8559. svr.Put("/put_customboundary",
  8560. [&](const Request &req, const Response & /*res*/,
  8561. const ContentReader &content_reader) {
  8562. if (req.is_multipart_form_data()) {
  8563. std::vector<FormData> items;
  8564. content_reader(
  8565. [&](const FormData &file) {
  8566. items.push_back(file);
  8567. return true;
  8568. },
  8569. [&](const char *data, size_t data_length) {
  8570. items.back().content.append(data, data_length);
  8571. return true;
  8572. });
  8573. EXPECT_TRUE(std::string(items[0].name) == "document");
  8574. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8575. EXPECT_TRUE(items[0].filename == "2MB_data");
  8576. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8577. EXPECT_TRUE(items[1].name == "hello");
  8578. EXPECT_TRUE(items[1].content == "world");
  8579. EXPECT_TRUE(items[1].filename == "");
  8580. EXPECT_TRUE(items[1].content_type == "");
  8581. } else {
  8582. std::string body;
  8583. content_reader([&](const char *data, size_t data_length) {
  8584. body.append(data, data_length);
  8585. return true;
  8586. });
  8587. }
  8588. });
  8589. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8590. auto se = detail::scope_exit([&] {
  8591. svr.stop();
  8592. t.join();
  8593. ASSERT_FALSE(svr.is_running());
  8594. });
  8595. svr.wait_until_ready();
  8596. {
  8597. std::string data(1024 * 1024 * 2, '&');
  8598. std::stringstream buffer;
  8599. buffer << data;
  8600. Client cli("https://localhost:8080");
  8601. cli.enable_server_certificate_verification(false);
  8602. UploadFormDataItems items{
  8603. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8604. {"hello", "world", "", ""},
  8605. };
  8606. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8607. ASSERT_TRUE(res);
  8608. ASSERT_EQ(StatusCode::OK_200, res->status);
  8609. }
  8610. }
  8611. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8612. std::string data(1024 * 1024 * 2, '&');
  8613. std::stringstream buffer;
  8614. buffer << data;
  8615. Client cli("https://localhost:8080");
  8616. cli.enable_server_certificate_verification(false);
  8617. UploadFormDataItems items{
  8618. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8619. {"hello", "world", "", ""},
  8620. };
  8621. for (const char &c : " \t\r\n") {
  8622. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8623. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8624. ASSERT_FALSE(res);
  8625. }
  8626. }
  8627. TEST(MultipartFormDataTest, AlternateFilename) {
  8628. auto handled = false;
  8629. Server svr;
  8630. svr.Post("/test", [&](const Request &req, Response &res) {
  8631. ASSERT_EQ(2u, req.form.files.size());
  8632. ASSERT_EQ(1u, req.form.fields.size());
  8633. // Test files
  8634. const auto &file1 = req.form.get_file("file1");
  8635. ASSERT_EQ("file1", file1.name);
  8636. ASSERT_EQ("A.txt", file1.filename);
  8637. ASSERT_EQ("text/plain", file1.content_type);
  8638. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8639. const auto &file2 = req.form.get_file("file2");
  8640. ASSERT_EQ("file2", file2.name);
  8641. ASSERT_EQ("a.html", file2.filename);
  8642. ASSERT_EQ("text/html", file2.content_type);
  8643. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8644. file2.content);
  8645. // Test text field
  8646. const auto &text = req.form.get_field("text");
  8647. ASSERT_EQ("text default", text);
  8648. res.set_content("ok", "text/plain");
  8649. handled = true;
  8650. });
  8651. thread t = thread([&] { svr.listen(HOST, PORT); });
  8652. auto se = detail::scope_exit([&] {
  8653. svr.stop();
  8654. t.join();
  8655. ASSERT_FALSE(svr.is_running());
  8656. ASSERT_TRUE(handled);
  8657. });
  8658. svr.wait_until_ready();
  8659. auto req = "POST /test HTTP/1.1\r\n"
  8660. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8661. "Content-Length: 399\r\n"
  8662. "\r\n"
  8663. "----------\r\n"
  8664. "Content-Disposition: form-data; name=\"text\"\r\n"
  8665. "\r\n"
  8666. "text default\r\n"
  8667. "----------\r\n"
  8668. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8669. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8670. "Content-Type: text/plain\r\n"
  8671. "\r\n"
  8672. "Content of a.txt.\r\n"
  8673. "\r\n"
  8674. "----------\r\n"
  8675. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8676. "\"a.html\"\r\n"
  8677. "Content-Type: text/html\r\n"
  8678. "\r\n"
  8679. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8680. "\r\n"
  8681. "------------\r\n";
  8682. ASSERT_TRUE(send_request(1, req));
  8683. }
  8684. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8685. auto handled = false;
  8686. Server svr;
  8687. svr.Post("/test", [&](const Request &req, Response &) {
  8688. ASSERT_EQ(2u, req.form.fields.size());
  8689. const auto &text1 = req.form.get_field("text1");
  8690. ASSERT_EQ("text1", text1);
  8691. const auto &text2 = req.form.get_field("text2");
  8692. ASSERT_EQ("text2", text2);
  8693. handled = true;
  8694. });
  8695. thread t = thread([&] { svr.listen(HOST, PORT); });
  8696. auto se = detail::scope_exit([&] {
  8697. svr.stop();
  8698. t.join();
  8699. ASSERT_FALSE(svr.is_running());
  8700. ASSERT_TRUE(handled);
  8701. });
  8702. svr.wait_until_ready();
  8703. auto req = "POST /test HTTP/1.1\r\n"
  8704. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8705. "Content-Length: 146\r\n"
  8706. "\r\n----------\r\n"
  8707. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8708. "\r\n"
  8709. "text1"
  8710. "\r\n----------\r\n"
  8711. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8712. "\r\n"
  8713. "text2"
  8714. "\r\n------------";
  8715. std::string response;
  8716. ASSERT_TRUE(send_request(1, req, &response));
  8717. ASSERT_EQ("200", response.substr(9, 3));
  8718. }
  8719. TEST(MultipartFormDataTest, ContentLength) {
  8720. auto handled = false;
  8721. Server svr;
  8722. svr.Post("/test", [&](const Request &req, Response &) {
  8723. ASSERT_EQ(2u, req.form.fields.size());
  8724. const auto &text1 = req.form.get_field("text1");
  8725. ASSERT_EQ("text1", text1);
  8726. const auto &text2 = req.form.get_field("text2");
  8727. ASSERT_EQ("text2", text2);
  8728. handled = true;
  8729. });
  8730. thread t = thread([&] { svr.listen(HOST, PORT); });
  8731. auto se = detail::scope_exit([&] {
  8732. svr.stop();
  8733. t.join();
  8734. ASSERT_FALSE(svr.is_running());
  8735. ASSERT_TRUE(handled);
  8736. });
  8737. svr.wait_until_ready();
  8738. auto req = "POST /test HTTP/1.1\r\n"
  8739. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8740. "Content-Length: 167\r\n"
  8741. "\r\n----------\r\n"
  8742. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8743. "Content-Length: 5\r\n"
  8744. "\r\n"
  8745. "text1"
  8746. "\r\n----------\r\n"
  8747. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8748. "\r\n"
  8749. "text2"
  8750. "\r\n------------\r\n";
  8751. std::string response;
  8752. ASSERT_TRUE(send_request(1, req, &response));
  8753. ASSERT_EQ("200", response.substr(9, 3));
  8754. }
  8755. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8756. auto handled = false;
  8757. Server svr;
  8758. svr.Post("/test", [&](const Request &req, Response &) {
  8759. ASSERT_EQ(2u, req.form.fields.size());
  8760. const auto &text1 = req.form.get_field("text1");
  8761. ASSERT_EQ("text1", text1);
  8762. // TODO: Add header access for text fields if needed
  8763. const auto &text2 = req.form.get_field("text2");
  8764. ASSERT_EQ("text2", text2);
  8765. // TODO: Header access for text fields needs to be implemented
  8766. // auto &headers = it->second.headers;
  8767. // ASSERT_EQ(3U, headers.size());
  8768. // auto custom_header = headers.find("x-whatever");
  8769. // ASSERT_TRUE(custom_header != headers.end());
  8770. // ASSERT_NE("customvalue", custom_header->second);
  8771. // ASSERT_EQ("CustomValue", custom_header->second);
  8772. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8773. handled = true;
  8774. });
  8775. thread t = thread([&] { svr.listen(HOST, PORT); });
  8776. auto se = detail::scope_exit([&] {
  8777. svr.stop();
  8778. t.join();
  8779. ASSERT_FALSE(svr.is_running());
  8780. ASSERT_TRUE(handled);
  8781. });
  8782. svr.wait_until_ready();
  8783. auto req = "POST /test HTTP/1.1\r\n"
  8784. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8785. "Content-Length: 232\r\n"
  8786. "\r\n----------\r\n"
  8787. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8788. "Content-Length: 5\r\n"
  8789. "X-Test: 1\r\n"
  8790. "\r\n"
  8791. "text1"
  8792. "\r\n----------\r\n"
  8793. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8794. "Content-Type: text/plain\r\n"
  8795. "X-Whatever: CustomValue\r\n"
  8796. "\r\n"
  8797. "text2"
  8798. "\r\n------------\r\n"
  8799. "That should be disregarded. Not even read";
  8800. std::string response;
  8801. ASSERT_TRUE(send_request(1, req, &response));
  8802. ASSERT_EQ("200", response.substr(9, 3));
  8803. }
  8804. #endif
  8805. TEST(MultipartFormDataTest, LargeHeader) {
  8806. auto handled = false;
  8807. Server svr;
  8808. svr.Post("/test", [&](const Request &req, Response &) {
  8809. ASSERT_EQ(1u, req.form.fields.size());
  8810. const auto &text = req.form.get_field("name1");
  8811. ASSERT_EQ("text1", text);
  8812. handled = true;
  8813. });
  8814. thread t = thread([&] { svr.listen(HOST, PORT); });
  8815. auto se = detail::scope_exit([&] {
  8816. svr.stop();
  8817. t.join();
  8818. ASSERT_FALSE(svr.is_running());
  8819. ASSERT_TRUE(handled);
  8820. });
  8821. svr.wait_until_ready();
  8822. auto boundary = std::string("cpp-httplib-multipart-data");
  8823. std::string content = "--" + boundary +
  8824. "\r\n"
  8825. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8826. "\r\n"
  8827. "text1\r\n"
  8828. "--" +
  8829. boundary + "--\r\n";
  8830. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8831. "Content-Type: multipart/form-data;boundary=" +
  8832. boundary +
  8833. "\r\n"
  8834. "Content-Length: " +
  8835. std::to_string(content.size()) +
  8836. "\r\n"
  8837. "Dummy-Header: ";
  8838. std::string header_suffix = "\r\n"
  8839. "\r\n";
  8840. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8841. size_t header_dummy_size =
  8842. read_buff_size -
  8843. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8844. auto header_dummy = std::string(header_dummy_size, '@');
  8845. auto req = header_prefix + header_dummy + header_suffix + content;
  8846. std::string response;
  8847. ASSERT_TRUE(send_request(1, req, &response));
  8848. ASSERT_EQ("200", response.substr(9, 3));
  8849. }
  8850. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8851. static constexpr unsigned int number_of_tasks{1000000};
  8852. std::atomic_uint count{0};
  8853. std::unique_ptr<TaskQueue> task_queue{
  8854. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8855. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8856. auto queued = task_queue->enqueue(
  8857. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8858. EXPECT_TRUE(queued);
  8859. }
  8860. EXPECT_NO_THROW(task_queue->shutdown());
  8861. EXPECT_EQ(number_of_tasks, count.load());
  8862. }
  8863. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8864. static constexpr unsigned int number_of_tasks{1000000};
  8865. static constexpr unsigned int qlimit{2};
  8866. unsigned int queued_count{0};
  8867. std::atomic_uint count{0};
  8868. std::unique_ptr<TaskQueue> task_queue{
  8869. new ThreadPool{/*num_threads=*/1, qlimit}};
  8870. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8871. if (task_queue->enqueue(
  8872. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8873. queued_count++;
  8874. }
  8875. }
  8876. EXPECT_NO_THROW(task_queue->shutdown());
  8877. EXPECT_EQ(queued_count, count.load());
  8878. EXPECT_TRUE(queued_count <= number_of_tasks);
  8879. EXPECT_TRUE(queued_count >= qlimit);
  8880. }
  8881. TEST(TaskQueueTest, MaxQueuedRequests) {
  8882. static constexpr unsigned int qlimit{3};
  8883. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8884. std::condition_variable sem_cv;
  8885. std::mutex sem_mtx;
  8886. int credits = 0;
  8887. bool queued;
  8888. /* Fill up the queue with tasks that will block until we give them credits to
  8889. * complete. */
  8890. for (unsigned int n = 0; n <= qlimit;) {
  8891. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8892. std::unique_lock<std::mutex> lock(sem_mtx);
  8893. while (credits <= 0) {
  8894. sem_cv.wait(lock);
  8895. }
  8896. /* Consume the credit and signal the test code if they are all gone. */
  8897. if (--credits == 0) { sem_cv.notify_one(); }
  8898. });
  8899. if (n < qlimit) {
  8900. /* The first qlimit enqueues must succeed. */
  8901. EXPECT_TRUE(queued);
  8902. } else {
  8903. /* The last one will succeed only when the worker thread
  8904. * starts and dequeues the first blocking task. Although
  8905. * not necessary for the correctness of this test, we sleep for
  8906. * a short while to avoid busy waiting. */
  8907. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8908. }
  8909. if (queued) { n++; }
  8910. }
  8911. /* Further enqueues must fail since the queue is full. */
  8912. for (auto i = 0; i < 4; i++) {
  8913. queued = task_queue->enqueue([] {});
  8914. EXPECT_FALSE(queued);
  8915. }
  8916. /* Give the credits to allow the previous tasks to complete. */
  8917. {
  8918. std::unique_lock<std::mutex> lock(sem_mtx);
  8919. credits += qlimit + 1;
  8920. }
  8921. sem_cv.notify_all();
  8922. /* Wait for all the credits to be consumed. */
  8923. {
  8924. std::unique_lock<std::mutex> lock(sem_mtx);
  8925. while (credits > 0) {
  8926. sem_cv.wait(lock);
  8927. }
  8928. }
  8929. /* Check that we are able again to enqueue at least qlimit tasks. */
  8930. for (unsigned int i = 0; i < qlimit; i++) {
  8931. queued = task_queue->enqueue([] {});
  8932. EXPECT_TRUE(queued);
  8933. }
  8934. EXPECT_NO_THROW(task_queue->shutdown());
  8935. }
  8936. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8937. Server svr;
  8938. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8939. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8940. });
  8941. svr.Get("/hello", [](const Request &req, Response &res) {
  8942. res.set_content(req.get_param_value("key"), "text/plain");
  8943. });
  8944. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8945. auto se = detail::scope_exit([&] {
  8946. svr.stop();
  8947. thread.join();
  8948. ASSERT_FALSE(svr.is_running());
  8949. });
  8950. svr.wait_until_ready();
  8951. {
  8952. Client cli(HOST, PORT);
  8953. cli.set_follow_location(true);
  8954. auto res = cli.Get("/");
  8955. ASSERT_TRUE(res);
  8956. EXPECT_EQ(StatusCode::OK_200, res->status);
  8957. EXPECT_EQ("val&key2=val2", res->body);
  8958. }
  8959. }
  8960. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8961. Server svr;
  8962. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8963. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8964. });
  8965. svr.Get("/hello", [](const Request &req, Response &res) {
  8966. res.set_content(req.get_param_value("key"), "text/plain");
  8967. });
  8968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8969. auto se = detail::scope_exit([&] {
  8970. svr.stop();
  8971. thread.join();
  8972. ASSERT_FALSE(svr.is_running());
  8973. });
  8974. svr.wait_until_ready();
  8975. {
  8976. Client cli(HOST, PORT);
  8977. cli.set_follow_location(true);
  8978. auto res = cli.Get("/");
  8979. ASSERT_TRUE(res);
  8980. EXPECT_EQ(StatusCode::OK_200, res->status);
  8981. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8982. }
  8983. }
  8984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8985. TEST(RedirectTest, Issue2185_Online) {
  8986. SSLClient client("github.com");
  8987. client.set_follow_location(true);
  8988. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8989. "Coollab-Windows.zip");
  8990. ASSERT_TRUE(res);
  8991. EXPECT_EQ(StatusCode::OK_200, res->status);
  8992. EXPECT_EQ(9920427U, res->body.size());
  8993. }
  8994. #endif
  8995. TEST(VulnerabilityTest, CRLFInjection) {
  8996. Server svr;
  8997. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8998. res.set_content("Hello 1", "text/plain");
  8999. });
  9000. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9001. res.set_content("Hello 2", "text/plain");
  9002. });
  9003. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9004. res.set_content("Hello 3", "text/plain");
  9005. });
  9006. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9007. res.set_content("Hello 4", "text/plain");
  9008. });
  9009. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9010. for (const auto &x : req.headers) {
  9011. auto key = x.first;
  9012. EXPECT_STRNE("evil", key.c_str());
  9013. }
  9014. });
  9015. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9016. auto se = detail::scope_exit([&] {
  9017. svr.stop();
  9018. thread.join();
  9019. ASSERT_FALSE(svr.is_running());
  9020. });
  9021. svr.wait_until_ready();
  9022. {
  9023. Client cli(HOST, PORT);
  9024. cli.Post("/test1", "A=B",
  9025. "application/x-www-form-urlencoded\r\nevil: hello1");
  9026. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9027. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9028. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9029. }
  9030. }
  9031. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9032. auto server_thread = std::thread([] {
  9033. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9034. default_socket_options(srv);
  9035. sockaddr_in addr{};
  9036. addr.sin_family = AF_INET;
  9037. addr.sin_port = htons(PORT + 1);
  9038. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9039. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9040. ::listen(srv, 1);
  9041. sockaddr_in cli_addr{};
  9042. socklen_t cli_len = sizeof(cli_addr);
  9043. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9044. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9045. std::string buf_all;
  9046. char buf[2048];
  9047. ssize_t n;
  9048. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9049. buf_all.append(buf, static_cast<size_t>(n));
  9050. size_t pos;
  9051. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9052. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9053. auto e = request_block.find("\r\n");
  9054. if (e != std::string::npos) {
  9055. auto request_line = request_block.substr(0, e);
  9056. std::string msg =
  9057. "CRLF injection detected in request line: '" + request_line + "'";
  9058. EXPECT_FALSE(true) << msg;
  9059. }
  9060. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9061. ::send(cli,
  9062. #ifdef _WIN32
  9063. static_cast<const char *>(resp.c_str()),
  9064. static_cast<int>(resp.size()),
  9065. #else
  9066. resp.c_str(), resp.size(),
  9067. #endif
  9068. 0);
  9069. buf_all.erase(0, pos + 4);
  9070. }
  9071. }
  9072. detail::close_socket(cli);
  9073. detail::close_socket(srv);
  9074. });
  9075. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9076. auto cli = Client("127.0.0.1", PORT + 1);
  9077. auto headers = Headers{
  9078. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9079. {"Connection", "keep-alive"}};
  9080. auto res = cli.Get("/hi", headers);
  9081. EXPECT_FALSE(res);
  9082. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9083. server_thread.join();
  9084. }
  9085. TEST(PathParamsTest, StaticMatch) {
  9086. const auto pattern = "/users/all";
  9087. detail::PathParamsMatcher matcher(pattern);
  9088. Request request;
  9089. request.path = "/users/all";
  9090. ASSERT_TRUE(matcher.match(request));
  9091. std::unordered_map<std::string, std::string> expected_params = {};
  9092. EXPECT_EQ(request.path_params, expected_params);
  9093. }
  9094. TEST(PathParamsTest, StaticMismatch) {
  9095. const auto pattern = "/users/all";
  9096. detail::PathParamsMatcher matcher(pattern);
  9097. Request request;
  9098. request.path = "/users/1";
  9099. ASSERT_FALSE(matcher.match(request));
  9100. }
  9101. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9102. const auto pattern = "/users/:id/subscriptions";
  9103. detail::PathParamsMatcher matcher(pattern);
  9104. Request request;
  9105. request.path = "/users/42/subscriptions";
  9106. ASSERT_TRUE(matcher.match(request));
  9107. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9108. EXPECT_EQ(request.path_params, expected_params);
  9109. }
  9110. TEST(PathParamsTest, SingleParamInTheEnd) {
  9111. const auto pattern = "/users/:id";
  9112. detail::PathParamsMatcher matcher(pattern);
  9113. Request request;
  9114. request.path = "/users/24";
  9115. ASSERT_TRUE(matcher.match(request));
  9116. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9117. EXPECT_EQ(request.path_params, expected_params);
  9118. }
  9119. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9120. const auto pattern = "/users/:id/";
  9121. detail::PathParamsMatcher matcher(pattern);
  9122. Request request;
  9123. request.path = "/users/42/";
  9124. ASSERT_TRUE(matcher.match(request));
  9125. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9126. EXPECT_EQ(request.path_params, expected_params);
  9127. }
  9128. TEST(PathParamsTest, EmptyParam) {
  9129. const auto pattern = "/users/:id/";
  9130. detail::PathParamsMatcher matcher(pattern);
  9131. Request request;
  9132. request.path = "/users//";
  9133. ASSERT_TRUE(matcher.match(request));
  9134. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9135. EXPECT_EQ(request.path_params, expected_params);
  9136. }
  9137. TEST(PathParamsTest, FragmentMismatch) {
  9138. const auto pattern = "/users/:id/";
  9139. detail::PathParamsMatcher matcher(pattern);
  9140. Request request;
  9141. request.path = "/admins/24/";
  9142. ASSERT_FALSE(matcher.match(request));
  9143. }
  9144. TEST(PathParamsTest, ExtraFragments) {
  9145. const auto pattern = "/users/:id";
  9146. detail::PathParamsMatcher matcher(pattern);
  9147. Request request;
  9148. request.path = "/users/42/subscriptions";
  9149. ASSERT_FALSE(matcher.match(request));
  9150. }
  9151. TEST(PathParamsTest, MissingTrailingParam) {
  9152. const auto pattern = "/users/:id";
  9153. detail::PathParamsMatcher matcher(pattern);
  9154. Request request;
  9155. request.path = "/users";
  9156. ASSERT_FALSE(matcher.match(request));
  9157. }
  9158. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9159. const auto pattern = "/users/:id/subscriptions";
  9160. detail::PathParamsMatcher matcher(pattern);
  9161. Request request;
  9162. request.path = "/users/subscriptions";
  9163. ASSERT_FALSE(matcher.match(request));
  9164. }
  9165. TEST(PathParamsTest, MultipleParams) {
  9166. const auto pattern = "/users/:userid/subscriptions/:subid";
  9167. detail::PathParamsMatcher matcher(pattern);
  9168. Request request;
  9169. request.path = "/users/42/subscriptions/2";
  9170. ASSERT_TRUE(matcher.match(request));
  9171. std::unordered_map<std::string, std::string> expected_params = {
  9172. {"userid", "42"}, {"subid", "2"}};
  9173. EXPECT_EQ(request.path_params, expected_params);
  9174. }
  9175. TEST(PathParamsTest, SequenceOfParams) {
  9176. const auto pattern = "/values/:x/:y/:z";
  9177. detail::PathParamsMatcher matcher(pattern);
  9178. Request request;
  9179. request.path = "/values/1/2/3";
  9180. ASSERT_TRUE(matcher.match(request));
  9181. std::unordered_map<std::string, std::string> expected_params = {
  9182. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9183. EXPECT_EQ(request.path_params, expected_params);
  9184. }
  9185. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9186. const auto pattern = "/prefix:suffix";
  9187. detail::PathParamsMatcher matcher(pattern);
  9188. Request request;
  9189. request.path = "/prefix:suffix";
  9190. ASSERT_TRUE(matcher.match(request));
  9191. const std::unordered_map<std::string, std::string> expected_params = {};
  9192. EXPECT_EQ(request.path_params, expected_params);
  9193. }
  9194. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9195. // If ipv6 regex working, regex match codepath is taken.
  9196. // else port will default to 80 in Client impl
  9197. int clientImplMagicPort = 80;
  9198. int port = 4321;
  9199. // above ports must be different to avoid false negative
  9200. EXPECT_NE(clientImplMagicPort, port);
  9201. std::string ipV6TestURL = "http://[ff06::c3]";
  9202. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9203. CLIENT_PRIVATE_KEY_FILE);
  9204. EXPECT_EQ(cli.port(), port);
  9205. }
  9206. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9207. auto file_path = "./www/dir/index.html";
  9208. auto dir_path = "./www/dir";
  9209. detail::FileStat stat_file(file_path);
  9210. EXPECT_TRUE(stat_file.is_file());
  9211. EXPECT_FALSE(stat_file.is_dir());
  9212. detail::FileStat stat_dir(dir_path);
  9213. EXPECT_FALSE(stat_dir.is_file());
  9214. EXPECT_TRUE(stat_dir.is_dir());
  9215. }
  9216. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9217. // IPv4 with default HTTP port (80)
  9218. EXPECT_EQ("example.com",
  9219. detail::make_host_and_port_string("example.com", 80, false));
  9220. // IPv4 with default HTTPS port (443)
  9221. EXPECT_EQ("example.com",
  9222. detail::make_host_and_port_string("example.com", 443, true));
  9223. // IPv4 with non-default HTTP port
  9224. EXPECT_EQ("example.com:8080",
  9225. detail::make_host_and_port_string("example.com", 8080, false));
  9226. // IPv4 with non-default HTTPS port
  9227. EXPECT_EQ("example.com:8443",
  9228. detail::make_host_and_port_string("example.com", 8443, true));
  9229. // IPv6 with default HTTP port (80)
  9230. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9231. // IPv6 with default HTTPS port (443)
  9232. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9233. // IPv6 with non-default HTTP port
  9234. EXPECT_EQ("[::1]:8080",
  9235. detail::make_host_and_port_string("::1", 8080, false));
  9236. // IPv6 with non-default HTTPS port
  9237. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9238. // IPv6 full address with default port
  9239. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9240. detail::make_host_and_port_string(
  9241. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9242. // IPv6 full address with non-default port
  9243. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9244. detail::make_host_and_port_string(
  9245. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9246. // IPv6 localhost with non-default port
  9247. EXPECT_EQ("[::1]:3000",
  9248. detail::make_host_and_port_string("::1", 3000, false));
  9249. // IPv6 with zone ID (link-local address) with default port
  9250. EXPECT_EQ("[fe80::1%eth0]",
  9251. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9252. // IPv6 with zone ID (link-local address) with non-default port
  9253. EXPECT_EQ("[fe80::1%eth0]:8080",
  9254. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9255. // Edge case: Port 443 with is_ssl=false (should add port)
  9256. EXPECT_EQ("example.com:443",
  9257. detail::make_host_and_port_string("example.com", 443, false));
  9258. // Edge case: Port 80 with is_ssl=true (should add port)
  9259. EXPECT_EQ("example.com:80",
  9260. detail::make_host_and_port_string("example.com", 80, true));
  9261. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9262. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9263. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9264. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9265. // Security fix: Already bracketed IPv6 should not get double brackets
  9266. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9267. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9268. EXPECT_EQ("[::1]:8080",
  9269. detail::make_host_and_port_string("[::1]", 8080, false));
  9270. EXPECT_EQ("[2001:db8::1]:8080",
  9271. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9272. EXPECT_EQ("[fe80::1%eth0]",
  9273. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9274. EXPECT_EQ("[fe80::1%eth0]:8080",
  9275. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9276. // Edge case: Empty host (should return as-is)
  9277. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9278. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9279. // This is a known limitation but shouldn't crash
  9280. EXPECT_EQ("[host:name]",
  9281. detail::make_host_and_port_string("host:name", 80, false));
  9282. // Port number edge cases (no validation, but should not crash)
  9283. EXPECT_EQ("example.com:0",
  9284. detail::make_host_and_port_string("example.com", 0, false));
  9285. EXPECT_EQ("example.com:-1",
  9286. detail::make_host_and_port_string("example.com", -1, false));
  9287. EXPECT_EQ("example.com:65535",
  9288. detail::make_host_and_port_string("example.com", 65535, false));
  9289. EXPECT_EQ("example.com:65536",
  9290. detail::make_host_and_port_string("example.com", 65536, false));
  9291. }
  9292. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9293. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  9294. httplib::SSLClient cli("roblox.com", 443);
  9295. cli.set_follow_location(true);
  9296. auto res = cli.Get("/");
  9297. ASSERT_TRUE(res);
  9298. EXPECT_EQ(StatusCode::OK_200, res->status);
  9299. }
  9300. #endif
  9301. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9302. Server svr;
  9303. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9304. EXPECT_EQ(res.status, 400);
  9305. });
  9306. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9307. auto se = detail::scope_exit([&] {
  9308. svr.stop();
  9309. thread.join();
  9310. ASSERT_FALSE(svr.is_running());
  9311. });
  9312. svr.wait_until_ready();
  9313. Client cli(HOST, PORT);
  9314. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9315. }
  9316. TEST(InvalidHeaderCharsTest, is_field_name) {
  9317. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9318. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9319. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9320. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9321. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9322. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9323. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9324. EXPECT_FALSE(detail::fields::is_field_name(""));
  9325. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9326. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9327. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9328. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9329. }
  9330. TEST(InvalidHeaderCharsTest, is_field_value) {
  9331. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9332. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9333. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9334. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9335. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9336. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9337. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9338. EXPECT_TRUE(detail::fields::is_field_value(""));
  9339. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9340. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9341. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9342. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9343. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9344. }
  9345. TEST(InvalidHeaderCharsTest, OnServer) {
  9346. Server svr;
  9347. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9348. std::string header = "Not Set";
  9349. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9350. res.set_header(header, "value");
  9351. res.set_content("Page Content Page Content", "text/plain");
  9352. });
  9353. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9354. std::string header = "Not Set";
  9355. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9356. res.set_header("X-Test", header);
  9357. res.set_content("Page Content Page Content", "text/plain");
  9358. });
  9359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9360. auto se = detail::scope_exit([&] {
  9361. svr.stop();
  9362. thread.join();
  9363. ASSERT_FALSE(svr.is_running());
  9364. });
  9365. svr.wait_until_ready();
  9366. Client cli(HOST, PORT);
  9367. {
  9368. auto res = cli.Get(
  9369. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9370. ASSERT_TRUE(res);
  9371. EXPECT_EQ("Page Content Page Content", res->body);
  9372. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9373. }
  9374. {
  9375. auto res = cli.Get(
  9376. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9377. ASSERT_TRUE(res);
  9378. EXPECT_EQ("Page Content Page Content", res->body);
  9379. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9380. }
  9381. }
  9382. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9383. auto handled = false;
  9384. Server svr;
  9385. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9386. thread t = thread([&] { svr.listen(HOST, PORT); });
  9387. auto se = detail::scope_exit([&] {
  9388. svr.stop();
  9389. t.join();
  9390. ASSERT_FALSE(svr.is_running());
  9391. ASSERT_FALSE(handled);
  9392. });
  9393. svr.wait_until_ready();
  9394. auto req = "POST /test HTTP/1.1\r\n"
  9395. "Content-Length: x\r\n"
  9396. "\r\n";
  9397. std::string response;
  9398. ASSERT_TRUE(send_request(1, req, &response));
  9399. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9400. response.substr(0, response.find("\r\n")));
  9401. }
  9402. #ifndef _WIN32
  9403. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9404. static constexpr char reject[] = "Unauthorized";
  9405. static constexpr char accept[] = "Upload accepted";
  9406. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9407. Server svr;
  9408. svr.set_expect_100_continue_handler(
  9409. [](const Request & /*req*/, Response &res) {
  9410. res.status = StatusCode::Unauthorized_401;
  9411. res.set_content(reject, "text/plain");
  9412. return res.status;
  9413. });
  9414. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9415. res.set_content(accept, "text/plain");
  9416. });
  9417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9418. auto se = detail::scope_exit([&] {
  9419. svr.stop();
  9420. thread.join();
  9421. ASSERT_FALSE(svr.is_running());
  9422. });
  9423. svr.wait_until_ready();
  9424. {
  9425. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9426. curl_easy_init(), &curl_easy_cleanup};
  9427. ASSERT_NE(curl, nullptr);
  9428. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9429. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9430. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9431. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9432. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9433. &curl_slist_free_all};
  9434. ASSERT_NE(list, nullptr);
  9435. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9436. struct read_data {
  9437. size_t read_size;
  9438. size_t total_size;
  9439. } data = {0, total_size};
  9440. using read_callback_t =
  9441. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9442. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9443. void *userdata) -> size_t {
  9444. read_data *data = (read_data *)userdata;
  9445. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9446. std::fill_n(ptr, size * nmemb, 'A');
  9447. data->read_size += size * nmemb;
  9448. return size * nmemb;
  9449. };
  9450. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9451. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9452. std::vector<char> buffer;
  9453. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9454. using write_callback_t =
  9455. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9456. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9457. void *userdata) -> size_t {
  9458. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9459. buffer->reserve(buffer->size() + size * nmemb + 1);
  9460. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9461. return size * nmemb;
  9462. };
  9463. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9464. {
  9465. const auto res = curl_easy_perform(curl.get());
  9466. ASSERT_EQ(res, CURLE_OK);
  9467. }
  9468. {
  9469. auto response_code = long{};
  9470. const auto res =
  9471. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9472. ASSERT_EQ(res, CURLE_OK);
  9473. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9474. }
  9475. {
  9476. auto dl = curl_off_t{};
  9477. const auto res =
  9478. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9479. ASSERT_EQ(res, CURLE_OK);
  9480. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9481. }
  9482. {
  9483. buffer.push_back('\0');
  9484. ASSERT_STRCASEEQ(buffer.data(), reject);
  9485. }
  9486. }
  9487. }
  9488. #endif
  9489. template <typename S, typename C>
  9490. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9491. svr.Get("/stream", [&](const Request &, Response &res) {
  9492. auto data = new std::string("01234567890123456789");
  9493. res.set_content_provider(
  9494. data->size(), "text/plain",
  9495. [&, data](size_t offset, size_t length, DataSink &sink) {
  9496. const size_t DATA_CHUNK_SIZE = 4;
  9497. const auto &d = *data;
  9498. std::this_thread::sleep_for(std::chrono::seconds(1));
  9499. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9500. return true;
  9501. },
  9502. [data](bool success) {
  9503. EXPECT_FALSE(success);
  9504. delete data;
  9505. });
  9506. });
  9507. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9508. auto i = new size_t(0);
  9509. res.set_content_provider(
  9510. "text/plain",
  9511. [i](size_t, DataSink &sink) {
  9512. if (*i < 5) {
  9513. std::this_thread::sleep_for(std::chrono::seconds(1));
  9514. sink.write("abcd", 4);
  9515. (*i)++;
  9516. } else {
  9517. sink.done();
  9518. }
  9519. return true;
  9520. },
  9521. [i](bool success) {
  9522. EXPECT_FALSE(success);
  9523. delete i;
  9524. });
  9525. });
  9526. svr.Get("/chunked", [&](const Request &, Response &res) {
  9527. auto i = new size_t(0);
  9528. res.set_chunked_content_provider(
  9529. "text/plain",
  9530. [i](size_t, DataSink &sink) {
  9531. if (*i < 5) {
  9532. std::this_thread::sleep_for(std::chrono::seconds(1));
  9533. sink.os << "abcd";
  9534. (*i)++;
  9535. } else {
  9536. sink.done();
  9537. }
  9538. return true;
  9539. },
  9540. [i](bool success) {
  9541. EXPECT_FALSE(success);
  9542. delete i;
  9543. });
  9544. });
  9545. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9546. auto se = detail::scope_exit([&] {
  9547. svr.stop();
  9548. listen_thread.join();
  9549. ASSERT_FALSE(svr.is_running());
  9550. });
  9551. svr.wait_until_ready();
  9552. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9553. {
  9554. auto start = std::chrono::steady_clock::now();
  9555. auto res = cli.Get("/stream");
  9556. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9557. std::chrono::steady_clock::now() - start)
  9558. .count();
  9559. ASSERT_FALSE(res);
  9560. EXPECT_EQ(Error::Read, res.error());
  9561. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9562. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9563. }
  9564. {
  9565. auto start = std::chrono::steady_clock::now();
  9566. auto res = cli.Get("/stream_without_length");
  9567. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9568. std::chrono::steady_clock::now() - start)
  9569. .count();
  9570. ASSERT_FALSE(res);
  9571. EXPECT_EQ(Error::Read, res.error());
  9572. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9573. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9574. }
  9575. {
  9576. auto start = std::chrono::steady_clock::now();
  9577. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9578. EXPECT_EQ("abcd", string(data, data_length));
  9579. return true;
  9580. });
  9581. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9582. std::chrono::steady_clock::now() - start)
  9583. .count();
  9584. ASSERT_FALSE(res);
  9585. EXPECT_EQ(Error::Read, res.error());
  9586. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9587. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9588. }
  9589. }
  9590. TEST(MaxTimeoutTest, ContentStream) {
  9591. time_t timeout = 2000;
  9592. time_t threshold = 200;
  9593. Server svr;
  9594. Client cli("localhost", PORT);
  9595. max_timeout_test(svr, cli, timeout, threshold);
  9596. }
  9597. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9598. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9599. time_t timeout = 2000;
  9600. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9602. SSLClient cli("localhost", PORT);
  9603. cli.enable_server_certificate_verification(false);
  9604. max_timeout_test(svr, cli, timeout, threshold);
  9605. }
  9606. #endif
  9607. class EventDispatcher {
  9608. public:
  9609. EventDispatcher() {}
  9610. bool wait_event(DataSink *sink) {
  9611. unique_lock<mutex> lk(m_);
  9612. int id = id_;
  9613. // Wait with timeout to prevent hanging if client disconnects
  9614. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9615. [&] { return cid_ == id; })) {
  9616. return false; // Timeout occurred
  9617. }
  9618. sink->write(message_.data(), message_.size());
  9619. return true;
  9620. }
  9621. void send_event(const string &message) {
  9622. lock_guard<mutex> lk(m_);
  9623. cid_ = id_++;
  9624. message_ = message;
  9625. cv_.notify_all();
  9626. }
  9627. private:
  9628. mutex m_;
  9629. condition_variable cv_;
  9630. atomic_int id_{0};
  9631. atomic_int cid_{-1};
  9632. string message_;
  9633. };
  9634. TEST(ClientInThreadTest, Issue2068) {
  9635. EventDispatcher ed;
  9636. Server svr;
  9637. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9638. res.set_chunked_content_provider("text/event-stream",
  9639. [&](size_t /*offset*/, DataSink &sink) {
  9640. return ed.wait_event(&sink);
  9641. });
  9642. });
  9643. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9644. svr.wait_until_ready();
  9645. thread event_thread([&] {
  9646. int id = 0;
  9647. while (svr.is_running()) {
  9648. this_thread::sleep_for(chrono::milliseconds(500));
  9649. std::stringstream ss;
  9650. ss << "data: " << id << "\n\n";
  9651. ed.send_event(ss.str());
  9652. id++;
  9653. }
  9654. });
  9655. auto se = detail::scope_exit([&] {
  9656. svr.stop();
  9657. listen_thread.join();
  9658. event_thread.join();
  9659. ASSERT_FALSE(svr.is_running());
  9660. });
  9661. {
  9662. auto client = detail::make_unique<Client>(HOST, PORT);
  9663. client->set_read_timeout(std::chrono::minutes(10));
  9664. std::atomic<bool> stop{false};
  9665. std::thread t([&] {
  9666. client->Get("/event1",
  9667. [&](const char *, size_t) -> bool { return !stop; });
  9668. });
  9669. std::this_thread::sleep_for(std::chrono::seconds(2));
  9670. stop = true;
  9671. client->stop();
  9672. t.join();
  9673. // Reset client after thread has finished
  9674. client.reset();
  9675. }
  9676. }
  9677. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9678. Server svr;
  9679. svr.Get("/", [](const Request &req, Response &res) {
  9680. EXPECT_EQ(2U, req.trailers.size());
  9681. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9682. // Denied
  9683. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9684. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9685. // Accepted
  9686. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9687. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9688. EXPECT_TRUE(req.has_trailer("X-World"));
  9689. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9690. res.set_content("ok", "text/plain");
  9691. });
  9692. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9693. auto se = detail::scope_exit([&] {
  9694. svr.stop();
  9695. t.join();
  9696. ASSERT_FALSE(svr.is_running());
  9697. });
  9698. svr.wait_until_ready();
  9699. const std::string req = "GET / HTTP/1.1\r\n"
  9700. "Transfer-Encoding: chunked\r\n"
  9701. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9702. "\r\n"
  9703. "0\r\n"
  9704. "Content-Length: 10\r\n"
  9705. "Host: internal.local\r\n"
  9706. "Content-Type: malicious/content\r\n"
  9707. "Cookie: any\r\n"
  9708. "Set-Cookie: any\r\n"
  9709. "X-Forwarded-For: attacker.com\r\n"
  9710. "X-Real-Ip: 1.1.1.1\r\n"
  9711. "X-Hello: hello\r\n"
  9712. "X-World: world\r\n"
  9713. "\r\n";
  9714. std::string res;
  9715. ASSERT_TRUE(send_request(1, req, &res));
  9716. }
  9717. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9718. Server svr;
  9719. std::string observed_remote_addr;
  9720. std::string observed_xff;
  9721. svr.Get("/ip", [&](const Request &req, Response &res) {
  9722. observed_remote_addr = req.remote_addr;
  9723. observed_xff = req.get_header_value("X-Forwarded-For");
  9724. res.set_content("ok", "text/plain");
  9725. });
  9726. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9727. auto se = detail::scope_exit([&] {
  9728. svr.stop();
  9729. t.join();
  9730. ASSERT_FALSE(svr.is_running());
  9731. });
  9732. svr.wait_until_ready();
  9733. Client cli(HOST, PORT);
  9734. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9735. ASSERT_TRUE(res);
  9736. EXPECT_EQ(StatusCode::OK_200, res->status);
  9737. EXPECT_EQ(observed_xff, "203.0.113.66");
  9738. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9739. observed_remote_addr == "127.0.0.1");
  9740. }
  9741. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9742. Server svr;
  9743. svr.set_trusted_proxies({"203.0.113.66"});
  9744. std::string observed_remote_addr;
  9745. std::string observed_xff;
  9746. svr.Get("/ip", [&](const Request &req, Response &res) {
  9747. observed_remote_addr = req.remote_addr;
  9748. observed_xff = req.get_header_value("X-Forwarded-For");
  9749. res.set_content("ok", "text/plain");
  9750. });
  9751. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9752. auto se = detail::scope_exit([&] {
  9753. svr.stop();
  9754. t.join();
  9755. ASSERT_FALSE(svr.is_running());
  9756. });
  9757. svr.wait_until_ready();
  9758. Client cli(HOST, PORT);
  9759. auto res = cli.Get("/ip");
  9760. ASSERT_TRUE(res);
  9761. EXPECT_EQ(StatusCode::OK_200, res->status);
  9762. EXPECT_EQ(observed_xff, "");
  9763. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9764. observed_remote_addr == "127.0.0.1");
  9765. }
  9766. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9767. Server svr;
  9768. svr.set_trusted_proxies({"203.0.113.66"});
  9769. std::string observed_remote_addr;
  9770. std::string observed_xff;
  9771. svr.Get("/ip", [&](const Request &req, Response &res) {
  9772. observed_remote_addr = req.remote_addr;
  9773. observed_xff = req.get_header_value("X-Forwarded-For");
  9774. res.set_content("ok", "text/plain");
  9775. });
  9776. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9777. auto se = detail::scope_exit([&] {
  9778. svr.stop();
  9779. t.join();
  9780. ASSERT_FALSE(svr.is_running());
  9781. });
  9782. svr.wait_until_ready();
  9783. Client cli(HOST, PORT);
  9784. auto res =
  9785. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9786. ASSERT_TRUE(res);
  9787. EXPECT_EQ(StatusCode::OK_200, res->status);
  9788. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9789. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9790. }
  9791. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9792. Server svr;
  9793. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9794. std::string observed_remote_addr;
  9795. std::string observed_xff;
  9796. svr.Get("/ip", [&](const Request &req, Response &res) {
  9797. observed_remote_addr = req.remote_addr;
  9798. observed_xff = req.get_header_value("X-Forwarded-For");
  9799. res.set_content("ok", "text/plain");
  9800. });
  9801. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9802. auto se = detail::scope_exit([&] {
  9803. svr.stop();
  9804. t.join();
  9805. ASSERT_FALSE(svr.is_running());
  9806. });
  9807. svr.wait_until_ready();
  9808. Client cli(HOST, PORT);
  9809. auto res = cli.Get(
  9810. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9811. ASSERT_TRUE(res);
  9812. EXPECT_EQ(StatusCode::OK_200, res->status);
  9813. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9814. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9815. }
  9816. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9817. Server svr;
  9818. svr.set_trusted_proxies({"192.0.2.45"});
  9819. std::string observed_remote_addr;
  9820. std::string observed_xff;
  9821. svr.Get("/ip", [&](const Request &req, Response &res) {
  9822. observed_remote_addr = req.remote_addr;
  9823. observed_xff = req.get_header_value("X-Forwarded-For");
  9824. res.set_content("ok", "text/plain");
  9825. });
  9826. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9827. auto se = detail::scope_exit([&] {
  9828. svr.stop();
  9829. t.join();
  9830. ASSERT_FALSE(svr.is_running());
  9831. });
  9832. svr.wait_until_ready();
  9833. Client cli(HOST, PORT);
  9834. auto res =
  9835. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9836. ASSERT_TRUE(res);
  9837. EXPECT_EQ(StatusCode::OK_200, res->status);
  9838. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9839. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9840. }
  9841. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9842. Server svr;
  9843. svr.set_trusted_proxies({"192.0.2.45"});
  9844. std::string observed_remote_addr;
  9845. std::string observed_xff;
  9846. svr.Get("/ip", [&](const Request &req, Response &res) {
  9847. observed_remote_addr = req.remote_addr;
  9848. observed_xff = req.get_header_value("X-Forwarded-For");
  9849. res.set_content("ok", "text/plain");
  9850. });
  9851. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9852. auto se = detail::scope_exit([&] {
  9853. svr.stop();
  9854. t.join();
  9855. ASSERT_FALSE(svr.is_running());
  9856. });
  9857. svr.wait_until_ready();
  9858. Client cli(HOST, PORT);
  9859. auto res = cli.Get(
  9860. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9861. ASSERT_TRUE(res);
  9862. EXPECT_EQ(StatusCode::OK_200, res->status);
  9863. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9864. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9865. }
  9866. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9867. Server svr;
  9868. svr.set_trusted_proxies({"192.0.2.45"});
  9869. std::string observed_remote_addr;
  9870. std::string observed_xff;
  9871. svr.Get("/ip", [&](const Request &req, Response &res) {
  9872. observed_remote_addr = req.remote_addr;
  9873. observed_xff = req.get_header_value("X-Forwarded-For");
  9874. res.set_content("ok", "text/plain");
  9875. });
  9876. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9877. auto se = detail::scope_exit([&] {
  9878. svr.stop();
  9879. t.join();
  9880. ASSERT_FALSE(svr.is_running());
  9881. });
  9882. svr.wait_until_ready();
  9883. std::string raw_req =
  9884. "GET /ip HTTP/1.1\r\n"
  9885. "Host: localhost\r\n"
  9886. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  9887. "Connection: close\r\n"
  9888. "\r\n";
  9889. std::string out;
  9890. ASSERT_TRUE(send_request(5, raw_req, &out));
  9891. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9892. // Header parser trims surrounding whitespace of the header value
  9893. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9894. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9895. }
  9896. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9897. Server svr;
  9898. svr.Post("/post", [&](const Request &req, Response &res) {
  9899. res.set_content(req.body, "text/plain");
  9900. });
  9901. svr.Put("/put", [&](const Request &req, Response &res) {
  9902. res.set_content(req.body, "text/plain");
  9903. });
  9904. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9905. res.set_content(req.body, "text/plain");
  9906. });
  9907. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9908. res.set_content(req.body, "text/plain");
  9909. });
  9910. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9911. auto se = detail::scope_exit([&] {
  9912. svr.stop();
  9913. t.join();
  9914. ASSERT_FALSE(svr.is_running());
  9915. });
  9916. svr.wait_until_ready();
  9917. std::string resp;
  9918. // POST without Content-Length
  9919. ASSERT_TRUE(send_request(5,
  9920. "POST /post HTTP/1.1\r\n"
  9921. "Host: localhost\r\n"
  9922. "Connection: close\r\n"
  9923. "\r\n",
  9924. &resp));
  9925. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9926. // PUT without Content-Length
  9927. resp.clear();
  9928. ASSERT_TRUE(send_request(5,
  9929. "PUT /put HTTP/1.1\r\n"
  9930. "Host: localhost\r\n"
  9931. "Connection: close\r\n"
  9932. "\r\n",
  9933. &resp));
  9934. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9935. // PATCH without Content-Length
  9936. resp.clear();
  9937. ASSERT_TRUE(send_request(5,
  9938. "PATCH /patch HTTP/1.1\r\n"
  9939. "Host: localhost\r\n"
  9940. "Connection: close\r\n"
  9941. "\r\n",
  9942. &resp));
  9943. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9944. // DELETE without Content-Length
  9945. resp.clear();
  9946. ASSERT_TRUE(send_request(5,
  9947. "DELETE /delete HTTP/1.1\r\n"
  9948. "Host: localhost\r\n"
  9949. "Connection: close\r\n"
  9950. "\r\n",
  9951. &resp));
  9952. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9953. }
  9954. //==============================================================================
  9955. // open_stream() Tests
  9956. //==============================================================================
  9957. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9958. std::string result;
  9959. char buf[8192];
  9960. ssize_t n;
  9961. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9962. result.append(buf, static_cast<size_t>(n));
  9963. }
  9964. return result;
  9965. }
  9966. // Mock stream for unit tests
  9967. class MockStream : public Stream {
  9968. public:
  9969. std::string data;
  9970. size_t pos = 0;
  9971. ssize_t error_after = -1; // -1 = no error
  9972. explicit MockStream(const std::string &d, ssize_t err = -1)
  9973. : data(d), error_after(err) {}
  9974. bool is_readable() const override { return true; }
  9975. bool wait_readable() const override { return true; }
  9976. bool wait_writable() const override { return true; }
  9977. ssize_t read(char *ptr, size_t size) override {
  9978. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9979. if (pos >= data.size()) return 0;
  9980. size_t limit =
  9981. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9982. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9983. std::memcpy(ptr, data.data() + pos, to_read);
  9984. pos += to_read;
  9985. return static_cast<ssize_t>(to_read);
  9986. }
  9987. ssize_t write(const char *, size_t) override { return -1; }
  9988. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9989. ip = "127.0.0.1";
  9990. port = 0;
  9991. }
  9992. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9993. ip = "127.0.0.1";
  9994. port = 0;
  9995. }
  9996. socket_t socket() const override { return INVALID_SOCKET; }
  9997. time_t duration() const override { return 0; }
  9998. };
  9999. TEST(StreamHandleTest, Basic) {
  10000. ClientImpl::StreamHandle handle;
  10001. EXPECT_FALSE(handle.is_valid());
  10002. handle.response = detail::make_unique<Response>();
  10003. handle.error = Error::Connection;
  10004. EXPECT_FALSE(handle.is_valid());
  10005. handle.error = Error::Success;
  10006. EXPECT_TRUE(handle.is_valid());
  10007. }
  10008. TEST(BodyReaderTest, Basic) {
  10009. MockStream stream("Hello, World!");
  10010. detail::BodyReader reader;
  10011. reader.stream = &stream;
  10012. reader.content_length = 13;
  10013. char buf[32];
  10014. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10015. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10016. EXPECT_TRUE(reader.eof);
  10017. }
  10018. TEST(BodyReaderTest, NoStream) {
  10019. detail::BodyReader reader;
  10020. char buf[32];
  10021. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10022. EXPECT_EQ(Error::Connection, reader.last_error);
  10023. }
  10024. TEST(BodyReaderTest, Error) {
  10025. MockStream stream("Hello, World!", 5);
  10026. detail::BodyReader reader;
  10027. reader.stream = &stream;
  10028. reader.content_length = 13;
  10029. char buf[32];
  10030. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10031. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10032. EXPECT_EQ(Error::Read, reader.last_error);
  10033. }
  10034. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10035. // Mock-based StreamHandle tests relying on private internals are removed.
  10036. class OpenStreamTest : public ::testing::Test {
  10037. protected:
  10038. void SetUp() override {
  10039. svr_.Get("/hello", [](const Request &, Response &res) {
  10040. res.set_content("Hello World!", "text/plain");
  10041. });
  10042. svr_.Get("/large", [](const Request &, Response &res) {
  10043. res.set_content(std::string(10000, 'X'), "text/plain");
  10044. });
  10045. svr_.Get("/chunked", [](const Request &, Response &res) {
  10046. res.set_chunked_content_provider("text/plain",
  10047. [](size_t offset, DataSink &sink) {
  10048. if (offset < 15) {
  10049. sink.write("chunk", 5);
  10050. return true;
  10051. }
  10052. sink.done();
  10053. return true;
  10054. });
  10055. });
  10056. svr_.Get("/compressible", [](const Request &, Response &res) {
  10057. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10058. DataSink &sink) {
  10059. if (offset < 100 * 1024) {
  10060. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10061. sink.write(chunk.data(), chunk.size());
  10062. return true;
  10063. }
  10064. sink.done();
  10065. return true;
  10066. });
  10067. });
  10068. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10069. [](const Request & /*req*/, Response &res) {
  10070. auto i = new int(0);
  10071. res.set_header("Trailer", "Content-Length, X-Allowed");
  10072. res.set_chunked_content_provider(
  10073. "text/plain",
  10074. [i](size_t /*offset*/, DataSink &sink) {
  10075. switch (*i) {
  10076. case 0: sink.os << "123"; break;
  10077. case 1: sink.os << "456"; break;
  10078. case 2: sink.os << "789"; break;
  10079. case 3: {
  10080. sink.done_with_trailer(
  10081. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10082. } break;
  10083. }
  10084. (*i)++;
  10085. return true;
  10086. },
  10087. [i](bool success) {
  10088. EXPECT_TRUE(success);
  10089. delete i;
  10090. });
  10091. });
  10092. // Echo headers endpoint for header-related tests
  10093. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10094. std::string body;
  10095. for (const auto &h : req.headers) {
  10096. body.append(h.first);
  10097. body.push_back(':');
  10098. body.append(h.second);
  10099. body.push_back('\n');
  10100. }
  10101. res.set_content(body, "text/plain");
  10102. });
  10103. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10104. std::string body;
  10105. for (const auto &h : req.headers) {
  10106. body.append(h.first);
  10107. body.push_back(':');
  10108. body.append(h.second);
  10109. body.push_back('\n');
  10110. }
  10111. res.set_content(body, "text/plain");
  10112. });
  10113. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10114. svr_.wait_until_ready();
  10115. }
  10116. void TearDown() override {
  10117. svr_.stop();
  10118. if (thread_.joinable()) thread_.join();
  10119. }
  10120. Server svr_;
  10121. std::thread thread_;
  10122. };
  10123. TEST_F(OpenStreamTest, Basic) {
  10124. Client cli("127.0.0.1", 8787);
  10125. auto handle = cli.open_stream("GET", "/hello");
  10126. EXPECT_TRUE(handle.is_valid());
  10127. EXPECT_EQ("Hello World!", read_all(handle));
  10128. }
  10129. TEST_F(OpenStreamTest, SmallBuffer) {
  10130. Client cli("127.0.0.1", 8787);
  10131. auto handle = cli.open_stream("GET", "/hello");
  10132. std::string result;
  10133. char buf[4];
  10134. ssize_t n;
  10135. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10136. result.append(buf, static_cast<size_t>(n));
  10137. EXPECT_EQ("Hello World!", result);
  10138. }
  10139. TEST_F(OpenStreamTest, DefaultHeaders) {
  10140. Client cli("127.0.0.1", 8787);
  10141. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10142. {
  10143. auto handle = cli.open_stream("GET", "/echo-headers");
  10144. ASSERT_TRUE(handle.is_valid());
  10145. auto body = read_all(handle);
  10146. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10147. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10148. std::string::npos);
  10149. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10150. }
  10151. // open_stream POST with body and no explicit content_type should NOT add
  10152. // text/plain Content-Type (behavior differs from non-streaming path), but
  10153. // should include Content-Length
  10154. {
  10155. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10156. ASSERT_TRUE(handle.is_valid());
  10157. auto body = read_all(handle);
  10158. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10159. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10160. }
  10161. // open_stream POST with explicit Content-Type should preserve it
  10162. {
  10163. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10164. {{"Content-Type", "application/custom"}},
  10165. "{}", "application/custom");
  10166. ASSERT_TRUE(handle.is_valid());
  10167. auto body = read_all(handle);
  10168. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10169. }
  10170. // User-specified User-Agent must not be overwritten for stream API
  10171. {
  10172. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10173. {{"User-Agent", "MyAgent/1.2"}});
  10174. ASSERT_TRUE(handle.is_valid());
  10175. auto body = read_all(handle);
  10176. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10177. }
  10178. }
  10179. TEST_F(OpenStreamTest, Large) {
  10180. Client cli("127.0.0.1", 8787);
  10181. auto handle = cli.open_stream("GET", "/large");
  10182. EXPECT_EQ(10000u, read_all(handle).size());
  10183. }
  10184. TEST_F(OpenStreamTest, ConnectionError) {
  10185. Client cli("127.0.0.1", 9999);
  10186. auto handle = cli.open_stream("GET", "/hello");
  10187. EXPECT_FALSE(handle.is_valid());
  10188. }
  10189. TEST_F(OpenStreamTest, Chunked) {
  10190. Client cli("127.0.0.1", 8787);
  10191. auto handle = cli.open_stream("GET", "/chunked");
  10192. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10193. "Transfer-Encoding") == "chunked");
  10194. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10195. }
  10196. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10197. Client cli("127.0.0.1", 8787);
  10198. auto handle =
  10199. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10200. ASSERT_TRUE(handle.is_valid());
  10201. // Consume body to allow trailers to be received/parsed
  10202. auto body = read_all(handle);
  10203. // Explicitly parse trailers (ensure trailers are available for assertion)
  10204. handle.parse_trailers_if_needed();
  10205. EXPECT_EQ(std::string("123456789"), body);
  10206. // The response should include a Trailer header declaring both names
  10207. ASSERT_TRUE(handle.response);
  10208. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10209. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10210. handle.response->get_header_value("Trailer"));
  10211. // Prohibited trailer must not be present
  10212. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10213. // Allowed trailer should be present
  10214. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10215. EXPECT_EQ(std::string("yes"),
  10216. handle.response->get_trailer_value("X-Allowed"));
  10217. // Verify trailers are NOT present as regular headers
  10218. EXPECT_EQ(std::string(""),
  10219. handle.response->get_header_value("Content-Length"));
  10220. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10221. }
  10222. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10223. TEST_F(OpenStreamTest, Gzip) {
  10224. Client cli("127.0.0.1", 8787);
  10225. auto handle = cli.open_stream("GET", "/compressible", {},
  10226. {{"Accept-Encoding", "gzip"}});
  10227. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10228. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10229. }
  10230. #endif
  10231. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10232. TEST_F(OpenStreamTest, Brotli) {
  10233. Client cli("127.0.0.1", 8787);
  10234. auto handle =
  10235. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10236. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10237. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10238. }
  10239. #endif
  10240. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10241. TEST_F(OpenStreamTest, Zstd) {
  10242. Client cli("127.0.0.1", 8787);
  10243. auto handle = cli.open_stream("GET", "/compressible", {},
  10244. {{"Accept-Encoding", "zstd"}});
  10245. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10246. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10247. }
  10248. #endif
  10249. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10250. class SSLOpenStreamTest : public ::testing::Test {
  10251. protected:
  10252. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10253. void SetUp() override {
  10254. svr_.Get("/hello", [](const Request &, Response &res) {
  10255. res.set_content("Hello SSL World!", "text/plain");
  10256. });
  10257. svr_.Get("/chunked", [](const Request &, Response &res) {
  10258. res.set_chunked_content_provider("text/plain",
  10259. [](size_t offset, DataSink &sink) {
  10260. if (offset < 15) {
  10261. sink.write("chunk", 5);
  10262. return true;
  10263. }
  10264. sink.done();
  10265. return true;
  10266. });
  10267. });
  10268. svr_.Post("/echo", [](const Request &req, Response &res) {
  10269. res.set_content(req.body, req.get_header_value("Content-Type"));
  10270. });
  10271. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10272. std::string body = req.body;
  10273. res.set_chunked_content_provider(
  10274. "text/plain", [body](size_t offset, DataSink &sink) {
  10275. if (offset < body.size()) {
  10276. sink.write(body.data() + offset, body.size() - offset);
  10277. }
  10278. sink.done();
  10279. return true;
  10280. });
  10281. });
  10282. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10283. svr_.wait_until_ready();
  10284. }
  10285. void TearDown() override {
  10286. svr_.stop();
  10287. if (thread_.joinable()) thread_.join();
  10288. }
  10289. SSLServer svr_;
  10290. std::thread thread_;
  10291. };
  10292. TEST_F(SSLOpenStreamTest, Basic) {
  10293. SSLClient cli("127.0.0.1", 8788);
  10294. cli.enable_server_certificate_verification(false);
  10295. auto handle = cli.open_stream("GET", "/hello");
  10296. ASSERT_TRUE(handle.is_valid());
  10297. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10298. }
  10299. TEST_F(SSLOpenStreamTest, Chunked) {
  10300. SSLClient cli("127.0.0.1", 8788);
  10301. cli.enable_server_certificate_verification(false);
  10302. auto handle = cli.open_stream("GET", "/chunked");
  10303. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10304. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10305. "Transfer-Encoding") == "chunked");
  10306. auto body = read_all(handle);
  10307. EXPECT_EQ("chunkchunkchunk", body);
  10308. }
  10309. TEST_F(SSLOpenStreamTest, Post) {
  10310. SSLClient cli("127.0.0.1", 8788);
  10311. cli.enable_server_certificate_verification(false);
  10312. auto handle =
  10313. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10314. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10315. EXPECT_EQ(200, handle.response->status);
  10316. auto body = read_all(handle);
  10317. EXPECT_EQ("Hello SSL POST", body);
  10318. }
  10319. TEST_F(SSLOpenStreamTest, PostChunked) {
  10320. SSLClient cli("127.0.0.1", 8788);
  10321. cli.enable_server_certificate_verification(false);
  10322. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10323. "Chunked SSL Data", "text/plain");
  10324. ASSERT_TRUE(handle.is_valid());
  10325. EXPECT_EQ(200, handle.response->status);
  10326. auto body = read_all(handle);
  10327. EXPECT_EQ("Chunked SSL Data", body);
  10328. }
  10329. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10330. //==============================================================================
  10331. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10332. // results for various scenarios.
  10333. //==============================================================================
  10334. TEST(ParityTest, GetVsOpenStream) {
  10335. Server svr;
  10336. const std::string path = "/parity";
  10337. const std::string content = "Parity test content: hello world";
  10338. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10339. res.set_content(content, "text/plain");
  10340. });
  10341. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10342. auto se = detail::scope_exit([&] {
  10343. svr.stop();
  10344. t.join();
  10345. ASSERT_FALSE(svr.is_running());
  10346. });
  10347. svr.wait_until_ready();
  10348. Client cli(HOST, PORT);
  10349. // Non-stream path
  10350. auto r1 = cli.Get(path);
  10351. ASSERT_TRUE(r1);
  10352. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10353. // Stream path
  10354. auto h = cli.open_stream("GET", path);
  10355. ASSERT_TRUE(h.is_valid());
  10356. EXPECT_EQ(r1->body, read_all(h));
  10357. }
  10358. // Helper to compress data with provided compressor type T
  10359. template <typename Compressor>
  10360. static std::string compress_payload_for_parity(const std::string &in) {
  10361. std::string out;
  10362. Compressor compressor;
  10363. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10364. [&](const char *data, size_t n) {
  10365. out.append(data, n);
  10366. return true;
  10367. });
  10368. EXPECT_TRUE(ok);
  10369. return out;
  10370. }
  10371. // Helper function for compression parity tests
  10372. template <typename Compressor>
  10373. static void test_compression_parity(const std::string &original,
  10374. const std::string &path,
  10375. const std::string &encoding) {
  10376. const std::string compressed =
  10377. compress_payload_for_parity<Compressor>(original);
  10378. Server svr;
  10379. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10380. res.set_content(compressed, "application/octet-stream");
  10381. res.set_header("Content-Encoding", encoding);
  10382. });
  10383. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10384. auto se = detail::scope_exit([&] {
  10385. svr.stop();
  10386. t.join();
  10387. ASSERT_FALSE(svr.is_running());
  10388. });
  10389. svr.wait_until_ready();
  10390. Client cli(HOST, PORT);
  10391. // Non-streaming
  10392. {
  10393. auto res = cli.Get(path);
  10394. ASSERT_TRUE(res);
  10395. EXPECT_EQ(StatusCode::OK_200, res->status);
  10396. EXPECT_EQ(original, res->body);
  10397. }
  10398. // Streaming
  10399. {
  10400. auto h = cli.open_stream("GET", path);
  10401. ASSERT_TRUE(h.is_valid());
  10402. EXPECT_EQ(original, read_all(h));
  10403. }
  10404. }
  10405. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10406. TEST(ParityTest, Gzip) {
  10407. test_compression_parity<detail::gzip_compressor>(
  10408. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10409. }
  10410. #endif
  10411. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10412. TEST(ParityTest, Brotli) {
  10413. test_compression_parity<detail::brotli_compressor>(
  10414. "Hello, brotli parity test payload", "/parity-br", "br");
  10415. }
  10416. #endif
  10417. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10418. TEST(ParityTest, Zstd) {
  10419. test_compression_parity<detail::zstd_compressor>(
  10420. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10421. }
  10422. #endif
  10423. //==============================================================================
  10424. // New Stream API Tests
  10425. //==============================================================================
  10426. inline std::string read_body(httplib::stream::Result &result) {
  10427. std::string body;
  10428. while (result.next()) {
  10429. body.append(result.data(), result.size());
  10430. }
  10431. return body;
  10432. }
  10433. TEST(ClientConnectionTest, Basic) {
  10434. httplib::ClientConnection conn;
  10435. EXPECT_FALSE(conn.is_open());
  10436. conn.sock = 1;
  10437. EXPECT_TRUE(conn.is_open());
  10438. httplib::ClientConnection conn2(std::move(conn));
  10439. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10440. conn2.sock = INVALID_SOCKET;
  10441. }
  10442. // Unified test server for all stream::* tests
  10443. class StreamApiTest : public ::testing::Test {
  10444. protected:
  10445. void SetUp() override {
  10446. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10447. res.set_content("Hello World!", "text/plain");
  10448. });
  10449. svr_.Get("/echo-params",
  10450. [](const httplib::Request &req, httplib::Response &res) {
  10451. std::string r;
  10452. for (const auto &p : req.params) {
  10453. if (!r.empty()) r += "&";
  10454. r += p.first + "=" + p.second;
  10455. }
  10456. res.set_content(r, "text/plain");
  10457. });
  10458. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10459. res.set_content(req.body, req.get_header_value("Content-Type"));
  10460. });
  10461. svr_.Post("/echo-headers",
  10462. [](const httplib::Request &req, httplib::Response &res) {
  10463. std::string r;
  10464. for (const auto &h : req.headers)
  10465. r += h.first + ": " + h.second + "\n";
  10466. res.set_content(r, "text/plain");
  10467. });
  10468. svr_.Post("/echo-params",
  10469. [](const httplib::Request &req, httplib::Response &res) {
  10470. std::string r = "params:";
  10471. for (const auto &p : req.params)
  10472. r += p.first + "=" + p.second + ";";
  10473. res.set_content(r + " body:" + req.body, "text/plain");
  10474. });
  10475. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10476. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10477. });
  10478. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10479. res.set_content("PUT:" + req.body, "text/plain");
  10480. });
  10481. svr_.Patch("/echo",
  10482. [](const httplib::Request &req, httplib::Response &res) {
  10483. res.set_content("PATCH:" + req.body, "text/plain");
  10484. });
  10485. svr_.Delete(
  10486. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10487. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10488. "text/plain");
  10489. });
  10490. svr_.Get("/head-test",
  10491. [](const httplib::Request &, httplib::Response &res) {
  10492. res.set_content("body for HEAD", "text/plain");
  10493. });
  10494. svr_.Options("/options",
  10495. [](const httplib::Request &, httplib::Response &res) {
  10496. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10497. });
  10498. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10499. svr_.wait_until_ready();
  10500. }
  10501. void TearDown() override {
  10502. svr_.stop();
  10503. if (thread_.joinable()) thread_.join();
  10504. }
  10505. httplib::Server svr_;
  10506. std::thread thread_;
  10507. };
  10508. // stream::Get tests
  10509. TEST_F(StreamApiTest, GetBasic) {
  10510. httplib::Client cli(HOST, PORT);
  10511. auto result = httplib::stream::Get(cli, "/hello");
  10512. ASSERT_TRUE(result.is_valid());
  10513. EXPECT_EQ(200, result.status());
  10514. EXPECT_EQ("Hello World!", read_body(result));
  10515. }
  10516. TEST_F(StreamApiTest, GetWithParams) {
  10517. httplib::Client cli(HOST, PORT);
  10518. httplib::Params params{{"foo", "bar"}};
  10519. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10520. ASSERT_TRUE(result.is_valid());
  10521. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10522. }
  10523. TEST_F(StreamApiTest, GetConnectionError) {
  10524. httplib::Client cli(HOST, 9999);
  10525. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10526. }
  10527. TEST_F(StreamApiTest, Get404) {
  10528. httplib::Client cli(HOST, PORT);
  10529. auto result = httplib::stream::Get(cli, "/nonexistent");
  10530. EXPECT_TRUE(result.is_valid());
  10531. EXPECT_EQ(404, result.status());
  10532. }
  10533. // stream::Post tests
  10534. TEST_F(StreamApiTest, PostBasic) {
  10535. httplib::Client cli(HOST, PORT);
  10536. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10537. "application/json");
  10538. ASSERT_TRUE(result.is_valid());
  10539. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10540. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10541. }
  10542. TEST_F(StreamApiTest, PostWithHeaders) {
  10543. httplib::Client cli(HOST, PORT);
  10544. httplib::Headers headers{{"X-Custom", "value"}};
  10545. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10546. "text/plain");
  10547. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10548. }
  10549. TEST_F(StreamApiTest, PostWithParams) {
  10550. httplib::Client cli(HOST, PORT);
  10551. httplib::Params params{{"k", "v"}};
  10552. auto result =
  10553. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10554. auto body = read_body(result);
  10555. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10556. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10557. }
  10558. TEST_F(StreamApiTest, PostLarge) {
  10559. httplib::Client cli(HOST, PORT);
  10560. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10561. size_t total = 0;
  10562. while (result.next()) {
  10563. total += result.size();
  10564. }
  10565. EXPECT_EQ(100u * 1024u, total);
  10566. }
  10567. // stream::Put/Patch tests
  10568. TEST_F(StreamApiTest, PutAndPatch) {
  10569. httplib::Client cli(HOST, PORT);
  10570. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10571. EXPECT_EQ("PUT:test", read_body(put));
  10572. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10573. EXPECT_EQ("PATCH:test", read_body(patch));
  10574. }
  10575. // stream::Delete tests
  10576. TEST_F(StreamApiTest, Delete) {
  10577. httplib::Client cli(HOST, PORT);
  10578. auto del1 = httplib::stream::Delete(cli, "/resource");
  10579. EXPECT_EQ("Deleted", read_body(del1));
  10580. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10581. EXPECT_EQ("Deleted:data", read_body(del2));
  10582. }
  10583. // stream::Head/Options tests
  10584. TEST_F(StreamApiTest, HeadAndOptions) {
  10585. httplib::Client cli(HOST, PORT);
  10586. auto head = httplib::stream::Head(cli, "/head-test");
  10587. EXPECT_TRUE(head.is_valid());
  10588. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10589. auto opts = httplib::stream::Options(cli, "/options");
  10590. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10591. }
  10592. // SSL stream::* tests
  10593. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10594. class SSLStreamApiTest : public ::testing::Test {
  10595. protected:
  10596. void SetUp() override {
  10597. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10598. res.set_content("Hello SSL!", "text/plain");
  10599. });
  10600. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10601. res.set_content(req.body, "text/plain");
  10602. });
  10603. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10604. svr_.wait_until_ready();
  10605. }
  10606. void TearDown() override {
  10607. svr_.stop();
  10608. if (thread_.joinable()) thread_.join();
  10609. }
  10610. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10611. std::thread thread_;
  10612. };
  10613. TEST_F(SSLStreamApiTest, GetAndPost) {
  10614. httplib::SSLClient cli("127.0.0.1", 8803);
  10615. cli.enable_server_certificate_verification(false);
  10616. auto get = httplib::stream::Get(cli, "/hello");
  10617. EXPECT_EQ("Hello SSL!", read_body(get));
  10618. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10619. EXPECT_EQ("test", read_body(post));
  10620. }
  10621. #endif
  10622. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10623. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10624. // BodyReader
  10625. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10626. // Test that read timeout during streaming is detected
  10627. // Use a large content-length response where server delays mid-stream
  10628. Server svr;
  10629. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10630. // Send a large response with delay in the middle
  10631. res.set_content_provider(
  10632. 1000, // content_length
  10633. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10634. if (offset < 100) {
  10635. // Send first 100 bytes immediately
  10636. std::string data(100, 'A');
  10637. sink.write(data.c_str(), data.size());
  10638. return true;
  10639. }
  10640. // Then delay longer than client timeout
  10641. std::this_thread::sleep_for(std::chrono::seconds(3));
  10642. std::string data(900, 'B');
  10643. sink.write(data.c_str(), data.size());
  10644. return true;
  10645. });
  10646. });
  10647. auto port = 8091;
  10648. std::thread t([&]() { svr.listen("localhost", port); });
  10649. svr.wait_until_ready();
  10650. Client cli("localhost", port);
  10651. cli.set_read_timeout(1, 0); // 1 second timeout
  10652. auto handle = cli.open_stream("GET", "/slow-stream");
  10653. ASSERT_TRUE(handle.is_valid());
  10654. char buf[256];
  10655. ssize_t total = 0;
  10656. ssize_t n;
  10657. bool got_error = false;
  10658. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10659. total += n;
  10660. }
  10661. if (n < 0) {
  10662. got_error = true;
  10663. // Should be timeout or read error
  10664. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10665. handle.get_read_error() == Error::Read)
  10666. << "Actual error: " << to_string(handle.get_read_error());
  10667. }
  10668. // Either we got an error, or we got less data than expected
  10669. EXPECT_TRUE(got_error || total < 1000)
  10670. << "Expected timeout but got all " << total << " bytes";
  10671. svr.stop();
  10672. t.join();
  10673. }
  10674. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10675. // Test connection closed detection via BodyReader
  10676. Server svr;
  10677. std::atomic<bool> close_now{false};
  10678. svr.Get("/will-close", [&](const Request &, Response &res) {
  10679. res.set_content_provider(
  10680. 10000, // Large content_length that we won't fully send
  10681. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10682. if (offset < 100) {
  10683. std::string data(100, 'X');
  10684. sink.write(data.c_str(), data.size());
  10685. return true;
  10686. }
  10687. // Wait for signal then abort
  10688. while (!close_now) {
  10689. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10690. }
  10691. return false; // Abort - server will close connection
  10692. });
  10693. });
  10694. auto port = 8092;
  10695. std::thread t([&]() { svr.listen("localhost", port); });
  10696. svr.wait_until_ready();
  10697. Client cli("localhost", port);
  10698. auto handle = cli.open_stream("GET", "/will-close");
  10699. ASSERT_TRUE(handle.is_valid());
  10700. char buf[256];
  10701. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10702. EXPECT_GT(n, 0) << "First read should succeed";
  10703. // Signal server to close
  10704. close_now = true;
  10705. // Keep reading until error or EOF
  10706. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10707. // Keep reading
  10708. }
  10709. // Should get an error since content_length wasn't satisfied
  10710. if (n < 0) {
  10711. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10712. handle.get_read_error() == Error::Read)
  10713. << "Actual error: " << to_string(handle.get_read_error());
  10714. }
  10715. svr.stop();
  10716. t.join();
  10717. }
  10718. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10719. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10720. // Test that read timeout during SSL streaming is detected
  10721. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10722. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10723. res.set_content_provider(
  10724. 1000, "text/plain",
  10725. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10726. if (offset < 100) {
  10727. std::string data(100, 'A');
  10728. sink.write(data.c_str(), data.size());
  10729. return true;
  10730. }
  10731. std::this_thread::sleep_for(std::chrono::seconds(3));
  10732. std::string data(900, 'B');
  10733. sink.write(data.c_str(), data.size());
  10734. return true;
  10735. });
  10736. });
  10737. auto port = 8093;
  10738. std::thread t([&]() { svr.listen("localhost", port); });
  10739. svr.wait_until_ready();
  10740. SSLClient cli("localhost", port);
  10741. cli.enable_server_certificate_verification(false);
  10742. cli.set_read_timeout(1, 0); // 1 second timeout
  10743. auto handle = cli.open_stream("GET", "/slow-stream");
  10744. ASSERT_TRUE(handle.is_valid());
  10745. char buf[256];
  10746. ssize_t total = 0;
  10747. ssize_t n;
  10748. bool got_error = false;
  10749. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10750. total += n;
  10751. }
  10752. if (n < 0) {
  10753. got_error = true;
  10754. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10755. handle.get_read_error() == Error::Read)
  10756. << "Actual error: " << to_string(handle.get_read_error());
  10757. }
  10758. EXPECT_TRUE(got_error || total < 1000)
  10759. << "Expected timeout but got all " << total << " bytes";
  10760. svr.stop();
  10761. t.join();
  10762. }
  10763. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10764. // Test SSL connection closed detection
  10765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10766. std::atomic<bool> close_now{false};
  10767. svr.Get("/will-close", [&](const Request &, Response &res) {
  10768. res.set_content_provider(
  10769. 10000, "text/plain",
  10770. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10771. if (offset < 100) {
  10772. std::string data(100, 'X');
  10773. sink.write(data.c_str(), data.size());
  10774. return true;
  10775. }
  10776. while (!close_now) {
  10777. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10778. }
  10779. return false;
  10780. });
  10781. });
  10782. auto port = 8094;
  10783. std::thread t([&]() { svr.listen("localhost", port); });
  10784. svr.wait_until_ready();
  10785. SSLClient cli("localhost", port);
  10786. cli.enable_server_certificate_verification(false);
  10787. auto handle = cli.open_stream("GET", "/will-close");
  10788. ASSERT_TRUE(handle.is_valid());
  10789. char buf[256];
  10790. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10791. EXPECT_GT(n, 0);
  10792. // Signal server to close
  10793. close_now = true;
  10794. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10795. // Keep reading
  10796. }
  10797. if (n < 0) {
  10798. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10799. handle.get_read_error() == Error::Read)
  10800. << "Actual error: " << to_string(handle.get_read_error());
  10801. }
  10802. svr.stop();
  10803. t.join();
  10804. }
  10805. #endif
  10806. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10807. using namespace httplib;
  10808. // Create a test file
  10809. const char *fname = "etag_testfile.txt";
  10810. const char *content = "etag-content";
  10811. {
  10812. std::ofstream ofs(fname);
  10813. ofs << content;
  10814. ASSERT_TRUE(ofs.good());
  10815. }
  10816. Server svr;
  10817. svr.set_mount_point("/static", ".");
  10818. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  10819. svr.wait_until_ready();
  10820. Client cli(HOST, PORT);
  10821. // First request: should get 200 with ETag header
  10822. auto res1 = cli.Get("/static/etag_testfile.txt");
  10823. ASSERT_TRUE(res1);
  10824. ASSERT_EQ(200, res1->status);
  10825. ASSERT_TRUE(res1->has_header("ETag"));
  10826. std::string etag = res1->get_header_value("ETag");
  10827. EXPECT_FALSE(etag.empty());
  10828. // Verify ETag format: W/"hex-hex"
  10829. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10830. EXPECT_EQ('W', etag[0]);
  10831. EXPECT_EQ('/', etag[1]);
  10832. EXPECT_EQ('"', etag[2]);
  10833. EXPECT_EQ('"', etag.back());
  10834. // Exact match: expect 304 Not Modified
  10835. Headers h2 = {{"If-None-Match", etag}};
  10836. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10837. ASSERT_TRUE(res2);
  10838. EXPECT_EQ(304, res2->status);
  10839. // Wildcard match: expect 304 Not Modified
  10840. Headers h3 = {{"If-None-Match", "*"}};
  10841. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10842. ASSERT_TRUE(res3);
  10843. EXPECT_EQ(304, res3->status);
  10844. // Non-matching ETag: expect 200
  10845. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10846. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10847. ASSERT_TRUE(res4);
  10848. EXPECT_EQ(200, res4->status);
  10849. // Multiple ETags with one matching: expect 304
  10850. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10851. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10852. ASSERT_TRUE(res5);
  10853. EXPECT_EQ(304, res5->status);
  10854. svr.stop();
  10855. t.join();
  10856. std::remove(fname);
  10857. }
  10858. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10859. using namespace httplib;
  10860. Server svr;
  10861. svr.set_mount_point("/static", ".");
  10862. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10863. svr.wait_until_ready();
  10864. Client cli(HOST, PORT);
  10865. // Send If-None-Match: * to a non-existent file
  10866. Headers h = {{"If-None-Match", "*"}};
  10867. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10868. ASSERT_TRUE(res);
  10869. EXPECT_EQ(404, res->status);
  10870. svr.stop();
  10871. t.join();
  10872. }
  10873. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10874. using namespace httplib;
  10875. // Create a test file
  10876. const char *fname = "ims_testfile.txt";
  10877. const char *content = "if-modified-since-test";
  10878. {
  10879. std::ofstream ofs(fname);
  10880. ofs << content;
  10881. ASSERT_TRUE(ofs.good());
  10882. }
  10883. Server svr;
  10884. svr.set_mount_point("/static", ".");
  10885. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10886. svr.wait_until_ready();
  10887. Client cli(HOST, PORT);
  10888. // First request: should get 200 with Last-Modified header
  10889. auto res1 = cli.Get("/static/ims_testfile.txt");
  10890. ASSERT_TRUE(res1);
  10891. ASSERT_EQ(200, res1->status);
  10892. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10893. std::string last_modified = res1->get_header_value("Last-Modified");
  10894. EXPECT_FALSE(last_modified.empty());
  10895. // If-Modified-Since with same time: expect 304
  10896. Headers h2 = {{"If-Modified-Since", last_modified}};
  10897. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10898. ASSERT_TRUE(res2);
  10899. EXPECT_EQ(304, res2->status);
  10900. // If-Modified-Since with future time: expect 304
  10901. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10902. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10903. ASSERT_TRUE(res3);
  10904. EXPECT_EQ(304, res3->status);
  10905. // If-Modified-Since with past time: expect 200
  10906. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10907. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10908. ASSERT_TRUE(res4);
  10909. EXPECT_EQ(200, res4->status);
  10910. // If-None-Match takes precedence over If-Modified-Since
  10911. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10912. ASSERT_TRUE(res1->has_header("ETag"));
  10913. std::string etag = res1->get_header_value("ETag");
  10914. Headers h5 = {{"If-None-Match", etag},
  10915. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10916. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10917. ASSERT_TRUE(res5);
  10918. EXPECT_EQ(304, res5->status);
  10919. svr.stop();
  10920. t.join();
  10921. std::remove(fname);
  10922. }
  10923. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10924. using namespace httplib;
  10925. Server svr;
  10926. // Endpoint that returns compressible content
  10927. svr.Get("/compressible", [](const Request &, Response &res) {
  10928. // Return a large enough body to trigger compression
  10929. std::string body(1000, 'a');
  10930. res.set_content(body, "text/plain");
  10931. });
  10932. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10933. svr.wait_until_ready();
  10934. Client cli(HOST, PORT);
  10935. // Request with gzip support: should get Vary header when compressed
  10936. cli.set_compress(true);
  10937. auto res1 = cli.Get("/compressible");
  10938. ASSERT_TRUE(res1);
  10939. EXPECT_EQ(200, res1->status);
  10940. // If Content-Encoding is set, Vary should also be set
  10941. if (res1->has_header("Content-Encoding")) {
  10942. EXPECT_TRUE(res1->has_header("Vary"));
  10943. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10944. }
  10945. // Request without Accept-Encoding header: should not have compression
  10946. Headers h_no_compress;
  10947. auto res2 = cli.Get("/compressible", h_no_compress);
  10948. ASSERT_TRUE(res2);
  10949. EXPECT_EQ(200, res2->status);
  10950. // Verify Vary header is present when compression is applied
  10951. // (the exact behavior depends on server configuration)
  10952. svr.stop();
  10953. t.join();
  10954. }
  10955. TEST(ETagTest, IfRangeWithETag) {
  10956. using namespace httplib;
  10957. // Create a test file with known content
  10958. const char *fname = "if_range_testfile.txt";
  10959. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10960. {
  10961. std::ofstream ofs(fname);
  10962. ofs << content;
  10963. ASSERT_TRUE(ofs.good());
  10964. }
  10965. Server svr;
  10966. svr.set_mount_point("/static", ".");
  10967. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10968. svr.wait_until_ready();
  10969. Client cli(HOST, PORT);
  10970. // First request: get ETag
  10971. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10972. ASSERT_TRUE(res1);
  10973. ASSERT_EQ(200, res1->status);
  10974. ASSERT_TRUE(res1->has_header("ETag"));
  10975. std::string etag = res1->get_header_value("ETag");
  10976. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10977. // Since our server generates weak ETags (W/"..."), If-Range with our
  10978. // ETag should NOT result in partial content - it should return full content.
  10979. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10980. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10981. ASSERT_TRUE(res2);
  10982. // Weak ETag in If-Range -> full content (200), not partial (206)
  10983. EXPECT_EQ(200, res2->status);
  10984. EXPECT_EQ(content, res2->body);
  10985. EXPECT_FALSE(res2->has_header("Content-Range"));
  10986. // Range request with non-matching If-Range (ETag): should get 200 (full
  10987. // content)
  10988. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10989. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10990. ASSERT_TRUE(res3);
  10991. EXPECT_EQ(200, res3->status);
  10992. EXPECT_EQ(content, res3->body);
  10993. EXPECT_FALSE(res3->has_header("Content-Range"));
  10994. // Range request with strong ETag (hypothetical - our server doesn't generate
  10995. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10996. // should return full content)
  10997. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10998. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10999. ASSERT_TRUE(res4);
  11000. EXPECT_EQ(200, res4->status);
  11001. EXPECT_EQ(content, res4->body);
  11002. EXPECT_FALSE(res4->has_header("Content-Range"));
  11003. svr.stop();
  11004. t.join();
  11005. std::remove(fname);
  11006. }
  11007. TEST(ETagTest, IfRangeWithDate) {
  11008. using namespace httplib;
  11009. // Create a test file
  11010. const char *fname = "if_range_date_testfile.txt";
  11011. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  11012. {
  11013. std::ofstream ofs(fname);
  11014. ofs << content;
  11015. ASSERT_TRUE(ofs.good());
  11016. }
  11017. Server svr;
  11018. svr.set_mount_point("/static", ".");
  11019. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11020. svr.wait_until_ready();
  11021. Client cli(HOST, PORT);
  11022. // First request: get Last-Modified
  11023. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11024. ASSERT_TRUE(res1);
  11025. ASSERT_EQ(200, res1->status);
  11026. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11027. std::string last_modified = res1->get_header_value("Last-Modified");
  11028. // Range request with matching If-Range (date): should get 206
  11029. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11030. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11031. ASSERT_TRUE(res2);
  11032. EXPECT_EQ(206, res2->status);
  11033. EXPECT_EQ("FGHIJ", res2->body);
  11034. // Range request with old If-Range date: should get 200 (full content)
  11035. Headers h3 = {{"Range", "bytes=5-9"},
  11036. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11037. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11038. ASSERT_TRUE(res3);
  11039. EXPECT_EQ(200, res3->status);
  11040. EXPECT_EQ(content, res3->body);
  11041. // Range request with future If-Range date: should get 206
  11042. Headers h4 = {{"Range", "bytes=0-4"},
  11043. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11044. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11045. ASSERT_TRUE(res4);
  11046. EXPECT_EQ(206, res4->status);
  11047. EXPECT_EQ("ABCDE", res4->body);
  11048. svr.stop();
  11049. t.join();
  11050. std::remove(fname);
  11051. }
  11052. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11053. using namespace httplib;
  11054. const char *fname = "etag_malformed.txt";
  11055. const char *content = "malformed-etag";
  11056. {
  11057. std::ofstream ofs(fname);
  11058. ofs << content;
  11059. ASSERT_TRUE(ofs.good());
  11060. }
  11061. Server svr;
  11062. svr.set_mount_point("/static", ".");
  11063. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11064. svr.wait_until_ready();
  11065. Client cli(HOST, PORT);
  11066. // baseline: should get 200 and an ETag
  11067. auto res1 = cli.Get("/static/etag_malformed.txt");
  11068. ASSERT_TRUE(res1);
  11069. ASSERT_EQ(200, res1->status);
  11070. ASSERT_TRUE(res1->has_header("ETag"));
  11071. // Malformed ETag value (missing quotes) should be treated as non-matching
  11072. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11073. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11074. ASSERT_TRUE(res_bad);
  11075. EXPECT_EQ(200, res_bad->status);
  11076. // Whitespace-only header value should be considered invalid / non-matching
  11077. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11078. "Host: localhost\r\n"
  11079. "If-None-Match: \r\n"
  11080. "Connection: close\r\n"
  11081. "\r\n";
  11082. std::string out;
  11083. ASSERT_TRUE(send_request(5, raw_req, &out));
  11084. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11085. svr.stop();
  11086. t.join();
  11087. std::remove(fname);
  11088. }
  11089. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11090. using namespace httplib;
  11091. const char *fname = "ims_invalid_format.txt";
  11092. const char *content = "ims-bad-format";
  11093. {
  11094. std::ofstream ofs(fname);
  11095. ofs << content;
  11096. ASSERT_TRUE(ofs.good());
  11097. }
  11098. Server svr;
  11099. svr.set_mount_point("/static", ".");
  11100. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11101. svr.wait_until_ready();
  11102. Client cli(HOST, PORT);
  11103. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11104. ASSERT_TRUE(res1);
  11105. ASSERT_EQ(200, res1->status);
  11106. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11107. // If-Modified-Since with invalid format should not result in 304
  11108. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11109. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11110. ASSERT_TRUE(res_bad);
  11111. EXPECT_EQ(200, res_bad->status);
  11112. // If-Range with invalid date format should be treated as mismatch -> full
  11113. // content (200)
  11114. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11115. {"If-Range", "invalid-date"}};
  11116. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11117. ASSERT_TRUE(res_ifrange);
  11118. EXPECT_EQ(200, res_ifrange->status);
  11119. svr.stop();
  11120. t.join();
  11121. std::remove(fname);
  11122. }
  11123. TEST(ETagTest, IfRangeWithMalformedETag) {
  11124. using namespace httplib;
  11125. const char *fname = "ifrange_malformed.txt";
  11126. const std::string content = "0123456789";
  11127. {
  11128. std::ofstream ofs(fname);
  11129. ofs << content;
  11130. ASSERT_TRUE(ofs.good());
  11131. }
  11132. Server svr;
  11133. svr.set_mount_point("/static", ".");
  11134. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11135. svr.wait_until_ready();
  11136. Client cli(HOST, PORT);
  11137. // First request: get ETag
  11138. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11139. ASSERT_TRUE(res1);
  11140. ASSERT_EQ(200, res1->status);
  11141. ASSERT_TRUE(res1->has_header("ETag"));
  11142. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11143. // full content (200)
  11144. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11145. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11146. ASSERT_TRUE(res2);
  11147. EXPECT_EQ(200, res2->status);
  11148. EXPECT_EQ(content, res2->body);
  11149. svr.stop();
  11150. t.join();
  11151. std::remove(fname);
  11152. }
  11153. TEST(ETagTest, ExtremeLargeDateValues) {
  11154. using namespace httplib;
  11155. const char *fname = "ims_extreme_date.txt";
  11156. const char *content = "ims-extreme-date";
  11157. {
  11158. std::ofstream ofs(fname);
  11159. ofs << content;
  11160. ASSERT_TRUE(ofs.good());
  11161. }
  11162. Server svr;
  11163. svr.set_mount_point("/static", ".");
  11164. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11165. svr.wait_until_ready();
  11166. Client cli(HOST, PORT);
  11167. auto res1 = cli.Get(std::string("/static/") + fname);
  11168. ASSERT_TRUE(res1);
  11169. ASSERT_EQ(200, res1->status);
  11170. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11171. // Extremely large year that may overflow date parsing routines.
  11172. Headers h_large_date = {
  11173. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11174. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11175. ASSERT_TRUE(res_bad);
  11176. // Expect server to treat this as invalid/mismatch and return full content
  11177. EXPECT_EQ(200, res_bad->status);
  11178. // If-Range with extremely large date should be treated as mismatch -> full
  11179. // content (200)
  11180. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11181. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11182. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11183. ASSERT_TRUE(res_ifrange);
  11184. EXPECT_EQ(200, res_ifrange->status);
  11185. svr.stop();
  11186. t.join();
  11187. std::remove(fname);
  11188. }
  11189. TEST(ETagTest, NegativeFileModificationTime) {
  11190. using namespace httplib;
  11191. const char *fname = "ims_negative_mtime.txt";
  11192. const std::string content = "negative-mtime";
  11193. {
  11194. std::ofstream ofs(fname);
  11195. ofs << content;
  11196. ASSERT_TRUE(ofs.good());
  11197. }
  11198. // Try to set file mtime to a negative value. This may fail on some
  11199. // platforms/filesystems; if it fails, the test will still verify server
  11200. // behaves safely by performing a regular conditional request.
  11201. #if defined(__APPLE__) || defined(__linux__)
  11202. bool set_negative = false;
  11203. do {
  11204. struct timeval times[2];
  11205. // access time: now
  11206. times[0].tv_sec = time(nullptr);
  11207. times[0].tv_usec = 0;
  11208. // modification time: negative (e.g., -1)
  11209. times[1].tv_sec = -1;
  11210. times[1].tv_usec = 0;
  11211. if (utimes(fname, times) == 0) { set_negative = true; }
  11212. } while (0);
  11213. #else
  11214. bool set_negative = false;
  11215. #endif
  11216. Server svr;
  11217. svr.set_mount_point("/static", ".");
  11218. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11219. svr.wait_until_ready();
  11220. Client cli(HOST, PORT);
  11221. auto res1 = cli.Get(std::string("/static/") + fname);
  11222. ASSERT_TRUE(res1);
  11223. ASSERT_EQ(200, res1->status);
  11224. bool has_last_modified = res1->has_header("Last-Modified");
  11225. std::string last_modified;
  11226. if (has_last_modified) {
  11227. last_modified = res1->get_header_value("Last-Modified");
  11228. }
  11229. if (set_negative) {
  11230. // If we successfully set a negative mtime, ensure server returns a
  11231. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11232. // with an old date and ensure server handles it without crash.
  11233. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11234. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11235. ASSERT_TRUE(res2);
  11236. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11237. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11238. } else {
  11239. // Could not set negative mtime on this platform; fall back to verifying
  11240. // that normal invalid/malformed dates are treated safely (non-304).
  11241. Headers h_bad_date = {
  11242. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11243. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11244. ASSERT_TRUE(res_bad);
  11245. EXPECT_EQ(200, res_bad->status);
  11246. }
  11247. svr.stop();
  11248. t.join();
  11249. std::remove(fname);
  11250. }
  11251. //==============================================================================
  11252. // SSE Parsing Tests
  11253. //==============================================================================
  11254. class SSEParsingTest : public ::testing::Test {
  11255. protected:
  11256. // Test helper that mimics SSE parsing behavior
  11257. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11258. int &retry_ms) {
  11259. // Blank line signals end of event
  11260. if (line.empty() || line == "\r") { return true; }
  11261. // Lines starting with ':' are comments (ignored)
  11262. if (!line.empty() && line[0] == ':') { return false; }
  11263. // Find the colon separator
  11264. auto colon_pos = line.find(':');
  11265. if (colon_pos == std::string::npos) {
  11266. // Line with no colon is treated as field name with empty value
  11267. return false;
  11268. }
  11269. std::string field = line.substr(0, colon_pos);
  11270. std::string value;
  11271. // Value starts after colon, skip optional single space
  11272. if (colon_pos + 1 < line.size()) {
  11273. size_t value_start = colon_pos + 1;
  11274. if (line[value_start] == ' ') { value_start++; }
  11275. value = line.substr(value_start);
  11276. // Remove trailing \r if present
  11277. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11278. }
  11279. // Handle known fields
  11280. if (field == "event") {
  11281. msg.event = value;
  11282. } else if (field == "data") {
  11283. // Multiple data lines are concatenated with newlines
  11284. if (!msg.data.empty()) { msg.data += "\n"; }
  11285. msg.data += value;
  11286. } else if (field == "id") {
  11287. // Empty id is valid (clears the last event ID)
  11288. msg.id = value;
  11289. } else if (field == "retry") {
  11290. // Parse retry interval in milliseconds
  11291. try {
  11292. retry_ms = std::stoi(value);
  11293. } catch (...) {
  11294. // Invalid retry value, ignore
  11295. }
  11296. }
  11297. // Unknown fields are ignored per SSE spec
  11298. return false;
  11299. }
  11300. };
  11301. // Test: Single-line data
  11302. TEST_F(SSEParsingTest, SingleLineData) {
  11303. sse::SSEMessage msg;
  11304. int retry_ms = 3000;
  11305. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11306. EXPECT_EQ(msg.data, "hello");
  11307. EXPECT_EQ(msg.event, "message");
  11308. // Blank line ends event
  11309. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11310. }
  11311. // Test: Multi-line data
  11312. TEST_F(SSEParsingTest, MultiLineData) {
  11313. sse::SSEMessage msg;
  11314. int retry_ms = 3000;
  11315. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11316. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11317. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11318. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11319. }
  11320. // Test: Custom event types
  11321. TEST_F(SSEParsingTest, CustomEventType) {
  11322. sse::SSEMessage msg;
  11323. int retry_ms = 3000;
  11324. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11325. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11326. EXPECT_EQ(msg.event, "update");
  11327. EXPECT_EQ(msg.data, "payload");
  11328. }
  11329. // Test: Event ID handling
  11330. TEST_F(SSEParsingTest, EventIdHandling) {
  11331. sse::SSEMessage msg;
  11332. int retry_ms = 3000;
  11333. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11334. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11335. EXPECT_EQ(msg.id, "12345");
  11336. }
  11337. // Test: Empty event ID (clears last event ID)
  11338. TEST_F(SSEParsingTest, EmptyEventId) {
  11339. sse::SSEMessage msg;
  11340. msg.id = "previous";
  11341. int retry_ms = 3000;
  11342. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11343. EXPECT_EQ(msg.id, "");
  11344. }
  11345. // Test: Retry field parsing
  11346. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11347. sse::SSEMessage msg;
  11348. int retry_ms = 3000;
  11349. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11350. EXPECT_EQ(retry_ms, 5000);
  11351. }
  11352. // Test: Invalid retry value
  11353. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11354. sse::SSEMessage msg;
  11355. int retry_ms = 3000;
  11356. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11357. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11358. }
  11359. // Test: Comments (lines starting with :)
  11360. TEST_F(SSEParsingTest, CommentsIgnored) {
  11361. sse::SSEMessage msg;
  11362. int retry_ms = 3000;
  11363. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11364. EXPECT_EQ(msg.data, "");
  11365. EXPECT_EQ(msg.event, "message");
  11366. }
  11367. // Test: Colon in value
  11368. TEST_F(SSEParsingTest, ColonInValue) {
  11369. sse::SSEMessage msg;
  11370. int retry_ms = 3000;
  11371. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11372. EXPECT_EQ(msg.data, "hello:world:test");
  11373. }
  11374. // Test: Line with no colon (field name only)
  11375. TEST_F(SSEParsingTest, FieldNameOnly) {
  11376. sse::SSEMessage msg;
  11377. int retry_ms = 3000;
  11378. // According to SSE spec, this is treated as field name with empty value
  11379. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11380. // Since we don't recognize "data" without colon, data should be empty
  11381. EXPECT_EQ(msg.data, "");
  11382. }
  11383. // Test: Trailing \r handling
  11384. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11385. sse::SSEMessage msg;
  11386. int retry_ms = 3000;
  11387. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11388. EXPECT_EQ(msg.data, "hello");
  11389. }
  11390. // Test: Unknown fields ignored
  11391. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11392. sse::SSEMessage msg;
  11393. int retry_ms = 3000;
  11394. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11395. EXPECT_EQ(msg.data, "");
  11396. EXPECT_EQ(msg.event, "message");
  11397. }
  11398. // Test: Space after colon is optional
  11399. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11400. sse::SSEMessage msg1, msg2;
  11401. int retry_ms = 3000;
  11402. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11403. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11404. EXPECT_EQ(msg1.data, "hello");
  11405. EXPECT_EQ(msg2.data, "hello");
  11406. }
  11407. // Test: SSEMessage clear
  11408. TEST_F(SSEParsingTest, MessageClear) {
  11409. sse::SSEMessage msg;
  11410. msg.event = "custom";
  11411. msg.data = "some data";
  11412. msg.id = "123";
  11413. msg.clear();
  11414. EXPECT_EQ(msg.event, "message");
  11415. EXPECT_EQ(msg.data, "");
  11416. EXPECT_EQ(msg.id, "");
  11417. }
  11418. // Test: Complete event parsing
  11419. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11420. sse::SSEMessage msg;
  11421. int retry_ms = 3000;
  11422. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11423. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11424. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11425. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11426. // Blank line ends event
  11427. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11428. EXPECT_EQ(msg.event, "notification");
  11429. EXPECT_EQ(msg.id, "evt-42");
  11430. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11431. EXPECT_EQ(retry_ms, 1000);
  11432. }
  11433. //==============================================================================
  11434. // Integration Tests with Server
  11435. //==============================================================================
  11436. class SSEIntegrationTest : public ::testing::Test {
  11437. protected:
  11438. void SetUp() override {
  11439. stop_server_.store(false);
  11440. events_.clear();
  11441. server_ = httplib::detail::make_unique<Server>();
  11442. setup_server();
  11443. start_server();
  11444. }
  11445. void TearDown() override {
  11446. stop_server_.store(true);
  11447. event_cv_.notify_all();
  11448. server_->stop();
  11449. if (server_thread_.joinable()) { server_thread_.join(); }
  11450. }
  11451. void setup_server() {
  11452. // Simple SSE endpoint
  11453. server_->Get("/events", [this](const Request &req, Response &res) {
  11454. auto last_id = req.get_header_value("Last-Event-ID");
  11455. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11456. res.set_chunked_content_provider(
  11457. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11458. std::unique_lock<std::mutex> lock(event_mutex_);
  11459. if (event_cv_.wait_for(
  11460. lock, std::chrono::milliseconds(200), [this] {
  11461. return !events_.empty() || stop_server_.load();
  11462. })) {
  11463. if (stop_server_.load()) { return false; }
  11464. if (!events_.empty()) {
  11465. std::string event = events_.front();
  11466. events_.erase(events_.begin());
  11467. sink.write(event.data(), event.size());
  11468. return true;
  11469. }
  11470. }
  11471. return !stop_server_.load();
  11472. });
  11473. });
  11474. // Endpoint that returns error
  11475. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11476. res.status = 500;
  11477. res.set_content("Internal Server Error", "text/plain");
  11478. });
  11479. // Endpoint for custom event types
  11480. server_->Get("/custom-events", [](const Request &, Response &res) {
  11481. res.set_chunked_content_provider(
  11482. "text/event-stream", [](size_t offset, DataSink &sink) {
  11483. if (offset == 0) {
  11484. std::string event = "event: update\ndata: updated\n\n"
  11485. "event: delete\ndata: deleted\n\n";
  11486. sink.write(event.data(), event.size());
  11487. }
  11488. return false; // End stream after sending
  11489. });
  11490. });
  11491. }
  11492. void start_server() {
  11493. port_ = server_->bind_to_any_port(HOST);
  11494. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11495. // Wait for server to start
  11496. while (!server_->is_running()) {
  11497. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11498. }
  11499. }
  11500. int get_port() const { return port_; }
  11501. void send_event(const std::string &event) {
  11502. std::lock_guard<std::mutex> lock(event_mutex_);
  11503. events_.push_back(event);
  11504. event_cv_.notify_all();
  11505. }
  11506. std::unique_ptr<Server> server_;
  11507. std::thread server_thread_;
  11508. std::mutex event_mutex_;
  11509. std::condition_variable event_cv_;
  11510. std::vector<std::string> events_;
  11511. std::atomic<bool> stop_server_{false};
  11512. std::string last_received_event_id_;
  11513. int port_ = 0;
  11514. };
  11515. // Test: Successful connection and on_open callback
  11516. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11517. // Add a simple endpoint that sends one event and closes
  11518. server_->Get("/simple-event", [](const Request &, Response &res) {
  11519. res.set_chunked_content_provider(
  11520. "text/event-stream", [](size_t offset, DataSink &sink) {
  11521. if (offset == 0) {
  11522. std::string event = "data: hello\n\n";
  11523. sink.write(event.data(), event.size());
  11524. }
  11525. return false; // Close stream after sending
  11526. });
  11527. });
  11528. Client client("localhost", get_port());
  11529. sse::SSEClient sse(client, "/simple-event");
  11530. std::atomic<bool> open_called{false};
  11531. std::atomic<bool> message_received{false};
  11532. sse.on_open([&open_called]() { open_called.store(true); });
  11533. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11534. if (msg.data == "hello") { message_received.store(true); }
  11535. });
  11536. sse.set_reconnect_interval(100);
  11537. sse.set_max_reconnect_attempts(1);
  11538. // Start async
  11539. sse.start_async();
  11540. // Wait for message to be processed
  11541. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11542. sse.stop();
  11543. EXPECT_TRUE(open_called.load());
  11544. EXPECT_TRUE(message_received.load());
  11545. }
  11546. // Test: on_message callback
  11547. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11548. // Endpoint that sends multiple events then closes
  11549. server_->Get("/multi-event", [](const Request &, Response &res) {
  11550. res.set_chunked_content_provider(
  11551. "text/event-stream", [](size_t offset, DataSink &sink) {
  11552. if (offset == 0) {
  11553. std::string events = "data: message1\n\ndata: message2\n\n";
  11554. sink.write(events.data(), events.size());
  11555. }
  11556. return false;
  11557. });
  11558. });
  11559. Client client("localhost", get_port());
  11560. sse::SSEClient sse(client, "/multi-event");
  11561. std::vector<std::string> received_messages;
  11562. std::mutex messages_mutex;
  11563. sse.on_message([&](const sse::SSEMessage &msg) {
  11564. std::lock_guard<std::mutex> lock(messages_mutex);
  11565. received_messages.push_back(msg.data);
  11566. });
  11567. sse.set_reconnect_interval(100);
  11568. sse.set_max_reconnect_attempts(1);
  11569. sse.start_async();
  11570. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11571. sse.stop();
  11572. std::lock_guard<std::mutex> lock(messages_mutex);
  11573. EXPECT_GE(received_messages.size(), 2u);
  11574. if (received_messages.size() >= 2) {
  11575. EXPECT_EQ(received_messages[0], "message1");
  11576. EXPECT_EQ(received_messages[1], "message2");
  11577. }
  11578. }
  11579. // Test: on_event for specific types
  11580. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11581. Client client("localhost", get_port());
  11582. sse::SSEClient sse(client, "/custom-events");
  11583. std::atomic<bool> update_received{false};
  11584. std::atomic<bool> delete_received{false};
  11585. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11586. if (msg.data == "updated") { update_received.store(true); }
  11587. });
  11588. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11589. if (msg.data == "deleted") { delete_received.store(true); }
  11590. });
  11591. sse.set_max_reconnect_attempts(1);
  11592. sse.start_async();
  11593. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11594. sse.stop();
  11595. EXPECT_TRUE(update_received.load());
  11596. EXPECT_TRUE(delete_received.load());
  11597. }
  11598. // Test: on_error callback on connection failure
  11599. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11600. // Connect to a non-existent port
  11601. Client client("localhost", 59999);
  11602. sse::SSEClient sse(client, "/events");
  11603. std::atomic<bool> error_called{false};
  11604. Error received_error = Error::Success;
  11605. sse.on_error([&](Error err) {
  11606. error_called.store(true);
  11607. received_error = err;
  11608. });
  11609. sse.set_reconnect_interval(50);
  11610. sse.set_max_reconnect_attempts(1);
  11611. sse.start_async();
  11612. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11613. sse.stop();
  11614. EXPECT_TRUE(error_called.load());
  11615. EXPECT_NE(received_error, Error::Success);
  11616. }
  11617. // Test: Last-Event-ID header sent on reconnect
  11618. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11619. // Endpoint that sends event with ID
  11620. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11621. res.set_chunked_content_provider(
  11622. "text/event-stream", [](size_t offset, DataSink &sink) {
  11623. if (offset == 0) {
  11624. std::string event = "id: evt-123\ndata: test\n\n";
  11625. sink.write(event.data(), event.size());
  11626. }
  11627. return false;
  11628. });
  11629. });
  11630. Client client("localhost", get_port());
  11631. sse::SSEClient sse(client, "/event-with-id");
  11632. std::atomic<bool> id_received{false};
  11633. sse.on_message([&](const sse::SSEMessage &msg) {
  11634. if (!msg.id.empty()) { id_received.store(true); }
  11635. });
  11636. sse.set_reconnect_interval(100);
  11637. sse.set_max_reconnect_attempts(1);
  11638. sse.start_async();
  11639. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11640. sse.stop();
  11641. EXPECT_TRUE(id_received.load());
  11642. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11643. }
  11644. // Test: Manual stop
  11645. TEST_F(SSEIntegrationTest, ManualStop) {
  11646. // Endpoint that sends one event and stays open briefly
  11647. std::atomic<bool> handler_running{true};
  11648. server_->Get("/stay-open", [&handler_running](const Request &,
  11649. Response &res) {
  11650. res.set_chunked_content_provider(
  11651. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11652. if (offset == 0) {
  11653. std::string event = "data: connected\n\n";
  11654. sink.write(event.data(), event.size());
  11655. }
  11656. // Keep connection open while handler_running is true
  11657. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11658. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11659. }
  11660. return false;
  11661. });
  11662. });
  11663. Client client("localhost", get_port());
  11664. sse::SSEClient sse(client, "/stay-open");
  11665. std::atomic<bool> connected{false};
  11666. sse.on_open([&connected]() { connected.store(true); });
  11667. sse.set_reconnect_interval(100);
  11668. sse.set_max_reconnect_attempts(1);
  11669. sse.start_async();
  11670. // Wait for connection to establish
  11671. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11672. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11673. }
  11674. EXPECT_TRUE(connected.load());
  11675. EXPECT_TRUE(sse.is_connected());
  11676. // Signal handler to stop
  11677. handler_running.store(false);
  11678. // Stop SSE client
  11679. sse.stop();
  11680. EXPECT_FALSE(sse.is_connected());
  11681. }
  11682. // Test: SSEClient with custom headers
  11683. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11684. // Setup a server endpoint that checks for custom header
  11685. std::atomic<bool> header_received{false};
  11686. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11687. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11688. header_received.store(true);
  11689. }
  11690. res.set_chunked_content_provider("text/event-stream",
  11691. [](size_t, DataSink &) { return false; });
  11692. });
  11693. Client client("localhost", get_port());
  11694. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11695. sse::SSEClient sse(client, "/header-check", headers);
  11696. sse.set_max_reconnect_attempts(1);
  11697. sse.start_async();
  11698. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11699. sse.stop();
  11700. EXPECT_TRUE(header_received.load());
  11701. }
  11702. // Test: Reconnect interval configuration
  11703. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11704. Client client("localhost", get_port());
  11705. sse::SSEClient sse(client, "/events");
  11706. auto &result = sse.set_reconnect_interval(500);
  11707. // Builder pattern should return reference to self
  11708. EXPECT_EQ(&result, &sse);
  11709. }
  11710. // Test: Max reconnect attempts
  11711. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11712. // Connect to non-existent port to force reconnects
  11713. Client client("localhost", 59998);
  11714. sse::SSEClient sse(client, "/events");
  11715. std::atomic<int> error_count{0};
  11716. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11717. sse.set_reconnect_interval(50);
  11718. sse.set_max_reconnect_attempts(2);
  11719. auto start = std::chrono::steady_clock::now();
  11720. sse.start(); // Blocking call
  11721. auto end = std::chrono::steady_clock::now();
  11722. // Should have stopped after 2 failed attempts
  11723. EXPECT_GE(error_count.load(), 2);
  11724. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11725. auto duration =
  11726. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11727. #ifdef _WIN32
  11728. // Windows is much slower for socket connection failures
  11729. EXPECT_LT(duration.count(), 7000);
  11730. #else
  11731. EXPECT_LT(duration.count(), 1000);
  11732. #endif
  11733. }
  11734. // Test: Multi-line data in integration
  11735. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11736. // Endpoint with multi-line data
  11737. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11738. res.set_chunked_content_provider(
  11739. "text/event-stream", [](size_t offset, DataSink &sink) {
  11740. if (offset == 0) {
  11741. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11742. sink.write(event.data(), event.size());
  11743. }
  11744. return false;
  11745. });
  11746. });
  11747. Client client("localhost", get_port());
  11748. sse::SSEClient sse(client, "/multiline-data");
  11749. std::string received_data;
  11750. std::mutex data_mutex;
  11751. sse.on_message([&](const sse::SSEMessage &msg) {
  11752. std::lock_guard<std::mutex> lock(data_mutex);
  11753. received_data = msg.data;
  11754. });
  11755. sse.set_reconnect_interval(100);
  11756. sse.set_max_reconnect_attempts(1);
  11757. sse.start_async();
  11758. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11759. sse.stop();
  11760. std::lock_guard<std::mutex> lock(data_mutex);
  11761. EXPECT_EQ(received_data, "line1\nline2\nline3");
  11762. }
  11763. // Test: Auto-reconnect after server disconnection
  11764. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  11765. std::atomic<int> connection_count{0};
  11766. std::atomic<int> message_count{0};
  11767. // Endpoint that sends one event and closes, forcing reconnect
  11768. server_->Get("/reconnect-test",
  11769. [&connection_count](const Request &, Response &res) {
  11770. connection_count.fetch_add(1);
  11771. res.set_chunked_content_provider(
  11772. "text/event-stream", [](size_t offset, DataSink &sink) {
  11773. if (offset == 0) {
  11774. std::string event = "data: hello\n\n";
  11775. sink.write(event.data(), event.size());
  11776. }
  11777. return false; // Close connection after sending
  11778. });
  11779. });
  11780. Client client("localhost", get_port());
  11781. sse::SSEClient sse(client, "/reconnect-test");
  11782. sse.on_message([&message_count](const sse::SSEMessage &) {
  11783. message_count.fetch_add(1);
  11784. });
  11785. sse.set_reconnect_interval(100);
  11786. sse.set_max_reconnect_attempts(3);
  11787. sse.start_async();
  11788. // Wait long enough for multiple reconnects
  11789. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  11790. sse.stop();
  11791. // Should have connected multiple times (initial + reconnects)
  11792. EXPECT_GE(connection_count.load(), 2);
  11793. // Should have received messages from multiple connections
  11794. EXPECT_GE(message_count.load(), 2);
  11795. }
  11796. // Test: Last-Event-ID sent on reconnect
  11797. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  11798. std::atomic<int> connection_count{0};
  11799. std::vector<std::string> received_last_event_ids;
  11800. std::mutex id_mutex;
  11801. // Endpoint that checks Last-Event-ID header and sends event with ID
  11802. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  11803. int conn = connection_count.fetch_add(1);
  11804. // Capture the Last-Event-ID header from each connection
  11805. {
  11806. std::lock_guard<std::mutex> lock(id_mutex);
  11807. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  11808. }
  11809. res.set_chunked_content_provider(
  11810. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  11811. if (offset == 0) {
  11812. std::string event =
  11813. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  11814. sink.write(event.data(), event.size());
  11815. }
  11816. return false;
  11817. });
  11818. });
  11819. Client client("localhost", get_port());
  11820. sse::SSEClient sse(client, "/reconnect-with-id");
  11821. sse.set_reconnect_interval(100);
  11822. sse.set_max_reconnect_attempts(3);
  11823. sse.start_async();
  11824. // Wait for at least 2 connections
  11825. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11826. sse.stop();
  11827. // Verify behavior
  11828. std::lock_guard<std::mutex> lock(id_mutex);
  11829. EXPECT_GE(received_last_event_ids.size(), 2u);
  11830. // First connection should have no Last-Event-ID
  11831. if (!received_last_event_ids.empty()) {
  11832. EXPECT_EQ(received_last_event_ids[0], "");
  11833. }
  11834. // Second connection should have Last-Event-ID from first connection
  11835. if (received_last_event_ids.size() >= 2) {
  11836. EXPECT_EQ(received_last_event_ids[1], "event-0");
  11837. }
  11838. }
  11839. TEST(Issue2318Test, EmptyHostString) {
  11840. {
  11841. httplib::Client cli_empty("", PORT);
  11842. auto res = cli_empty.Get("/");
  11843. ASSERT_FALSE(res);
  11844. EXPECT_EQ(httplib::Error::Connection, res.error());
  11845. }
  11846. {
  11847. httplib::Client cli(" ", PORT);
  11848. auto res = cli.Get("/");
  11849. ASSERT_FALSE(res);
  11850. EXPECT_EQ(httplib::Error::Connection, res.error());
  11851. }
  11852. }
  11853. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11854. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  11855. Server svr;
  11856. // Set a small payload limit (1KB)
  11857. svr.set_payload_max_length(1024);
  11858. svr.Post("/test", [&](const Request &req, Response &res) {
  11859. res.set_content("Body size: " + std::to_string(req.body.size()),
  11860. "text/plain");
  11861. });
  11862. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11863. auto se = detail::scope_exit([&] {
  11864. svr.stop();
  11865. listen_thread.join();
  11866. });
  11867. svr.wait_until_ready();
  11868. // Create data that compresses well but exceeds limit when decompressed
  11869. // 8KB of repeated null bytes compresses to a very small size
  11870. std::string original_data(8 * 1024, '\0');
  11871. // Compress the data using gzip
  11872. std::string compressed_data;
  11873. detail::gzip_compressor compressor;
  11874. compressor.compress(original_data.data(), original_data.size(), true,
  11875. [&](const char *data, size_t size) {
  11876. compressed_data.append(data, size);
  11877. return true;
  11878. });
  11879. // Verify compression worked (compressed should be much smaller)
  11880. ASSERT_LT(compressed_data.size(), original_data.size());
  11881. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  11882. // Send compressed data with Content-Encoding: gzip
  11883. Client cli(HOST, PORT);
  11884. Headers headers = {{"Content-Encoding", "gzip"}};
  11885. auto res =
  11886. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  11887. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  11888. ASSERT_TRUE(res);
  11889. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11890. }
  11891. #endif