test.cc 697 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895
  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 <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  258. ASSERT_EQ(0, listen(s, 1));
  259. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  260. ASSERT_EQ(0, close(s));
  261. }};
  262. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  263. std::thread cli{[&] {
  264. const int s = socket(AF_INET, SOCK_STREAM, 0);
  265. ASSERT_LE(0, s);
  266. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, close(s));
  268. }};
  269. cli.join();
  270. svr.join();
  271. ASSERT_NE(disconnected_svr_sock, -1);
  272. const auto asSocketStream = [&](socket_t fd,
  273. std::function<bool(Stream &)> func) {
  274. return detail::process_client_socket(
  275. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  276. };
  277. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  278. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  279. // wait_writable() returns true because select_write() only checks if the
  280. // send buffer has space. Peer disconnection is detected later by send().
  281. EXPECT_TRUE(ss.wait_writable());
  282. return true;
  283. });
  284. ASSERT_EQ(0, close(disconnected_svr_sock));
  285. }
  286. #endif // #ifndef _WIN32
  287. TEST(SetSocketOptTest, TcpNoDelay) {
  288. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  289. ASSERT_NE(sock, INVALID_SOCKET);
  290. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  291. int val = 0;
  292. socklen_t len = sizeof(val);
  293. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  294. reinterpret_cast<char *>(&val), &len));
  295. EXPECT_NE(val, 0);
  296. detail::close_socket(sock);
  297. }
  298. TEST(ClientTest, MoveConstructible) {
  299. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  300. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  301. }
  302. TEST(ClientTest, MoveAssignable) {
  303. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  304. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  305. }
  306. #ifdef _WIN32
  307. TEST(StartupTest, WSAStartup) {
  308. WSADATA wsaData;
  309. int ret = WSAStartup(0x0002, &wsaData);
  310. ASSERT_EQ(0, ret);
  311. }
  312. #endif
  313. TEST(DecodePathTest, PercentCharacter) {
  314. EXPECT_EQ(
  315. decode_path_component(
  316. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  317. U8("descrip=Gastos áéíóúñÑ 6"));
  318. }
  319. TEST(DecodePathTest, PercentCharacterNUL) {
  320. string expected;
  321. expected.push_back('x');
  322. expected.push_back('\0');
  323. expected.push_back('x');
  324. EXPECT_EQ(decode_path_component("x%00x"), expected);
  325. }
  326. TEST(DecodePathTest, UnicodeEncoding) {
  327. // %u0041 = 'A' (1-byte UTF-8)
  328. EXPECT_EQ("A", decode_path_component("%u0041"));
  329. // %u00E9 = 'é' (2-byte UTF-8)
  330. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  331. // %u3042 = 'あ' (3-byte UTF-8)
  332. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  333. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  334. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  335. // %uD800 = surrogate (invalid, silently dropped)
  336. EXPECT_EQ("", decode_path_component("%uD800"));
  337. }
  338. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  339. // A sign or whitespace inside the two-character escape window must not be
  340. // accepted as a valid percent-encoding; the sequence is passed through
  341. // literally, matching decode_uri_component / decode_path_component.
  342. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  343. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  344. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  345. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  346. // Well-formed escapes still decode.
  347. EXPECT_EQ("-", decode_query_component("%2D", false));
  348. EXPECT_EQ("A", decode_query_component("%41", false));
  349. }
  350. TEST(SanitizeFilenameTest, VariousPatterns) {
  351. // Path traversal
  352. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  353. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  354. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  355. // Normal and edge cases
  356. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  357. EXPECT_EQ("filename.txt",
  358. httplib::sanitize_filename("/path/to/filename.txt"));
  359. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  360. EXPECT_EQ("", httplib::sanitize_filename(".."));
  361. EXPECT_EQ("", httplib::sanitize_filename(""));
  362. // Null bytes stripped
  363. EXPECT_EQ("safe.txt",
  364. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  365. // Whitespace-only rejected
  366. EXPECT_EQ("", httplib::sanitize_filename(" "));
  367. }
  368. // Forward declaration (see the base64_encode note below): split builds move the
  369. // definition into httplib.cc, so re-declaring it here lets the test link.
  370. namespace httplib {
  371. namespace detail {
  372. bool is_chunked_transfer_encoding(const Headers &headers);
  373. } // namespace detail
  374. } // namespace httplib
  375. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  376. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  377. auto make = [](std::initializer_list<const char *> lines) {
  378. Headers h;
  379. for (auto te : lines) {
  380. if (te) { h.emplace("Transfer-Encoding", te); }
  381. }
  382. return h;
  383. };
  384. // Sole coding, matched case-insensitively.
  385. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  386. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  387. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  388. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  389. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  390. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  392. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  393. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  395. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  396. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  397. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  398. // were received, into one list. Headers preserves that order, so the answer
  399. // is decided by the last coding of the last line and the order the lines
  400. // arrived in is significant.
  401. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  403. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  404. // The split can fall anywhere in the list.
  405. EXPECT_TRUE(
  406. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  407. EXPECT_FALSE(
  408. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  409. // A trailing line naming no coding leaves the list ending in nothing, so it
  410. // must not inherit the chunked from the line before it.
  411. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  412. }
  413. // Forward declaration: in split builds split.py strips `inline` and moves the
  414. // definition into httplib.cc, so detail::base64_encode is not visible from the
  415. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  416. // in both header-only and split builds.
  417. namespace httplib {
  418. namespace detail {
  419. std::string base64_encode(const std::string &in);
  420. } // namespace detail
  421. } // namespace httplib
  422. TEST(Base64EncodeTest, KnownAnswers) {
  423. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  424. // where the accumulator's top bit is already set before the next shift.
  425. EXPECT_EQ("", detail::base64_encode(""));
  426. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  427. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  428. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  429. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  430. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  431. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  432. // High bytes keep the top bit set across several rounds.
  433. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  434. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  435. }
  436. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  437. string unescapedCharacters = "-_.!~*'()";
  438. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  439. }
  440. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  441. string reservedCharacters = ";,/?:@&=+$";
  442. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  443. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  444. }
  445. TEST(ClientQueryOrder, PreserveOrder) {
  446. // This test reproduces Issue #2259: client may reorder query parameters
  447. // when sending a GET request. The expected behavior is that the client
  448. // preserves the original query string order when the caller supplied it
  449. // as part of the path.
  450. Server svr;
  451. svr.Get("/", [&](const Request &req, Response &res) {
  452. // Echo back the raw target so the test can assert ordering
  453. res.set_content(req.target, "text/plain");
  454. });
  455. std::thread t{[&] { svr.listen(HOST, PORT); }};
  456. auto se = detail::scope_exit([&] {
  457. svr.stop();
  458. t.join();
  459. ASSERT_FALSE(svr.is_running());
  460. });
  461. svr.wait_until_ready();
  462. Client cli(HOST, PORT);
  463. ASSERT_TRUE(cli.is_valid());
  464. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  465. auto res = cli.Get(original);
  466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  467. // Expect the echoed target to exactly match the original path (order
  468. // preserved)
  469. EXPECT_EQ(res->body, original);
  470. }
  471. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  472. string chineseCharacters = U8("中国語");
  473. string russianCharacters = U8("дом");
  474. string brazilianCharacters = U8("óculos");
  475. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  476. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  477. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  478. "%D0%B4%D0%BE%D0%BC");
  479. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  480. }
  481. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  482. string unescapedCharacters = "-_.!~*'()";
  483. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  484. }
  485. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  486. string reservedCharacters = ";,/?:@&=+$";
  487. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  488. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  489. }
  490. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  491. string chineseCharacters = U8("中国語");
  492. string russianCharacters = U8("дом");
  493. string brazilianCharacters = U8("óculos");
  494. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  495. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  496. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  497. "%D0%B4%D0%BE%D0%BC");
  498. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  499. }
  500. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  501. // Issue #2082 use case: encoding path component with ampersand
  502. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  503. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  504. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  505. }
  506. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  507. string unescapedCharacters = "-_.!~*'()";
  508. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  509. }
  510. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  511. string reservedCharacters = ";,/?:@&=+$#";
  512. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  513. }
  514. TEST(EncodeUriTest, TestUTF8Characters) {
  515. string chineseCharacters = U8("中国語");
  516. string russianCharacters = U8("дом");
  517. string brazilianCharacters = U8("óculos");
  518. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  519. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  520. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  521. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  522. }
  523. TEST(EncodeUriTest, TestCompleteUri) {
  524. string uri =
  525. "https://example.com/path/to/resource?query=value&param=test#fragment";
  526. EXPECT_EQ(
  527. httplib::encode_uri(uri),
  528. "https://example.com/path/to/resource?query=value&param=test#fragment");
  529. }
  530. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  531. string uri =
  532. "https://example.com/path with spaces/file name.html?q=hello world";
  533. EXPECT_EQ(httplib::encode_uri(uri),
  534. "https://example.com/path%20with%20spaces/"
  535. "file%20name.html?q=hello%20world");
  536. }
  537. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  538. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  539. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  540. }
  541. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  542. string unescapedCharacters = "-_.!~*'()";
  543. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  544. }
  545. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  546. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  547. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  548. string encodedBrazilian = "%C3%B3culos";
  549. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  550. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  551. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  552. }
  553. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  554. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  556. "Piri Tommy Villiers - on & on");
  557. }
  558. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  559. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  560. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  561. }
  562. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  563. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  564. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  565. }
  566. TEST(DecodeUriTest, TestUTF8Characters) {
  567. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  568. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  569. string encodedBrazilian = "%C3%B3culos";
  570. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  571. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  572. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  573. }
  574. TEST(DecodeUriTest, TestCompleteUri) {
  575. string encodedUri = "https://example.com/path%20with%20spaces/"
  576. "file%20name.html?q=hello%20world";
  577. EXPECT_EQ(
  578. httplib::decode_uri(encodedUri),
  579. "https://example.com/path with spaces/file name.html?q=hello world");
  580. }
  581. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  582. string original =
  583. "https://example.com/path with spaces/file name.html?q=hello world";
  584. string encoded = httplib::encode_uri(original);
  585. string decoded = httplib::decode_uri(encoded);
  586. EXPECT_EQ(decoded, original);
  587. }
  588. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  589. string original = "Piri Tommy Villiers - on & on";
  590. string encoded = httplib::encode_uri_component(original);
  591. string decoded = httplib::decode_uri_component(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(TrimTests, TrimStringTests) {
  595. EXPECT_EQ("abc", detail::trim_copy("abc"));
  596. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  597. EXPECT_TRUE(detail::trim_copy("").empty());
  598. }
  599. TEST(AsciiTest, LocaleIndependentClassification) {
  600. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  601. // which consult the global C locale: std::isalnum(0xC5) can return true
  602. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  603. // helpers must classify every byte by the ASCII grammar alone.
  604. for (int i = 0; i < 256; i++) {
  605. auto c = static_cast<char>(i);
  606. auto is_digit = i >= '0' && i <= '9';
  607. auto is_upper = i >= 'A' && i <= 'Z';
  608. auto is_lower = i >= 'a' && i <= 'z';
  609. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  610. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  611. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  612. << "byte " << i;
  613. }
  614. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  615. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  616. // Non-ASCII bytes must be percent-encoded, never passed through as
  617. // alphanumeric.
  618. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  619. }
  620. TEST(FromCharsTest, Double) {
  621. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  622. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  623. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  624. auto parse = [](const std::string &s, double &v) {
  625. return detail::from_chars(s.data(), s.data() + s.size(), v);
  626. };
  627. double v = -1.0;
  628. // Representative quality values.
  629. EXPECT_EQ(parse("0", v).ec, std::errc{});
  630. EXPECT_DOUBLE_EQ(v, 0.0);
  631. EXPECT_EQ(parse("1", v).ec, std::errc{});
  632. EXPECT_DOUBLE_EQ(v, 1.0);
  633. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  634. EXPECT_DOUBLE_EQ(v, 0.8);
  635. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  636. EXPECT_DOUBLE_EQ(v, 0.001);
  637. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  638. EXPECT_DOUBLE_EQ(v, 1.0);
  639. // A missing integer or fractional part is tolerated.
  640. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  641. EXPECT_DOUBLE_EQ(v, 0.5);
  642. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  643. EXPECT_DOUBLE_EQ(v, 5.0);
  644. // Values outside [0, 1] still parse; the caller range-checks them.
  645. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  646. EXPECT_DOUBLE_EQ(v, 123.456);
  647. // Stops at the first byte that is not part of the number and reports where.
  648. std::string trailing = "0.9, text/html";
  649. auto r = parse(trailing, v);
  650. EXPECT_EQ(r.ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 0.9);
  652. EXPECT_EQ(*r.ptr, ',');
  653. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  654. // outright, and an 'e'/'E' simply ends the number.
  655. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  656. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  657. std::string exp_input = "1.5e3";
  658. r = parse(exp_input, v);
  659. EXPECT_EQ(r.ec, std::errc{});
  660. EXPECT_DOUBLE_EQ(v, 1.5);
  661. EXPECT_EQ(*r.ptr, 'e');
  662. // Invalid inputs.
  663. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  664. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  665. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  666. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  667. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  668. // Pathological but well-formed inputs must stay bounded (no overflow, no
  669. // out-of-bounds table access) and stay within [0, 1] for the caller.
  670. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  671. std::errc{});
  672. EXPECT_DOUBLE_EQ(v, 0.0);
  673. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  674. std::errc{});
  675. EXPECT_GE(v, 0.0);
  676. EXPECT_LE(v, 1.0);
  677. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  678. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  679. }
  680. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  681. // Simple case without quality values
  682. std::vector<std::string> result1;
  683. EXPECT_TRUE(detail::parse_accept_header(
  684. "text/html,application/json,text/plain", result1));
  685. EXPECT_EQ(result1.size(), 3U);
  686. EXPECT_EQ(result1[0], "text/html");
  687. EXPECT_EQ(result1[1], "application/json");
  688. EXPECT_EQ(result1[2], "text/plain");
  689. // With quality values
  690. std::vector<std::string> result2;
  691. EXPECT_TRUE(detail::parse_accept_header(
  692. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  693. EXPECT_EQ(result2.size(), 3U);
  694. EXPECT_EQ(result2[0], "application/json"); // highest q value
  695. EXPECT_EQ(result2[1], "text/html");
  696. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  697. }
  698. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  699. // Mixed with and without quality values
  700. std::vector<std::string> result;
  701. EXPECT_TRUE(detail::parse_accept_header(
  702. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  703. EXPECT_EQ(result.size(), 3U);
  704. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  705. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  706. EXPECT_EQ(result[2], "application/json"); // q=0.5
  707. }
  708. TEST(ParseAcceptHeaderTest, EdgeCases) {
  709. // Empty header
  710. std::vector<std::string> empty_result;
  711. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  712. EXPECT_TRUE(empty_result.empty());
  713. // Single type
  714. std::vector<std::string> single_result;
  715. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  716. EXPECT_EQ(single_result.size(), 1U);
  717. EXPECT_EQ(single_result[0], "application/json");
  718. // Wildcard types
  719. std::vector<std::string> wildcard_result;
  720. EXPECT_TRUE(detail::parse_accept_header(
  721. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  722. EXPECT_EQ(wildcard_result.size(), 3U);
  723. EXPECT_EQ(wildcard_result[0], "application/json");
  724. EXPECT_EQ(wildcard_result[1], "text/*");
  725. EXPECT_EQ(wildcard_result[2], "*/*");
  726. }
  727. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  728. // Common browser Accept header
  729. std::vector<std::string> browser_result;
  730. EXPECT_TRUE(
  731. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  732. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  733. browser_result));
  734. EXPECT_EQ(browser_result.size(), 6U);
  735. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  736. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  737. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  738. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  739. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  740. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  741. // API client header
  742. std::vector<std::string> api_result;
  743. EXPECT_TRUE(detail::parse_accept_header(
  744. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  745. api_result));
  746. EXPECT_EQ(api_result.size(), 3U);
  747. EXPECT_EQ(api_result[0], "application/json");
  748. EXPECT_EQ(api_result[1], "application/xml");
  749. EXPECT_EQ(api_result[2], "text/plain");
  750. }
  751. TEST(ParseAcceptHeaderTest, SpecialCases) {
  752. // Quality value with 3 decimal places
  753. std::vector<std::string> decimal_result;
  754. EXPECT_TRUE(detail::parse_accept_header(
  755. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  756. EXPECT_EQ(decimal_result.size(), 2U);
  757. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  758. EXPECT_EQ(decimal_result[1], "text/html");
  759. // Zero quality (should still be included but with lowest priority)
  760. std::vector<std::string> zero_q_result;
  761. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  762. zero_q_result));
  763. EXPECT_EQ(zero_q_result.size(), 2U);
  764. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  765. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  766. // No spaces around commas
  767. std::vector<std::string> no_space_result;
  768. EXPECT_TRUE(detail::parse_accept_header(
  769. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  770. no_space_result));
  771. EXPECT_EQ(no_space_result.size(), 3U);
  772. EXPECT_EQ(no_space_result[0], "text/html");
  773. EXPECT_EQ(no_space_result[1], "application/json");
  774. EXPECT_EQ(no_space_result[2], "text/plain");
  775. }
  776. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  777. // Quality values always use '.' as the decimal separator, so parsing must
  778. // not depend on the process locale. An embedding application may have
  779. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  780. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  781. std::string saved = cur ? cur : "C";
  782. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  783. "fr_FR.UTF-8"};
  784. bool switched = false;
  785. for (const auto loc : comma_locales) {
  786. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  787. std::localeconv()->decimal_point[0] == ',') {
  788. switched = true;
  789. break;
  790. }
  791. }
  792. if (!switched) {
  793. std::setlocale(LC_NUMERIC, saved.c_str());
  794. GTEST_SKIP() << "no comma-decimal locale available on this host";
  795. }
  796. // The higher-weighted type appears later in the list, so a correct parse
  797. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  798. // sensitive parse reads both weights as 0 and leaves the original order.
  799. std::vector<std::string> result;
  800. EXPECT_TRUE(detail::parse_accept_header(
  801. "application/json;q=0.1,text/html;q=0.9", result));
  802. ASSERT_EQ(result.size(), 2U);
  803. EXPECT_EQ(result[0], "text/html");
  804. EXPECT_EQ(result[1], "application/json");
  805. std::setlocale(LC_NUMERIC, saved.c_str());
  806. }
  807. TEST(ParseAcceptHeaderTest, InvalidCases) {
  808. std::vector<std::string> result;
  809. // Invalid quality value (> 1.0)
  810. EXPECT_FALSE(
  811. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  812. // Invalid quality value (< 0.0)
  813. EXPECT_FALSE(
  814. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  815. // Invalid quality value (not a number)
  816. EXPECT_FALSE(detail::parse_accept_header(
  817. "text/html;q=invalid,application/json", result));
  818. // Empty quality value
  819. EXPECT_FALSE(
  820. detail::parse_accept_header("text/html;q=,application/json", result));
  821. // Invalid media type format (no slash and not wildcard)
  822. EXPECT_FALSE(
  823. detail::parse_accept_header("invalidtype,application/json", result));
  824. // Empty media type
  825. result.clear();
  826. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  827. // Only commas
  828. result.clear();
  829. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  830. // Valid cases should still work
  831. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  832. EXPECT_EQ(result.size(), 1U);
  833. EXPECT_EQ(result[0], "*/*");
  834. EXPECT_TRUE(detail::parse_accept_header("*", result));
  835. EXPECT_EQ(result.size(), 1U);
  836. EXPECT_EQ(result[0], "*");
  837. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  838. EXPECT_EQ(result.size(), 1U);
  839. EXPECT_EQ(result[0], "text/*");
  840. }
  841. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  842. Server svr;
  843. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  844. EXPECT_EQ(req.accept_content_types.size(), 3U);
  845. EXPECT_EQ(req.accept_content_types[0], "application/json");
  846. EXPECT_EQ(req.accept_content_types[1], "text/html");
  847. EXPECT_EQ(req.accept_content_types[2], "*/*");
  848. res.set_content("ok", "text/plain");
  849. });
  850. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  851. EXPECT_TRUE(false);
  852. res.set_content("bad request", "text/plain");
  853. });
  854. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  855. auto se = detail::scope_exit([&] {
  856. svr.stop();
  857. listen_thread.join();
  858. ASSERT_FALSE(svr.is_running());
  859. });
  860. svr.wait_until_ready();
  861. Client cli("localhost", PORT);
  862. {
  863. auto res = cli.Get(
  864. "/accept_ok",
  865. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  867. EXPECT_EQ(StatusCode::OK_200, res->status);
  868. }
  869. {
  870. auto res = cli.Get("/accept_bad_request",
  871. Headers{{"Accept", "text/html;q=abc,application/json"}});
  872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  873. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  874. }
  875. }
  876. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  877. Server svr;
  878. svr.Get("/", [](const Request & /*req*/, Response &res) {
  879. res.set_content("ok", "text/plain");
  880. });
  881. std::atomic<int> start_count{0};
  882. std::atomic<bool> running_when_called{false};
  883. svr.set_start_handler([&]() {
  884. running_when_called = svr.is_running();
  885. start_count++;
  886. });
  887. auto port = svr.bind_to_any_port(HOST);
  888. std::thread t([&]() { svr.listen_after_bind(); });
  889. auto se = detail::scope_exit([&] {
  890. svr.stop();
  891. t.join();
  892. ASSERT_FALSE(svr.is_running());
  893. });
  894. svr.wait_until_ready();
  895. // A successful request proves the accept loop is running, which the start
  896. // handler precedes; so by now the handler must have run exactly once.
  897. Client cli(HOST, port);
  898. cli.set_connection_timeout(std::chrono::seconds(5));
  899. auto res = cli.Get("/");
  900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  901. EXPECT_EQ(StatusCode::OK_200, res->status);
  902. EXPECT_EQ(1, start_count.load());
  903. EXPECT_TRUE(running_when_called.load());
  904. }
  905. TEST(DivideTest, DivideStringTests) {
  906. auto divide = [](const std::string &str, char d) {
  907. std::string lhs;
  908. std::string rhs;
  909. detail::divide(str, d,
  910. [&](const char *lhs_data, std::size_t lhs_size,
  911. const char *rhs_data, std::size_t rhs_size) {
  912. lhs.assign(lhs_data, lhs_size);
  913. rhs.assign(rhs_data, rhs_size);
  914. });
  915. return std::make_pair(std::move(lhs), std::move(rhs));
  916. };
  917. {
  918. const auto res = divide("", '=');
  919. EXPECT_EQ(res.first, "");
  920. EXPECT_EQ(res.second, "");
  921. }
  922. {
  923. const auto res = divide("=", '=');
  924. EXPECT_EQ(res.first, "");
  925. EXPECT_EQ(res.second, "");
  926. }
  927. {
  928. const auto res = divide(" ", '=');
  929. EXPECT_EQ(res.first, " ");
  930. EXPECT_EQ(res.second, "");
  931. }
  932. {
  933. const auto res = divide("a", '=');
  934. EXPECT_EQ(res.first, "a");
  935. EXPECT_EQ(res.second, "");
  936. }
  937. {
  938. const auto res = divide("a=", '=');
  939. EXPECT_EQ(res.first, "a");
  940. EXPECT_EQ(res.second, "");
  941. }
  942. {
  943. const auto res = divide("=b", '=');
  944. EXPECT_EQ(res.first, "");
  945. EXPECT_EQ(res.second, "b");
  946. }
  947. {
  948. const auto res = divide("a=b", '=');
  949. EXPECT_EQ(res.first, "a");
  950. EXPECT_EQ(res.second, "b");
  951. }
  952. {
  953. const auto res = divide("a=b=", '=');
  954. EXPECT_EQ(res.first, "a");
  955. EXPECT_EQ(res.second, "b=");
  956. }
  957. {
  958. const auto res = divide("a=b=c", '=');
  959. EXPECT_EQ(res.first, "a");
  960. EXPECT_EQ(res.second, "b=c");
  961. }
  962. }
  963. TEST(SplitTest, ParseQueryString) {
  964. string s = "key1=val1&key2=val2&key3=val3";
  965. Params dic;
  966. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  967. [&](const char *b, const char *e) {
  968. string key, val;
  969. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  970. if (key.empty()) {
  971. key.assign(b2, e2);
  972. } else {
  973. val.assign(b2, e2);
  974. }
  975. });
  976. dic.emplace(key, val);
  977. });
  978. EXPECT_EQ("val1", dic.find("key1")->second);
  979. EXPECT_EQ("val2", dic.find("key2")->second);
  980. EXPECT_EQ("val3", dic.find("key3")->second);
  981. }
  982. TEST(SplitTest, ParseInvalidQueryTests) {
  983. {
  984. string s = " ";
  985. Params dict;
  986. detail::parse_query_text(s, dict);
  987. EXPECT_TRUE(dict.empty());
  988. }
  989. {
  990. string s = " = =";
  991. Params dict;
  992. detail::parse_query_text(s, dict);
  993. EXPECT_TRUE(dict.empty());
  994. }
  995. }
  996. TEST(ParseQueryTest, ParseQueryString) {
  997. {
  998. std::string s = "key1=val1&key2=val2&key3=val3";
  999. Params dic;
  1000. detail::parse_query_text(s, dic);
  1001. EXPECT_EQ("val1", dic.find("key1")->second);
  1002. EXPECT_EQ("val2", dic.find("key2")->second);
  1003. EXPECT_EQ("val3", dic.find("key3")->second);
  1004. }
  1005. {
  1006. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1007. Params dic;
  1008. detail::parse_query_text(s, dic);
  1009. EXPECT_EQ("", dic.find("key1")->second);
  1010. EXPECT_EQ("val1", dic.find("key2")->second);
  1011. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1012. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1013. }
  1014. }
  1015. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1016. Params dic;
  1017. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1018. dic.emplace("key1", "val1");
  1019. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1020. dic.emplace("key2", "val2");
  1021. dic.emplace("key3", "val3");
  1022. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1023. }
  1024. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1025. string content_type = "multipart/form-data; boundary=something";
  1026. string boundary;
  1027. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1028. EXPECT_TRUE(ret);
  1029. EXPECT_EQ(boundary, "something");
  1030. }
  1031. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1032. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1033. string boundary;
  1034. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1035. EXPECT_TRUE(ret);
  1036. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1037. }
  1038. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1039. string content_type =
  1040. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1041. string boundary;
  1042. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1043. EXPECT_TRUE(ret);
  1044. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1045. }
  1046. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1047. string content_type =
  1048. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1049. string boundary;
  1050. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1051. EXPECT_TRUE(ret);
  1052. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1053. }
  1054. TEST(GetHeaderValueTest, DefaultValue) {
  1055. Headers headers = {{"Dummy", "Dummy"}};
  1056. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1057. EXPECT_STREQ("text/plain", val);
  1058. }
  1059. TEST(GetHeaderValueTest, DefaultValueInt) {
  1060. Headers headers = {{"Dummy", "Dummy"}};
  1061. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1062. EXPECT_EQ(100ull, val);
  1063. }
  1064. TEST(GetHeaderValueTest, RegularValue) {
  1065. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1066. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1067. EXPECT_STREQ("text/html", val);
  1068. }
  1069. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1070. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1071. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1072. EXPECT_STREQ("text/html", val);
  1073. }
  1074. TEST(GetHeaderValueTest, SetContent) {
  1075. Response res;
  1076. res.set_content("html", "text/html");
  1077. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1078. res.set_content("text", "text/plain");
  1079. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1080. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1081. }
  1082. TEST(GetHeaderValueTest, RegularValueInt) {
  1083. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1084. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1085. EXPECT_EQ(100ull, val);
  1086. }
  1087. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1088. Headers headers = {{"Content-Length", "x"}};
  1089. auto is_invalid_value = false;
  1090. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1091. is_invalid_value);
  1092. EXPECT_EQ(0ull, val);
  1093. EXPECT_TRUE(is_invalid_value);
  1094. }
  1095. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1096. // An all-digit value that overflows size_t must be reported as invalid, not
  1097. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1098. // a large length to a small one on 32-bit builds, leaving the framing length
  1099. // wrong while is_invalid_value stayed false.
  1100. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1101. auto is_invalid_value = false;
  1102. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1103. is_invalid_value);
  1104. EXPECT_TRUE(is_invalid_value);
  1105. // A well-formed length is unaffected.
  1106. Headers ok = {{"Content-Length", "1234"}};
  1107. is_invalid_value = false;
  1108. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1109. is_invalid_value);
  1110. EXPECT_EQ(1234ull, val);
  1111. EXPECT_FALSE(is_invalid_value);
  1112. }
  1113. TEST(GetHeaderValueTest, Range) {
  1114. {
  1115. Headers headers = {make_range_header({{1, -1}})};
  1116. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1117. EXPECT_STREQ("bytes=1-", val);
  1118. }
  1119. {
  1120. Headers headers = {make_range_header({{-1, 1}})};
  1121. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1122. EXPECT_STREQ("bytes=-1", val);
  1123. }
  1124. {
  1125. Headers headers = {make_range_header({{1, 10}})};
  1126. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1127. EXPECT_STREQ("bytes=1-10", val);
  1128. }
  1129. {
  1130. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1131. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1132. EXPECT_STREQ("bytes=1-10, 100-", val);
  1133. }
  1134. {
  1135. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1136. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1137. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1138. }
  1139. {
  1140. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1141. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1142. EXPECT_STREQ("bytes=0-0, -1", val);
  1143. }
  1144. }
  1145. // Joins every field of a Headers into "name=value " so a whole traversal can
  1146. // be compared in one assertion.
  1147. static std::string headers_to_string(const Headers &headers) {
  1148. std::string s;
  1149. for (const auto &header : headers) {
  1150. s += header.first + "=" + header.second + " ";
  1151. }
  1152. return s;
  1153. }
  1154. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1155. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1156. // to depend on the standard library (libstdc++ handed back duplicates in
  1157. // reverse insertion order, libc++ in insertion order).
  1158. Request req;
  1159. req.set_header("Accept-Encoding", "gzip");
  1160. req.set_header("Accept-Encoding", "deflate");
  1161. req.set_header("Accept-Encoding", "br");
  1162. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1163. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1164. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1165. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1166. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1167. }
  1168. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1169. Request req;
  1170. req.set_header("X-Test", "only");
  1171. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1172. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1173. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1174. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1175. }
  1176. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1177. Headers headers;
  1178. headers.emplace("Host", "example.com");
  1179. headers.emplace("Accept-Encoding", "gzip");
  1180. headers.emplace("User-Agent", "test");
  1181. headers.emplace("Accept-Encoding", "deflate");
  1182. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1183. "Accept-Encoding=deflate ",
  1184. headers_to_string(headers));
  1185. }
  1186. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1187. Headers headers = {{"Content-Type", "text/html"},
  1188. {"CONTENT-TYPE", "text/xml"}};
  1189. EXPECT_EQ(2U, headers.count("content-type"));
  1190. auto it = headers.find("content-type");
  1191. ASSERT_TRUE(it != headers.end());
  1192. EXPECT_EQ("text/html", it->second);
  1193. }
  1194. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1195. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1196. // drop only those fields and leave everything positioned between them.
  1197. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1198. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1199. auto rng = headers.equal_range("a");
  1200. headers.erase(rng.first, rng.second);
  1201. EXPECT_EQ("X=x Y=y Z=z ", headers_to_string(headers));
  1202. }
  1203. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1204. Headers headers = {
  1205. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1206. EXPECT_EQ(3U, headers.erase("A"));
  1207. EXPECT_EQ(0U, headers.count("A"));
  1208. EXPECT_EQ("B=2 C=4 ", headers_to_string(headers));
  1209. }
  1210. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1211. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1212. headers.emplace_front("Host", "example.com");
  1213. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1214. headers_to_string(headers));
  1215. }
  1216. TEST(ParseHeaderValueTest, Range) {
  1217. {
  1218. Ranges ranges;
  1219. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1220. EXPECT_TRUE(ret);
  1221. EXPECT_EQ(1u, ranges.size());
  1222. EXPECT_EQ(1u, ranges[0].first);
  1223. EXPECT_EQ(-1, ranges[0].second);
  1224. }
  1225. {
  1226. Ranges ranges;
  1227. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1228. EXPECT_TRUE(ret);
  1229. EXPECT_EQ(1u, ranges.size());
  1230. EXPECT_EQ(-1, ranges[0].first);
  1231. EXPECT_EQ(1u, ranges[0].second);
  1232. }
  1233. {
  1234. Ranges ranges;
  1235. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1236. EXPECT_TRUE(ret);
  1237. EXPECT_EQ(1u, ranges.size());
  1238. EXPECT_EQ(1u, ranges[0].first);
  1239. EXPECT_EQ(10u, ranges[0].second);
  1240. }
  1241. {
  1242. Ranges ranges;
  1243. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1244. EXPECT_FALSE(ret);
  1245. }
  1246. {
  1247. Ranges ranges;
  1248. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1249. EXPECT_TRUE(ret);
  1250. EXPECT_EQ(2u, ranges.size());
  1251. EXPECT_EQ(1u, ranges[0].first);
  1252. EXPECT_EQ(10u, ranges[0].second);
  1253. EXPECT_EQ(100u, ranges[1].first);
  1254. EXPECT_EQ(-1, ranges[1].second);
  1255. }
  1256. {
  1257. Ranges ranges;
  1258. auto ret =
  1259. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1260. EXPECT_TRUE(ret);
  1261. EXPECT_EQ(3u, ranges.size());
  1262. EXPECT_EQ(1u, ranges[0].first);
  1263. EXPECT_EQ(10u, ranges[0].second);
  1264. EXPECT_EQ(100u, ranges[1].first);
  1265. EXPECT_EQ(200u, ranges[1].second);
  1266. EXPECT_EQ(300u, ranges[2].first);
  1267. EXPECT_EQ(400u, ranges[2].second);
  1268. }
  1269. {
  1270. Ranges ranges;
  1271. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1272. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1273. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1274. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1275. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1276. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1277. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1278. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1279. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1280. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1281. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1282. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1283. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1284. EXPECT_TRUE(ranges.empty());
  1285. }
  1286. }
  1287. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1288. Request req;
  1289. req.set_header("Accept-Encoding", "gzip");
  1290. Response res;
  1291. res.set_header("Content-Type", "text/plain");
  1292. auto ret = detail::encoding_type(req, res);
  1293. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1294. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1295. #else
  1296. EXPECT_TRUE(ret == detail::EncodingType::None);
  1297. #endif
  1298. }
  1299. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1300. Request req;
  1301. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1302. Response res;
  1303. res.set_header("Content-Type", "text/plain");
  1304. auto ret = detail::encoding_type(req, res);
  1305. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1306. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1307. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1308. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1309. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1310. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1311. #else
  1312. EXPECT_TRUE(ret == detail::EncodingType::None);
  1313. #endif
  1314. }
  1315. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1316. Request req;
  1317. req.set_header("Accept-Encoding",
  1318. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1319. Response res;
  1320. res.set_header("Content-Type", "text/plain");
  1321. auto ret = detail::encoding_type(req, res);
  1322. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1323. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1324. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1325. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1326. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1327. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1328. #else
  1329. EXPECT_TRUE(ret == detail::EncodingType::None);
  1330. #endif
  1331. }
  1332. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1333. // All supported encodings rejected with q=0 should return None
  1334. Request req;
  1335. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1336. Response res;
  1337. res.set_header("Content-Type", "text/plain");
  1338. auto ret = detail::encoding_type(req, res);
  1339. EXPECT_TRUE(ret == detail::EncodingType::None);
  1340. }
  1341. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1342. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1343. Request req;
  1344. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1345. Response res;
  1346. res.set_header("Content-Type", "text/plain");
  1347. auto ret = detail::encoding_type(req, res);
  1348. EXPECT_TRUE(ret == detail::EncodingType::None);
  1349. }
  1350. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1351. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1352. Request req;
  1353. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1354. Response res;
  1355. res.set_header("Content-Type", "text/plain");
  1356. auto ret = detail::encoding_type(req, res);
  1357. EXPECT_TRUE(ret == detail::EncodingType::None);
  1358. }
  1359. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1360. // RFC 7231: Accept-Encoding values are case-insensitive
  1361. Request req;
  1362. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1363. Response res;
  1364. res.set_header("Content-Type", "text/plain");
  1365. auto ret = detail::encoding_type(req, res);
  1366. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1367. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1368. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1369. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1370. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1371. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1372. #else
  1373. EXPECT_TRUE(ret == detail::EncodingType::None);
  1374. #endif
  1375. }
  1376. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1377. // q value should determine priority, not hardcoded order
  1378. Request req;
  1379. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1380. Response res;
  1381. res.set_header("Content-Type", "text/plain");
  1382. auto ret = detail::encoding_type(req, res);
  1383. // gzip has highest q=1.0, so it should be selected even though
  1384. // br and zstd are also supported
  1385. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1386. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1387. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1388. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1389. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1390. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1391. #else
  1392. EXPECT_TRUE(ret == detail::EncodingType::None);
  1393. #endif
  1394. }
  1395. TEST(BufferStreamTest, read) {
  1396. detail::BufferStream strm1;
  1397. Stream &strm = strm1;
  1398. EXPECT_EQ(5, strm.write("hello"));
  1399. char buf[512];
  1400. EXPECT_EQ(2, strm.read(buf, 2));
  1401. EXPECT_EQ('h', buf[0]);
  1402. EXPECT_EQ('e', buf[1]);
  1403. EXPECT_EQ(2, strm.read(buf, 2));
  1404. EXPECT_EQ('l', buf[0]);
  1405. EXPECT_EQ('l', buf[1]);
  1406. EXPECT_EQ(1, strm.read(buf, 1));
  1407. EXPECT_EQ('o', buf[0]);
  1408. EXPECT_EQ(0, strm.read(buf, 1));
  1409. }
  1410. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1411. auto host = "www.httpwatch.com";
  1412. auto ip = hosted_at(host);
  1413. EXPECT_EQ("23.96.13.243", ip);
  1414. std::vector<std::string> addrs;
  1415. hosted_at(host, addrs);
  1416. EXPECT_EQ(1u, addrs.size());
  1417. }
  1418. #if 0 // It depends on each test environment...
  1419. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1420. auto host = "www.youtube.com";
  1421. std::vector<std::string> addrs;
  1422. hosted_at(host, addrs);
  1423. EXPECT_EQ(20u, addrs.size());
  1424. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1425. EXPECT_TRUE(it != addrs.end());
  1426. }
  1427. #endif
  1428. class ChunkedEncodingTest : public ::testing::Test {
  1429. protected:
  1430. ChunkedEncodingTest()
  1431. : cli_(HOST, PORT)
  1432. #ifdef CPPHTTPLIB_SSL_ENABLED
  1433. ,
  1434. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1435. #endif
  1436. {
  1437. cli_.set_connection_timeout(2);
  1438. #ifdef CPPHTTPLIB_SSL_ENABLED
  1439. cli_.enable_server_certificate_verification(false);
  1440. #endif
  1441. }
  1442. virtual void SetUp() {
  1443. read_file("./image.jpg", image_data_);
  1444. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1445. res.set_content("Hello World!", "text/plain");
  1446. });
  1447. svr_.Get(
  1448. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1449. res.set_chunked_content_provider(
  1450. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1451. size_t remaining = image_data_.size() - offset;
  1452. if (remaining == 0) {
  1453. sink.done();
  1454. } else {
  1455. constexpr size_t CHUNK_SIZE = 1024;
  1456. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1457. sink.write(&image_data_[offset], send_size);
  1458. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1459. }
  1460. return true;
  1461. });
  1462. });
  1463. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1464. svr_.wait_until_ready();
  1465. }
  1466. virtual void TearDown() {
  1467. svr_.stop();
  1468. if (!request_threads_.empty()) {
  1469. std::this_thread::sleep_for(std::chrono::seconds(1));
  1470. for (auto &t : request_threads_) {
  1471. t.join();
  1472. }
  1473. }
  1474. t_.join();
  1475. }
  1476. #ifdef CPPHTTPLIB_SSL_ENABLED
  1477. SSLClient cli_;
  1478. SSLServer svr_;
  1479. #else
  1480. Client cli_;
  1481. Server svr_;
  1482. #endif
  1483. thread t_;
  1484. std::vector<thread> request_threads_;
  1485. std::string image_data_;
  1486. };
  1487. TEST_F(ChunkedEncodingTest, NormalGet) {
  1488. auto res = cli_.Get("/chunked");
  1489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1490. std::string out;
  1491. read_file("./image.jpg", out);
  1492. EXPECT_EQ(StatusCode::OK_200, res->status);
  1493. EXPECT_EQ(out, res->body);
  1494. }
  1495. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1496. std::string body;
  1497. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1498. body.append(data, data_length);
  1499. return true;
  1500. });
  1501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1502. std::string out;
  1503. read_file("./image.jpg", out);
  1504. EXPECT_EQ(StatusCode::OK_200, res->status);
  1505. EXPECT_EQ(out, body);
  1506. }
  1507. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1508. std::string body;
  1509. auto res = cli_.Get(
  1510. "/chunked",
  1511. [&](const Response &response) {
  1512. EXPECT_EQ(StatusCode::OK_200, response.status);
  1513. return true;
  1514. },
  1515. [&](const char *data, size_t data_length) {
  1516. body.append(data, data_length);
  1517. return true;
  1518. });
  1519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1520. std::string out;
  1521. read_file("./image.jpg", out);
  1522. EXPECT_EQ(StatusCode::OK_200, res->status);
  1523. EXPECT_EQ(out, body);
  1524. }
  1525. TEST(RangeTest, FromHTTPBin_Online) {
  1526. auto host = "httpbingo.org";
  1527. auto path = std::string{"/range/32"};
  1528. #ifdef CPPHTTPLIB_SSL_ENABLED
  1529. auto port = 443;
  1530. SSLClient cli(host, port);
  1531. #else
  1532. auto port = 80;
  1533. Client cli(host, port);
  1534. #endif
  1535. cli.set_connection_timeout(5);
  1536. {
  1537. auto res = cli.Get(path);
  1538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1539. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1540. EXPECT_EQ(StatusCode::OK_200, res->status);
  1541. }
  1542. {
  1543. Headers headers = {make_range_header({{1, -1}})};
  1544. auto res = cli.Get(path, headers);
  1545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1546. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1547. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1548. }
  1549. {
  1550. Headers headers = {make_range_header({{1, 10}})};
  1551. auto res = cli.Get(path, headers);
  1552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1553. EXPECT_EQ("bcdefghijk", res->body);
  1554. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1555. }
  1556. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1557. // entire resource, while the original httpbin returned 200. Both are
  1558. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1559. {
  1560. Headers headers = {make_range_header({{0, 31}})};
  1561. auto res = cli.Get(path, headers);
  1562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1563. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1564. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1565. res->status == StatusCode::PartialContent_206);
  1566. }
  1567. {
  1568. Headers headers = {make_range_header({{0, -1}})};
  1569. auto res = cli.Get(path, headers);
  1570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1571. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1572. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1573. res->status == StatusCode::PartialContent_206);
  1574. }
  1575. // go-httpbin returns 206 with clamped range for over-range requests,
  1576. // while the original httpbin returned 416. Both behaviors are observed
  1577. // in real servers, so we only verify the request succeeds.
  1578. {
  1579. Headers headers = {make_range_header({{0, 32}})};
  1580. auto res = cli.Get(path, headers);
  1581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1582. }
  1583. }
  1584. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1585. auto host = "unresolvableaddress.local";
  1586. auto path = std::string{"/"};
  1587. #ifdef CPPHTTPLIB_SSL_ENABLED
  1588. auto port = 443;
  1589. SSLClient cli(host, port);
  1590. #else
  1591. auto port = 80;
  1592. Client cli(host, port);
  1593. #endif
  1594. cli.set_connection_timeout(1);
  1595. {
  1596. auto res = cli.Get(path);
  1597. ASSERT_FALSE(res);
  1598. }
  1599. std::this_thread::sleep_for(std::chrono::seconds(8));
  1600. }
  1601. #if defined(__linux__) && defined(__GLIBC__) && \
  1602. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1603. // Forward declaration: in split builds split.py strips `inline` and moves the
  1604. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1605. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1606. // against the symbol in both header-only and split builds.
  1607. namespace httplib {
  1608. namespace detail {
  1609. int getaddrinfo_with_timeout(const char *node, const char *service,
  1610. const struct addrinfo *hints,
  1611. struct addrinfo **res, time_t timeout_sec);
  1612. } // namespace detail
  1613. } // namespace httplib
  1614. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1615. //
  1616. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1617. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1618. // gai_suspend() call hits the connection timeout the function calls
  1619. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1620. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1621. // still alive and still references the now-destroyed stack frame.
  1622. //
  1623. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1624. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1625. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1626. // and runs them in a container.
  1627. namespace {
  1628. bool should_run_issue_2431_tests() {
  1629. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1630. return v && *v && std::string(v) != "0";
  1631. }
  1632. std::string unique_unresolvable_host(int n) {
  1633. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1634. // glibc still asks the configured nameserver — which is exactly the path
  1635. // we want to exercise. A unique label per call avoids the resolver cache.
  1636. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1637. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1638. std::to_string(n) + ".invalid";
  1639. }
  1640. } // namespace
  1641. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1642. if (!should_run_issue_2431_tests()) {
  1643. GTEST_SKIP()
  1644. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1645. }
  1646. for (int i = 0; i < 8; ++i) {
  1647. struct addrinfo hints;
  1648. memset(&hints, 0, sizeof(hints));
  1649. hints.ai_family = AF_UNSPEC;
  1650. hints.ai_socktype = SOCK_STREAM;
  1651. auto host = unique_unresolvable_host(i);
  1652. struct addrinfo *result = nullptr;
  1653. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1654. &result, /*timeout_sec=*/1);
  1655. if (rc == 0 && result) { freeaddrinfo(result); }
  1656. }
  1657. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1658. // stack region they still believe holds their gaicb.
  1659. std::this_thread::sleep_for(std::chrono::seconds(3));
  1660. }
  1661. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1662. if (!should_run_issue_2431_tests()) {
  1663. GTEST_SKIP()
  1664. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1665. }
  1666. std::atomic<bool> stop{false};
  1667. std::vector<std::thread> threads;
  1668. for (int t = 0; t < 8; ++t) {
  1669. threads.emplace_back([t, &stop] {
  1670. int i = 0;
  1671. while (!stop.load(std::memory_order_relaxed)) {
  1672. struct addrinfo hints;
  1673. memset(&hints, 0, sizeof(hints));
  1674. hints.ai_family = AF_UNSPEC;
  1675. hints.ai_socktype = SOCK_STREAM;
  1676. auto host = unique_unresolvable_host(t * 100000 + i++);
  1677. struct addrinfo *result = nullptr;
  1678. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1679. &result, /*timeout_sec=*/1);
  1680. if (rc == 0 && result) { freeaddrinfo(result); }
  1681. }
  1682. });
  1683. }
  1684. std::this_thread::sleep_for(std::chrono::seconds(8));
  1685. stop.store(true, std::memory_order_relaxed);
  1686. for (auto &th : threads) {
  1687. th.join();
  1688. }
  1689. std::this_thread::sleep_for(std::chrono::seconds(3));
  1690. }
  1691. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1692. if (!should_run_issue_2431_tests()) {
  1693. GTEST_SKIP()
  1694. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1695. }
  1696. std::atomic<bool> stop{false};
  1697. std::vector<std::thread> threads;
  1698. for (int t = 0; t < 8; ++t) {
  1699. threads.emplace_back([t, &stop] {
  1700. int i = 0;
  1701. while (!stop.load(std::memory_order_relaxed)) {
  1702. auto host = unique_unresolvable_host(t * 100000 + i++);
  1703. Client cli(host, 80);
  1704. cli.set_connection_timeout(1, 0);
  1705. cli.set_read_timeout(1, 0);
  1706. cli.set_write_timeout(1, 0);
  1707. (void)cli.Get("/");
  1708. }
  1709. });
  1710. }
  1711. std::this_thread::sleep_for(std::chrono::seconds(8));
  1712. stop.store(true, std::memory_order_relaxed);
  1713. for (auto &th : threads) {
  1714. th.join();
  1715. }
  1716. std::this_thread::sleep_for(std::chrono::seconds(3));
  1717. }
  1718. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1719. TEST(ConnectionErrorTest, InvalidHost) {
  1720. auto host = "-abcde.com";
  1721. #ifdef CPPHTTPLIB_SSL_ENABLED
  1722. auto port = 443;
  1723. SSLClient cli(host, port);
  1724. #else
  1725. auto port = 80;
  1726. Client cli(host, port);
  1727. #endif
  1728. cli.set_connection_timeout(std::chrono::seconds(2));
  1729. auto res = cli.Get("/");
  1730. ASSERT_TRUE(!res);
  1731. EXPECT_EQ(Error::Connection, res.error());
  1732. }
  1733. TEST(ConnectionErrorTest, InvalidHost2) {
  1734. auto host = "httpcan.org/";
  1735. #ifdef CPPHTTPLIB_SSL_ENABLED
  1736. SSLClient cli(host);
  1737. #else
  1738. Client cli(host);
  1739. #endif
  1740. cli.set_connection_timeout(std::chrono::seconds(2));
  1741. auto res = cli.Get("/");
  1742. ASSERT_TRUE(!res);
  1743. EXPECT_EQ(Error::Connection, res.error());
  1744. }
  1745. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1746. auto host = "httpcan.org/";
  1747. #ifdef CPPHTTPLIB_SSL_ENABLED
  1748. SSLClient cli(host);
  1749. #else
  1750. Client cli(host);
  1751. #endif
  1752. cli.set_connection_timeout(std::chrono::seconds(2));
  1753. auto res = cli.Get("/");
  1754. ASSERT_TRUE(!res);
  1755. stringstream s;
  1756. s << "error code: " << res.error();
  1757. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1758. }
  1759. TEST(ConnectionErrorTest, InvalidPort) {
  1760. auto host = "localhost";
  1761. auto port = 44380;
  1762. #ifdef CPPHTTPLIB_SSL_ENABLED
  1763. SSLClient cli(host, port);
  1764. #else
  1765. Client cli(host, port);
  1766. #endif
  1767. cli.set_connection_timeout(std::chrono::seconds(2));
  1768. auto res = cli.Get("/");
  1769. ASSERT_TRUE(!res);
  1770. EXPECT_TRUE(Error::Connection == res.error() ||
  1771. Error::ConnectionTimeout == res.error());
  1772. }
  1773. TEST(ConnectionErrorTest, Timeout_Online) {
  1774. auto host = "google.com";
  1775. #ifdef CPPHTTPLIB_SSL_ENABLED
  1776. auto port = 44380;
  1777. SSLClient cli(host, port);
  1778. #else
  1779. auto port = 8080;
  1780. Client cli(host, port);
  1781. #endif
  1782. cli.set_connection_timeout(std::chrono::seconds(2));
  1783. // only probe one address type so that the error reason
  1784. // correlates to the timed-out IPv4, not the unsupported
  1785. // IPv6 connection attempt
  1786. cli.set_address_family(AF_INET);
  1787. auto res = cli.Get("/");
  1788. ASSERT_TRUE(!res);
  1789. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1790. }
  1791. TEST(CancelTest, NoCancel_Online) {
  1792. auto host = "httpbingo.org";
  1793. auto path = std::string{"/range/32"};
  1794. #ifdef CPPHTTPLIB_SSL_ENABLED
  1795. auto port = 443;
  1796. SSLClient cli(host, port);
  1797. #else
  1798. auto port = 80;
  1799. Client cli(host, port);
  1800. #endif
  1801. cli.set_connection_timeout(std::chrono::seconds(5));
  1802. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1804. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1805. EXPECT_EQ(StatusCode::OK_200, res->status);
  1806. }
  1807. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1808. // Use /bytes with a large payload so that the DownloadProgress callback
  1809. // (which only fires for Content-Length responses) is invoked before the
  1810. // entire body is received, giving cancellation a chance to fire.
  1811. auto host = "httpbingo.org";
  1812. auto path = std::string{"/bytes/524288"};
  1813. #ifdef CPPHTTPLIB_SSL_ENABLED
  1814. auto port = 443;
  1815. SSLClient cli(host, port);
  1816. #else
  1817. auto port = 80;
  1818. Client cli(host, port);
  1819. #endif
  1820. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1821. cli.set_connection_timeout(std::chrono::seconds(5));
  1822. ASSERT_TRUE(!res);
  1823. EXPECT_EQ(Error::Canceled, res.error());
  1824. }
  1825. TEST(CancelTest, WithCancelLargePayload_Online) {
  1826. auto host = "httpbingo.org";
  1827. auto path = std::string{"/bytes/524288"};
  1828. #ifdef CPPHTTPLIB_SSL_ENABLED
  1829. auto port = 443;
  1830. SSLClient cli(host, port);
  1831. #else
  1832. auto port = 80;
  1833. Client cli(host, port);
  1834. #endif
  1835. cli.set_connection_timeout(std::chrono::seconds(5));
  1836. uint32_t count = 0;
  1837. auto res =
  1838. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1839. ASSERT_TRUE(!res);
  1840. EXPECT_EQ(Error::Canceled, res.error());
  1841. }
  1842. TEST(CancelTest, NoCancelPost) {
  1843. Server svr;
  1844. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1845. res.set_content("Hello World!", "text/plain");
  1846. });
  1847. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1848. auto se = detail::scope_exit([&] {
  1849. svr.stop();
  1850. thread.join();
  1851. ASSERT_FALSE(svr.is_running());
  1852. });
  1853. svr.wait_until_ready();
  1854. Client cli(HOST, PORT);
  1855. cli.set_connection_timeout(std::chrono::seconds(5));
  1856. auto res =
  1857. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1858. "application/json", [](uint64_t, uint64_t) { return true; });
  1859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1860. EXPECT_EQ("Hello World!", res->body);
  1861. EXPECT_EQ(StatusCode::OK_200, res->status);
  1862. }
  1863. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1864. Server svr;
  1865. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1866. res.set_content("Hello World!", "text/plain");
  1867. });
  1868. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1869. auto se = detail::scope_exit([&] {
  1870. svr.stop();
  1871. thread.join();
  1872. ASSERT_FALSE(svr.is_running());
  1873. });
  1874. svr.wait_until_ready();
  1875. Client cli(HOST, PORT);
  1876. cli.set_connection_timeout(std::chrono::seconds(5));
  1877. auto res =
  1878. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1879. "application/json", [](uint64_t, uint64_t) { return false; });
  1880. ASSERT_TRUE(!res);
  1881. EXPECT_EQ(Error::Canceled, res.error());
  1882. }
  1883. TEST(CancelTest, WithCancelLargePayloadPost) {
  1884. Server svr;
  1885. svr.set_payload_max_length(200 * 1024 * 1024);
  1886. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1887. res.set_content(LARGE_DATA, "text/plain");
  1888. });
  1889. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1890. auto se = detail::scope_exit([&] {
  1891. svr.stop();
  1892. thread.join();
  1893. ASSERT_FALSE(svr.is_running());
  1894. });
  1895. svr.wait_until_ready();
  1896. Client cli(HOST, PORT);
  1897. cli.set_payload_max_length(200 * 1024 * 1024);
  1898. cli.set_connection_timeout(std::chrono::seconds(5));
  1899. auto res =
  1900. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1901. "application/json", [](uint64_t, uint64_t) { return false; });
  1902. ASSERT_TRUE(!res);
  1903. EXPECT_EQ(Error::Canceled, res.error());
  1904. }
  1905. TEST(CancelTest, NoCancelPut) {
  1906. Server svr;
  1907. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1908. res.set_content("Hello World!", "text/plain");
  1909. });
  1910. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1911. auto se = detail::scope_exit([&] {
  1912. svr.stop();
  1913. thread.join();
  1914. ASSERT_FALSE(svr.is_running());
  1915. });
  1916. svr.wait_until_ready();
  1917. Client cli(HOST, PORT);
  1918. cli.set_connection_timeout(std::chrono::seconds(5));
  1919. auto res =
  1920. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1921. "application/json", [](uint64_t, uint64_t) { return true; });
  1922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1923. EXPECT_EQ("Hello World!", res->body);
  1924. EXPECT_EQ(StatusCode::OK_200, res->status);
  1925. }
  1926. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1927. Server svr;
  1928. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1929. res.set_content("Hello World!", "text/plain");
  1930. });
  1931. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1932. auto se = detail::scope_exit([&] {
  1933. svr.stop();
  1934. thread.join();
  1935. ASSERT_FALSE(svr.is_running());
  1936. });
  1937. svr.wait_until_ready();
  1938. Client cli(HOST, PORT);
  1939. cli.set_connection_timeout(std::chrono::seconds(5));
  1940. auto res =
  1941. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1942. "application/json", [](uint64_t, uint64_t) { return false; });
  1943. ASSERT_TRUE(!res);
  1944. EXPECT_EQ(Error::Canceled, res.error());
  1945. }
  1946. TEST(CancelTest, WithCancelLargePayloadPut) {
  1947. Server svr;
  1948. svr.set_payload_max_length(200 * 1024 * 1024);
  1949. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1950. res.set_content(LARGE_DATA, "text/plain");
  1951. });
  1952. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1953. auto se = detail::scope_exit([&] {
  1954. svr.stop();
  1955. thread.join();
  1956. ASSERT_FALSE(svr.is_running());
  1957. });
  1958. svr.wait_until_ready();
  1959. Client cli(HOST, PORT);
  1960. cli.set_payload_max_length(200 * 1024 * 1024);
  1961. cli.set_connection_timeout(std::chrono::seconds(5));
  1962. auto res =
  1963. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1964. "application/json", [](uint64_t, uint64_t) { return false; });
  1965. ASSERT_TRUE(!res);
  1966. EXPECT_EQ(Error::Canceled, res.error());
  1967. }
  1968. TEST(CancelTest, NoCancelPatch) {
  1969. Server svr;
  1970. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1971. res.set_content("Hello World!", "text/plain");
  1972. });
  1973. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1974. auto se = detail::scope_exit([&] {
  1975. svr.stop();
  1976. thread.join();
  1977. ASSERT_FALSE(svr.is_running());
  1978. });
  1979. svr.wait_until_ready();
  1980. Client cli(HOST, PORT);
  1981. cli.set_connection_timeout(std::chrono::seconds(5));
  1982. auto res =
  1983. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1984. "application/json", [](uint64_t, uint64_t) { return true; });
  1985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1986. EXPECT_EQ("Hello World!", res->body);
  1987. EXPECT_EQ(StatusCode::OK_200, res->status);
  1988. }
  1989. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1990. Server svr;
  1991. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1992. res.set_content("Hello World!", "text/plain");
  1993. });
  1994. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1995. auto se = detail::scope_exit([&] {
  1996. svr.stop();
  1997. thread.join();
  1998. ASSERT_FALSE(svr.is_running());
  1999. });
  2000. svr.wait_until_ready();
  2001. Client cli(HOST, PORT);
  2002. cli.set_connection_timeout(std::chrono::seconds(5));
  2003. auto res =
  2004. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2005. "application/json", [](uint64_t, uint64_t) { return false; });
  2006. ASSERT_TRUE(!res);
  2007. EXPECT_EQ(Error::Canceled, res.error());
  2008. }
  2009. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2010. Server svr;
  2011. svr.set_payload_max_length(200 * 1024 * 1024);
  2012. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2013. res.set_content(LARGE_DATA, "text/plain");
  2014. });
  2015. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2016. auto se = detail::scope_exit([&] {
  2017. svr.stop();
  2018. thread.join();
  2019. ASSERT_FALSE(svr.is_running());
  2020. });
  2021. svr.wait_until_ready();
  2022. Client cli(HOST, PORT);
  2023. cli.set_payload_max_length(200 * 1024 * 1024);
  2024. cli.set_connection_timeout(std::chrono::seconds(5));
  2025. auto res =
  2026. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2027. "application/json", [](uint64_t, uint64_t) { return false; });
  2028. ASSERT_TRUE(!res);
  2029. EXPECT_EQ(Error::Canceled, res.error());
  2030. }
  2031. TEST(CancelTest, NoCancelDelete) {
  2032. Server svr;
  2033. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2034. res.set_content("Hello World!", "text/plain");
  2035. });
  2036. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2037. auto se = detail::scope_exit([&] {
  2038. svr.stop();
  2039. thread.join();
  2040. ASSERT_FALSE(svr.is_running());
  2041. });
  2042. svr.wait_until_ready();
  2043. Client cli(HOST, PORT);
  2044. cli.set_connection_timeout(std::chrono::seconds(5));
  2045. auto res =
  2046. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2047. "application/json", [](uint64_t, uint64_t) { return true; });
  2048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2049. EXPECT_EQ("Hello World!", res->body);
  2050. EXPECT_EQ(StatusCode::OK_200, res->status);
  2051. }
  2052. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2053. Server svr;
  2054. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2055. res.set_content("Hello World!", "text/plain");
  2056. });
  2057. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2058. auto se = detail::scope_exit([&] {
  2059. svr.stop();
  2060. thread.join();
  2061. ASSERT_FALSE(svr.is_running());
  2062. });
  2063. svr.wait_until_ready();
  2064. Client cli(HOST, PORT);
  2065. cli.set_connection_timeout(std::chrono::seconds(5));
  2066. auto res =
  2067. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2068. "application/json", [](uint64_t, uint64_t) { return false; });
  2069. ASSERT_TRUE(!res);
  2070. EXPECT_EQ(Error::Canceled, res.error());
  2071. }
  2072. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2073. Server svr;
  2074. svr.set_payload_max_length(200 * 1024 * 1024);
  2075. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2076. res.set_content(LARGE_DATA, "text/plain");
  2077. });
  2078. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2079. auto se = detail::scope_exit([&] {
  2080. svr.stop();
  2081. thread.join();
  2082. ASSERT_FALSE(svr.is_running());
  2083. });
  2084. svr.wait_until_ready();
  2085. Client cli(HOST, PORT);
  2086. cli.set_payload_max_length(200 * 1024 * 1024);
  2087. cli.set_connection_timeout(std::chrono::seconds(5));
  2088. auto res =
  2089. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2090. "application/json", [](uint64_t, uint64_t) { return false; });
  2091. ASSERT_TRUE(!res);
  2092. EXPECT_EQ(Error::Canceled, res.error());
  2093. }
  2094. static std::string remove_whitespace(const std::string &input) {
  2095. std::string output;
  2096. output.reserve(input.size());
  2097. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2098. [](unsigned char c) { return !std::isspace(c); });
  2099. return output;
  2100. }
  2101. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2102. auto host = "httpbingo.org";
  2103. auto path = std::string{"/basic-auth/hello/world"};
  2104. #ifdef CPPHTTPLIB_SSL_ENABLED
  2105. auto port = 443;
  2106. SSLClient cli(host, port);
  2107. #else
  2108. auto port = 80;
  2109. Client cli(host, port);
  2110. #endif
  2111. {
  2112. auto res = cli.Get(path);
  2113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2114. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2115. }
  2116. {
  2117. auto res = cli.Get(
  2118. path, Headers{make_basic_authentication_header("hello", "world")});
  2119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2120. auto body = remove_whitespace(res->body);
  2121. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2122. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2123. EXPECT_EQ(StatusCode::OK_200, res->status);
  2124. }
  2125. {
  2126. cli.set_basic_auth("hello", "world");
  2127. auto res = cli.Get(path);
  2128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2129. auto body = remove_whitespace(res->body);
  2130. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2131. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2132. EXPECT_EQ(StatusCode::OK_200, res->status);
  2133. }
  2134. {
  2135. cli.set_basic_auth("hello", "bad");
  2136. auto res = cli.Get(path);
  2137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2138. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2139. }
  2140. {
  2141. cli.set_basic_auth("bad", "world");
  2142. auto res = cli.Get(path);
  2143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2144. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2145. }
  2146. }
  2147. #ifdef CPPHTTPLIB_SSL_ENABLED
  2148. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2149. auto host = "httpbingo.org";
  2150. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2151. auto paths = std::vector<std::string>{
  2152. "/digest-auth/auth/hello/world/MD5",
  2153. "/digest-auth/auth/hello/world/SHA-256",
  2154. };
  2155. auto port = 443;
  2156. SSLClient cli(host, port);
  2157. {
  2158. auto res = cli.Get(unauth_path);
  2159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2160. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2161. }
  2162. {
  2163. cli.set_digest_auth("hello", "world");
  2164. for (const auto &path : paths) {
  2165. auto res = cli.Get(path.c_str());
  2166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2167. auto body = remove_whitespace(res->body);
  2168. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2169. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2170. EXPECT_EQ(StatusCode::OK_200, res->status);
  2171. }
  2172. cli.set_digest_auth("hello", "bad");
  2173. for (const auto &path : paths) {
  2174. auto res = cli.Get(path.c_str());
  2175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2176. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2177. }
  2178. }
  2179. }
  2180. #endif
  2181. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2182. auto host = "google.com";
  2183. auto another_host = "example.com";
  2184. auto wrong_ip = "0.0.0.0";
  2185. #ifdef CPPHTTPLIB_SSL_ENABLED
  2186. SSLClient cli(host);
  2187. #else
  2188. Client cli(host);
  2189. #endif
  2190. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2191. auto res = cli.Get("/");
  2192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2193. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2194. }
  2195. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2196. auto host = "google.com";
  2197. auto wrong_ip = "0.0.0.0";
  2198. #ifdef CPPHTTPLIB_SSL_ENABLED
  2199. SSLClient cli(host);
  2200. #else
  2201. Client cli(host);
  2202. #endif
  2203. cli.set_hostname_addr_map({{host, wrong_ip}});
  2204. auto res = cli.Get("/");
  2205. ASSERT_TRUE(!res);
  2206. EXPECT_EQ(Error::Connection, res.error());
  2207. }
  2208. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2209. // A mapped value that is not an IP literal must be resolved. "localhost"
  2210. // resolves from the hosts file, so this test needs no external DNS.
  2211. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2212. auto host = "target.invalid";
  2213. Server svr;
  2214. std::string received_host;
  2215. svr.Get("/hi", [&](const Request &req, Response &res) {
  2216. received_host = req.get_header_value("Host");
  2217. res.set_content("Hello World!", "text/plain");
  2218. });
  2219. auto port = svr.bind_to_any_port(HOST);
  2220. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2221. auto se = detail::scope_exit([&] {
  2222. svr.stop();
  2223. thread.join();
  2224. ASSERT_FALSE(svr.is_running());
  2225. });
  2226. svr.wait_until_ready();
  2227. Client cli(host, port);
  2228. cli.set_hostname_addr_map({{host, HOST}});
  2229. auto res = cli.Get("/hi");
  2230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. // The mapping only redirects the connection; the identity stays host_.
  2233. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2234. }
  2235. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2236. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2237. auto host = "target.invalid";
  2238. Server svr;
  2239. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2240. res.set_content("Hello World!", "text/plain");
  2241. });
  2242. auto port = svr.bind_to_any_port("127.0.0.1");
  2243. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2244. auto se = detail::scope_exit([&] {
  2245. svr.stop();
  2246. thread.join();
  2247. ASSERT_FALSE(svr.is_running());
  2248. });
  2249. svr.wait_until_ready();
  2250. Client cli(host, port);
  2251. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2252. auto res = cli.Get("/hi");
  2253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2254. EXPECT_EQ(StatusCode::OK_200, res->status);
  2255. }
  2256. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2257. // An empty mapped value must leave host_ as the connection target. Without
  2258. // that guard the empty value would become the host argument, getaddrinfo
  2259. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2260. // loopback - silently connecting somewhere the caller never asked for.
  2261. // The server listens on loopback, so such a fallback would succeed and is
  2262. // therefore observable as a failure of this test.
  2263. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2264. Server svr;
  2265. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2266. res.set_content("Hello World!", "text/plain");
  2267. });
  2268. auto port = svr.bind_to_any_port(HOST);
  2269. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2270. auto se = detail::scope_exit([&] {
  2271. svr.stop();
  2272. thread.join();
  2273. ASSERT_FALSE(svr.is_running());
  2274. });
  2275. svr.wait_until_ready();
  2276. Client cli(blackhole, port);
  2277. cli.set_hostname_addr_map({{blackhole, ""}});
  2278. cli.set_connection_timeout(1);
  2279. auto res = cli.Get("/hi");
  2280. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2281. }
  2282. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2283. auto host = "httpbingo.org";
  2284. auto path = std::string{"/absolute-redirect/3"};
  2285. #ifdef CPPHTTPLIB_SSL_ENABLED
  2286. SSLClient cli(host);
  2287. #else
  2288. Client cli(host);
  2289. #endif
  2290. cli.set_follow_location(true);
  2291. auto res = cli.Get(path);
  2292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2293. EXPECT_EQ(StatusCode::OK_200, res->status);
  2294. }
  2295. TEST(RedirectTest, Redirect_Online) {
  2296. auto host = "httpbingo.org";
  2297. auto path = std::string{"/redirect/3"};
  2298. #ifdef CPPHTTPLIB_SSL_ENABLED
  2299. SSLClient cli(host);
  2300. #else
  2301. Client cli(host);
  2302. #endif
  2303. cli.set_follow_location(true);
  2304. auto res = cli.Get(path);
  2305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2306. EXPECT_EQ(StatusCode::OK_200, res->status);
  2307. }
  2308. TEST(RelativeRedirectTest, Redirect_Online) {
  2309. auto host = "httpbingo.org";
  2310. auto path = std::string{"/relative-redirect/3"};
  2311. #ifdef CPPHTTPLIB_SSL_ENABLED
  2312. SSLClient cli(host);
  2313. #else
  2314. Client cli(host);
  2315. #endif
  2316. cli.set_follow_location(true);
  2317. auto res = cli.Get(path);
  2318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. }
  2321. TEST(TooManyRedirectTest, Redirect_Online) {
  2322. auto host = "httpbingo.org";
  2323. auto path = std::string{"/redirect/21"};
  2324. #ifdef CPPHTTPLIB_SSL_ENABLED
  2325. SSLClient cli(host);
  2326. #else
  2327. Client cli(host);
  2328. #endif
  2329. cli.set_follow_location(true);
  2330. auto res = cli.Get(path);
  2331. ASSERT_TRUE(!res);
  2332. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2333. }
  2334. #ifdef CPPHTTPLIB_SSL_ENABLED
  2335. TEST(YahooRedirectTest, Redirect_Online) {
  2336. Client cli("yahoo.com");
  2337. auto res = cli.Get("/");
  2338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2339. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2340. cli.set_follow_location(true);
  2341. res = cli.Get("/");
  2342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2343. EXPECT_EQ(StatusCode::OK_200, res->status);
  2344. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2345. }
  2346. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2347. #define REDIR_HOST "httpbingo.org"
  2348. #define REDIR_PATH "/redirect-to"
  2349. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2350. SSLClient cli(REDIR_HOST);
  2351. cli.set_follow_location(true);
  2352. auto res =
  2353. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2355. EXPECT_EQ(StatusCode::OK_200, res->status);
  2356. }
  2357. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2358. SSLClient cli(REDIR_HOST);
  2359. cli.set_follow_location(true);
  2360. Params params;
  2361. params.emplace("url", "http://example.com");
  2362. params.emplace("status_code", "302");
  2363. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2365. EXPECT_EQ(StatusCode::OK_200, res->status);
  2366. }
  2367. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2368. SSLClient cli(REDIR_HOST);
  2369. cli.set_follow_location(true);
  2370. Params params;
  2371. params.emplace("url", "http://example.com");
  2372. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2374. EXPECT_EQ(StatusCode::OK_200, res->status);
  2375. }
  2376. TEST(UrlWithSpace, Redirect_Online) {
  2377. SSLClient cli("edge.forgecdn.net");
  2378. cli.set_follow_location(true);
  2379. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. EXPECT_EQ(StatusCode::OK_200, res->status);
  2382. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2383. }
  2384. #endif
  2385. #if !defined(_WIN32) && !defined(_WIN64)
  2386. TEST(ReceiveSignals, Signal) {
  2387. auto setupSignalHandlers = []() {
  2388. struct sigaction act;
  2389. sigemptyset(&act.sa_mask);
  2390. act.sa_flags = SA_SIGINFO;
  2391. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2392. switch (sig) {
  2393. case SIGINT:
  2394. default: break;
  2395. }
  2396. };
  2397. ::sigaction(SIGINT, &act, nullptr);
  2398. };
  2399. Server svr;
  2400. int port = 0;
  2401. auto thread = std::thread([&]() {
  2402. setupSignalHandlers();
  2403. port = svr.bind_to_any_port(HOST);
  2404. svr.listen_after_bind();
  2405. });
  2406. auto se = detail::scope_exit([&] {
  2407. svr.stop();
  2408. thread.join();
  2409. ASSERT_FALSE(svr.is_running());
  2410. });
  2411. svr.wait_until_ready();
  2412. ASSERT_TRUE(svr.is_running());
  2413. pthread_kill(thread.native_handle(), SIGINT);
  2414. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2415. ASSERT_TRUE(svr.is_running());
  2416. }
  2417. #endif
  2418. TEST(RedirectToDifferentPort, Redirect) {
  2419. Server svr1;
  2420. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2421. res.set_content("Hello World!", "text/plain");
  2422. });
  2423. int svr1_port = 0;
  2424. auto thread1 = std::thread([&]() {
  2425. svr1_port = svr1.bind_to_any_port(HOST);
  2426. svr1.listen_after_bind();
  2427. });
  2428. Server svr2;
  2429. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2430. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2431. });
  2432. int svr2_port = 0;
  2433. auto thread2 = std::thread([&]() {
  2434. svr2_port = svr2.bind_to_any_port(HOST);
  2435. svr2.listen_after_bind();
  2436. });
  2437. auto se = detail::scope_exit([&] {
  2438. svr2.stop();
  2439. thread2.join();
  2440. svr1.stop();
  2441. thread1.join();
  2442. ASSERT_FALSE(svr2.is_running());
  2443. ASSERT_FALSE(svr1.is_running());
  2444. });
  2445. svr1.wait_until_ready();
  2446. svr2.wait_until_ready();
  2447. Client cli("localhost", svr2_port);
  2448. cli.set_follow_location(true);
  2449. auto res = cli.Get("/2");
  2450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2451. EXPECT_EQ(StatusCode::OK_200, res->status);
  2452. EXPECT_EQ("Hello World!", res->body);
  2453. }
  2454. static void
  2455. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2456. Server svr1;
  2457. std::string captured_authorization;
  2458. svr1.Get("/target", [&](const Request &req, Response &res) {
  2459. captured_authorization = req.get_header_value("Authorization");
  2460. res.set_content("OK", "text/plain");
  2461. });
  2462. int svr1_port = 0;
  2463. auto thread1 = std::thread([&]() {
  2464. svr1_port = svr1.bind_to_any_port(HOST);
  2465. svr1.listen_after_bind();
  2466. });
  2467. Server svr2;
  2468. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2469. res.set_redirect(
  2470. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2471. });
  2472. int svr2_port = 0;
  2473. auto thread2 = std::thread([&]() {
  2474. svr2_port = svr2.bind_to_any_port(HOST);
  2475. svr2.listen_after_bind();
  2476. });
  2477. auto se = detail::scope_exit([&] {
  2478. svr2.stop();
  2479. thread2.join();
  2480. svr1.stop();
  2481. thread1.join();
  2482. ASSERT_FALSE(svr2.is_running());
  2483. ASSERT_FALSE(svr1.is_running());
  2484. });
  2485. svr1.wait_until_ready();
  2486. svr2.wait_until_ready();
  2487. Client cli("localhost", svr2_port);
  2488. cli.set_follow_location(true);
  2489. set_auth(cli);
  2490. auto res = cli.Get("/redir");
  2491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2492. EXPECT_EQ(StatusCode::OK_200, res->status);
  2493. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2494. EXPECT_TRUE(captured_authorization.empty());
  2495. }
  2496. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2497. TestDoNotForwardCredentialsOnRedirect(
  2498. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2499. }
  2500. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2501. TestDoNotForwardCredentialsOnRedirect(
  2502. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2503. }
  2504. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2505. Server svr1;
  2506. std::string captured_cookie;
  2507. bool target_hit = false;
  2508. svr1.Get("/target", [&](const Request &req, Response &res) {
  2509. captured_cookie = req.get_header_value("Cookie");
  2510. target_hit = true;
  2511. res.set_content("OK", "text/plain");
  2512. });
  2513. int svr1_port = 0;
  2514. auto thread1 = std::thread([&]() {
  2515. svr1_port = svr1.bind_to_any_port(HOST);
  2516. svr1.listen_after_bind();
  2517. });
  2518. Server svr2;
  2519. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2520. res.set_redirect(
  2521. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2522. });
  2523. int svr2_port = 0;
  2524. auto thread2 = std::thread([&]() {
  2525. svr2_port = svr2.bind_to_any_port(HOST);
  2526. svr2.listen_after_bind();
  2527. });
  2528. auto se = detail::scope_exit([&] {
  2529. svr2.stop();
  2530. thread2.join();
  2531. svr1.stop();
  2532. thread1.join();
  2533. ASSERT_FALSE(svr2.is_running());
  2534. ASSERT_FALSE(svr1.is_running());
  2535. });
  2536. svr1.wait_until_ready();
  2537. svr2.wait_until_ready();
  2538. Client cli("localhost", svr2_port);
  2539. cli.set_follow_location(true);
  2540. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2541. auto res = cli.Get("/redir", headers);
  2542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2543. EXPECT_EQ(StatusCode::OK_200, res->status);
  2544. EXPECT_TRUE(target_hit);
  2545. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2546. EXPECT_TRUE(captured_cookie.empty());
  2547. }
  2548. TEST(RedirectToSamePort, ForwardCookie) {
  2549. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2550. // header so that ordinary session flows keep working.
  2551. Server svr;
  2552. std::string captured_cookie;
  2553. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2554. res.set_redirect("/target", 302);
  2555. });
  2556. svr.Get("/target", [&](const Request &req, Response &res) {
  2557. captured_cookie = req.get_header_value("Cookie");
  2558. res.set_content("OK", "text/plain");
  2559. });
  2560. auto port = svr.bind_to_any_port(HOST);
  2561. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2562. auto se = detail::scope_exit([&] {
  2563. svr.stop();
  2564. thread.join();
  2565. ASSERT_FALSE(svr.is_running());
  2566. });
  2567. svr.wait_until_ready();
  2568. Client cli(HOST, port);
  2569. cli.set_follow_location(true);
  2570. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2571. auto res = cli.Get("/redir", headers);
  2572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2573. EXPECT_EQ(StatusCode::OK_200, res->status);
  2574. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2575. }
  2576. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2577. Server svr;
  2578. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2579. // Port number that overflows int — should not crash
  2580. res.set_redirect("http://localhost:99999999999999999999/target");
  2581. });
  2582. auto port = svr.bind_to_any_port(HOST);
  2583. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2584. auto se = detail::scope_exit([&] {
  2585. svr.stop();
  2586. thread.join();
  2587. ASSERT_FALSE(svr.is_running());
  2588. });
  2589. svr.wait_until_ready();
  2590. Client cli(HOST, port);
  2591. cli.set_follow_location(true);
  2592. auto res = cli.Get("/redir");
  2593. // Should fail gracefully, not crash (no valid response due to bad port)
  2594. EXPECT_FALSE(res);
  2595. }
  2596. TEST(RedirectFromPageWithContent, Redirect) {
  2597. Server svr;
  2598. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2599. res.set_content("___", "text/plain");
  2600. res.set_redirect("/2");
  2601. });
  2602. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2603. res.set_content("Hello World!", "text/plain");
  2604. });
  2605. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2606. auto se = detail::scope_exit([&] {
  2607. svr.stop();
  2608. th.join();
  2609. ASSERT_FALSE(svr.is_running());
  2610. });
  2611. svr.wait_until_ready();
  2612. {
  2613. Client cli("localhost", PORT);
  2614. cli.set_follow_location(true);
  2615. std::string body;
  2616. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2617. body.append(data, data_length);
  2618. return true;
  2619. });
  2620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2621. EXPECT_EQ(StatusCode::OK_200, res->status);
  2622. EXPECT_EQ("Hello World!", body);
  2623. }
  2624. {
  2625. Client cli("localhost", PORT);
  2626. std::string body;
  2627. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2628. body.append(data, data_length);
  2629. return true;
  2630. });
  2631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2632. EXPECT_EQ(StatusCode::Found_302, res->status);
  2633. EXPECT_EQ("___", body);
  2634. }
  2635. }
  2636. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2637. Server svr;
  2638. auto port_str = std::to_string(PORT);
  2639. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2640. auto expected_host = "[::1]:" + port_str;
  2641. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2642. res.set_content("___", "text/plain");
  2643. // res.set_redirect("/2");
  2644. res.set_redirect(redirect_url);
  2645. });
  2646. svr.Get("/2", [&](const Request &req, Response &res) {
  2647. auto host_header = req.headers.find("Host");
  2648. ASSERT_TRUE(host_header != req.headers.end());
  2649. EXPECT_EQ(expected_host, host_header->second);
  2650. res.set_content("Hello World!", "text/plain");
  2651. });
  2652. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2653. auto se = detail::scope_exit([&] {
  2654. svr.stop();
  2655. th.join();
  2656. ASSERT_FALSE(svr.is_running());
  2657. });
  2658. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2659. // actually starts anything, so the condition !svr.is_running() will
  2660. // always remain true, and the loop never stops.
  2661. // This basically counts how many milliseconds have passed since the
  2662. // call to svr.listen(), and if after 5 seconds nothing started yet
  2663. // aborts the test.
  2664. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2665. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2666. ASSERT_LT(milliseconds, 5000U);
  2667. }
  2668. {
  2669. Client cli("::1", PORT);
  2670. cli.set_follow_location(true);
  2671. std::string body;
  2672. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2673. body.append(data, data_length);
  2674. return true;
  2675. });
  2676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2677. EXPECT_EQ(StatusCode::OK_200, res->status);
  2678. EXPECT_EQ("Hello World!", body);
  2679. }
  2680. {
  2681. Client cli("::1", PORT);
  2682. std::string body;
  2683. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2684. body.append(data, data_length);
  2685. return true;
  2686. });
  2687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2688. EXPECT_EQ(StatusCode::Found_302, res->status);
  2689. EXPECT_EQ("___", body);
  2690. }
  2691. }
  2692. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2693. Server svr;
  2694. svr.Get("/foo", [](const Request &req, Response &res) {
  2695. auto a = req.params.find("a");
  2696. if (a != req.params.end()) {
  2697. res.set_content((*a).second, "text/plain");
  2698. res.status = StatusCode::OK_200;
  2699. } else {
  2700. res.status = StatusCode::BadRequest_400;
  2701. }
  2702. });
  2703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2704. auto se = detail::scope_exit([&] {
  2705. svr.stop();
  2706. thread.join();
  2707. ASSERT_FALSE(svr.is_running());
  2708. });
  2709. svr.wait_until_ready();
  2710. {
  2711. Client cli(HOST, PORT);
  2712. cli.set_path_encode(false);
  2713. auto res = cli.Get("/foo?a=explicitly+encoded");
  2714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2715. EXPECT_EQ(StatusCode::OK_200, res->status);
  2716. // This expects it back with a space, as the `+` won't have been
  2717. // url-encoded, and server-side the params get decoded turning `+`
  2718. // into spaces.
  2719. EXPECT_EQ("explicitly encoded", res->body);
  2720. }
  2721. }
  2722. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2723. // When path encoding is disabled the client must transmit the supplied
  2724. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2725. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2726. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2727. // than a space (0x20). Assert on the raw wire target to catch this.
  2728. Server svr;
  2729. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2730. svr.Get("/foo", [&](const Request &req, Response &res) {
  2731. EXPECT_EQ(expected_target, req.target);
  2732. res.status = StatusCode::OK_200;
  2733. });
  2734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2735. auto se = detail::scope_exit([&] {
  2736. svr.stop();
  2737. thread.join();
  2738. ASSERT_FALSE(svr.is_running());
  2739. });
  2740. svr.wait_until_ready();
  2741. {
  2742. Client cli(HOST, PORT);
  2743. cli.set_path_encode(false);
  2744. auto res = cli.Get(expected_target.c_str());
  2745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2746. EXPECT_EQ(StatusCode::OK_200, res->status);
  2747. }
  2748. }
  2749. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2750. // `open_stream()` used to skip the path encoding that the buffered send
  2751. // path applies, so the same `path` produced different bytes in the request
  2752. // line depending on which API was used. Assert the two agree.
  2753. Server svr;
  2754. std::string target;
  2755. svr.Get(".*", [&](const Request &req, Response &res) {
  2756. target = req.target;
  2757. res.status = StatusCode::OK_200;
  2758. });
  2759. auto port = svr.bind_to_any_port(HOST);
  2760. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. struct {
  2768. const char *path;
  2769. const char *expected;
  2770. } cases[] = {
  2771. {"/a b?x=1", "/a%20b?x=1"},
  2772. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2773. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2774. };
  2775. for (const auto &c : cases) {
  2776. Client cli(HOST, port);
  2777. target.clear();
  2778. auto res = cli.Get(c.path);
  2779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2780. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2781. auto buffered_target = target;
  2782. target.clear();
  2783. auto handle = cli.open_stream("GET", c.path);
  2784. EXPECT_TRUE(handle.is_valid())
  2785. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2786. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2787. }
  2788. }
  2789. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2790. // The `set_path_encode(false)` contract — transmit the supplied target
  2791. // verbatim — must hold for the streaming API too.
  2792. Server svr;
  2793. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2794. std::string target;
  2795. svr.Get("/foo", [&](const Request &req, Response &res) {
  2796. target = req.target;
  2797. res.status = StatusCode::OK_200;
  2798. });
  2799. auto port = svr.bind_to_any_port(HOST);
  2800. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2801. auto se = detail::scope_exit([&] {
  2802. svr.stop();
  2803. thread.join();
  2804. ASSERT_FALSE(svr.is_running());
  2805. });
  2806. svr.wait_until_ready();
  2807. {
  2808. Client cli(HOST, port);
  2809. cli.set_path_encode(false);
  2810. auto handle = cli.open_stream("GET", expected_target);
  2811. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2812. EXPECT_EQ(expected_target, target);
  2813. }
  2814. }
  2815. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  2816. // With path encoding enabled a CR/LF in the target is percent-encoded
  2817. // rather than rejected, matching the buffered send path. The CR/LF guard in
  2818. // write_request_line still backstops `set_path_encode(false)`, which is
  2819. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  2820. Server svr;
  2821. // Captured before routing: the decoded path contains a newline, which a
  2822. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  2823. std::string target;
  2824. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  2825. target = req.target;
  2826. res.status = StatusCode::OK_200;
  2827. return Server::HandlerResponse::Handled;
  2828. });
  2829. auto port = svr.bind_to_any_port(HOST);
  2830. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2831. auto se = detail::scope_exit([&] {
  2832. svr.stop();
  2833. thread.join();
  2834. ASSERT_FALSE(svr.is_running());
  2835. });
  2836. svr.wait_until_ready();
  2837. {
  2838. Client cli(HOST, port);
  2839. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2840. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2841. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  2842. }
  2843. }
  2844. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  2845. // Nothing may reach the wire: a raw CR/LF target would split the request
  2846. // line and inject headers.
  2847. Server svr;
  2848. // Pre-routing so that "not called" means nothing reached the server at all,
  2849. // rather than merely failing to match a handler pattern.
  2850. auto handler_called = false;
  2851. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  2852. handler_called = true;
  2853. res.status = StatusCode::OK_200;
  2854. return Server::HandlerResponse::Handled;
  2855. });
  2856. auto port = svr.bind_to_any_port(HOST);
  2857. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2858. auto se = detail::scope_exit([&] {
  2859. svr.stop();
  2860. thread.join();
  2861. ASSERT_FALSE(svr.is_running());
  2862. });
  2863. svr.wait_until_ready();
  2864. {
  2865. Client cli(HOST, port);
  2866. cli.set_path_encode(false);
  2867. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2868. EXPECT_FALSE(handle.is_valid());
  2869. EXPECT_EQ(Error::Write, handle.error);
  2870. EXPECT_FALSE(handler_called);
  2871. }
  2872. }
  2873. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  2874. // Which of the two branches runs is decided by whether the query component
  2875. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  2876. // an empty query and must still fall back to building one from
  2877. // `req.params`, while a non-empty query must win over `req.params`.
  2878. Server svr;
  2879. std::string target;
  2880. svr.Get("/foo", [&](const Request &req, Response &res) {
  2881. target = req.target;
  2882. res.status = StatusCode::OK_200;
  2883. });
  2884. auto port = svr.bind_to_any_port(HOST);
  2885. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2886. auto se = detail::scope_exit([&] {
  2887. svr.stop();
  2888. thread.join();
  2889. ASSERT_FALSE(svr.is_running());
  2890. });
  2891. svr.wait_until_ready();
  2892. {
  2893. // Trailing `?` -> empty query component -> `req.params` is used.
  2894. Client cli(HOST, port);
  2895. Request req;
  2896. req.method = "GET";
  2897. req.path = "/foo?";
  2898. req.params.emplace("a", "1");
  2899. target.clear();
  2900. auto res = cli.send(req);
  2901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2902. EXPECT_EQ("/foo?a=1", target);
  2903. }
  2904. {
  2905. // Non-empty query in `req.path` -> `req.params` is not appended.
  2906. Client cli(HOST, port);
  2907. Request req;
  2908. req.method = "GET";
  2909. req.path = "/foo?b=2";
  2910. req.params.emplace("a", "1");
  2911. target.clear();
  2912. auto res = cli.send(req);
  2913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2914. EXPECT_EQ("/foo?b=2", target);
  2915. }
  2916. }
  2917. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2918. Server svr;
  2919. svr.Get("/", [](const Request &req, Response &) {
  2920. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2921. });
  2922. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2923. auto se = detail::scope_exit([&] {
  2924. svr.stop();
  2925. thread.join();
  2926. ASSERT_FALSE(svr.is_running());
  2927. });
  2928. svr.wait_until_ready();
  2929. {
  2930. Client cli(HOST, PORT);
  2931. cli.set_path_encode(false);
  2932. auto res = cli.Get("/?something=%0A");
  2933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2934. EXPECT_EQ(StatusCode::OK_200, res->status);
  2935. }
  2936. }
  2937. TEST(BindServerTest, BindDualStack) {
  2938. Server svr;
  2939. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2940. res.set_content("Hello World!", "text/plain");
  2941. });
  2942. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2943. auto se = detail::scope_exit([&] {
  2944. svr.stop();
  2945. thread.join();
  2946. ASSERT_FALSE(svr.is_running());
  2947. });
  2948. svr.wait_until_ready();
  2949. {
  2950. Client cli("127.0.0.1", PORT);
  2951. auto res = cli.Get("/1");
  2952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2953. EXPECT_EQ(StatusCode::OK_200, res->status);
  2954. EXPECT_EQ("Hello World!", res->body);
  2955. }
  2956. {
  2957. Client cli("::1", PORT);
  2958. auto res = cli.Get("/1");
  2959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2960. EXPECT_EQ(StatusCode::OK_200, res->status);
  2961. EXPECT_EQ("Hello World!", res->body);
  2962. }
  2963. }
  2964. TEST(BindServerTest, BindAndListenSeparately) {
  2965. Server svr;
  2966. int port = svr.bind_to_any_port("0.0.0.0");
  2967. ASSERT_TRUE(svr.is_valid());
  2968. ASSERT_TRUE(port > 0);
  2969. svr.stop();
  2970. }
  2971. // Reports whether anything is still listening on a loopback port. A plain
  2972. // connect() is used instead of a Client request because a socket left bound by
  2973. // mistake accepts the connection into its backlog and never answers, which
  2974. // would hang the test instead of failing it.
  2975. static bool is_loopback_port_accepting(int port) {
  2976. sockaddr_in addr{};
  2977. addr.sin_family = AF_INET;
  2978. addr.sin_port = htons(static_cast<uint16_t>(port));
  2979. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2980. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  2981. EXPECT_NE(sock, INVALID_SOCKET);
  2982. if (sock == INVALID_SOCKET) { return false; }
  2983. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  2984. static_cast<socklen_t>(sizeof(addr)));
  2985. detail::close_socket(sock);
  2986. return ret == 0;
  2987. }
  2988. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  2989. Server svr;
  2990. auto port = svr.bind_to_any_port("127.0.0.1");
  2991. ASSERT_TRUE(port > 0);
  2992. svr.stop();
  2993. // bind_to_any_port() already called listen(2), so until stop() closed the
  2994. // descriptor the port kept accepting connections into the backlog. ASSERT
  2995. // rather than EXPECT: with the socket still open, the listen_after_bind()
  2996. // below blocks forever in the accept loop.
  2997. ASSERT_FALSE(is_loopback_port_accepting(port));
  2998. // Nothing is left to accept on, so listen_after_bind() must report failure
  2999. // instead of returning success without ever serving.
  3000. EXPECT_FALSE(svr.listen_after_bind());
  3001. // The failed listen marks the server decommissioned, so a waiter returns
  3002. // instead of spinning forever.
  3003. svr.wait_until_ready();
  3004. }
  3005. #ifdef CPPHTTPLIB_SSL_ENABLED
  3006. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3008. CLIENT_CA_CERT_DIR);
  3009. int port = svr.bind_to_any_port("0.0.0.0");
  3010. ASSERT_TRUE(svr.is_valid());
  3011. ASSERT_TRUE(port > 0);
  3012. svr.stop();
  3013. }
  3014. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3015. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3016. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3017. int port = svr.bind_to_any_port("0.0.0.0");
  3018. ASSERT_TRUE(svr.is_valid());
  3019. ASSERT_TRUE(port > 0);
  3020. svr.stop();
  3021. }
  3022. TEST(BindServerTest, UpdateCertsPem) {
  3023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3024. int port = svr.bind_to_any_port("0.0.0.0");
  3025. ASSERT_TRUE(svr.is_valid());
  3026. ASSERT_TRUE(port > 0);
  3027. // Read PEM files
  3028. std::string cert_pem, key_pem, ca_pem;
  3029. read_file(SERVER_CERT_FILE, cert_pem);
  3030. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3031. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3032. // Update server certificates using PEM API
  3033. ASSERT_TRUE(
  3034. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3035. ASSERT_TRUE(svr.is_valid());
  3036. svr.stop();
  3037. }
  3038. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3039. // Start server with client CA (enables client auth)
  3040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3041. ASSERT_TRUE(svr.is_valid());
  3042. bool handler_called = false;
  3043. svr.Get("/test", [&](const Request &req, Response &res) {
  3044. handler_called = true;
  3045. // Verify client certificate is present
  3046. auto cert = req.peer_cert();
  3047. EXPECT_TRUE(static_cast<bool>(cert));
  3048. res.set_content("ok", "text/plain");
  3049. });
  3050. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3051. auto se = detail::scope_exit([&] {
  3052. svr.stop();
  3053. t.join();
  3054. ASSERT_FALSE(svr.is_running());
  3055. });
  3056. svr.wait_until_ready();
  3057. // Read PEM files
  3058. std::string cert_pem, key_pem, ca_pem;
  3059. read_file(SERVER_CERT_FILE, cert_pem);
  3060. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3061. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3062. // Update server certificates and client CA using PEM API while server running
  3063. ASSERT_TRUE(
  3064. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3065. // Connect with client certificate
  3066. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3067. cli.enable_server_certificate_verification(false);
  3068. cli.set_connection_timeout(30);
  3069. auto res = cli.Get("/test");
  3070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3071. ASSERT_EQ(StatusCode::OK_200, res->status);
  3072. ASSERT_TRUE(handler_called);
  3073. EXPECT_EQ("ok", res->body);
  3074. }
  3075. #endif
  3076. TEST(ErrorHandlerTest, ContentLength) {
  3077. Server svr;
  3078. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3079. res.status = StatusCode::OK_200;
  3080. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3081. "text/html"); // <= Content-Length still 13
  3082. });
  3083. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3084. res.set_content("Hello World!\n", "text/plain");
  3085. res.status = 524;
  3086. });
  3087. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3088. auto se = detail::scope_exit([&] {
  3089. svr.stop();
  3090. thread.join();
  3091. ASSERT_FALSE(svr.is_running());
  3092. });
  3093. svr.wait_until_ready();
  3094. {
  3095. Client cli(HOST, PORT);
  3096. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3098. EXPECT_EQ(StatusCode::OK_200, res->status);
  3099. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3100. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3101. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3102. }
  3103. }
  3104. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3105. TEST(ExceptionTest, WithoutExceptionHandler) {
  3106. Server svr;
  3107. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3108. throw std::runtime_error("exception...");
  3109. });
  3110. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3111. throw std::runtime_error("exception\r\n...");
  3112. });
  3113. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3114. auto se = detail::scope_exit([&] {
  3115. svr.stop();
  3116. listen_thread.join();
  3117. ASSERT_FALSE(svr.is_running());
  3118. });
  3119. svr.wait_until_ready();
  3120. Client cli("localhost", PORT);
  3121. {
  3122. auto res = cli.Get("/exception");
  3123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3124. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3125. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3126. }
  3127. {
  3128. auto res = cli.Get("/unknown");
  3129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3130. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3131. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3132. }
  3133. }
  3134. TEST(ExceptionTest, WithExceptionHandler) {
  3135. Server svr;
  3136. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3137. std::exception_ptr ep) {
  3138. EXPECT_FALSE(ep == nullptr);
  3139. try {
  3140. std::rethrow_exception(ep);
  3141. } catch (std::exception &e) {
  3142. EXPECT_EQ("abc", std::string(e.what()));
  3143. } catch (...) {}
  3144. res.status = StatusCode::InternalServerError_500;
  3145. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3146. "text/html"); // <= Content-Length still 13 at this point
  3147. });
  3148. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3149. res.set_content("Hello World!\n", "text/plain");
  3150. throw std::runtime_error("abc");
  3151. });
  3152. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3153. auto se = detail::scope_exit([&] {
  3154. svr.stop();
  3155. thread.join();
  3156. ASSERT_FALSE(svr.is_running());
  3157. });
  3158. svr.wait_until_ready();
  3159. for (size_t i = 0; i < 10; i++) {
  3160. Client cli(HOST, PORT);
  3161. for (size_t j = 0; j < 100; j++) {
  3162. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3164. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3165. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3166. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3168. }
  3169. cli.set_keep_alive(true);
  3170. for (size_t j = 0; j < 100; j++) {
  3171. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3173. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3174. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3175. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3176. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3177. }
  3178. }
  3179. }
  3180. TEST(ExceptionTest, AndErrorHandler) {
  3181. Server svr;
  3182. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3183. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3184. });
  3185. svr.set_exception_handler(
  3186. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3187. EXPECT_FALSE(ep == nullptr);
  3188. try {
  3189. std::rethrow_exception(ep);
  3190. } catch (std::exception &e) {
  3191. res.set_content(e.what(), "text/html");
  3192. } catch (...) {}
  3193. res.status = StatusCode::InternalServerError_500;
  3194. });
  3195. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3196. throw std::runtime_error("EXCEPTION");
  3197. });
  3198. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3199. res.set_content("ERROR", "text/html");
  3200. res.status = StatusCode::InternalServerError_500;
  3201. });
  3202. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3203. auto se = detail::scope_exit([&] {
  3204. svr.stop();
  3205. thread.join();
  3206. ASSERT_FALSE(svr.is_running());
  3207. });
  3208. svr.wait_until_ready();
  3209. Client cli(HOST, PORT);
  3210. {
  3211. auto res = cli.Get("/exception");
  3212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3213. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3214. EXPECT_EQ("EXCEPTION", res->body);
  3215. }
  3216. {
  3217. auto res = cli.Get("/error");
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3220. EXPECT_EQ("ERROR", res->body);
  3221. }
  3222. {
  3223. auto res = cli.Get("/invalid");
  3224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3225. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3226. EXPECT_EQ("NOT_FOUND", res->body);
  3227. }
  3228. }
  3229. #endif
  3230. TEST(NoContentTest, ContentLength) {
  3231. Server svr;
  3232. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3233. res.status = StatusCode::NoContent_204;
  3234. });
  3235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3236. auto se = detail::scope_exit([&] {
  3237. svr.stop();
  3238. thread.join();
  3239. ASSERT_FALSE(svr.is_running());
  3240. });
  3241. svr.wait_until_ready();
  3242. {
  3243. Client cli(HOST, PORT);
  3244. auto res = cli.Get("/hi");
  3245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3246. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3247. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3248. }
  3249. }
  3250. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3251. #ifdef CPPHTTPLIB_SSL_ENABLED
  3252. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3253. ASSERT_TRUE(svr.is_valid());
  3254. #else
  3255. Server svr;
  3256. #endif
  3257. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3258. if (req.path == "/routing_handler") {
  3259. res.set_header("PRE_ROUTING", "on");
  3260. res.set_content("Routing Handler", "text/plain");
  3261. return httplib::Server::HandlerResponse::Handled;
  3262. }
  3263. return httplib::Server::HandlerResponse::Unhandled;
  3264. });
  3265. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3266. res.set_content("Error", "text/html");
  3267. });
  3268. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3269. if (req.path == "/routing_handler") {
  3270. res.set_header("POST_ROUTING", "on");
  3271. }
  3272. });
  3273. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3274. res.set_content("Hello World!\n", "text/plain");
  3275. });
  3276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3277. auto se = detail::scope_exit([&] {
  3278. svr.stop();
  3279. thread.join();
  3280. ASSERT_FALSE(svr.is_running());
  3281. });
  3282. svr.wait_until_ready();
  3283. {
  3284. #ifdef CPPHTTPLIB_SSL_ENABLED
  3285. SSLClient cli(HOST, PORT);
  3286. cli.enable_server_certificate_verification(false);
  3287. #else
  3288. Client cli(HOST, PORT);
  3289. #endif
  3290. auto res = cli.Get("/routing_handler");
  3291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3292. EXPECT_EQ(StatusCode::OK_200, res->status);
  3293. EXPECT_EQ("Routing Handler", res->body);
  3294. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3295. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3296. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3297. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3298. }
  3299. {
  3300. #ifdef CPPHTTPLIB_SSL_ENABLED
  3301. SSLClient cli(HOST, PORT);
  3302. cli.enable_server_certificate_verification(false);
  3303. #else
  3304. Client cli(HOST, PORT);
  3305. #endif
  3306. auto res = cli.Get("/hi");
  3307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3308. EXPECT_EQ(StatusCode::OK_200, res->status);
  3309. EXPECT_EQ("Hello World!\n", res->body);
  3310. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3311. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3312. }
  3313. {
  3314. #ifdef CPPHTTPLIB_SSL_ENABLED
  3315. SSLClient cli(HOST, PORT);
  3316. cli.enable_server_certificate_verification(false);
  3317. #else
  3318. Client cli(HOST, PORT);
  3319. #endif
  3320. auto res = cli.Get("/aaa");
  3321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3322. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3323. EXPECT_EQ("Error", res->body);
  3324. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3325. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3326. }
  3327. }
  3328. TEST(RequestHandlerTest, PreRequestHandler) {
  3329. auto route_path = "/user/:user";
  3330. Server svr;
  3331. svr.Get("/hi", [](const Request &, Response &res) {
  3332. res.set_content("hi", "text/plain");
  3333. });
  3334. svr.Get(route_path, [](const Request &req, Response &res) {
  3335. res.set_content(req.path_params.at("user"), "text/plain");
  3336. });
  3337. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3338. if (req.matched_route == route_path) {
  3339. auto user = req.path_params.at("user");
  3340. if (user != "john") {
  3341. res.status = StatusCode::Forbidden_403;
  3342. res.set_content("error", "text/html");
  3343. return Server::HandlerResponse::Handled;
  3344. }
  3345. }
  3346. return Server::HandlerResponse::Unhandled;
  3347. });
  3348. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3349. auto se = detail::scope_exit([&] {
  3350. svr.stop();
  3351. thread.join();
  3352. ASSERT_FALSE(svr.is_running());
  3353. });
  3354. svr.wait_until_ready();
  3355. Client cli(HOST, PORT);
  3356. {
  3357. auto res = cli.Get("/hi");
  3358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3359. EXPECT_EQ(StatusCode::OK_200, res->status);
  3360. EXPECT_EQ("hi", res->body);
  3361. }
  3362. {
  3363. auto res = cli.Get("/user/john");
  3364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3365. EXPECT_EQ(StatusCode::OK_200, res->status);
  3366. EXPECT_EQ("john", res->body);
  3367. }
  3368. {
  3369. auto res = cli.Get("/user/invalid-user");
  3370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3371. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3372. EXPECT_EQ("error", res->body);
  3373. }
  3374. }
  3375. // The pre-request handler must run before the request body is read, so a
  3376. // rejected request never forces the server to buffer a (potentially large)
  3377. // body. Here the posted body is larger than the payload limit: if the body
  3378. // were read first the server would answer 413, but because the pre-request
  3379. // handler runs first it answers 403 and the body is never read.
  3380. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3381. Server svr;
  3382. svr.set_payload_max_length(8);
  3383. auto handler_ran = false;
  3384. svr.Post("/reject", [&](const Request &req, Response &res) {
  3385. handler_ran = true;
  3386. res.set_content(req.body, "text/plain");
  3387. });
  3388. svr.Post("/accept", [](const Request &req, Response &res) {
  3389. res.set_content(req.body, "text/plain");
  3390. });
  3391. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3392. if (req.matched_route == "/reject") {
  3393. res.status = StatusCode::Forbidden_403;
  3394. res.set_content("denied", "text/plain");
  3395. return Server::HandlerResponse::Handled;
  3396. }
  3397. return Server::HandlerResponse::Unhandled;
  3398. });
  3399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3400. auto se = detail::scope_exit([&] {
  3401. svr.stop();
  3402. thread.join();
  3403. ASSERT_FALSE(svr.is_running());
  3404. });
  3405. svr.wait_until_ready();
  3406. Client cli(HOST, PORT);
  3407. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3408. // rejects with 403 before the body is read, so 413 is never reached.
  3409. {
  3410. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3412. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3413. EXPECT_EQ("denied", res->body);
  3414. EXPECT_FALSE(handler_ran);
  3415. }
  3416. // An approved route still reads the body and enforces the payload limit.
  3417. {
  3418. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3420. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3421. }
  3422. }
  3423. TEST(UserDataTest, BasicOperations) {
  3424. httplib::UserData ud;
  3425. // Initially empty
  3426. EXPECT_FALSE(ud.has("key"));
  3427. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3428. // set and get
  3429. ud.set("key", 42);
  3430. EXPECT_TRUE(ud.has("key"));
  3431. auto *p = ud.get<int>("key");
  3432. ASSERT_NE(nullptr, p);
  3433. EXPECT_EQ(42, *p);
  3434. // Type mismatch → nullptr
  3435. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3436. // Overwrite with different type
  3437. ud.set("key", std::string("hello"));
  3438. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3439. auto *s = ud.get<std::string>("key");
  3440. ASSERT_NE(nullptr, s);
  3441. EXPECT_EQ("hello", *s);
  3442. // erase
  3443. ud.erase("key");
  3444. EXPECT_FALSE(ud.has("key"));
  3445. // clear
  3446. ud.set("a", 1);
  3447. ud.set("b", 2);
  3448. ud.clear();
  3449. EXPECT_FALSE(ud.has("a"));
  3450. EXPECT_FALSE(ud.has("b"));
  3451. }
  3452. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3453. struct AuthCtx {
  3454. std::string user_id;
  3455. };
  3456. Server svr;
  3457. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3458. res.user_data.set("auth", AuthCtx{"alice"});
  3459. return Server::HandlerResponse::Unhandled;
  3460. });
  3461. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3462. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3463. ASSERT_NE(nullptr, ctx);
  3464. res.set_content("Hello " + ctx->user_id, "text/plain");
  3465. });
  3466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3467. auto se = detail::scope_exit([&] {
  3468. svr.stop();
  3469. thread.join();
  3470. ASSERT_FALSE(svr.is_running());
  3471. });
  3472. svr.wait_until_ready();
  3473. Client cli(HOST, PORT);
  3474. auto res = cli.Get("/me");
  3475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3476. EXPECT_EQ(StatusCode::OK_200, res->status);
  3477. EXPECT_EQ("Hello alice", res->body);
  3478. }
  3479. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3480. struct RoleCtx {
  3481. std::string role;
  3482. };
  3483. Server svr;
  3484. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3485. res.user_data.set("role", RoleCtx{"admin"});
  3486. return Server::HandlerResponse::Unhandled;
  3487. });
  3488. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3489. auto *ctx = res.user_data.get<RoleCtx>("role");
  3490. ASSERT_NE(nullptr, ctx);
  3491. res.set_content(ctx->role, "text/plain");
  3492. });
  3493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3494. auto se = detail::scope_exit([&] {
  3495. svr.stop();
  3496. thread.join();
  3497. ASSERT_FALSE(svr.is_running());
  3498. });
  3499. svr.wait_until_ready();
  3500. Client cli(HOST, PORT);
  3501. auto res = cli.Get("/role");
  3502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3503. EXPECT_EQ(StatusCode::OK_200, res->status);
  3504. EXPECT_EQ("admin", res->body);
  3505. }
  3506. TEST(InvalidFormatTest, StatusCode) {
  3507. Server svr;
  3508. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3509. res.set_content("Hello World!\n", "text/plain");
  3510. res.status = 9999; // Status should be a three-digit code...
  3511. });
  3512. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3513. auto se = detail::scope_exit([&] {
  3514. svr.stop();
  3515. thread.join();
  3516. ASSERT_FALSE(svr.is_running());
  3517. });
  3518. svr.wait_until_ready();
  3519. {
  3520. Client cli(HOST, PORT);
  3521. auto res = cli.Get("/hi");
  3522. ASSERT_FALSE(res);
  3523. }
  3524. }
  3525. TEST(URLFragmentTest, WithFragment) {
  3526. Server svr;
  3527. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3528. EXPECT_TRUE(req.target == "/hi");
  3529. });
  3530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3531. auto se = detail::scope_exit([&] {
  3532. svr.stop();
  3533. thread.join();
  3534. ASSERT_FALSE(svr.is_running());
  3535. });
  3536. svr.wait_until_ready();
  3537. {
  3538. Client cli(HOST, PORT);
  3539. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3540. EXPECT_TRUE(res);
  3541. EXPECT_EQ(StatusCode::OK_200, res->status);
  3542. res = cli.Get("/hi%23key1=val1=key2=val2");
  3543. EXPECT_TRUE(res);
  3544. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3545. }
  3546. }
  3547. TEST(HeaderWriter, SetHeaderWriter) {
  3548. Server svr;
  3549. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3550. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3551. return detail::write_headers(strm, hdrs);
  3552. });
  3553. svr.Get("/hi", [](const Request &req, Response &res) {
  3554. auto it = req.headers.find("CustomClientHeader");
  3555. EXPECT_TRUE(it != req.headers.end());
  3556. EXPECT_EQ(it->second, "CustomClientValue");
  3557. res.set_content("Hello World!\n", "text/plain");
  3558. });
  3559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3560. auto se = detail::scope_exit([&] {
  3561. svr.stop();
  3562. thread.join();
  3563. ASSERT_FALSE(svr.is_running());
  3564. });
  3565. svr.wait_until_ready();
  3566. {
  3567. Client cli(HOST, PORT);
  3568. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3569. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3570. return detail::write_headers(strm, hdrs);
  3571. });
  3572. auto res = cli.Get("/hi");
  3573. EXPECT_TRUE(res);
  3574. EXPECT_EQ(StatusCode::OK_200, res->status);
  3575. auto it = res->headers.find("CustomServerHeader");
  3576. EXPECT_TRUE(it != res->headers.end());
  3577. EXPECT_EQ(it->second, "CustomServerValue");
  3578. }
  3579. }
  3580. class ServerTest : public ::testing::Test {
  3581. protected:
  3582. ServerTest()
  3583. : cli_(HOST, PORT)
  3584. #ifdef CPPHTTPLIB_SSL_ENABLED
  3585. ,
  3586. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3587. #endif
  3588. {
  3589. #ifdef CPPHTTPLIB_SSL_ENABLED
  3590. cli_.enable_server_certificate_verification(false);
  3591. #endif
  3592. // Allow LARGE_DATA (100MB) responses
  3593. cli_.set_payload_max_length(200 * 1024 * 1024);
  3594. }
  3595. virtual void SetUp() {
  3596. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3597. svr_.set_payload_max_length(200 * 1024 * 1024);
  3598. svr_.set_mount_point("/", "./www");
  3599. svr_.set_mount_point("/mount", "./www2");
  3600. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3601. svr_.Get("/hi",
  3602. [&](const Request & /*req*/, Response &res) {
  3603. res.set_content("Hello World!", "text/plain");
  3604. })
  3605. .Get("/file_content",
  3606. [&](const Request & /*req*/, Response &res) {
  3607. res.set_file_content("./www/dir/test.html");
  3608. })
  3609. .Get("/file_content_with_content_type",
  3610. [&](const Request & /*req*/, Response &res) {
  3611. res.set_file_content("./www/file", "text/plain");
  3612. })
  3613. .Get("/invalid_file_content",
  3614. [&](const Request & /*req*/, Response &res) {
  3615. res.set_file_content("./www/dir/invalid_file_path");
  3616. })
  3617. .Get("/http_response_splitting",
  3618. [&](const Request & /*req*/, Response &res) {
  3619. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3620. EXPECT_EQ(0U, res.headers.size());
  3621. EXPECT_FALSE(res.has_header("a"));
  3622. res.set_header("a", "1\nSet-Cookie: a=1");
  3623. EXPECT_EQ(0U, res.headers.size());
  3624. EXPECT_FALSE(res.has_header("a"));
  3625. res.set_header("a", "1\rSet-Cookie: a=1");
  3626. EXPECT_EQ(0U, res.headers.size());
  3627. EXPECT_FALSE(res.has_header("a"));
  3628. res.set_header("a\r\nb", "0");
  3629. EXPECT_EQ(0U, res.headers.size());
  3630. EXPECT_FALSE(res.has_header("a"));
  3631. res.set_header("a\rb", "0");
  3632. EXPECT_EQ(0U, res.headers.size());
  3633. EXPECT_FALSE(res.has_header("a"));
  3634. res.set_header("a\nb", "0");
  3635. EXPECT_EQ(0U, res.headers.size());
  3636. EXPECT_FALSE(res.has_header("a"));
  3637. res.set_redirect("1\r\nSet-Cookie: a=1");
  3638. EXPECT_EQ(0U, res.headers.size());
  3639. EXPECT_FALSE(res.has_header("Location"));
  3640. })
  3641. .Get("/slow",
  3642. [&](const Request & /*req*/, Response &res) {
  3643. std::this_thread::sleep_for(std::chrono::seconds(4));
  3644. res.set_content("slow", "text/plain");
  3645. })
  3646. #if 0
  3647. .Post("/slowpost",
  3648. [&](const Request & /*req*/, Response &res) {
  3649. std::this_thread::sleep_for(std::chrono::seconds(2));
  3650. res.set_content("slow", "text/plain");
  3651. })
  3652. #endif
  3653. .Get("/remote_addr",
  3654. [&](const Request &req, Response &res) {
  3655. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3656. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3657. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3658. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3659. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3660. #endif
  3661. res.set_content(req.remote_addr, "text/plain");
  3662. })
  3663. .Get("/local_addr",
  3664. [&](const Request &req, Response &res) {
  3665. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3666. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3667. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3668. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3669. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3670. #endif
  3671. auto local_addr = req.local_addr;
  3672. auto local_port = std::to_string(req.local_port);
  3673. res.set_content(local_addr.append(":").append(local_port),
  3674. "text/plain");
  3675. })
  3676. .Get("/endwith%",
  3677. [&](const Request & /*req*/, Response &res) {
  3678. res.set_content("Hello World!", "text/plain");
  3679. })
  3680. .Get("/a\\+\\+b",
  3681. [&](const Request &req, Response &res) {
  3682. ASSERT_TRUE(req.has_param("a +b"));
  3683. auto val = req.get_param_value("a +b");
  3684. res.set_content(val, "text/plain");
  3685. })
  3686. .Get("/", [&](const Request & /*req*/,
  3687. Response &res) { res.set_redirect("/hi"); })
  3688. .Post("/1",
  3689. [](const Request & /*req*/, Response &res) {
  3690. res.set_redirect("/2", StatusCode::SeeOther_303);
  3691. })
  3692. .Get("/2",
  3693. [](const Request & /*req*/, Response &res) {
  3694. res.set_content("redirected.", "text/plain");
  3695. res.status = StatusCode::OK_200;
  3696. })
  3697. .Post("/person",
  3698. [&](const Request &req, Response &res) {
  3699. if (req.has_param("name") && req.has_param("note")) {
  3700. persons_[req.get_param_value("name")] =
  3701. req.get_param_value("note");
  3702. } else {
  3703. res.status = StatusCode::BadRequest_400;
  3704. }
  3705. })
  3706. .Put("/person",
  3707. [&](const Request &req, Response &res) {
  3708. if (req.has_param("name") && req.has_param("note")) {
  3709. persons_[req.get_param_value("name")] =
  3710. req.get_param_value("note");
  3711. } else {
  3712. res.status = StatusCode::BadRequest_400;
  3713. }
  3714. })
  3715. .Get("/person/(.*)",
  3716. [&](const Request &req, Response &res) {
  3717. string name = req.matches[1];
  3718. if (persons_.find(name) != persons_.end()) {
  3719. auto note = persons_[name];
  3720. res.set_content(note, "text/plain");
  3721. } else {
  3722. res.status = StatusCode::NotFound_404;
  3723. }
  3724. })
  3725. .Delete("/person",
  3726. [&](const Request &req, Response &res) {
  3727. if (req.has_param("name")) {
  3728. string name = req.get_param_value("name");
  3729. if (persons_.find(name) != persons_.end()) {
  3730. persons_.erase(name);
  3731. res.set_content("DELETED", "text/plain");
  3732. } else {
  3733. res.status = StatusCode::NotFound_404;
  3734. }
  3735. } else {
  3736. res.status = StatusCode::BadRequest_400;
  3737. }
  3738. })
  3739. .Post("/x-www-form-urlencoded-json",
  3740. [&](const Request &req, Response &res) {
  3741. auto json = req.get_param_value("json");
  3742. ASSERT_EQ(JSON_DATA, json);
  3743. res.set_content(json, "appliation/json");
  3744. res.status = StatusCode::OK_200;
  3745. })
  3746. .Get("/streamed-chunked",
  3747. [&](const Request & /*req*/, Response &res) {
  3748. res.set_chunked_content_provider(
  3749. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3750. sink.os << "123";
  3751. sink.os << "456";
  3752. sink.os << "789";
  3753. sink.done();
  3754. return true;
  3755. });
  3756. })
  3757. .Get("/streamed-chunked-with-prohibited-trailer",
  3758. [&](const Request & /*req*/, Response &res) {
  3759. auto i = new int(0);
  3760. // Declare both a prohibited trailer (Content-Length) and an
  3761. // allowed one
  3762. res.set_header("Trailer", "Content-Length, X-Allowed");
  3763. res.set_chunked_content_provider(
  3764. "text/plain",
  3765. [i](size_t /*offset*/, DataSink &sink) {
  3766. switch (*i) {
  3767. case 0: sink.os << "123"; break;
  3768. case 1: sink.os << "456"; break;
  3769. case 2: sink.os << "789"; break;
  3770. case 3: {
  3771. sink.done_with_trailer(
  3772. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3773. } break;
  3774. }
  3775. (*i)++;
  3776. return true;
  3777. },
  3778. [i](bool success) {
  3779. EXPECT_TRUE(success);
  3780. delete i;
  3781. });
  3782. })
  3783. .Get("/streamed-chunked2",
  3784. [&](const Request & /*req*/, Response &res) {
  3785. auto i = new int(0);
  3786. res.set_chunked_content_provider(
  3787. "text/plain",
  3788. [i](size_t /*offset*/, DataSink &sink) {
  3789. switch (*i) {
  3790. case 0: sink.os << "123"; break;
  3791. case 1: sink.os << "456"; break;
  3792. case 2: sink.os << "789"; break;
  3793. case 3: sink.done(); break;
  3794. }
  3795. (*i)++;
  3796. return true;
  3797. },
  3798. [i](bool success) {
  3799. EXPECT_TRUE(success);
  3800. delete i;
  3801. });
  3802. })
  3803. .Get("/streamed-chunked-with-trailer",
  3804. [&](const Request & /*req*/, Response &res) {
  3805. auto i = new int(0);
  3806. res.set_header("Trailer", "Dummy1, Dummy2");
  3807. res.set_chunked_content_provider(
  3808. "text/plain",
  3809. [i](size_t /*offset*/, DataSink &sink) {
  3810. switch (*i) {
  3811. case 0: sink.os << "123"; break;
  3812. case 1: sink.os << "456"; break;
  3813. case 2: sink.os << "789"; break;
  3814. case 3: {
  3815. sink.done_with_trailer(
  3816. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3817. } break;
  3818. }
  3819. (*i)++;
  3820. return true;
  3821. },
  3822. [i](bool success) {
  3823. EXPECT_TRUE(success);
  3824. delete i;
  3825. });
  3826. })
  3827. .Get("/streamed",
  3828. [&](const Request & /*req*/, Response &res) {
  3829. res.set_content_provider(
  3830. 6, "text/plain",
  3831. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3832. sink.os << (offset < 3 ? "a" : "b");
  3833. return true;
  3834. });
  3835. })
  3836. .Get("/streamed-without-length",
  3837. [&](const Request & /*req*/, Response &res) {
  3838. auto data = new std::string("abcdefg");
  3839. res.set_content_provider(
  3840. "text/plain",
  3841. [data](size_t offset, DataSink &sink) {
  3842. if (offset < data->size()) {
  3843. sink.os << data->substr(offset);
  3844. }
  3845. sink.done();
  3846. return true;
  3847. },
  3848. [data](bool success) {
  3849. EXPECT_TRUE(success);
  3850. delete data;
  3851. });
  3852. })
  3853. .Get("/streamed-with-range",
  3854. [&](const Request &req, Response &res) {
  3855. auto data = new std::string("abcdefg");
  3856. // An explicit status keeps the server from picking the 206 it
  3857. // would otherwise choose for a ranged request, so the response
  3858. // is not a partial representation.
  3859. auto status = req.get_param_value("status");
  3860. if (status == "200") {
  3861. res.status = StatusCode::OK_200;
  3862. } else if (status == "403") {
  3863. res.status = StatusCode::Forbidden_403;
  3864. }
  3865. res.set_content_provider(
  3866. data->size(), "text/plain",
  3867. [data](size_t offset, size_t length, DataSink &sink) {
  3868. size_t DATA_CHUNK_SIZE = 4;
  3869. const auto &d = *data;
  3870. auto out_len =
  3871. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3872. auto ret =
  3873. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3874. EXPECT_TRUE(ret);
  3875. return true;
  3876. },
  3877. [data, &req](bool success) {
  3878. EXPECT_EQ(success, !req.has_param("error"));
  3879. delete data;
  3880. });
  3881. })
  3882. .Get("/streamed-cancel",
  3883. [&](const Request & /*req*/, Response &res) {
  3884. res.set_content_provider(
  3885. size_t(-1), "text/plain",
  3886. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3887. sink.os << "data_chunk";
  3888. return true;
  3889. });
  3890. })
  3891. .Get("/regex-with-delimiter",
  3892. [&](const Request &req, Response & /*res*/) {
  3893. ASSERT_TRUE(req.has_param("key"));
  3894. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3895. })
  3896. .Get("/with-range",
  3897. [&](const Request & /*req*/, Response &res) {
  3898. res.set_content("abcdefg", "text/plain");
  3899. })
  3900. .Get("/test-start-time",
  3901. [&](const Request &req, Response & /*res*/) {
  3902. EXPECT_NE(req.start_time_,
  3903. std::chrono::steady_clock::time_point::min());
  3904. })
  3905. .Get("/with-range-customized-response",
  3906. [&](const Request & /*req*/, Response &res) {
  3907. res.status = StatusCode::BadRequest_400;
  3908. res.set_content(JSON_DATA, "application/json");
  3909. })
  3910. .Post("/chunked",
  3911. [&](const Request &req, Response & /*res*/) {
  3912. EXPECT_EQ(req.body, "dechunked post body");
  3913. })
  3914. .Post("/large-chunked",
  3915. [&](const Request &req, Response & /*res*/) {
  3916. std::string expected(6 * 30 * 1024u, 'a');
  3917. EXPECT_EQ(req.body, expected);
  3918. })
  3919. .Post("/multipart",
  3920. [&](const Request &req, Response & /*res*/) {
  3921. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3922. req.form.get_field_count("text2") +
  3923. req.form.get_field_count("file3") +
  3924. req.form.get_field_count("file4"));
  3925. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3926. req.form.get_file_count("file2"));
  3927. ASSERT_TRUE(!req.form.has_file("???"));
  3928. ASSERT_TRUE(!req.form.has_field("???"));
  3929. ASSERT_TRUE(req.body.empty());
  3930. {
  3931. const auto &text = req.form.get_field("text1");
  3932. EXPECT_EQ("text default", text);
  3933. }
  3934. {
  3935. const auto &text = req.form.get_field("text2");
  3936. EXPECT_EQ("aωb", text);
  3937. }
  3938. {
  3939. const auto &file = req.form.get_file("file1");
  3940. EXPECT_EQ("hello.txt", file.filename);
  3941. EXPECT_EQ("text/plain", file.content_type);
  3942. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3943. }
  3944. {
  3945. const auto &file = req.form.get_file("file2");
  3946. EXPECT_EQ("world.json", file.filename);
  3947. EXPECT_EQ("application/json", file.content_type);
  3948. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3949. }
  3950. {
  3951. const auto &text = req.form.get_field("file3");
  3952. EXPECT_EQ(0u, text.size());
  3953. }
  3954. {
  3955. const auto &text = req.form.get_field("file4");
  3956. EXPECT_EQ(0u, text.size());
  3957. }
  3958. })
  3959. .Post("/multipart/multi_file_values",
  3960. [&](const Request &req, Response & /*res*/) {
  3961. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3962. req.form.get_field_count("multi_text1"));
  3963. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3964. ASSERT_TRUE(!req.form.has_file("???"));
  3965. ASSERT_TRUE(!req.form.has_field("???"));
  3966. ASSERT_TRUE(req.body.empty());
  3967. {
  3968. const auto &text = req.form.get_field("text");
  3969. EXPECT_EQ("default text", text);
  3970. }
  3971. {
  3972. const auto &text1_values = req.form.get_fields("multi_text1");
  3973. EXPECT_EQ(2u, text1_values.size());
  3974. EXPECT_EQ("aaaaa", text1_values[0]);
  3975. EXPECT_EQ("bbbbb", text1_values[1]);
  3976. }
  3977. {
  3978. const auto &file1_values = req.form.get_files("multi_file1");
  3979. EXPECT_EQ(2u, file1_values.size());
  3980. auto file1 = file1_values[0];
  3981. EXPECT_EQ(file1.filename, "hello.txt");
  3982. EXPECT_EQ(file1.content_type, "text/plain");
  3983. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3984. auto file2 = file1_values[1];
  3985. EXPECT_EQ(file2.filename, "world.json");
  3986. EXPECT_EQ(file2.content_type, "application/json");
  3987. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3988. }
  3989. })
  3990. .Post("/empty",
  3991. [&](const Request &req, Response &res) {
  3992. EXPECT_EQ(req.body, "");
  3993. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3994. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3995. res.set_content("empty", "text/plain");
  3996. })
  3997. .Post("/empty-no-content-type",
  3998. [&](const Request &req, Response &res) {
  3999. EXPECT_EQ(req.body, "");
  4000. EXPECT_FALSE(req.has_header("Content-Type"));
  4001. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4002. res.set_content("empty-no-content-type", "text/plain");
  4003. })
  4004. .Post("/path-only",
  4005. [&](const Request &req, Response &res) {
  4006. EXPECT_EQ(req.body, "");
  4007. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4008. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4009. res.set_content("path-only", "text/plain");
  4010. })
  4011. .Post("/path-headers-only",
  4012. [&](const Request &req, Response &res) {
  4013. EXPECT_EQ(req.body, "");
  4014. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4015. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4016. EXPECT_EQ("world", req.get_header_value("hello"));
  4017. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4018. res.set_content("path-headers-only", "text/plain");
  4019. })
  4020. .Post("/post-large",
  4021. [&](const Request &req, Response &res) {
  4022. EXPECT_EQ(req.body, LARGE_DATA);
  4023. res.set_content(req.body, "text/plain");
  4024. })
  4025. .Post("/post-loopback",
  4026. [&](const Request &, Response &res,
  4027. ContentReader const &content_reader) {
  4028. std::string body;
  4029. content_reader([&](const char *data, size_t data_length) {
  4030. body.append(data, data_length);
  4031. return true;
  4032. });
  4033. res.set_content(body, "text/plain");
  4034. })
  4035. .Put("/put-loopback",
  4036. [&](const Request &, Response &res,
  4037. ContentReader const &content_reader) {
  4038. std::string body;
  4039. content_reader([&](const char *data, size_t data_length) {
  4040. body.append(data, data_length);
  4041. return true;
  4042. });
  4043. res.set_content(body, "text/plain");
  4044. })
  4045. .Patch("/patch-loopback",
  4046. [&](const Request &, Response &res,
  4047. ContentReader const &content_reader) {
  4048. std::string body;
  4049. content_reader([&](const char *data, size_t data_length) {
  4050. body.append(data, data_length);
  4051. return true;
  4052. });
  4053. res.set_content(body, "text/plain");
  4054. })
  4055. .Put("/empty-no-content-type",
  4056. [&](const Request &req, Response &res) {
  4057. EXPECT_EQ(req.body, "");
  4058. EXPECT_FALSE(req.has_header("Content-Type"));
  4059. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4060. res.set_content("empty-no-content-type", "text/plain");
  4061. })
  4062. .Put("/put",
  4063. [&](const Request &req, Response &res) {
  4064. EXPECT_EQ(req.body, "PUT");
  4065. res.set_content(req.body, "text/plain");
  4066. })
  4067. .Put("/put-large",
  4068. [&](const Request &req, Response &res) {
  4069. EXPECT_EQ(req.body, LARGE_DATA);
  4070. res.set_content(req.body, "text/plain");
  4071. })
  4072. .Patch("/patch",
  4073. [&](const Request &req, Response &res) {
  4074. EXPECT_EQ(req.body, "PATCH");
  4075. res.set_content(req.body, "text/plain");
  4076. })
  4077. .Delete("/delete",
  4078. [&](const Request & /*req*/, Response &res) {
  4079. res.set_content("DELETE", "text/plain");
  4080. })
  4081. .Delete("/delete-body",
  4082. [&](const Request &req, Response &res) {
  4083. EXPECT_EQ(req.body, "content");
  4084. res.set_content(req.body, "text/plain");
  4085. })
  4086. .Options(R"(\*)",
  4087. [&](const Request & /*req*/, Response &res) {
  4088. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4089. })
  4090. .Get("/request-target",
  4091. [&](const Request &req, Response & /*res*/) {
  4092. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4093. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4094. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4095. })
  4096. .Get("/long-query-value",
  4097. [&](const Request &req, Response & /*res*/) {
  4098. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4099. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4100. })
  4101. .Get("/too-long-query-value",
  4102. [&](const Request &req, Response & /*res*/) {
  4103. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4104. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4105. })
  4106. .Get("/array-param",
  4107. [&](const Request &req, Response & /*res*/) {
  4108. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4109. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4110. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4111. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4112. })
  4113. .Get("/array-param-values",
  4114. [&](const Request &req, Response & /*res*/) {
  4115. auto values = req.get_param_values("array");
  4116. EXPECT_EQ(3u, values.size());
  4117. EXPECT_EQ("value1", values[0]);
  4118. EXPECT_EQ("value2", values[1]);
  4119. EXPECT_EQ("value3", values[2]);
  4120. auto empty = req.get_param_values("nonexistent");
  4121. EXPECT_TRUE(empty.empty());
  4122. })
  4123. .Post("/validate-no-multiple-headers",
  4124. [&](const Request &req, Response & /*res*/) {
  4125. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4126. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4127. })
  4128. .Post("/content_receiver",
  4129. [&](const Request &req, Response &res,
  4130. const ContentReader &content_reader) {
  4131. if (req.is_multipart_form_data()) {
  4132. std::vector<FormData> items;
  4133. content_reader(
  4134. [&](const FormData &file) {
  4135. items.push_back(file);
  4136. return true;
  4137. },
  4138. [&](const char *data, size_t data_length) {
  4139. items.back().content.append(data, data_length);
  4140. return true;
  4141. });
  4142. EXPECT_EQ(5u, items.size());
  4143. {
  4144. const auto &file = get_file_value(items, "text1");
  4145. EXPECT_TRUE(file.filename.empty());
  4146. EXPECT_EQ("text default", file.content);
  4147. }
  4148. {
  4149. const auto &file = get_file_value(items, "text2");
  4150. EXPECT_TRUE(file.filename.empty());
  4151. EXPECT_EQ("aωb", file.content);
  4152. }
  4153. {
  4154. const auto &file = get_file_value(items, "file1");
  4155. EXPECT_EQ("hello.txt", file.filename);
  4156. EXPECT_EQ("text/plain", file.content_type);
  4157. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4158. }
  4159. {
  4160. const auto &file = get_file_value(items, "file2");
  4161. EXPECT_EQ("world.json", file.filename);
  4162. EXPECT_EQ("application/json", file.content_type);
  4163. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4164. }
  4165. {
  4166. const auto &file = get_file_value(items, "file3");
  4167. EXPECT_TRUE(file.filename.empty());
  4168. EXPECT_EQ("application/octet-stream", file.content_type);
  4169. EXPECT_EQ(0u, file.content.size());
  4170. }
  4171. } else {
  4172. std::string body;
  4173. content_reader([&](const char *data, size_t data_length) {
  4174. EXPECT_EQ(7U, data_length);
  4175. body.append(data, data_length);
  4176. return true;
  4177. });
  4178. EXPECT_EQ(body, "content");
  4179. res.set_content(body, "text/plain");
  4180. }
  4181. })
  4182. .Put("/content_receiver",
  4183. [&](const Request & /*req*/, Response &res,
  4184. const ContentReader &content_reader) {
  4185. std::string body;
  4186. content_reader([&](const char *data, size_t data_length) {
  4187. body.append(data, data_length);
  4188. return true;
  4189. });
  4190. EXPECT_EQ(body, "content");
  4191. res.set_content(body, "text/plain");
  4192. })
  4193. .Patch("/content_receiver",
  4194. [&](const Request & /*req*/, Response &res,
  4195. const ContentReader &content_reader) {
  4196. std::string body;
  4197. content_reader([&](const char *data, size_t data_length) {
  4198. body.append(data, data_length);
  4199. return true;
  4200. });
  4201. EXPECT_EQ(body, "content");
  4202. res.set_content(body, "text/plain");
  4203. })
  4204. .Post("/query-string-and-body",
  4205. [&](const Request &req, Response & /*res*/) {
  4206. ASSERT_TRUE(req.has_param("key"));
  4207. EXPECT_EQ(req.get_param_value("key"), "value");
  4208. EXPECT_EQ(req.body, "content");
  4209. })
  4210. .Get("/last-request",
  4211. [&](const Request &req, Response & /*res*/) {
  4212. EXPECT_EQ("close", req.get_header_value("Connection"));
  4213. })
  4214. .Get(R"(/redirect/(\d+))",
  4215. [&](const Request &req, Response &res) {
  4216. auto num = std::stoi(req.matches[1]) + 1;
  4217. std::string url = "/redirect/" + std::to_string(num);
  4218. res.set_redirect(url);
  4219. })
  4220. .Post("/binary",
  4221. [&](const Request &req, Response &res) {
  4222. EXPECT_EQ(4U, req.body.size());
  4223. EXPECT_EQ("application/octet-stream",
  4224. req.get_header_value("Content-Type"));
  4225. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4226. res.set_content(req.body, "application/octet-stream");
  4227. })
  4228. .Put("/binary",
  4229. [&](const Request &req, Response &res) {
  4230. EXPECT_EQ(4U, req.body.size());
  4231. EXPECT_EQ("application/octet-stream",
  4232. req.get_header_value("Content-Type"));
  4233. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4234. res.set_content(req.body, "application/octet-stream");
  4235. })
  4236. .Patch("/binary",
  4237. [&](const Request &req, Response &res) {
  4238. EXPECT_EQ(4U, req.body.size());
  4239. EXPECT_EQ("application/octet-stream",
  4240. req.get_header_value("Content-Type"));
  4241. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4242. res.set_content(req.body, "application/octet-stream");
  4243. })
  4244. .Delete("/binary",
  4245. [&](const Request &req, Response &res) {
  4246. EXPECT_EQ(4U, req.body.size());
  4247. EXPECT_EQ("application/octet-stream",
  4248. req.get_header_value("Content-Type"));
  4249. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4250. res.set_content(req.body, "application/octet-stream");
  4251. })
  4252. .Get("/issue1772",
  4253. [&](const Request & /*req*/, Response &res) {
  4254. res.status = 401;
  4255. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4256. })
  4257. .Delete("/issue609",
  4258. [](const httplib::Request &, httplib::Response &res,
  4259. const httplib::ContentReader &) {
  4260. res.set_content("ok", "text/plain");
  4261. })
  4262. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4263. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4264. .Get("/compress",
  4265. [&](const Request & /*req*/, Response &res) {
  4266. res.set_content(
  4267. "12345678901234567890123456789012345678901234567890123456789"
  4268. "01234567890123456789012345678901234567890",
  4269. "text/plain");
  4270. })
  4271. .Get("/compress-with-charset",
  4272. [&](const Request & /*req*/, Response &res) {
  4273. res.set_content(
  4274. "12345678901234567890123456789012345678901234567890123456789"
  4275. "01234567890123456789012345678901234567890",
  4276. "application/json; charset=utf-8");
  4277. })
  4278. .Get("/nocompress",
  4279. [&](const Request & /*req*/, Response &res) {
  4280. res.set_content(
  4281. "12345678901234567890123456789012345678901234567890123456789"
  4282. "01234567890123456789012345678901234567890",
  4283. "application/octet-stream");
  4284. })
  4285. .Post("/compress-multipart",
  4286. [&](const Request &req, Response & /*res*/) {
  4287. EXPECT_EQ(2u, req.form.fields.size());
  4288. ASSERT_TRUE(!req.form.has_field("???"));
  4289. {
  4290. const auto &text = req.form.get_field("key1");
  4291. EXPECT_EQ("test", text);
  4292. }
  4293. {
  4294. const auto &text = req.form.get_field("key2");
  4295. EXPECT_EQ("--abcdefg123", text);
  4296. }
  4297. })
  4298. #endif
  4299. ;
  4300. persons_["john"] = "programmer";
  4301. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4302. svr_.wait_until_ready();
  4303. }
  4304. virtual void TearDown() {
  4305. svr_.stop();
  4306. if (!request_threads_.empty()) {
  4307. std::this_thread::sleep_for(std::chrono::seconds(1));
  4308. for (auto &t : request_threads_) {
  4309. t.join();
  4310. }
  4311. }
  4312. t_.join();
  4313. }
  4314. map<string, string> persons_;
  4315. #ifdef CPPHTTPLIB_SSL_ENABLED
  4316. SSLClient cli_;
  4317. SSLServer svr_;
  4318. #else
  4319. Client cli_;
  4320. Server svr_;
  4321. #endif
  4322. thread t_;
  4323. std::vector<thread> request_threads_;
  4324. };
  4325. TEST_F(ServerTest, GetMethod200) {
  4326. auto res = cli_.Get("/hi");
  4327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4328. EXPECT_EQ("HTTP/1.1", res->version);
  4329. EXPECT_EQ(StatusCode::OK_200, res->status);
  4330. EXPECT_EQ("OK", res->reason);
  4331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4332. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4333. EXPECT_EQ("Hello World!", res->body);
  4334. }
  4335. TEST_F(ServerTest, GetEmptyFile) {
  4336. auto res = cli_.Get("/empty_file");
  4337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4338. EXPECT_EQ(StatusCode::OK_200, res->status);
  4339. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4340. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4341. EXPECT_EQ("", res->body);
  4342. }
  4343. TEST_F(ServerTest, GetFileContent) {
  4344. auto res = cli_.Get("/file_content");
  4345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4346. EXPECT_EQ(StatusCode::OK_200, res->status);
  4347. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4348. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4349. EXPECT_EQ("test.html", res->body);
  4350. }
  4351. TEST_F(ServerTest, GetFileContentWithRange) {
  4352. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4355. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4356. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4357. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4358. EXPECT_EQ("est", res->body);
  4359. }
  4360. TEST_F(ServerTest, GetFileContentWithContentType) {
  4361. auto res = cli_.Get("/file_content_with_content_type");
  4362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4363. EXPECT_EQ(StatusCode::OK_200, res->status);
  4364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4365. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4366. EXPECT_EQ("file\n", res->body);
  4367. }
  4368. TEST_F(ServerTest, GetInvalidFileContent) {
  4369. auto res = cli_.Get("/invalid_file_content");
  4370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4371. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4372. }
  4373. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4374. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4376. EXPECT_EQ("HTTP/1.1", res->version);
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4379. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4380. EXPECT_EQ("Hello World!", res->body);
  4381. }
  4382. TEST_F(ServerTest, GetMethod302) {
  4383. auto res = cli_.Get("/");
  4384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4385. EXPECT_EQ(StatusCode::Found_302, res->status);
  4386. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4387. }
  4388. TEST_F(ServerTest, GetMethod302Redirect) {
  4389. cli_.set_follow_location(true);
  4390. auto res = cli_.Get("/");
  4391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4392. EXPECT_EQ(StatusCode::OK_200, res->status);
  4393. EXPECT_EQ("Hello World!", res->body);
  4394. EXPECT_EQ("/hi", res->location);
  4395. }
  4396. TEST_F(ServerTest, GetMethod404) {
  4397. auto res = cli_.Get("/invalid");
  4398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4399. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4400. }
  4401. TEST_F(ServerTest, HeadMethod200) {
  4402. auto res = cli_.Head("/hi");
  4403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4404. EXPECT_EQ(StatusCode::OK_200, res->status);
  4405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4406. EXPECT_TRUE(res->body.empty());
  4407. }
  4408. TEST_F(ServerTest, HeadMethod200Static) {
  4409. auto res = cli_.Head("/mount/dir/index.html");
  4410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4411. EXPECT_EQ(StatusCode::OK_200, res->status);
  4412. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4413. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4414. EXPECT_TRUE(res->body.empty());
  4415. }
  4416. TEST_F(ServerTest, HeadMethod404) {
  4417. auto res = cli_.Head("/invalid");
  4418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4419. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4420. EXPECT_TRUE(res->body.empty());
  4421. }
  4422. TEST_F(ServerTest, GetMethodPersonJohn) {
  4423. auto res = cli_.Get("/person/john");
  4424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4425. EXPECT_EQ(StatusCode::OK_200, res->status);
  4426. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4427. EXPECT_EQ("programmer", res->body);
  4428. }
  4429. TEST_F(ServerTest, PostMethod1) {
  4430. auto res = cli_.Get("/person/john1");
  4431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4432. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4433. res = cli_.Post("/person", "name=john1&note=coder",
  4434. "application/x-www-form-urlencoded");
  4435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4436. ASSERT_EQ(StatusCode::OK_200, res->status);
  4437. res = cli_.Get("/person/john1");
  4438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4439. ASSERT_EQ(StatusCode::OK_200, res->status);
  4440. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4441. ASSERT_EQ("coder", res->body);
  4442. }
  4443. TEST_F(ServerTest, PostMethod2) {
  4444. auto res = cli_.Get("/person/john2");
  4445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4446. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4447. Params params;
  4448. params.emplace("name", "john2");
  4449. params.emplace("note", "coder");
  4450. res = cli_.Post("/person", params);
  4451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4452. ASSERT_EQ(StatusCode::OK_200, res->status);
  4453. res = cli_.Get("/person/john2");
  4454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4455. ASSERT_EQ(StatusCode::OK_200, res->status);
  4456. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4457. ASSERT_EQ("coder", res->body);
  4458. }
  4459. TEST_F(ServerTest, PutMethod3) {
  4460. auto res = cli_.Get("/person/john3");
  4461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4462. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4463. Params params;
  4464. params.emplace("name", "john3");
  4465. params.emplace("note", "coder");
  4466. res = cli_.Put("/person", params);
  4467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4468. ASSERT_EQ(StatusCode::OK_200, res->status);
  4469. res = cli_.Get("/person/john3");
  4470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4471. ASSERT_EQ(StatusCode::OK_200, res->status);
  4472. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4473. ASSERT_EQ("coder", res->body);
  4474. }
  4475. TEST_F(ServerTest, DeleteMethod1) {
  4476. auto res = cli_.Get("/person/john4");
  4477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4478. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4479. Params params;
  4480. params.emplace("name", "john4");
  4481. params.emplace("note", "coder");
  4482. res = cli_.Post("/person", params);
  4483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4484. ASSERT_EQ(StatusCode::OK_200, res->status);
  4485. res = cli_.Get("/person/john4");
  4486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4487. ASSERT_EQ(StatusCode::OK_200, res->status);
  4488. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4489. ASSERT_EQ("coder", res->body);
  4490. Params delete_params;
  4491. delete_params.emplace("name", "john4");
  4492. res = cli_.Delete("/person", delete_params);
  4493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4494. ASSERT_EQ(StatusCode::OK_200, res->status);
  4495. ASSERT_EQ("DELETED", res->body);
  4496. res = cli_.Get("/person/john4");
  4497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4498. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4499. }
  4500. TEST_F(ServerTest, DeleteMethod2) {
  4501. auto res = cli_.Get("/person/john5");
  4502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4503. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4504. Params params;
  4505. params.emplace("name", "john5");
  4506. params.emplace("note", "developer");
  4507. res = cli_.Post("/person", params);
  4508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4509. ASSERT_EQ(StatusCode::OK_200, res->status);
  4510. res = cli_.Get("/person/john5");
  4511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4512. ASSERT_EQ(StatusCode::OK_200, res->status);
  4513. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4514. ASSERT_EQ("developer", res->body);
  4515. Params delete_params;
  4516. delete_params.emplace("name", "john5");
  4517. Headers headers;
  4518. headers.emplace("Custom-Header", "test-value");
  4519. res = cli_.Delete("/person", headers, delete_params);
  4520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4521. ASSERT_EQ(StatusCode::OK_200, res->status);
  4522. ASSERT_EQ("DELETED", res->body);
  4523. res = cli_.Get("/person/john5");
  4524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4525. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4526. }
  4527. TEST_F(ServerTest, DeleteMethod3) {
  4528. auto res = cli_.Get("/person/john6");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4531. Params params;
  4532. params.emplace("name", "john6");
  4533. params.emplace("note", "tester");
  4534. res = cli_.Post("/person", params);
  4535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4536. ASSERT_EQ(StatusCode::OK_200, res->status);
  4537. res = cli_.Get("/person/john6");
  4538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4539. ASSERT_EQ(StatusCode::OK_200, res->status);
  4540. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4541. ASSERT_EQ("tester", res->body);
  4542. Params delete_params;
  4543. delete_params.emplace("name", "john6");
  4544. Headers headers;
  4545. headers.emplace("Custom-Header", "test-value");
  4546. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4548. ASSERT_EQ(StatusCode::OK_200, res->status);
  4549. ASSERT_EQ("DELETED", res->body);
  4550. res = cli_.Get("/person/john6");
  4551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4552. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4553. }
  4554. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4555. Params params;
  4556. params.emplace("json", JSON_DATA);
  4557. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4559. ASSERT_EQ(StatusCode::OK_200, res->status);
  4560. ASSERT_EQ(JSON_DATA, res->body);
  4561. }
  4562. TEST_F(ServerTest, PostEmptyContent) {
  4563. auto res = cli_.Post("/empty", "", "text/plain");
  4564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4565. ASSERT_EQ(StatusCode::OK_200, res->status);
  4566. ASSERT_EQ("empty", res->body);
  4567. }
  4568. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4569. auto res = cli_.Post("/empty-no-content-type");
  4570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4571. ASSERT_EQ(StatusCode::OK_200, res->status);
  4572. ASSERT_EQ("empty-no-content-type", res->body);
  4573. }
  4574. TEST_F(ServerTest, PostPathOnly) {
  4575. auto res = cli_.Post("/path-only");
  4576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4577. ASSERT_EQ(StatusCode::OK_200, res->status);
  4578. ASSERT_EQ("path-only", res->body);
  4579. }
  4580. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4581. auto res = cli_.Post("/path-headers-only",
  4582. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4584. ASSERT_EQ(StatusCode::OK_200, res->status);
  4585. ASSERT_EQ("path-headers-only", res->body);
  4586. }
  4587. TEST_F(ServerTest, PostLarge) {
  4588. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4590. ASSERT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ(LARGE_DATA, res->body);
  4592. }
  4593. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4594. auto res = cli_.Put("/empty-no-content-type");
  4595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4596. ASSERT_EQ(StatusCode::OK_200, res->status);
  4597. ASSERT_EQ("empty-no-content-type", res->body);
  4598. }
  4599. TEST_F(ServerTest, GetMethodDir) {
  4600. auto res = cli_.Get("/dir/");
  4601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4602. EXPECT_EQ(StatusCode::OK_200, res->status);
  4603. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4604. auto body = R"(<html>
  4605. <head>
  4606. </head>
  4607. <body>
  4608. <a href="/dir/test.html">Test</a>
  4609. <a href="/hi">hi</a>
  4610. </body>
  4611. </html>
  4612. )";
  4613. EXPECT_EQ(body, res->body);
  4614. }
  4615. TEST_F(ServerTest, GetMethodDirTest) {
  4616. auto res = cli_.Get("/dir/test.html");
  4617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4618. EXPECT_EQ(StatusCode::OK_200, res->status);
  4619. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4620. EXPECT_EQ("test.html", res->body);
  4621. }
  4622. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4623. auto res = cli_.Get("/dir/../dir/test.html");
  4624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4625. EXPECT_EQ(StatusCode::OK_200, res->status);
  4626. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4627. EXPECT_EQ("test.html", res->body);
  4628. }
  4629. TEST_F(ServerTest, GetMethodInvalidPath) {
  4630. auto res = cli_.Get("/dir/../test.html");
  4631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4632. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4633. }
  4634. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4635. auto res = cli_.Get("/../www/dir/test.html");
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4638. }
  4639. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4640. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4642. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4643. }
  4644. TEST_F(ServerTest, GetMethodDirMountTest) {
  4645. auto res = cli_.Get("/mount/dir/test.html");
  4646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4647. EXPECT_EQ(StatusCode::OK_200, res->status);
  4648. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4649. EXPECT_EQ("test.html", res->body);
  4650. }
  4651. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4652. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4654. EXPECT_EQ(StatusCode::OK_200, res->status);
  4655. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4656. EXPECT_EQ("test.html", res->body);
  4657. }
  4658. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4659. auto res = cli_.Get("/mount/dir/../test.html");
  4660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4661. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4662. }
  4663. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4664. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4666. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4667. }
  4668. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4669. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4672. }
  4673. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4674. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4676. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4677. }
  4678. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4679. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4681. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4682. }
  4683. TEST_F(ServerTest, PostMethod303) {
  4684. auto res = cli_.Post("/1", "body", "text/plain");
  4685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4686. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4687. EXPECT_EQ("/2", res->get_header_value("Location"));
  4688. }
  4689. TEST_F(ServerTest, PostMethod303Redirect) {
  4690. cli_.set_follow_location(true);
  4691. auto res = cli_.Post("/1", "body", "text/plain");
  4692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4693. EXPECT_EQ(StatusCode::OK_200, res->status);
  4694. EXPECT_EQ("redirected.", res->body);
  4695. EXPECT_EQ("/2", res->location);
  4696. }
  4697. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4698. auto res = cli_.Get("/dir/test.abcde");
  4699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4700. EXPECT_EQ(StatusCode::OK_200, res->status);
  4701. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4702. EXPECT_EQ("abcde", res->body);
  4703. }
  4704. TEST_F(ServerTest, StaticFileRange) {
  4705. auto res =
  4706. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4708. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4709. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4710. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4711. EXPECT_EQ(true, res->has_header("Content-Range"));
  4712. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4713. EXPECT_EQ(std::string("cd"), res->body);
  4714. }
  4715. TEST_F(ServerTest, StaticFileRanges) {
  4716. auto res = cli_.Get("/dir/test.abcde",
  4717. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4720. EXPECT_TRUE(
  4721. res->get_header_value("Content-Type")
  4722. .find(
  4723. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4724. 0);
  4725. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4726. }
  4727. TEST_F(ServerTest, StaticFileRangeHead) {
  4728. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4730. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4731. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4732. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4733. EXPECT_EQ(true, res->has_header("Content-Range"));
  4734. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4735. }
  4736. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4737. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4739. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4740. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4741. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4742. EXPECT_EQ(true, res->has_header("Content-Range"));
  4743. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4744. res->get_header_value("Content-Range"));
  4745. EXPECT_EQ("LAST\n", res->body);
  4746. }
  4747. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4748. auto res =
  4749. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4752. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4753. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4754. EXPECT_EQ(true, res->has_header("Content-Range"));
  4755. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4756. }
  4757. TEST_F(ServerTest, StaticFileBigFile) {
  4758. auto res = cli_.Get("/dir/1MB.txt");
  4759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4760. EXPECT_EQ(StatusCode::OK_200, res->status);
  4761. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4762. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4763. }
  4764. TEST_F(ServerTest, InvalidBaseDirMount) {
  4765. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4766. }
  4767. TEST_F(ServerTest, Binary) {
  4768. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4769. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4770. "application/octet-stream");
  4771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4772. ASSERT_EQ(StatusCode::OK_200, res->status);
  4773. ASSERT_EQ(4U, res->body.size());
  4774. res = cli_.Put("/binary", binary.data(), binary.size(),
  4775. "application/octet-stream");
  4776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4777. ASSERT_EQ(StatusCode::OK_200, res->status);
  4778. ASSERT_EQ(4U, res->body.size());
  4779. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4780. "application/octet-stream");
  4781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4782. ASSERT_EQ(StatusCode::OK_200, res->status);
  4783. ASSERT_EQ(4U, res->body.size());
  4784. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4785. "application/octet-stream");
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. ASSERT_EQ(StatusCode::OK_200, res->status);
  4788. ASSERT_EQ(4U, res->body.size());
  4789. }
  4790. TEST_F(ServerTest, BinaryString) {
  4791. auto binary = std::string("\x00\x01\x02\x03", 4);
  4792. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4794. ASSERT_EQ(StatusCode::OK_200, res->status);
  4795. ASSERT_EQ(4U, res->body.size());
  4796. res = cli_.Put("/binary", binary, "application/octet-stream");
  4797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4798. ASSERT_EQ(StatusCode::OK_200, res->status);
  4799. ASSERT_EQ(4U, res->body.size());
  4800. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4802. ASSERT_EQ(StatusCode::OK_200, res->status);
  4803. ASSERT_EQ(4U, res->body.size());
  4804. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4806. ASSERT_EQ(StatusCode::OK_200, res->status);
  4807. ASSERT_EQ(4U, res->body.size());
  4808. }
  4809. TEST_F(ServerTest, EmptyRequest) {
  4810. auto res = cli_.Get("");
  4811. ASSERT_TRUE(!res);
  4812. EXPECT_EQ(Error::Connection, res.error());
  4813. }
  4814. TEST_F(ServerTest, LongRequest) {
  4815. std::string request;
  4816. for (size_t i = 0; i < 545; i++) {
  4817. request += "/TooLongRequest";
  4818. }
  4819. request += "OK";
  4820. auto res = cli_.Get(request.c_str());
  4821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4822. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4823. }
  4824. TEST_F(ServerTest, TooLongRequest) {
  4825. std::string request;
  4826. for (size_t i = 0; i < 546; i++) {
  4827. request += "/TooLongRequest";
  4828. }
  4829. request += "_NG";
  4830. auto start = std::chrono::high_resolution_clock::now();
  4831. cli_.set_keep_alive(true);
  4832. auto res = cli_.Get(request.c_str());
  4833. auto end = std::chrono::high_resolution_clock::now();
  4834. auto elapsed =
  4835. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4836. .count();
  4837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4838. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4839. EXPECT_LE(elapsed, 1000);
  4840. EXPECT_EQ("close", res->get_header_value("Connection"));
  4841. EXPECT_FALSE(cli_.is_socket_open());
  4842. }
  4843. TEST_F(ServerTest, AlmostTooLongRequest) {
  4844. // test for #2046 - URI length check shouldn't include other content on req
  4845. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4846. // leading /, space, HTTP/1.1)
  4847. std::string request =
  4848. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4849. auto res = cli_.Get(request.c_str());
  4850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4851. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4852. }
  4853. TEST_F(ServerTest, LongHeader) {
  4854. Request req;
  4855. req.method = "GET";
  4856. req.path = "/hi";
  4857. std::string host_and_port;
  4858. host_and_port += HOST;
  4859. host_and_port += ":";
  4860. host_and_port += std::to_string(PORT);
  4861. req.headers.emplace("Host", host_and_port.c_str());
  4862. req.headers.emplace("Accept", "*/*");
  4863. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4864. req.headers.emplace(
  4865. "Header-Name",
  4866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4882. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4885. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4886. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4887. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4888. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4889. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4890. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4891. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4892. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4893. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4894. "@@@@@@@@@@@@@@@@");
  4895. auto res = std::make_shared<Response>();
  4896. auto error = Error::Success;
  4897. auto ret = cli_.send(req, *res, error);
  4898. ASSERT_TRUE(ret);
  4899. EXPECT_EQ(StatusCode::OK_200, res->status);
  4900. }
  4901. TEST_F(ServerTest, LongQueryValue) {
  4902. auto start = std::chrono::high_resolution_clock::now();
  4903. cli_.set_keep_alive(true);
  4904. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4905. auto end = std::chrono::high_resolution_clock::now();
  4906. auto elapsed =
  4907. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4908. .count();
  4909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4910. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4911. EXPECT_LE(elapsed, 1000);
  4912. EXPECT_EQ("close", res->get_header_value("Connection"));
  4913. EXPECT_FALSE(cli_.is_socket_open());
  4914. }
  4915. TEST_F(ServerTest, TooLongQueryValue) {
  4916. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4917. ASSERT_FALSE(res);
  4918. EXPECT_EQ(Error::Read, res.error());
  4919. }
  4920. TEST_F(ServerTest, TooLongHeader) {
  4921. Request req;
  4922. req.method = "GET";
  4923. req.path = "/hi";
  4924. std::string host_and_port;
  4925. host_and_port += HOST;
  4926. host_and_port += ":";
  4927. host_and_port += std::to_string(PORT);
  4928. req.headers.emplace("Host", host_and_port.c_str());
  4929. req.headers.emplace("Accept", "*/*");
  4930. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4931. req.headers.emplace(
  4932. "Header-Name",
  4933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4959. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4960. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4961. "@@@@@@@@@@@@@@@@@");
  4962. auto res = std::make_shared<Response>();
  4963. auto error = Error::Success;
  4964. auto ret = cli_.send(req, *res, error);
  4965. ASSERT_TRUE(ret);
  4966. EXPECT_EQ(StatusCode::OK_200, res->status);
  4967. }
  4968. TEST_F(ServerTest, HeaderCountAtLimit) {
  4969. // Test with headers just under the 100 limit
  4970. httplib::Headers headers;
  4971. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4972. // This should keep us just under the 100 header limit
  4973. for (int i = 0; i < 95; i++) {
  4974. std::string name = "X-Test-Header-" + std::to_string(i);
  4975. std::string value = "value" + std::to_string(i);
  4976. headers.emplace(name, value);
  4977. }
  4978. // This should work fine as we're under the limit
  4979. auto res = cli_.Get("/hi", headers);
  4980. EXPECT_TRUE(res);
  4981. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4982. }
  4983. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4984. // Test with many headers to exceed the 100 limit
  4985. httplib::Headers headers;
  4986. // Add 150 headers to definitely exceed the 100 limit
  4987. for (int i = 0; i < 150; i++) {
  4988. std::string name = "X-Test-Header-" + std::to_string(i);
  4989. std::string value = "value" + std::to_string(i);
  4990. headers.emplace(name, value);
  4991. }
  4992. // This should fail due to exceeding header count limit
  4993. cli_.set_keep_alive(true);
  4994. auto res = cli_.Get("/hi", headers);
  4995. // The server should respond with 400 Bad Request
  4996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4997. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4998. EXPECT_EQ("close", res->get_header_value("Connection"));
  4999. EXPECT_FALSE(cli_.is_socket_open());
  5000. }
  5001. TEST_F(ServerTest, PercentEncoding) {
  5002. auto res = cli_.Get("/e%6edwith%");
  5003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5004. EXPECT_EQ(StatusCode::OK_200, res->status);
  5005. }
  5006. TEST_F(ServerTest, PercentEncodingUnicode) {
  5007. auto res = cli_.Get("/e%u006edwith%");
  5008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5009. EXPECT_EQ(StatusCode::OK_200, res->status);
  5010. }
  5011. TEST_F(ServerTest, InvalidPercentEncoding) {
  5012. auto res = cli_.Get("/%endwith%");
  5013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5014. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5015. }
  5016. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5017. auto res = cli_.Get("/%uendwith%");
  5018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5019. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5020. }
  5021. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5022. auto res = cli_.Get("/hello?aaa=bbb%");
  5023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5024. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5025. }
  5026. TEST_F(ServerTest, PlusSignEncoding) {
  5027. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ(StatusCode::OK_200, res->status);
  5030. EXPECT_EQ("a +b", res->body);
  5031. }
  5032. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5033. // This test simulates a potential DoS attack using many headers
  5034. // to verify our security fix prevents memory exhaustion
  5035. httplib::Headers attack_headers;
  5036. // Attempt to add many headers like an attacker would (200 headers to far
  5037. // exceed limit)
  5038. for (int i = 0; i < 200; i++) {
  5039. std::string name = "X-Attack-Header-" + std::to_string(i);
  5040. std::string value = "attack_payload_" + std::to_string(i);
  5041. attack_headers.emplace(name, value);
  5042. }
  5043. // Try to POST with excessive headers
  5044. cli_.set_keep_alive(true);
  5045. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5046. // Should either fail or return 400 Bad Request due to security limit
  5047. if (res) {
  5048. // If we get a response, it should be 400 Bad Request
  5049. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5050. EXPECT_EQ("close", res->get_header_value("Connection"));
  5051. }
  5052. EXPECT_FALSE(cli_.is_socket_open());
  5053. }
  5054. TEST_F(ServerTest, MultipartFormData) {
  5055. UploadFormDataItems items = {
  5056. {"text1", "text default", "", ""},
  5057. {"text2", "aωb", "", ""},
  5058. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5059. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5060. {"file3", "", "", "application/octet-stream"},
  5061. {"file4", "", "", " application/json tmp-string "}};
  5062. auto res = cli_.Post("/multipart", items);
  5063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5064. EXPECT_EQ(StatusCode::OK_200, res->status);
  5065. }
  5066. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5067. UploadFormDataItems items = {
  5068. {"text", "default text", "", ""},
  5069. {"multi_text1", "aaaaa", "", ""},
  5070. {"multi_text1", "bbbbb", "", ""},
  5071. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5072. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5073. "application/json"},
  5074. };
  5075. auto res = cli_.Post("/multipart/multi_file_values", items);
  5076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5077. EXPECT_EQ(StatusCode::OK_200, res->status);
  5078. }
  5079. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5080. auto res = cli_.Get("/hi");
  5081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5082. EXPECT_EQ(StatusCode::OK_200, res->status);
  5083. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5084. EXPECT_EQ("Hello World!", res->body);
  5085. }
  5086. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5087. Request req;
  5088. req.method = "POST";
  5089. req.path = "/chunked";
  5090. std::string host_and_port;
  5091. host_and_port += HOST;
  5092. host_and_port += ":";
  5093. host_and_port += std::to_string(PORT);
  5094. req.headers.emplace("Host", host_and_port.c_str());
  5095. req.headers.emplace("Accept", "*/*");
  5096. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5097. req.headers.emplace("Content-Type", "text/plain");
  5098. req.headers.emplace("Content-Length", "0");
  5099. req.headers.emplace(
  5100. "Transfer-Encoding",
  5101. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5102. // Client does not chunk, so make a chunked body manually.
  5103. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5104. auto res = std::make_shared<Response>();
  5105. auto error = Error::Success;
  5106. auto ret = cli_.send(req, *res, error);
  5107. ASSERT_TRUE(ret);
  5108. EXPECT_EQ(StatusCode::OK_200, res->status);
  5109. }
  5110. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5111. // rather than treat them as valid lengths.
  5112. template <typename ClientT>
  5113. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5114. Request req;
  5115. req.method = "POST";
  5116. req.path = "/chunked";
  5117. std::string host_and_port;
  5118. host_and_port += HOST;
  5119. host_and_port += ":";
  5120. host_and_port += std::to_string(PORT);
  5121. req.headers.emplace("Host", host_and_port.c_str());
  5122. req.headers.emplace("Content-Length", "0");
  5123. req.headers.emplace("Transfer-Encoding", "chunked");
  5124. req.body = body;
  5125. auto res = std::make_shared<Response>();
  5126. auto error = Error::Success;
  5127. ASSERT_TRUE(cli.send(req, *res, error));
  5128. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5129. }
  5130. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5131. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5132. }
  5133. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5134. expect_chunked_body_rejected(
  5135. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5136. }
  5137. TEST_F(ServerTest, GetStreamed2) {
  5138. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5141. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5142. EXPECT_EQ(true, res->has_header("Content-Range"));
  5143. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5144. EXPECT_EQ(std::string("ab"), res->body);
  5145. }
  5146. TEST_F(ServerTest, GetStreamed) {
  5147. auto res = cli_.Get("/streamed");
  5148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5149. EXPECT_EQ(StatusCode::OK_200, res->status);
  5150. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5151. EXPECT_EQ(std::string("aaabbb"), res->body);
  5152. }
  5153. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5154. auto res = cli_.Get("/streamed-without-length",
  5155. Headers{make_range_header({{0, -1}})});
  5156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5157. EXPECT_EQ(StatusCode::OK_200, res->status);
  5158. EXPECT_EQ(false, res->has_header("Content-Length"));
  5159. EXPECT_EQ(false, res->has_header("Content-Range"));
  5160. EXPECT_EQ(std::string("abcdefg"), res->body);
  5161. }
  5162. TEST_F(ServerTest, GetStreamedWithRange1) {
  5163. auto res =
  5164. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5167. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5168. EXPECT_EQ(true, res->has_header("Content-Range"));
  5169. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5170. EXPECT_EQ(std::string("def"), res->body);
  5171. }
  5172. TEST_F(ServerTest, GetStreamedWithRange2) {
  5173. auto res =
  5174. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5177. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5178. EXPECT_EQ(true, res->has_header("Content-Range"));
  5179. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5180. EXPECT_EQ(std::string("bcdefg"), res->body);
  5181. }
  5182. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5183. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5185. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5186. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5187. EXPECT_EQ(true, res->has_header("Content-Range"));
  5188. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5189. EXPECT_EQ(std::string("efg"), res->body);
  5190. }
  5191. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5192. auto res =
  5193. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5195. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5196. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5197. EXPECT_EQ(false, res->has_header("Content-Range"));
  5198. EXPECT_EQ(0U, res->body.size());
  5199. }
  5200. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5201. // Only a 206 is served as a partial representation. Under any other status
  5202. // `apply_ranges()` reported the full content length, so the body must match
  5203. // that header, and the content provider must never be asked for an offset
  5204. // outside the representation.
  5205. auto check = [&](int status, const char *range) {
  5206. auto path =
  5207. std::string("/streamed-with-range?status=") + std::to_string(status);
  5208. auto ctx = path + " Range: " + range;
  5209. auto res = cli_.Get(path, Headers{{"Range", range}});
  5210. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5211. EXPECT_EQ(status, res->status) << ctx;
  5212. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5214. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5215. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5216. };
  5217. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5218. check(403, "bytes=3-5");
  5219. // The offset is far past the representation.
  5220. check(403, "bytes=100000-100200");
  5221. // `first_pos` is still -1 here, and the bounds asserts in
  5222. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5223. check(403, "bytes=-3");
  5224. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5225. // multipart branch would have written one that is empty.
  5226. check(403, "bytes=1-2, 4-5");
  5227. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5228. // covers the whole representation.
  5229. check(200, "bytes=3-5");
  5230. check(200, "bytes=1-2, 4-5");
  5231. }
  5232. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5233. auto res =
  5234. cli_.Get("/streamed-with-range",
  5235. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5236. "92233720368547758079223372036854775807"}});
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5239. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5240. EXPECT_EQ(false, res->has_header("Content-Range"));
  5241. EXPECT_EQ(0U, res->body.size());
  5242. }
  5243. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5244. auto res = cli_.Get(
  5245. "/with-range",
  5246. Headers{{"Range",
  5247. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5248. {"Accept-Encoding", ""}});
  5249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5250. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5251. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5252. EXPECT_EQ(true, res->has_header("Content-Range"));
  5253. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5254. EXPECT_EQ(std::string("abcdefg"), res->body);
  5255. }
  5256. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5257. auto res = cli_.Get("/with-range", Headers{
  5258. {"Range", "bytes=0-"},
  5259. {"Accept-Encoding", ""},
  5260. });
  5261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5262. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5263. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5264. EXPECT_EQ(true, res->has_header("Content-Range"));
  5265. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5266. EXPECT_EQ(std::string("abcdefg"), res->body);
  5267. }
  5268. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5269. auto res = cli_.Get("/streamed-with-range",
  5270. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5272. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5273. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5274. EXPECT_EQ(false, res->has_header("Content-Range"));
  5275. EXPECT_EQ(267U, res->body.size());
  5276. // Check that both range contents are present
  5277. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5278. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5279. // Check that Content-Range headers are present for both ranges
  5280. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5281. std::string::npos);
  5282. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5283. std::string::npos);
  5284. }
  5285. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5286. Ranges ranges;
  5287. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5288. ranges.emplace_back(0, -1);
  5289. }
  5290. auto res = cli_.Get("/streamed-with-range?error",
  5291. Headers{{make_range_header(ranges)}});
  5292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5293. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5294. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5295. EXPECT_EQ(false, res->has_header("Content-Range"));
  5296. EXPECT_EQ(0U, res->body.size());
  5297. }
  5298. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5299. auto res = cli_.Get("/streamed-with-range",
  5300. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5302. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5303. EXPECT_EQ(5U, res->body.size());
  5304. // Check that overlapping ranges are coalesced into a single range
  5305. EXPECT_EQ("bcdef", res->body);
  5306. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5307. // Should be single range, not multipart
  5308. EXPECT_TRUE(res->has_header("Content-Range"));
  5309. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5310. }
  5311. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5312. auto res = cli_.Get("/streamed-with-range",
  5313. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5315. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5316. EXPECT_EQ(268U, res->body.size());
  5317. // Check that both range contents are present
  5318. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5319. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5320. // Check that Content-Range headers are present for both ranges
  5321. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5322. std::string::npos);
  5323. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5324. std::string::npos);
  5325. }
  5326. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5327. auto res = cli_.Get("/streamed-with-range",
  5328. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5331. EXPECT_EQ(269U, res->body.size());
  5332. // Check that both duplicate range contents are present
  5333. size_t first_abc = res->body.find("abc\r\n");
  5334. EXPECT_TRUE(first_abc != std::string::npos);
  5335. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5336. EXPECT_TRUE(second_abc != std::string::npos);
  5337. // Check that Content-Range headers are present for both ranges
  5338. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5339. EXPECT_TRUE(first_range != std::string::npos);
  5340. size_t second_range =
  5341. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5342. EXPECT_TRUE(second_range != std::string::npos);
  5343. }
  5344. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5345. auto res =
  5346. cli_.Get("/streamed-with-range?error",
  5347. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5349. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5350. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5351. EXPECT_EQ(false, res->has_header("Content-Range"));
  5352. EXPECT_EQ(0U, res->body.size());
  5353. }
  5354. TEST_F(ServerTest, GetStreamedEndless) {
  5355. uint64_t offset = 0;
  5356. auto res = cli_.Get("/streamed-cancel",
  5357. [&](const char * /*data*/, uint64_t data_length) {
  5358. if (offset < 100) {
  5359. offset += data_length;
  5360. return true;
  5361. }
  5362. return false;
  5363. });
  5364. ASSERT_TRUE(!res);
  5365. EXPECT_EQ(Error::Canceled, res.error());
  5366. }
  5367. TEST_F(ServerTest, ClientStop) {
  5368. std::atomic_size_t count{4};
  5369. std::vector<std::thread> threads;
  5370. for (auto i = count.load(); i != 0; --i) {
  5371. threads.emplace_back([&]() {
  5372. auto res = cli_.Get("/streamed-cancel",
  5373. [&](const char *, uint64_t) { return true; });
  5374. --count;
  5375. ASSERT_TRUE(!res);
  5376. EXPECT_TRUE(res.error() == Error::Canceled ||
  5377. res.error() == Error::Read || res.error() == Error::Write);
  5378. });
  5379. }
  5380. std::this_thread::sleep_for(std::chrono::seconds(2));
  5381. while (count != 0) {
  5382. cli_.stop();
  5383. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5384. }
  5385. for (auto &t : threads) {
  5386. t.join();
  5387. }
  5388. }
  5389. TEST_F(ServerTest, GetWithRange1) {
  5390. auto res = cli_.Get("/with-range", Headers{
  5391. make_range_header({{3, 5}}),
  5392. {"Accept-Encoding", ""},
  5393. });
  5394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5395. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5396. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5397. EXPECT_EQ(true, res->has_header("Content-Range"));
  5398. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5399. EXPECT_EQ(std::string("def"), res->body);
  5400. }
  5401. TEST_F(ServerTest, GetWithRange2) {
  5402. auto res = cli_.Get("/with-range", Headers{
  5403. make_range_header({{1, -1}}),
  5404. {"Accept-Encoding", ""},
  5405. });
  5406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5407. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5408. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5409. EXPECT_EQ(true, res->has_header("Content-Range"));
  5410. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5411. EXPECT_EQ(std::string("bcdefg"), res->body);
  5412. }
  5413. TEST_F(ServerTest, GetWithRange3) {
  5414. auto res = cli_.Get("/with-range", Headers{
  5415. make_range_header({{0, 0}}),
  5416. {"Accept-Encoding", ""},
  5417. });
  5418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5419. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5420. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5421. EXPECT_EQ(true, res->has_header("Content-Range"));
  5422. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5423. EXPECT_EQ(std::string("a"), res->body);
  5424. }
  5425. TEST_F(ServerTest, GetWithRange4) {
  5426. auto res = cli_.Get("/with-range", Headers{
  5427. make_range_header({{-1, 2}}),
  5428. {"Accept-Encoding", ""},
  5429. });
  5430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5432. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5433. EXPECT_EQ(true, res->has_header("Content-Range"));
  5434. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5435. EXPECT_EQ(std::string("fg"), res->body);
  5436. }
  5437. TEST_F(ServerTest, GetWithRange5) {
  5438. auto res = cli_.Get("/with-range", Headers{
  5439. make_range_header({{0, 5}}),
  5440. {"Accept-Encoding", ""},
  5441. });
  5442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5443. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5444. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5445. EXPECT_EQ(true, res->has_header("Content-Range"));
  5446. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5447. EXPECT_EQ(std::string("abcdef"), res->body);
  5448. }
  5449. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5450. auto res =
  5451. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5453. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5454. }
  5455. TEST_F(ServerTest, GetWithRangeMultipart) {
  5456. auto res =
  5457. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5460. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5461. EXPECT_EQ(false, res->has_header("Content-Range"));
  5462. EXPECT_EQ(267U, res->body.size());
  5463. }
  5464. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5465. auto res = cli_.Get("/with-range",
  5466. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5469. }
  5470. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5471. auto res = cli_.Get("/with-range-customized-response",
  5472. Headers{{make_range_header({{1, 2}})}});
  5473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5474. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5475. EXPECT_EQ(true, res->has_header("Content-Length"));
  5476. EXPECT_EQ(false, res->has_header("Content-Range"));
  5477. EXPECT_EQ(JSON_DATA, res->body);
  5478. }
  5479. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5480. auto res = cli_.Get("/with-range-customized-response",
  5481. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5483. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5484. EXPECT_EQ(true, res->has_header("Content-Length"));
  5485. EXPECT_EQ(false, res->has_header("Content-Range"));
  5486. EXPECT_EQ(JSON_DATA, res->body);
  5487. }
  5488. TEST_F(ServerTest, Issue1772) {
  5489. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5491. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5492. }
  5493. TEST_F(ServerTest, Issue609) {
  5494. auto res = cli_.Delete("/issue609");
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. EXPECT_EQ(StatusCode::OK_200, res->status);
  5497. EXPECT_EQ(std::string("ok"), res->body);
  5498. }
  5499. TEST_F(ServerTest, GetStreamedChunked) {
  5500. auto res = cli_.Get("/streamed-chunked");
  5501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5502. EXPECT_EQ(StatusCode::OK_200, res->status);
  5503. EXPECT_EQ(std::string("123456789"), res->body);
  5504. }
  5505. TEST_F(ServerTest, GetStreamedChunked2) {
  5506. auto res = cli_.Get("/streamed-chunked2");
  5507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. EXPECT_EQ(std::string("123456789"), res->body);
  5510. }
  5511. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5512. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_EQ(std::string("123456789"), res->body);
  5516. EXPECT_TRUE(res->has_header("Trailer"));
  5517. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5518. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5519. // Trailers are now stored separately from headers (security fix)
  5520. EXPECT_EQ(2U, res->trailers.size());
  5521. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5522. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5523. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5524. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5525. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5526. // Verify trailers are NOT in headers (security verification)
  5527. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5528. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5529. }
  5530. TEST_F(ServerTest, LargeChunkedPost) {
  5531. Request req;
  5532. req.method = "POST";
  5533. req.path = "/large-chunked";
  5534. std::string host_and_port;
  5535. host_and_port += HOST;
  5536. host_and_port += ":";
  5537. host_and_port += std::to_string(PORT);
  5538. req.headers.emplace("Host", host_and_port.c_str());
  5539. req.headers.emplace("Accept", "*/*");
  5540. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5541. req.headers.emplace("Content-Type", "text/plain");
  5542. req.headers.emplace("Content-Length", "0");
  5543. req.headers.emplace("Transfer-Encoding", "chunked");
  5544. std::string long_string(30 * 1024u, 'a');
  5545. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5546. // Attempt to make a large enough post to exceed OS buffers, to test that
  5547. // the server handles short reads if the full chunk data isn't available.
  5548. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5549. auto res = std::make_shared<Response>();
  5550. auto error = Error::Success;
  5551. auto ret = cli_.send(req, *res, error);
  5552. ASSERT_TRUE(ret);
  5553. EXPECT_EQ(StatusCode::OK_200, res->status);
  5554. }
  5555. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5556. auto res = cli_.Get("/remote_addr");
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. EXPECT_EQ(StatusCode::OK_200, res->status);
  5559. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5560. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5561. }
  5562. TEST_F(ServerTest, GetMethodLocalAddr) {
  5563. auto res = cli_.Get("/local_addr");
  5564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5565. EXPECT_EQ(StatusCode::OK_200, res->status);
  5566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5567. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5568. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5569. }
  5570. TEST_F(ServerTest, HTTPResponseSplitting) {
  5571. auto res = cli_.Get("/http_response_splitting");
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. }
  5575. TEST_F(ServerTest, SlowRequest) {
  5576. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5577. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5578. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5579. }
  5580. #if 0
  5581. TEST_F(ServerTest, SlowPost) {
  5582. char buffer[64 * 1024];
  5583. memset(buffer, 0x42, sizeof(buffer));
  5584. auto res = cli_.Post(
  5585. "/slowpost", 64 * 1024 * 1024,
  5586. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5587. auto ret = sink.write(buffer, sizeof(buffer));
  5588. EXPECT_TRUE(ret);
  5589. return true;
  5590. },
  5591. "text/plain");
  5592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5593. EXPECT_EQ(StatusCode::OK_200, res->status);
  5594. }
  5595. TEST_F(ServerTest, SlowPostFail) {
  5596. char buffer[64 * 1024];
  5597. memset(buffer, 0x42, sizeof(buffer));
  5598. cli_.set_write_timeout(std::chrono::seconds(0));
  5599. auto res = cli_.Post(
  5600. "/slowpost", 64 * 1024 * 1024,
  5601. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5602. sink.write(buffer, sizeof(buffer));
  5603. return true;
  5604. },
  5605. "text/plain");
  5606. ASSERT_TRUE(!res);
  5607. EXPECT_EQ(Error::Write, res.error());
  5608. }
  5609. #endif
  5610. TEST_F(ServerTest, Put) {
  5611. auto res = cli_.Put("/put", "PUT", "text/plain");
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::OK_200, res->status);
  5614. EXPECT_EQ("PUT", res->body);
  5615. }
  5616. TEST_F(ServerTest, PutWithContentProvider) {
  5617. auto res = cli_.Put(
  5618. "/put", 3,
  5619. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5620. sink.os << "PUT";
  5621. return true;
  5622. },
  5623. "text/plain");
  5624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5625. EXPECT_EQ(StatusCode::OK_200, res->status);
  5626. EXPECT_EQ("PUT", res->body);
  5627. }
  5628. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5629. auto res = cli_.Post(
  5630. "/post", 42,
  5631. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5632. return false;
  5633. },
  5634. "text/plain");
  5635. ASSERT_TRUE(!res);
  5636. EXPECT_EQ(Error::Canceled, res.error());
  5637. }
  5638. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5639. auto res = cli_.Put(
  5640. "/put",
  5641. [](size_t /*offset*/, DataSink &sink) {
  5642. sink.os << "PUT";
  5643. sink.done();
  5644. return true;
  5645. },
  5646. "text/plain");
  5647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5648. EXPECT_EQ(StatusCode::OK_200, res->status);
  5649. EXPECT_EQ("PUT", res->body);
  5650. }
  5651. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5652. auto res = cli_.Post(
  5653. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5654. "text/plain");
  5655. ASSERT_TRUE(!res);
  5656. EXPECT_EQ(Error::Canceled, res.error());
  5657. }
  5658. TEST_F(ServerTest, PostLoopBack) {
  5659. std::string body;
  5660. auto res = cli_.Post(
  5661. "/post-loopback", 9,
  5662. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5663. EXPECT_EQ(9u, length);
  5664. sink.write("123", 3);
  5665. sink.write("456", 3);
  5666. sink.write("789", 3);
  5667. return true;
  5668. },
  5669. "text/plain",
  5670. [&body](const char *data, size_t data_length) {
  5671. body.append(data, data_length);
  5672. return true;
  5673. });
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. EXPECT_EQ(StatusCode::OK_200, res->status);
  5676. EXPECT_EQ("123456789", body);
  5677. }
  5678. TEST_F(ServerTest, PutLoopBack) {
  5679. std::string body;
  5680. auto res = cli_.Put(
  5681. "/put-loopback", 9,
  5682. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5683. EXPECT_EQ(9u, length);
  5684. sink.write("123", 3);
  5685. sink.write("456", 3);
  5686. sink.write("789", 3);
  5687. return true;
  5688. },
  5689. "text/plain",
  5690. [&body](const char *data, size_t data_length) {
  5691. body.append(data, data_length);
  5692. return true;
  5693. });
  5694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5695. EXPECT_EQ(StatusCode::OK_200, res->status);
  5696. EXPECT_EQ("123456789", body);
  5697. }
  5698. TEST_F(ServerTest, PatchLoopBack) {
  5699. std::string body;
  5700. auto res = cli_.Patch(
  5701. "/patch-loopback", 9,
  5702. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5703. EXPECT_EQ(9u, length);
  5704. sink.write("123", 3);
  5705. sink.write("456", 3);
  5706. sink.write("789", 3);
  5707. return true;
  5708. },
  5709. "text/plain",
  5710. [&body](const char *data, size_t data_length) {
  5711. body.append(data, data_length);
  5712. return true;
  5713. });
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. EXPECT_EQ(StatusCode::OK_200, res->status);
  5716. EXPECT_EQ("123456789", body);
  5717. }
  5718. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5719. std::string body;
  5720. auto res = cli_.Post(
  5721. "/post-loopback",
  5722. [](size_t /*offset*/, DataSink &sink) {
  5723. sink.write("123", 3);
  5724. sink.write("456", 3);
  5725. sink.write("789", 3);
  5726. sink.done();
  5727. return true;
  5728. },
  5729. "text/plain",
  5730. [&body](const char *data, size_t data_length) {
  5731. body.append(data, data_length);
  5732. return true;
  5733. });
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. EXPECT_EQ(StatusCode::OK_200, res->status);
  5736. EXPECT_EQ("123456789", body);
  5737. }
  5738. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5739. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5740. cli_.set_compress(true);
  5741. auto res = cli_.Put(
  5742. "/put", 3,
  5743. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5744. sink.os << "PUT";
  5745. return true;
  5746. },
  5747. "text/plain");
  5748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5749. EXPECT_EQ(StatusCode::OK_200, res->status);
  5750. EXPECT_EQ("PUT", res->body);
  5751. }
  5752. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5753. cli_.set_compress(true);
  5754. auto res = cli_.Post(
  5755. "/post", 42,
  5756. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5757. return false;
  5758. },
  5759. "text/plain");
  5760. ASSERT_TRUE(!res);
  5761. EXPECT_EQ(Error::Canceled, res.error());
  5762. }
  5763. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5764. cli_.set_compress(true);
  5765. auto res = cli_.Put(
  5766. "/put",
  5767. [](size_t /*offset*/, DataSink &sink) {
  5768. sink.os << "PUT";
  5769. sink.done();
  5770. return true;
  5771. },
  5772. "text/plain");
  5773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5774. EXPECT_EQ(StatusCode::OK_200, res->status);
  5775. EXPECT_EQ("PUT", res->body);
  5776. }
  5777. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5778. cli_.set_compress(true);
  5779. auto res = cli_.Post(
  5780. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5781. "text/plain");
  5782. ASSERT_TRUE(!res);
  5783. EXPECT_EQ(Error::Canceled, res.error());
  5784. }
  5785. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5786. cli_.set_compress(true);
  5787. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5789. EXPECT_EQ(StatusCode::OK_200, res->status);
  5790. EXPECT_EQ(LARGE_DATA, res->body);
  5791. }
  5792. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5793. #ifdef CPPHTTPLIB_SSL_ENABLED
  5794. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5795. Client cli(s.c_str());
  5796. cli.enable_server_certificate_verification(false);
  5797. #else
  5798. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5799. Client cli(s.c_str());
  5800. #endif
  5801. cli.set_compress(true);
  5802. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5804. EXPECT_EQ(StatusCode::OK_200, res->status);
  5805. EXPECT_EQ(LARGE_DATA, res->body);
  5806. // The compressed size should be less than a 10th of the original. May vary
  5807. // depending on the zlib library.
  5808. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5809. static_cast<uint64_t>(10 * 1024 * 1024));
  5810. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5811. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5812. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5813. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5814. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5815. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5816. #endif
  5817. }
  5818. TEST_F(ServerTest, PutContentWithDeflate) {
  5819. cli_.set_compress(false);
  5820. Headers headers;
  5821. headers.emplace("Content-Encoding", "deflate");
  5822. // PUT in deflate format:
  5823. auto res = cli_.Put("/put", headers,
  5824. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::OK_200, res->status);
  5827. EXPECT_EQ("PUT", res->body);
  5828. }
  5829. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5830. Headers headers;
  5831. headers.emplace("Accept-Encoding", "gzip, deflate");
  5832. auto res = cli_.Get("/streamed-chunked", headers);
  5833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5834. EXPECT_EQ(StatusCode::OK_200, res->status);
  5835. EXPECT_EQ(std::string("123456789"), res->body);
  5836. }
  5837. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5838. Headers headers;
  5839. headers.emplace("Accept-Encoding", "gzip, deflate");
  5840. auto res = cli_.Get("/streamed-chunked2", headers);
  5841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5842. EXPECT_EQ(StatusCode::OK_200, res->status);
  5843. EXPECT_EQ(std::string("123456789"), res->body);
  5844. }
  5845. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5846. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::OK_200, res->status);
  5849. }
  5850. TEST(GzipDecompressor, ChunkedDecompression) {
  5851. std::string data;
  5852. for (size_t i = 0; i < 32 * 1024; ++i) {
  5853. data.push_back(static_cast<char>('a' + i % 26));
  5854. }
  5855. std::string compressed_data;
  5856. {
  5857. httplib::detail::gzip_compressor compressor;
  5858. bool result = compressor.compress(
  5859. data.data(), data.size(),
  5860. /*last=*/true,
  5861. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5862. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5863. compressed_data_size);
  5864. return true;
  5865. });
  5866. ASSERT_TRUE(result);
  5867. }
  5868. std::string decompressed_data;
  5869. {
  5870. httplib::detail::gzip_decompressor decompressor;
  5871. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5872. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5873. size_t chunk_size = 130;
  5874. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5875. chunk_begin += chunk_size) {
  5876. size_t current_chunk_size =
  5877. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5878. bool result = decompressor.decompress(
  5879. compressed_data.data() + chunk_begin, current_chunk_size,
  5880. [&](const char *decompressed_data_chunk,
  5881. size_t decompressed_data_chunk_size) {
  5882. decompressed_data.insert(decompressed_data.size(),
  5883. decompressed_data_chunk,
  5884. decompressed_data_chunk_size);
  5885. return true;
  5886. });
  5887. ASSERT_TRUE(result);
  5888. }
  5889. }
  5890. ASSERT_EQ(data, decompressed_data);
  5891. }
  5892. TEST(GzipDecompressor, DeflateDecompression) {
  5893. std::string original_text = "Raw deflate without gzip";
  5894. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5895. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5896. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5897. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5898. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5899. std::string decompressed_data;
  5900. {
  5901. httplib::detail::gzip_decompressor decompressor;
  5902. bool result = decompressor.decompress(
  5903. compressed_data.data(), compressed_data.size(),
  5904. [&](const char *decompressed_data_chunk,
  5905. size_t decompressed_data_chunk_size) {
  5906. decompressed_data.insert(decompressed_data.size(),
  5907. decompressed_data_chunk,
  5908. decompressed_data_chunk_size);
  5909. return true;
  5910. });
  5911. ASSERT_TRUE(result);
  5912. }
  5913. ASSERT_EQ(original_text, decompressed_data);
  5914. }
  5915. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5916. std::string original_text = "Raw deflate without gzip";
  5917. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5918. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5919. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5920. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5921. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5922. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5923. std::string decompressed_data;
  5924. {
  5925. httplib::detail::gzip_decompressor decompressor;
  5926. bool result = decompressor.decompress(
  5927. compressed_data.data(), compressed_data.size(),
  5928. [&](const char *decompressed_data_chunk,
  5929. size_t decompressed_data_chunk_size) {
  5930. decompressed_data.insert(decompressed_data.size(),
  5931. decompressed_data_chunk,
  5932. decompressed_data_chunk_size);
  5933. return true;
  5934. });
  5935. ASSERT_TRUE(result);
  5936. }
  5937. ASSERT_EQ(original_text, decompressed_data);
  5938. }
  5939. #endif
  5940. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5941. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5942. Headers headers;
  5943. headers.emplace("Accept-Encoding", "br");
  5944. auto res = cli_.Get("/streamed-chunked", headers);
  5945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5946. EXPECT_EQ(StatusCode::OK_200, res->status);
  5947. EXPECT_EQ(std::string("123456789"), res->body);
  5948. }
  5949. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5950. Headers headers;
  5951. headers.emplace("Accept-Encoding", "br");
  5952. auto res = cli_.Get("/streamed-chunked2", headers);
  5953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5954. EXPECT_EQ(StatusCode::OK_200, res->status);
  5955. EXPECT_EQ(std::string("123456789"), res->body);
  5956. }
  5957. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5958. cli_.set_compress(true);
  5959. auto res = cli_.Put(
  5960. "/put", 3,
  5961. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5962. sink.os << "PUT";
  5963. return true;
  5964. },
  5965. "text/plain");
  5966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. EXPECT_EQ("PUT", res->body);
  5969. }
  5970. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5971. cli_.set_compress(true);
  5972. auto res = cli_.Put(
  5973. "/put",
  5974. [](size_t /*offset*/, DataSink &sink) {
  5975. sink.os << "PUT";
  5976. sink.done();
  5977. return true;
  5978. },
  5979. "text/plain");
  5980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5981. EXPECT_EQ(StatusCode::OK_200, res->status);
  5982. EXPECT_EQ("PUT", res->body);
  5983. }
  5984. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5985. cli_.set_compress(true);
  5986. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5988. EXPECT_EQ(StatusCode::OK_200, res->status);
  5989. EXPECT_EQ(LARGE_DATA, res->body);
  5990. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5991. }
  5992. #endif
  5993. TEST_F(ServerTest, Patch) {
  5994. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5996. EXPECT_EQ(StatusCode::OK_200, res->status);
  5997. EXPECT_EQ("PATCH", res->body);
  5998. }
  5999. TEST_F(ServerTest, Delete) {
  6000. auto res = cli_.Delete("/delete");
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. EXPECT_EQ(StatusCode::OK_200, res->status);
  6003. EXPECT_EQ("DELETE", res->body);
  6004. }
  6005. TEST_F(ServerTest, DeleteContentReceiver) {
  6006. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6008. EXPECT_EQ(StatusCode::OK_200, res->status);
  6009. EXPECT_EQ("content", res->body);
  6010. }
  6011. TEST_F(ServerTest, Options) {
  6012. auto res = cli_.Options("*");
  6013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6014. EXPECT_EQ(StatusCode::OK_200, res->status);
  6015. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6016. EXPECT_TRUE(res->body.empty());
  6017. }
  6018. TEST_F(ServerTest, URL) {
  6019. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6021. EXPECT_EQ(StatusCode::OK_200, res->status);
  6022. }
  6023. TEST_F(ServerTest, ArrayParam) {
  6024. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::OK_200, res->status);
  6027. }
  6028. TEST_F(ServerTest, ArrayParamValues) {
  6029. auto res =
  6030. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6032. EXPECT_EQ(StatusCode::OK_200, res->status);
  6033. }
  6034. TEST_F(ServerTest, NoMultipleHeaders) {
  6035. Headers headers = {{"Content-Length", "5"}};
  6036. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6037. "text/plain");
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. EXPECT_EQ(StatusCode::OK_200, res->status);
  6040. }
  6041. TEST_F(ServerTest, PostContentReceiver) {
  6042. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6044. ASSERT_EQ(StatusCode::OK_200, res->status);
  6045. ASSERT_EQ("content", res->body);
  6046. }
  6047. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6048. UploadFormDataItems items = {
  6049. {"text1", "text default", "", ""},
  6050. {"text2", "aωb", "", ""},
  6051. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6052. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6053. {"file3", "", "", "application/octet-stream"},
  6054. };
  6055. auto res = cli_.Post("/content_receiver", items);
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::OK_200, res->status);
  6058. }
  6059. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6060. UploadFormDataItems items = {
  6061. {"text1", "text default", "", ""},
  6062. {"text2", "aωb", "", ""},
  6063. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6064. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6065. {"file3", "", "", "application/octet-stream"},
  6066. };
  6067. auto boundary = std::string("+++++");
  6068. std::string body;
  6069. for (const auto &item : items) {
  6070. body += "--" + boundary + "\r\n";
  6071. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6072. if (!item.filename.empty()) {
  6073. body += "; filename=\"" + item.filename + "\"";
  6074. }
  6075. body += "\r\n";
  6076. if (!item.content_type.empty()) {
  6077. body += "Content-Type: " + item.content_type + "\r\n";
  6078. }
  6079. body += "\r\n";
  6080. body += item.content + "\r\n";
  6081. }
  6082. body += "--" + boundary + "--\r\n";
  6083. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6084. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. EXPECT_EQ(StatusCode::OK_200, res->status);
  6087. }
  6088. TEST(MultipartFormDataTest, FieldEscaping) {
  6089. Server svr;
  6090. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6091. const ContentReader &content_reader) {
  6092. ASSERT_TRUE(req.is_multipart_form_data());
  6093. std::vector<FormData> received;
  6094. content_reader(
  6095. [&](const FormData &file) {
  6096. received.push_back(file);
  6097. return true;
  6098. },
  6099. [&](const char *data, size_t data_length) {
  6100. received.back().content.append(data, data_length);
  6101. return true;
  6102. });
  6103. // '"', CR and LF in names and filenames are escaped following the
  6104. // WHATWG HTML standard, so each part still parses as a single part
  6105. // with no injected headers. Content types get CR/LF escaped too,
  6106. // while '"' (legal there, e.g. quoted charset) is preserved.
  6107. ASSERT_EQ(4U, received.size());
  6108. EXPECT_EQ("na%22me", received[0].name);
  6109. EXPECT_EQ("quoted name", received[0].content);
  6110. EXPECT_EQ("file", received[1].name);
  6111. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6112. received[1].filename);
  6113. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6114. EXPECT_EQ("injected", received[1].content);
  6115. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6116. EXPECT_EQ("my%22file.txt", received[2].filename);
  6117. EXPECT_EQ("cr lf name", received[2].content);
  6118. EXPECT_EQ("typed", received[3].name);
  6119. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6120. received[3].content_type);
  6121. EXPECT_EQ("typed content", received[3].content);
  6122. });
  6123. auto port = svr.bind_to_any_port("localhost");
  6124. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6125. auto se = detail::scope_exit([&] {
  6126. svr.stop();
  6127. t.join();
  6128. ASSERT_FALSE(svr.is_running());
  6129. });
  6130. svr.wait_until_ready();
  6131. Client cli("localhost", port);
  6132. UploadFormDataItems items = {
  6133. {"na\"me", "quoted name", "", ""},
  6134. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6135. "application/octet-stream"},
  6136. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6137. {"typed", "typed content", "",
  6138. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6139. };
  6140. auto res = cli.Post("/post", items);
  6141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6142. EXPECT_EQ(StatusCode::OK_200, res->status);
  6143. }
  6144. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6145. const UploadFormDataItems items = {
  6146. {"name1", "Content 1", "", ""},
  6147. {"name2", "Content 2", "file2.txt", "text/plain"},
  6148. };
  6149. Server svr;
  6150. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6151. const ContentReader &content_reader) {
  6152. ASSERT_TRUE(req.is_multipart_form_data());
  6153. std::vector<FormData> received;
  6154. content_reader(
  6155. [&](const FormData &file) {
  6156. received.push_back(file);
  6157. return true;
  6158. },
  6159. [&](const char *data, size_t data_length) {
  6160. received.back().content.append(data, data_length);
  6161. return true;
  6162. });
  6163. ASSERT_EQ(2U, received.size());
  6164. EXPECT_EQ("name1", received[0].name);
  6165. EXPECT_EQ("Content 1", received[0].content);
  6166. EXPECT_EQ("name2", received[1].name);
  6167. EXPECT_EQ("Content 2", received[1].content);
  6168. EXPECT_EQ("file2.txt", received[1].filename);
  6169. EXPECT_EQ("text/plain", received[1].content_type);
  6170. });
  6171. auto port = svr.bind_to_any_port("localhost");
  6172. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6173. auto se = detail::scope_exit([&] {
  6174. svr.stop();
  6175. t.join();
  6176. ASSERT_FALSE(svr.is_running());
  6177. });
  6178. svr.wait_until_ready();
  6179. Client cli("localhost", port);
  6180. // Whole-body serialization with a generated boundary
  6181. {
  6182. MultipartFormDataWriter writer;
  6183. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6184. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6185. writer.content_type());
  6186. auto body = writer.serialize(items);
  6187. EXPECT_EQ(body.size(), writer.content_length(items));
  6188. auto res = cli.Post("/post", body, writer.content_type());
  6189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6190. EXPECT_EQ(StatusCode::OK_200, res->status);
  6191. }
  6192. // Per-part framing with a custom boundary via a content provider
  6193. {
  6194. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6195. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6196. MultipartFormDataWriter writer("custom-boundary_123");
  6197. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6198. std::string body;
  6199. for (const auto &item : items) {
  6200. body += writer.item_begin(item);
  6201. body += item.content;
  6202. body += MultipartFormDataWriter::item_end();
  6203. }
  6204. body += writer.finish();
  6205. EXPECT_EQ(body.size(), writer.content_length(items));
  6206. auto res = cli.Post(
  6207. "/post", body.size(),
  6208. [&](size_t offset, size_t length, DataSink &sink) {
  6209. sink.write(body.data() + offset, length);
  6210. return true;
  6211. },
  6212. writer.content_type());
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. }
  6216. }
  6217. TEST_F(ServerTest, PostContentReceiverGzip) {
  6218. cli_.set_compress(true);
  6219. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::OK_200, res->status);
  6222. ASSERT_EQ("content", res->body);
  6223. }
  6224. TEST_F(ServerTest, PutContentReceiver) {
  6225. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. ASSERT_EQ(StatusCode::OK_200, res->status);
  6228. ASSERT_EQ("content", res->body);
  6229. }
  6230. TEST_F(ServerTest, PatchContentReceiver) {
  6231. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6233. ASSERT_EQ(StatusCode::OK_200, res->status);
  6234. ASSERT_EQ("content", res->body);
  6235. }
  6236. template <typename ClientType>
  6237. void TestWithHeadersAndContentReceiver(
  6238. ClientType &cli,
  6239. std::function<Result(ClientType &, const std::string &, const Headers &,
  6240. const std::string &, const std::string &,
  6241. ContentReceiver, DownloadProgress)>
  6242. request_func) {
  6243. Headers headers;
  6244. headers.emplace("X-Custom-Header", "test-value");
  6245. std::string received_body;
  6246. auto res = request_func(
  6247. cli, "/content_receiver", headers, "content", "application/json",
  6248. [&](const char *data, size_t data_length) {
  6249. received_body.append(data, data_length);
  6250. return true;
  6251. },
  6252. nullptr);
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. EXPECT_EQ(StatusCode::OK_200, res->status);
  6255. EXPECT_EQ("content", received_body);
  6256. }
  6257. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6258. #ifdef CPPHTTPLIB_SSL_ENABLED
  6259. using ClientT = SSLClient;
  6260. #else
  6261. using ClientT = Client;
  6262. #endif
  6263. TestWithHeadersAndContentReceiver<ClientT>(
  6264. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6265. const std::string &body, const std::string &content_type,
  6266. ContentReceiver receiver, DownloadProgress progress) {
  6267. return cli.Post(path, headers, body, content_type, receiver, progress);
  6268. });
  6269. }
  6270. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6271. #ifdef CPPHTTPLIB_SSL_ENABLED
  6272. using ClientT = SSLClient;
  6273. #else
  6274. using ClientT = Client;
  6275. #endif
  6276. TestWithHeadersAndContentReceiver<ClientT>(
  6277. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6278. const std::string &body, const std::string &content_type,
  6279. ContentReceiver receiver, DownloadProgress progress) {
  6280. return cli.Put(path, headers, body, content_type, receiver, progress);
  6281. });
  6282. }
  6283. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6284. #ifdef CPPHTTPLIB_SSL_ENABLED
  6285. using ClientT = SSLClient;
  6286. #else
  6287. using ClientT = Client;
  6288. #endif
  6289. TestWithHeadersAndContentReceiver<ClientT>(
  6290. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6291. const std::string &body, const std::string &content_type,
  6292. ContentReceiver receiver, DownloadProgress progress) {
  6293. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6294. });
  6295. }
  6296. template <typename ClientType>
  6297. void TestWithHeadersAndContentReceiverWithProgress(
  6298. ClientType &cli,
  6299. std::function<Result(ClientType &, const std::string &, const Headers &,
  6300. const std::string &, const std::string &,
  6301. ContentReceiver, DownloadProgress)>
  6302. request_func) {
  6303. Headers headers;
  6304. headers.emplace("X-Test-Header", "progress-test");
  6305. std::string received_body;
  6306. auto progress_called = false;
  6307. auto res = request_func(
  6308. cli, "/content_receiver", headers, "content", "text/plain",
  6309. [&](const char *data, size_t data_length) {
  6310. received_body.append(data, data_length);
  6311. return true;
  6312. },
  6313. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6314. progress_called = true;
  6315. return true;
  6316. });
  6317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. EXPECT_EQ("content", received_body);
  6320. EXPECT_TRUE(progress_called);
  6321. }
  6322. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6323. #ifdef CPPHTTPLIB_SSL_ENABLED
  6324. using ClientT = SSLClient;
  6325. #else
  6326. using ClientT = Client;
  6327. #endif
  6328. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6329. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6330. const std::string &body, const std::string &content_type,
  6331. ContentReceiver receiver, DownloadProgress progress) {
  6332. return cli.Post(path, headers, body, content_type, receiver, progress);
  6333. });
  6334. }
  6335. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6336. #ifdef CPPHTTPLIB_SSL_ENABLED
  6337. using ClientT = SSLClient;
  6338. #else
  6339. using ClientT = Client;
  6340. #endif
  6341. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6342. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6343. const std::string &body, const std::string &content_type,
  6344. ContentReceiver receiver, DownloadProgress progress) {
  6345. return cli.Put(path, headers, body, content_type, receiver, progress);
  6346. });
  6347. }
  6348. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6349. #ifdef CPPHTTPLIB_SSL_ENABLED
  6350. using ClientT = SSLClient;
  6351. #else
  6352. using ClientT = Client;
  6353. #endif
  6354. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6355. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6356. const std::string &body, const std::string &content_type,
  6357. ContentReceiver receiver, DownloadProgress progress) {
  6358. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6359. });
  6360. }
  6361. template <typename ClientType>
  6362. void TestWithHeadersAndContentReceiverError(
  6363. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6364. const Headers &, const std::string &,
  6365. const std::string &, ContentReceiver)>
  6366. request_func) {
  6367. Headers headers;
  6368. headers.emplace("X-Error-Test", "true");
  6369. std::string received_body;
  6370. auto receiver_failed = false;
  6371. auto res =
  6372. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6373. [&](const char *data, size_t data_length) {
  6374. received_body.append(data, data_length);
  6375. receiver_failed = true;
  6376. return false;
  6377. });
  6378. ASSERT_FALSE(res);
  6379. EXPECT_TRUE(receiver_failed);
  6380. }
  6381. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6382. #ifdef CPPHTTPLIB_SSL_ENABLED
  6383. using ClientT = SSLClient;
  6384. #else
  6385. using ClientT = Client;
  6386. #endif
  6387. TestWithHeadersAndContentReceiverError<ClientT>(
  6388. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6389. const std::string &body, const std::string &content_type,
  6390. ContentReceiver receiver) {
  6391. return cli.Post(path, headers, body, content_type, receiver);
  6392. });
  6393. }
  6394. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6395. #ifdef CPPHTTPLIB_SSL_ENABLED
  6396. using ClientT = SSLClient;
  6397. #else
  6398. using ClientT = Client;
  6399. #endif
  6400. TestWithHeadersAndContentReceiverError<ClientT>(
  6401. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6402. const std::string &body, const std::string &content_type,
  6403. ContentReceiver receiver) {
  6404. return cli.Put(path, headers, body, content_type, receiver);
  6405. });
  6406. }
  6407. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6408. #ifdef CPPHTTPLIB_SSL_ENABLED
  6409. using ClientT = SSLClient;
  6410. #else
  6411. using ClientT = Client;
  6412. #endif
  6413. TestWithHeadersAndContentReceiverError<ClientT>(
  6414. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6415. const std::string &body, const std::string &content_type,
  6416. ContentReceiver receiver) {
  6417. return cli.Patch(path, headers, body, content_type, receiver);
  6418. });
  6419. }
  6420. TEST_F(ServerTest, PostQueryStringAndBody) {
  6421. auto res =
  6422. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. ASSERT_EQ(StatusCode::OK_200, res->status);
  6425. }
  6426. TEST_F(ServerTest, HTTP2Magic) {
  6427. Request req;
  6428. req.method = "PRI";
  6429. req.path = "*";
  6430. req.body = "SM";
  6431. auto res = std::make_shared<Response>();
  6432. auto error = Error::Success;
  6433. auto ret = cli_.send(req, *res, error);
  6434. ASSERT_TRUE(ret);
  6435. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6436. }
  6437. TEST_F(ServerTest, KeepAlive) {
  6438. auto res = cli_.Get("/hi");
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::OK_200, res->status);
  6441. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6442. EXPECT_EQ("Hello World!", res->body);
  6443. res = cli_.Get("/hi");
  6444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6445. EXPECT_EQ(StatusCode::OK_200, res->status);
  6446. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6447. EXPECT_EQ("Hello World!", res->body);
  6448. res = cli_.Get("/hi");
  6449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6450. EXPECT_EQ(StatusCode::OK_200, res->status);
  6451. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6452. EXPECT_EQ("Hello World!", res->body);
  6453. res = cli_.Get("/not-exist");
  6454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6455. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6456. res = cli_.Post("/empty", "", "text/plain");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::OK_200, res->status);
  6459. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6460. EXPECT_EQ("empty", res->body);
  6461. EXPECT_EQ("close", res->get_header_value("Connection"));
  6462. res = cli_.Post(
  6463. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6464. "text/plain");
  6465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6466. EXPECT_EQ(StatusCode::OK_200, res->status);
  6467. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6468. EXPECT_EQ("empty", res->body);
  6469. cli_.set_keep_alive(false);
  6470. res = cli_.Get("/last-request");
  6471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6472. EXPECT_EQ(StatusCode::OK_200, res->status);
  6473. EXPECT_EQ("close", res->get_header_value("Connection"));
  6474. }
  6475. TEST_F(ServerTest, TooManyRedirect) {
  6476. cli_.set_follow_location(true);
  6477. auto res = cli_.Get("/redirect/0");
  6478. ASSERT_TRUE(!res);
  6479. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6480. }
  6481. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6482. Request req;
  6483. req.method = "FOOBAR";
  6484. req.path = "/hi";
  6485. cli_.set_keep_alive(true);
  6486. auto res = cli_.send(req);
  6487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6488. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6489. EXPECT_EQ("close", res->get_header_value("Connection"));
  6490. EXPECT_FALSE(cli_.is_socket_open());
  6491. }
  6492. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6493. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6494. TEST_F(ServerTest, Gzip) {
  6495. Headers headers;
  6496. headers.emplace("Accept-Encoding", "gzip, deflate");
  6497. auto res = cli_.Get("/compress", headers);
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6500. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6501. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6502. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6503. "7890123456789012345678901234567890",
  6504. res->body);
  6505. EXPECT_EQ(StatusCode::OK_200, res->status);
  6506. }
  6507. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6508. Headers headers;
  6509. headers.emplace("Accept-Encoding", "gzip, deflate");
  6510. auto res = cli_.Get("/compress-with-charset", headers);
  6511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6512. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6513. EXPECT_EQ("application/json; charset=utf-8",
  6514. res->get_header_value("Content-Type"));
  6515. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6516. "7890123456789012345678901234567890",
  6517. res->body);
  6518. EXPECT_EQ(StatusCode::OK_200, res->status);
  6519. }
  6520. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6521. Headers headers;
  6522. headers.emplace("Accept-Encoding", "");
  6523. auto res = cli_.Get("/compress", headers);
  6524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6525. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6526. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6527. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6528. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6529. "7890123456789012345678901234567890",
  6530. res->body);
  6531. EXPECT_EQ(StatusCode::OK_200, res->status);
  6532. }
  6533. TEST_F(ServerTest, GzipWithContentReceiver) {
  6534. Headers headers;
  6535. headers.emplace("Accept-Encoding", "gzip, deflate");
  6536. std::string body;
  6537. auto res = cli_.Get("/compress", headers,
  6538. [&](const char *data, uint64_t data_length) {
  6539. EXPECT_EQ(100U, data_length);
  6540. body.append(data, data_length);
  6541. return true;
  6542. });
  6543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6544. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6545. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6546. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6547. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6548. "7890123456789012345678901234567890",
  6549. body);
  6550. EXPECT_EQ(StatusCode::OK_200, res->status);
  6551. }
  6552. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6553. Headers headers;
  6554. headers.emplace("Accept-Encoding", "gzip, deflate");
  6555. cli_.set_decompress(false);
  6556. auto res = cli_.Get("/compress", headers);
  6557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6558. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6559. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6560. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6561. EXPECT_EQ(33U, res->body.size());
  6562. EXPECT_EQ(StatusCode::OK_200, res->status);
  6563. }
  6564. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6565. Headers headers;
  6566. headers.emplace("Accept-Encoding", "");
  6567. std::string body;
  6568. auto res = cli_.Get("/compress", headers,
  6569. [&](const char *data, uint64_t data_length) {
  6570. EXPECT_EQ(100U, data_length);
  6571. body.append(data, data_length);
  6572. return true;
  6573. });
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6577. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6578. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6579. "7890123456789012345678901234567890",
  6580. body);
  6581. EXPECT_EQ(StatusCode::OK_200, res->status);
  6582. }
  6583. TEST_F(ServerTest, NoGzip) {
  6584. Headers headers;
  6585. headers.emplace("Accept-Encoding", "gzip, deflate");
  6586. auto res = cli_.Get("/nocompress", headers);
  6587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6588. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6589. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6590. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6591. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6592. "7890123456789012345678901234567890",
  6593. res->body);
  6594. EXPECT_EQ(StatusCode::OK_200, res->status);
  6595. }
  6596. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6597. Headers headers;
  6598. headers.emplace("Accept-Encoding", "gzip, deflate");
  6599. std::string body;
  6600. auto res = cli_.Get("/nocompress", headers,
  6601. [&](const char *data, uint64_t data_length) {
  6602. EXPECT_EQ(100U, data_length);
  6603. body.append(data, data_length);
  6604. return true;
  6605. });
  6606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6607. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6608. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6609. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6610. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6611. "7890123456789012345678901234567890",
  6612. body);
  6613. EXPECT_EQ(StatusCode::OK_200, res->status);
  6614. }
  6615. TEST_F(ServerTest, MultipartFormDataGzip) {
  6616. UploadFormDataItems items = {
  6617. {"key1", "test", "", ""},
  6618. {"key2", "--abcdefg123", "", ""},
  6619. };
  6620. cli_.set_compress(true);
  6621. auto res = cli_.Post("/compress-multipart", items);
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. EXPECT_EQ(StatusCode::OK_200, res->status);
  6624. }
  6625. #endif
  6626. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6627. TEST_F(ServerTest, Brotli) {
  6628. Headers headers;
  6629. headers.emplace("Accept-Encoding", "br");
  6630. auto res = cli_.Get("/compress", headers);
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6634. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6635. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6636. "7890123456789012345678901234567890",
  6637. res->body);
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. }
  6640. #endif
  6641. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6642. TEST_F(ServerTest, Zstd) {
  6643. Headers headers;
  6644. headers.emplace("Accept-Encoding", "zstd");
  6645. auto res = cli_.Get("/compress", headers);
  6646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6647. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6649. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6650. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6651. "7890123456789012345678901234567890",
  6652. res->body);
  6653. EXPECT_EQ(StatusCode::OK_200, res->status);
  6654. }
  6655. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6656. Headers headers;
  6657. headers.emplace("Accept-Encoding", "");
  6658. auto res = cli_.Get("/compress", headers);
  6659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6660. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6661. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6662. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6663. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6664. "7890123456789012345678901234567890",
  6665. res->body);
  6666. EXPECT_EQ(StatusCode::OK_200, res->status);
  6667. }
  6668. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6669. Headers headers;
  6670. headers.emplace("Accept-Encoding", "zstd");
  6671. std::string body;
  6672. auto res = cli_.Get("/compress", headers,
  6673. [&](const char *data, uint64_t data_length) {
  6674. EXPECT_EQ(100U, data_length);
  6675. body.append(data, data_length);
  6676. return true;
  6677. });
  6678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6679. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6680. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6681. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6682. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6683. "7890123456789012345678901234567890",
  6684. body);
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. }
  6687. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6688. Headers headers;
  6689. headers.emplace("Accept-Encoding", "zstd");
  6690. cli_.set_decompress(false);
  6691. auto res = cli_.Get("/compress", headers);
  6692. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6693. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6694. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6695. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6699. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6700. EXPECT_EQ(StatusCode::OK_200, res->status);
  6701. ASSERT_EQ(26U, res->body.size());
  6702. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6703. 0);
  6704. }
  6705. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6706. Headers headers;
  6707. headers.emplace("Accept-Encoding", "");
  6708. std::string body;
  6709. auto res = cli_.Get("/compress", headers,
  6710. [&](const char *data, uint64_t data_length) {
  6711. EXPECT_EQ(100U, data_length);
  6712. body.append(data, data_length);
  6713. return true;
  6714. });
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6717. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6718. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6719. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6720. "7890123456789012345678901234567890",
  6721. body);
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. }
  6724. TEST_F(ServerTest, NoZstd) {
  6725. Headers headers;
  6726. headers.emplace("Accept-Encoding", "zstd");
  6727. auto res = cli_.Get("/nocompress", headers);
  6728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6729. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6730. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6731. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6732. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6733. "7890123456789012345678901234567890",
  6734. res->body);
  6735. EXPECT_EQ(StatusCode::OK_200, res->status);
  6736. }
  6737. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6738. Headers headers;
  6739. headers.emplace("Accept-Encoding", "zstd");
  6740. std::string body;
  6741. auto res = cli_.Get("/nocompress", headers,
  6742. [&](const char *data, uint64_t data_length) {
  6743. EXPECT_EQ(100U, data_length);
  6744. body.append(data, data_length);
  6745. return true;
  6746. });
  6747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6748. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6749. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6750. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6751. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6752. "7890123456789012345678901234567890",
  6753. body);
  6754. EXPECT_EQ(StatusCode::OK_200, res->status);
  6755. }
  6756. // TODO: How to enable zstd ??
  6757. TEST_F(ServerTest, MultipartFormDataZstd) {
  6758. UploadFormDataItems items = {
  6759. {"key1", "test", "", ""},
  6760. {"key2", "--abcdefg123", "", ""},
  6761. };
  6762. Headers headers;
  6763. headers.emplace("Accept-Encoding", "zstd");
  6764. cli_.set_compress(true);
  6765. auto res = cli_.Post("/compress-multipart", headers, items);
  6766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6767. EXPECT_EQ(StatusCode::OK_200, res->status);
  6768. }
  6769. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6770. Headers headers;
  6771. headers.emplace("Accept-Encoding", "zstd");
  6772. cli_.set_compress(true);
  6773. auto res = cli_.Put(
  6774. "/put", headers, 3,
  6775. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6776. sink.os << "PUT";
  6777. return true;
  6778. },
  6779. "text/plain");
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::OK_200, res->status);
  6782. EXPECT_EQ("PUT", res->body);
  6783. }
  6784. // Pre-compression logging tests
  6785. TEST_F(ServerTest, PreCompressionLogging) {
  6786. // Test data for compression (matches the actual /compress endpoint content)
  6787. const std::string test_content =
  6788. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6789. "3456789012345678901234567890";
  6790. // Variables to capture logging data
  6791. std::string pre_compression_body;
  6792. std::string pre_compression_content_type;
  6793. std::string pre_compression_content_encoding;
  6794. std::string post_compression_body;
  6795. std::string post_compression_content_type;
  6796. std::string post_compression_content_encoding;
  6797. // Set up pre-compression logger
  6798. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6799. const Response &res) {
  6800. pre_compression_body = res.body;
  6801. pre_compression_content_type = res.get_header_value("Content-Type");
  6802. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6803. });
  6804. // Set up post-compression logger
  6805. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6806. post_compression_body = res.body;
  6807. post_compression_content_type = res.get_header_value("Content-Type");
  6808. post_compression_content_encoding =
  6809. res.get_header_value("Content-Encoding");
  6810. });
  6811. // Test with gzip compression
  6812. Headers headers;
  6813. headers.emplace("Accept-Encoding", "gzip");
  6814. auto res = cli_.Get("/compress", headers);
  6815. // Verify response was compressed
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. EXPECT_EQ(StatusCode::OK_200, res->status);
  6818. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6819. // Verify pre-compression logger captured uncompressed content
  6820. EXPECT_EQ(test_content, pre_compression_body);
  6821. EXPECT_EQ("text/plain", pre_compression_content_type);
  6822. EXPECT_TRUE(pre_compression_content_encoding
  6823. .empty()); // No encoding header before compression
  6824. // Verify post-compression logger captured compressed content
  6825. EXPECT_NE(test_content,
  6826. post_compression_body); // Should be different after compression
  6827. EXPECT_EQ("text/plain", post_compression_content_type);
  6828. EXPECT_EQ("gzip", post_compression_content_encoding);
  6829. // Verify compressed content is smaller
  6830. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6831. }
  6832. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6833. const std::string test_content =
  6834. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6835. "3456789012345678901234567890";
  6836. std::string pre_compression_body;
  6837. std::string post_compression_body;
  6838. svr_.set_pre_compression_logger(
  6839. [&](const Request & /*req*/, const Response &res) {
  6840. pre_compression_body = res.body;
  6841. });
  6842. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6843. post_compression_body = res.body;
  6844. });
  6845. Headers headers;
  6846. headers.emplace("Accept-Encoding", "br");
  6847. auto res = cli_.Get("/compress", headers);
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6851. // Verify pre-compression content is uncompressed
  6852. EXPECT_EQ(test_content, pre_compression_body);
  6853. // Verify post-compression content is compressed
  6854. EXPECT_NE(test_content, post_compression_body);
  6855. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6856. }
  6857. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6858. const std::string test_content =
  6859. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6860. "3456789012345678901234567890";
  6861. std::string pre_compression_body;
  6862. std::string post_compression_body;
  6863. svr_.set_pre_compression_logger(
  6864. [&](const Request & /*req*/, const Response &res) {
  6865. pre_compression_body = res.body;
  6866. });
  6867. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6868. post_compression_body = res.body;
  6869. });
  6870. // Request without compression (use /nocompress endpoint)
  6871. Headers headers;
  6872. auto res = cli_.Get("/nocompress", headers);
  6873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6874. EXPECT_EQ(StatusCode::OK_200, res->status);
  6875. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6876. // Pre-compression logger should not be called when no compression is applied
  6877. EXPECT_TRUE(
  6878. pre_compression_body.empty()); // Pre-compression logger not called
  6879. EXPECT_EQ(
  6880. test_content,
  6881. post_compression_body); // Post-compression logger captures final content
  6882. }
  6883. TEST_F(ServerTest, LoggerSeesContentLength) {
  6884. size_t logged_content_length = 0;
  6885. std::string logged_content_length_header;
  6886. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6887. logged_content_length = res.content_length_;
  6888. logged_content_length_header = res.get_header_value("Content-Length");
  6889. });
  6890. auto res = cli_.Get("/nocompress");
  6891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6892. EXPECT_EQ(StatusCode::OK_200, res->status);
  6893. EXPECT_EQ(res->body.size(), logged_content_length);
  6894. EXPECT_EQ(std::to_string(logged_content_length),
  6895. logged_content_length_header);
  6896. }
  6897. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6898. const std::string test_content =
  6899. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6900. "3456789012345678901234567890";
  6901. std::string pre_compression_body;
  6902. bool pre_logger_called = false;
  6903. // Set only pre-compression logger
  6904. svr_.set_pre_compression_logger(
  6905. [&](const Request & /*req*/, const Response &res) {
  6906. pre_compression_body = res.body;
  6907. pre_logger_called = true;
  6908. });
  6909. Headers headers;
  6910. headers.emplace("Accept-Encoding", "gzip");
  6911. auto res = cli_.Get("/compress", headers);
  6912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6913. EXPECT_EQ(StatusCode::OK_200, res->status);
  6914. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6915. // Verify pre-compression logger was called
  6916. EXPECT_TRUE(pre_logger_called);
  6917. EXPECT_EQ(test_content, pre_compression_body);
  6918. }
  6919. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6920. {
  6921. // Test with Expect: 100-continue header - success case
  6922. // Server returns 100 Continue, client sends body, server returns 200 OK
  6923. Request req;
  6924. req.method = "POST";
  6925. req.path = "/post-large";
  6926. req.set_header("Expect", "100-continue");
  6927. req.body = LARGE_DATA;
  6928. Response res;
  6929. auto error = Error::Success;
  6930. cli_.set_keep_alive(true);
  6931. auto ret = cli_.send(req, res, error);
  6932. EXPECT_TRUE(ret);
  6933. EXPECT_EQ(StatusCode::OK_200, res.status);
  6934. EXPECT_EQ(LARGE_DATA, res.body);
  6935. }
  6936. {
  6937. // Test with Expect: 100-continue header - error case
  6938. // Client should not send the body when server returns an error
  6939. Request req;
  6940. req.method = "POST";
  6941. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6942. req.set_header("Expect", "100-continue");
  6943. req.body = LARGE_DATA;
  6944. Response res;
  6945. auto error = Error::Success;
  6946. auto start = std::chrono::high_resolution_clock::now();
  6947. cli_.set_keep_alive(true);
  6948. auto ret = cli_.send(req, res, error);
  6949. auto end = std::chrono::high_resolution_clock::now();
  6950. auto elapsed =
  6951. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6952. .count();
  6953. // With Expect: 100-continue, request completes successfully but with error
  6954. EXPECT_TRUE(ret);
  6955. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6956. EXPECT_EQ("close", res.get_header_value("Connection"));
  6957. EXPECT_FALSE(cli_.is_socket_open());
  6958. EXPECT_LE(elapsed, 2000);
  6959. }
  6960. {
  6961. // Send an extra GET request to ensure error recovery without hanging
  6962. Request req;
  6963. req.method = "GET";
  6964. req.path = "/hi";
  6965. auto start = std::chrono::high_resolution_clock::now();
  6966. auto res = cli_.send(req);
  6967. auto end = std::chrono::high_resolution_clock::now();
  6968. auto elapsed =
  6969. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6970. .count();
  6971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6972. EXPECT_EQ(StatusCode::OK_200, res->status);
  6973. EXPECT_EQ("Hello World!", res->body);
  6974. EXPECT_LE(elapsed, 500);
  6975. }
  6976. }
  6977. TEST(ZstdDecompressor, ChunkedDecompression) {
  6978. std::string data;
  6979. for (size_t i = 0; i < 32 * 1024; ++i) {
  6980. data.push_back(static_cast<char>('a' + i % 26));
  6981. }
  6982. std::string compressed_data;
  6983. {
  6984. httplib::detail::zstd_compressor compressor;
  6985. bool result = compressor.compress(
  6986. data.data(), data.size(),
  6987. /*last=*/true,
  6988. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6989. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6990. compressed_data_size);
  6991. return true;
  6992. });
  6993. ASSERT_TRUE(result);
  6994. }
  6995. std::string decompressed_data;
  6996. {
  6997. httplib::detail::zstd_decompressor decompressor;
  6998. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6999. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7000. size_t chunk_size = 130;
  7001. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7002. chunk_begin += chunk_size) {
  7003. size_t current_chunk_size =
  7004. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7005. bool result = decompressor.decompress(
  7006. compressed_data.data() + chunk_begin, current_chunk_size,
  7007. [&](const char *decompressed_data_chunk,
  7008. size_t decompressed_data_chunk_size) {
  7009. decompressed_data.insert(decompressed_data.size(),
  7010. decompressed_data_chunk,
  7011. decompressed_data_chunk_size);
  7012. return true;
  7013. });
  7014. ASSERT_TRUE(result);
  7015. }
  7016. }
  7017. ASSERT_EQ(data, decompressed_data);
  7018. }
  7019. TEST(ZstdDecompressor, Decompress) {
  7020. std::string original_text = "Compressed with ZSTD";
  7021. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7022. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7023. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7024. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7025. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7026. std::string decompressed_data;
  7027. {
  7028. httplib::detail::zstd_decompressor decompressor;
  7029. bool result = decompressor.decompress(
  7030. compressed_data.data(), compressed_data.size(),
  7031. [&](const char *decompressed_data_chunk,
  7032. size_t decompressed_data_chunk_size) {
  7033. decompressed_data.insert(decompressed_data.size(),
  7034. decompressed_data_chunk,
  7035. decompressed_data_chunk_size);
  7036. return true;
  7037. });
  7038. ASSERT_TRUE(result);
  7039. }
  7040. ASSERT_EQ(original_text, decompressed_data);
  7041. }
  7042. #endif
  7043. // Sends a raw request to a server listening at HOST:PORT.
  7044. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7045. std::string *resp = nullptr) {
  7046. auto error = Error::Success;
  7047. auto client_sock = detail::create_client_socket(
  7048. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  7049. /*connection_timeout_sec=*/5, 0,
  7050. /*read_timeout_sec=*/5, 0,
  7051. /*write_timeout_sec=*/5, 0, std::string(), error);
  7052. if (client_sock == INVALID_SOCKET) { return false; }
  7053. auto ret = detail::process_client_socket(
  7054. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7055. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7056. if (req.size() !=
  7057. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7058. return false;
  7059. }
  7060. char buf[512];
  7061. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7062. while (line_reader.getline()) {
  7063. if (resp) { *resp += line_reader.ptr(); }
  7064. }
  7065. return true;
  7066. });
  7067. detail::close_socket(client_sock);
  7068. return ret;
  7069. }
  7070. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7071. Server svr;
  7072. std::string header_value;
  7073. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7074. header_value = req.get_header_value("foo");
  7075. res.set_content("ok", "text/plain");
  7076. });
  7077. thread t = thread([&] { svr.listen(HOST, PORT); });
  7078. auto se = detail::scope_exit([&] {
  7079. svr.stop();
  7080. t.join();
  7081. ASSERT_FALSE(svr.is_running());
  7082. });
  7083. svr.wait_until_ready();
  7084. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7085. // like characters are not treated the same - use vertical tab and escape.
  7086. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7087. "foo: \t \v bar \x1B\t \r\n"
  7088. "Connection: close\r\n"
  7089. "\r\n";
  7090. std::string res;
  7091. ASSERT_TRUE(send_request(5, req, &res));
  7092. EXPECT_EQ(header_value, "");
  7093. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7094. }
  7095. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7096. Server svr;
  7097. std::string received;
  7098. svr.Get("/order", [&](const Request &req, Response &res) {
  7099. received = headers_to_string(req.headers);
  7100. res.set_content("ok", "text/plain");
  7101. });
  7102. thread t = thread([&] { svr.listen(HOST, PORT); });
  7103. auto se = detail::scope_exit([&] {
  7104. svr.stop();
  7105. t.join();
  7106. ASSERT_FALSE(svr.is_running());
  7107. });
  7108. svr.wait_until_ready();
  7109. const std::string req = "GET /order HTTP/1.1\r\n"
  7110. "X-First: 1\r\n"
  7111. "X-Dup: a\r\n"
  7112. "X-Second: 2\r\n"
  7113. "X-Dup: b\r\n"
  7114. "Connection: close\r\n"
  7115. "\r\n";
  7116. std::string res;
  7117. ASSERT_TRUE(send_request(5, req, &res));
  7118. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7119. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7120. }
  7121. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7122. Server svr;
  7123. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7124. res.set_header("Set-Cookie", "first=1");
  7125. res.set_header("X-Between", "y");
  7126. res.set_header("Set-Cookie", "second=2");
  7127. res.set_content("ok", "text/plain");
  7128. });
  7129. thread t = thread([&] { svr.listen(HOST, PORT); });
  7130. auto se = detail::scope_exit([&] {
  7131. svr.stop();
  7132. t.join();
  7133. ASSERT_FALSE(svr.is_running());
  7134. });
  7135. svr.wait_until_ready();
  7136. Client cli(HOST, PORT);
  7137. auto res = cli.Get("/cookies");
  7138. ASSERT_TRUE(res);
  7139. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7140. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7141. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7142. }
  7143. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7144. Server svr;
  7145. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7146. auto i = new int(0);
  7147. res.set_header("Trailer", "X-Safe, X-Reflected");
  7148. res.set_chunked_content_provider(
  7149. "text/plain",
  7150. [i](size_t /*offset*/, DataSink &sink) {
  7151. if (*i == 0) {
  7152. sink.os << "body";
  7153. } else {
  7154. Headers trailer;
  7155. // A valid trailer that must survive.
  7156. trailer.emplace("X-Safe", "safe");
  7157. // Attacker-controlled value carrying CR/LF (response splitting).
  7158. trailer.emplace("X-Reflected",
  7159. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7160. // Attacker-controlled name carrying CR/LF.
  7161. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7162. sink.done_with_trailer(trailer);
  7163. }
  7164. (*i)++;
  7165. return true;
  7166. },
  7167. [i](bool /*success*/) { delete i; });
  7168. });
  7169. thread t = thread([&] { svr.listen(HOST, PORT); });
  7170. auto se = detail::scope_exit([&] {
  7171. svr.stop();
  7172. t.join();
  7173. ASSERT_FALSE(svr.is_running());
  7174. });
  7175. svr.wait_until_ready();
  7176. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7177. "Host: " + HOST +
  7178. "\r\n"
  7179. "Connection: close\r\n"
  7180. "\r\n";
  7181. std::string res;
  7182. ASSERT_TRUE(send_request(5, req, &res));
  7183. // The injected fields must not appear anywhere in the raw response.
  7184. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7185. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7186. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7187. // Invalid trailers are dropped entirely, matching set_header().
  7188. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7189. // The valid trailer still passes through.
  7190. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7191. }
  7192. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7193. Server svr;
  7194. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7195. // res.headers is a public field an application can populate directly,
  7196. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7197. // A valid header that must survive.
  7198. res.headers.emplace("X-Safe", "safe");
  7199. // Attacker-controlled value carrying CR/LF (response splitting).
  7200. res.headers.emplace("X-Reflected",
  7201. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7202. // Attacker-controlled name carrying CR/LF.
  7203. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7204. res.set_content("body", "text/plain");
  7205. });
  7206. thread t = thread([&] { svr.listen(HOST, PORT); });
  7207. auto se = detail::scope_exit([&] {
  7208. svr.stop();
  7209. t.join();
  7210. ASSERT_FALSE(svr.is_running());
  7211. });
  7212. svr.wait_until_ready();
  7213. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7214. "Host: " + HOST +
  7215. "\r\n"
  7216. "Connection: close\r\n"
  7217. "\r\n";
  7218. std::string res;
  7219. ASSERT_TRUE(send_request(5, req, &res));
  7220. // The injected fields must not appear anywhere in the raw response.
  7221. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7222. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7223. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7224. // Invalid headers are dropped entirely, matching set_header().
  7225. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7226. // The valid header still passes through.
  7227. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7228. }
  7229. // Forward declaration: in split builds split.py strips `inline` and moves the
  7230. // definition into httplib.cc, so detail::write_request_line is not visible from
  7231. // the public httplib.h. Re-declaring it here lets the tests link against the
  7232. // symbol in both header-only and split builds.
  7233. namespace httplib {
  7234. namespace detail {
  7235. ssize_t write_request_line(Stream &strm, const std::string &method,
  7236. const std::string &path);
  7237. } // namespace detail
  7238. } // namespace httplib
  7239. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7240. // A well-formed target is written verbatim.
  7241. {
  7242. detail::BufferStream strm;
  7243. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7244. EXPECT_GT(n, 0);
  7245. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7246. }
  7247. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7248. // otherwise it splits the request line and injects a header or a whole
  7249. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7250. // when path encoding is disabled.
  7251. const std::string evil_targets[] = {
  7252. "/a\r\nInjected: pwned",
  7253. "/a\rInjected",
  7254. "/a\nInjected",
  7255. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7256. };
  7257. for (const auto &evil : evil_targets) {
  7258. detail::BufferStream strm;
  7259. auto n = detail::write_request_line(strm, "GET", evil);
  7260. EXPECT_LT(n, 0);
  7261. EXPECT_TRUE(strm.get_buffer().empty());
  7262. }
  7263. }
  7264. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7265. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7266. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7267. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7268. // client must fail cleanly with Error::Write instead of putting a
  7269. // request-line-less, header-injecting request on the wire.
  7270. Server svr;
  7271. svr.Get("/a", [](const Request &, Response &res) {
  7272. res.set_content("ok", "text/plain");
  7273. });
  7274. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7275. auto se = detail::scope_exit([&] {
  7276. svr.stop();
  7277. thread.join();
  7278. ASSERT_FALSE(svr.is_running());
  7279. });
  7280. svr.wait_until_ready();
  7281. {
  7282. Client cli(HOST, PORT);
  7283. cli.set_path_encode(false);
  7284. // The request is rejected before anything is written, so the connection
  7285. // stays silent and the subsequent response read would otherwise block for
  7286. // the full default read timeout. Shorten it -- the assertion is on the
  7287. // error, not the timeout.
  7288. cli.set_read_timeout(1, 0);
  7289. auto res = cli.Get("/a\r\nInjected: pwned");
  7290. EXPECT_FALSE(res);
  7291. EXPECT_EQ(Error::Write, res.error());
  7292. }
  7293. }
  7294. // Sends a raw request and verifies that there isn't a crash or exception.
  7295. static void test_raw_request(const std::string &req,
  7296. std::string *out = nullptr) {
  7297. Server svr;
  7298. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7299. res.set_content("ok", "text/plain");
  7300. });
  7301. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7302. res.set_content("ok", "text/plain");
  7303. });
  7304. svr.Get("/header_field_value_check",
  7305. [&](const Request & /*req*/, Response &res) {
  7306. res.set_content("ok", "text/plain");
  7307. });
  7308. // Server read timeout must be longer than the client read timeout for the
  7309. // bug to reproduce, probably to force the server to process a request
  7310. // without a trailing blank line.
  7311. const time_t client_read_timeout_sec = 1;
  7312. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7313. bool listen_thread_ok = false;
  7314. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7315. auto se = detail::scope_exit([&] {
  7316. svr.stop();
  7317. t.join();
  7318. ASSERT_FALSE(svr.is_running());
  7319. EXPECT_TRUE(listen_thread_ok);
  7320. });
  7321. svr.wait_until_ready();
  7322. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7323. }
  7324. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7325. // A certain header line causes an exception if the header property is parsed
  7326. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7327. test_raw_request(
  7328. "GET /hi HTTP/1.1\r\n"
  7329. " : "
  7330. " "
  7331. " ");
  7332. }
  7333. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7334. // A certain header line causes an exception if the header property *name* is
  7335. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7336. // greedy matcher and requires backtracking when there are a lot of ":"
  7337. // characters.
  7338. // This occurs with libc++ but not libstdc++.
  7339. test_raw_request(
  7340. "GET /hi HTTP/1.1\r\n"
  7341. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7342. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7343. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7344. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7345. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7346. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7347. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7348. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7349. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7350. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7351. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7352. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7353. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7354. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7355. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7356. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7357. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7358. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7359. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7360. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7361. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7362. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7363. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7364. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7365. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7366. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7367. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7368. "&&&%%%");
  7369. }
  7370. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7371. // Make sure this doesn't crash the server.
  7372. // In a previous version of the header line regex, the "\r" rendered the line
  7373. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7374. // a new position where the leading white space ended and the field value
  7375. // began.
  7376. // The crash occurs with libc++ but not libstdc++.
  7377. test_raw_request("GET /hi HTTP/1.1\r\n"
  7378. "a:" +
  7379. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7380. "\r\n"
  7381. "\r\n");
  7382. }
  7383. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7384. std::string out;
  7385. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7386. "Content-Type: text/plain\r\n"
  7387. "Transfer-Encoding: chunked\r\n"
  7388. "\r\n"
  7389. "nothex\r\n",
  7390. &out);
  7391. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7392. }
  7393. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7394. std::string out;
  7395. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7396. "Content-Type: text/plain\r\n"
  7397. "Transfer-Encoding: chunked\r\n"
  7398. "\r\n"
  7399. "3\r\n"
  7400. "xyz\r\n"
  7401. "NaN\r\n",
  7402. &out);
  7403. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7404. }
  7405. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7406. std::string out;
  7407. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7408. "Content-Type: text/plain\r\n"
  7409. "Transfer-Encoding: chunked\r\n"
  7410. "\r\n"
  7411. // Length is too large for 64 bits.
  7412. "1ffffffffffffffff\r\n"
  7413. "xyz\r\n",
  7414. &out);
  7415. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7416. }
  7417. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7418. test_raw_request("GET /hi HTTP/1.1\r\n"
  7419. "Content-Type: text/plain\r\n\r");
  7420. }
  7421. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7422. std::string out;
  7423. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7424. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7425. }
  7426. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7427. Server svr;
  7428. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7429. EXPECT_TRUE(!req.remote_addr.empty());
  7430. });
  7431. thread t = thread([&] { svr.listen(HOST, PORT); });
  7432. auto se = detail::scope_exit([&] {
  7433. svr.stop();
  7434. t.join();
  7435. ASSERT_FALSE(svr.is_running());
  7436. });
  7437. svr.wait_until_ready();
  7438. // Send an invalid request line to trigger Bad Request
  7439. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7440. std::string out;
  7441. ASSERT_TRUE(send_request(5, bad_req, &out));
  7442. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7443. }
  7444. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7445. std::string out;
  7446. std::string request(
  7447. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7448. test_raw_request(request, &out);
  7449. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7450. }
  7451. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7452. std::string out;
  7453. std::string request(
  7454. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7455. test_raw_request(request, &out);
  7456. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7457. }
  7458. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7459. std::string out;
  7460. std::string request(
  7461. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7462. test_raw_request(request, &out);
  7463. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7464. }
  7465. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7466. std::string out;
  7467. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7468. "Test: \r\n\r\n",
  7469. &out);
  7470. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7471. }
  7472. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7473. Server svr;
  7474. std::string x_custom;
  7475. std::string cookie;
  7476. std::string xff;
  7477. std::string x_unicode;
  7478. std::string x_iis;
  7479. svr.Get("/check", [&](const Request &req, Response &res) {
  7480. x_custom = req.get_header_value("X-Custom");
  7481. cookie = req.get_header_value("Cookie");
  7482. xff = req.get_header_value("X-Forwarded-For");
  7483. x_unicode = req.get_header_value("X-Unicode");
  7484. x_iis = req.get_header_value("X-IIS");
  7485. res.set_content("ok", "text/plain");
  7486. });
  7487. thread t = thread([&] { svr.listen(HOST, PORT); });
  7488. auto se = detail::scope_exit([&] {
  7489. svr.stop();
  7490. t.join();
  7491. ASSERT_FALSE(svr.is_running());
  7492. });
  7493. svr.wait_until_ready();
  7494. const std::string req = "GET /check HTTP/1.1\r\n"
  7495. "Host: localhost\r\n"
  7496. "X-Custom: a%0D%0AInjected: b\r\n"
  7497. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7498. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7499. "X-Unicode: %E3%81%82\r\n"
  7500. "X-IIS: %u00E9\r\n"
  7501. "Connection: close\r\n"
  7502. "\r\n";
  7503. std::string res;
  7504. ASSERT_TRUE(send_request(5, req, &res));
  7505. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7506. // Every value must be returned verbatim (wire form), with no decoding.
  7507. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7508. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7509. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7510. EXPECT_EQ("%E3%81%82", x_unicode);
  7511. EXPECT_EQ("%u00E9", x_iis);
  7512. }
  7513. // Applications that previously relied on automatic percent-decoding can
  7514. // reproduce the old behavior by explicitly calling decode_path_component()
  7515. // or, for RFC 3986 conformance, decode_uri_component().
  7516. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7517. Server svr;
  7518. std::string decoded;
  7519. svr.Get("/check", [&](const Request &req, Response &res) {
  7520. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7521. res.set_content("ok", "text/plain");
  7522. });
  7523. thread t = thread([&] { svr.listen(HOST, PORT); });
  7524. auto se = detail::scope_exit([&] {
  7525. svr.stop();
  7526. t.join();
  7527. ASSERT_FALSE(svr.is_running());
  7528. });
  7529. svr.wait_until_ready();
  7530. const std::string req = "GET /check HTTP/1.1\r\n"
  7531. "Host: localhost\r\n"
  7532. "X-Custom: hello%20world\r\n"
  7533. "Connection: close\r\n"
  7534. "\r\n";
  7535. std::string res;
  7536. ASSERT_TRUE(send_request(5, req, &res));
  7537. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7538. EXPECT_EQ("hello world", decoded);
  7539. }
  7540. // Regression test for #2033. Browsers send Referer values that include
  7541. // percent-encoded characters such as %0A inside the URL. Decoding the
  7542. // header value would either trip the post-decode CR/LF/NUL guard (the
  7543. // original bug, returning 400) or, after that guard was relaxed, silently
  7544. // store a literal LF — both unacceptable. The wire form must round-trip.
  7545. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7546. Server svr;
  7547. std::string referer;
  7548. svr.Get("/check", [&](const Request &req, Response &res) {
  7549. referer = req.get_header_value("Referer");
  7550. res.set_content("ok", "text/plain");
  7551. });
  7552. thread t = thread([&] { svr.listen(HOST, PORT); });
  7553. auto se = detail::scope_exit([&] {
  7554. svr.stop();
  7555. t.join();
  7556. ASSERT_FALSE(svr.is_running());
  7557. });
  7558. svr.wait_until_ready();
  7559. const std::string req = "GET /check HTTP/1.1\r\n"
  7560. "Host: localhost\r\n"
  7561. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7562. "Connection: close\r\n"
  7563. "\r\n";
  7564. std::string res;
  7565. ASSERT_TRUE(send_request(5, req, &res));
  7566. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7567. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7568. }
  7569. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7570. Server svr;
  7571. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7572. res.set_header("Cache-Control", "no-cache");
  7573. res.set_chunked_content_provider(
  7574. "text/event-stream", [](size_t offset, DataSink &sink) {
  7575. std::string s = "data:";
  7576. s += std::to_string(offset);
  7577. s += "\n\n";
  7578. auto ret = sink.write(s.data(), s.size());
  7579. EXPECT_TRUE(ret);
  7580. std::this_thread::sleep_for(std::chrono::seconds(1));
  7581. return true;
  7582. });
  7583. });
  7584. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7585. svr.wait_until_ready();
  7586. Client client(HOST, PORT);
  7587. const Headers headers = {{"Accept", "text/event-stream"}};
  7588. auto get_thread = std::thread([&client, &headers]() {
  7589. auto res = client.Get(
  7590. "/events", headers,
  7591. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7592. });
  7593. auto se = detail::scope_exit([&] {
  7594. svr.stop();
  7595. get_thread.join();
  7596. listen_thread.join();
  7597. ASSERT_FALSE(svr.is_running());
  7598. });
  7599. // Give GET time to get a few messages.
  7600. std::this_thread::sleep_for(std::chrono::seconds(2));
  7601. }
  7602. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7603. httplib::Server svr;
  7604. svr.Post("/hi",
  7605. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7606. res.status = StatusCode::OK_200;
  7607. });
  7608. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7609. svr.wait_until_ready();
  7610. Client cli(HOST, PORT);
  7611. auto res = cli.Post("/hi", "data", "text/plain");
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ(StatusCode::OK_200, res->status);
  7614. svr.stop();
  7615. thread.join();
  7616. ASSERT_FALSE(svr.is_running());
  7617. res = cli.Post("/hi", "data", "text/plain");
  7618. ASSERT_FALSE(res);
  7619. }
  7620. TEST(ServerStopTest, ListenFailure) {
  7621. Server svr;
  7622. auto t = thread([&]() {
  7623. auto ret = svr.listen("????", PORT);
  7624. EXPECT_FALSE(ret);
  7625. });
  7626. svr.wait_until_ready();
  7627. svr.stop();
  7628. t.join();
  7629. }
  7630. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7631. TEST(ServerStopTest, Decommision) {
  7632. Server svr;
  7633. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7634. for (int i = 0; i < 4; i++) {
  7635. auto is_even = !(i % 2);
  7636. std::thread t{[&] {
  7637. try {
  7638. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7639. if (is_even) {
  7640. throw std::runtime_error("Some thing that happens to go wrong.");
  7641. }
  7642. svr.listen(HOST, PORT);
  7643. } catch (...) { svr.decommission(); }
  7644. }};
  7645. svr.wait_until_ready();
  7646. // Server is up
  7647. {
  7648. Client cli(HOST, PORT);
  7649. auto res = cli.Get("/hi");
  7650. if (is_even) {
  7651. EXPECT_FALSE(res);
  7652. } else {
  7653. EXPECT_TRUE(res);
  7654. EXPECT_EQ("hi...", res->body);
  7655. }
  7656. }
  7657. svr.stop();
  7658. t.join();
  7659. // Server is down...
  7660. {
  7661. Client cli(HOST, PORT);
  7662. auto res = cli.Get("/hi");
  7663. EXPECT_FALSE(res);
  7664. }
  7665. }
  7666. }
  7667. #endif
  7668. // Helper function for string body upload progress tests
  7669. template <typename SetupHandler, typename ClientCall>
  7670. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7671. ClientCall &&client_call,
  7672. const string &body) {
  7673. Server svr;
  7674. setup_handler(svr);
  7675. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7676. auto se = detail::scope_exit([&] {
  7677. svr.stop();
  7678. t.join();
  7679. });
  7680. svr.wait_until_ready();
  7681. Client cli(HOST, PORT);
  7682. vector<uint64_t> progress_values;
  7683. bool progress_called = false;
  7684. auto res =
  7685. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7686. progress_values.push_back(current);
  7687. progress_called = true;
  7688. return true;
  7689. });
  7690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7691. EXPECT_EQ(200, res->status);
  7692. EXPECT_TRUE(progress_called);
  7693. }
  7694. TEST(UploadProgressTest, PostStringBodyBasic) {
  7695. TestStringBodyUploadProgress(
  7696. [](Server &svr) {
  7697. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7698. res.set_content("received", "text/plain");
  7699. });
  7700. },
  7701. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7702. return cli.Post("/test", body, "text/plain", progress_callback);
  7703. },
  7704. "test data for upload progress");
  7705. }
  7706. TEST(UploadProgressTest, PutStringBodyBasic) {
  7707. TestStringBodyUploadProgress(
  7708. [](Server &svr) {
  7709. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7710. res.set_content("put received", "text/plain");
  7711. });
  7712. },
  7713. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7714. return cli.Put("/test", body, "text/plain", progress_callback);
  7715. },
  7716. "put test data for upload progress");
  7717. }
  7718. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7719. TestStringBodyUploadProgress(
  7720. [](Server &svr) {
  7721. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7722. res.set_content("patch received", "text/plain");
  7723. });
  7724. },
  7725. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7726. return cli.Patch("/test", body, "text/plain", progress_callback);
  7727. },
  7728. "patch test data for upload progress");
  7729. }
  7730. // Helper function for content provider upload progress tests
  7731. template <typename SetupHandler, typename ClientCall>
  7732. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7733. ClientCall &&client_call) {
  7734. Server svr;
  7735. setup_handler(svr);
  7736. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7737. auto se = detail::scope_exit([&] {
  7738. svr.stop();
  7739. t.join();
  7740. });
  7741. svr.wait_until_ready();
  7742. Client cli(HOST, PORT);
  7743. vector<uint64_t> progress_values;
  7744. auto res =
  7745. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7746. progress_values.push_back(current);
  7747. return true;
  7748. });
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(200, res->status);
  7751. EXPECT_FALSE(progress_values.empty());
  7752. }
  7753. TEST(UploadProgressTest, PostContentProviderProgress) {
  7754. TestContentProviderUploadProgress(
  7755. [](Server &svr) {
  7756. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7757. res.set_content("provider received", "text/plain");
  7758. });
  7759. },
  7760. [](Client &cli, UploadProgress progress_callback) {
  7761. return cli.Post(
  7762. "/test", 10,
  7763. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7764. sink.os << "test data";
  7765. return true;
  7766. },
  7767. "text/plain", progress_callback);
  7768. });
  7769. }
  7770. // Helper function for multipart upload progress tests
  7771. template <typename SetupHandler, typename ClientCall>
  7772. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7773. ClientCall &&client_call,
  7774. const string &endpoint) {
  7775. Server svr;
  7776. setup_handler(svr);
  7777. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7778. auto se = detail::scope_exit([&] {
  7779. svr.stop();
  7780. t.join();
  7781. });
  7782. svr.wait_until_ready();
  7783. Client cli(HOST, PORT);
  7784. vector<uint64_t> progress_values;
  7785. UploadFormDataItems items = {
  7786. {"field1", "value1", "", ""},
  7787. {"field2", "longer value for progress tracking test", "", ""},
  7788. {"file1", "file content data for upload progress", "test.txt",
  7789. "text/plain"}};
  7790. auto res = client_call(cli, endpoint, items,
  7791. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7792. progress_values.push_back(current);
  7793. return true;
  7794. });
  7795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7796. EXPECT_EQ(200, res->status);
  7797. EXPECT_FALSE(progress_values.empty());
  7798. }
  7799. TEST(UploadProgressTest, PostMultipartProgress) {
  7800. TestMultipartUploadProgress(
  7801. [](Server &svr) {
  7802. svr.Post("/multipart", [](const Request &req, Response &res) {
  7803. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7804. res.set_content("multipart received", "text/plain");
  7805. });
  7806. },
  7807. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7808. UploadProgress progress_callback) {
  7809. return cli.Post(endpoint, items, progress_callback);
  7810. },
  7811. "/multipart");
  7812. }
  7813. // Helper function for basic download progress tests
  7814. template <typename SetupHandler, typename ClientCall>
  7815. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7816. ClientCall &&client_call, const string &endpoint,
  7817. size_t expected_content_size) {
  7818. Server svr;
  7819. setup_handler(svr);
  7820. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7821. auto se = detail::scope_exit([&] {
  7822. svr.stop();
  7823. t.join();
  7824. });
  7825. svr.wait_until_ready();
  7826. Client cli(HOST, PORT);
  7827. vector<uint64_t> progress_values;
  7828. auto res = client_call(cli, endpoint,
  7829. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7830. progress_values.push_back(current);
  7831. return true;
  7832. });
  7833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7834. EXPECT_EQ(200, res->status);
  7835. EXPECT_FALSE(progress_values.empty());
  7836. EXPECT_EQ(expected_content_size, res->body.size());
  7837. }
  7838. TEST(DownloadProgressTest, GetBasic) {
  7839. TestBasicDownloadProgress(
  7840. [](Server &svr) {
  7841. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7842. string content(1000, 'D');
  7843. res.set_content(content, "text/plain");
  7844. });
  7845. },
  7846. [](Client &cli, const string &endpoint,
  7847. DownloadProgress progress_callback) {
  7848. return cli.Get(endpoint, progress_callback);
  7849. },
  7850. "/download", 1000u);
  7851. }
  7852. // Helper function for content receiver download progress tests
  7853. template <typename SetupHandler, typename ClientCall>
  7854. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7855. ClientCall &&client_call,
  7856. const string &endpoint,
  7857. size_t expected_content_size) {
  7858. Server svr;
  7859. setup_handler(svr);
  7860. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7861. auto se = detail::scope_exit([&] {
  7862. svr.stop();
  7863. t.join();
  7864. });
  7865. svr.wait_until_ready();
  7866. Client cli(HOST, PORT);
  7867. vector<uint64_t> progress_values;
  7868. string received_body;
  7869. auto res = client_call(
  7870. cli, endpoint,
  7871. [&](const char *data, size_t data_length) -> bool {
  7872. received_body.append(data, data_length);
  7873. return true;
  7874. },
  7875. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7876. progress_values.push_back(current);
  7877. return true;
  7878. });
  7879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7880. EXPECT_EQ(200, res->status);
  7881. EXPECT_FALSE(progress_values.empty());
  7882. EXPECT_EQ(expected_content_size, received_body.size());
  7883. EXPECT_TRUE(res->body.empty());
  7884. }
  7885. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7886. TestContentReceiverDownloadProgress(
  7887. [](Server &svr) {
  7888. svr.Get("/download-receiver",
  7889. [](const Request & /*req*/, Response &res) {
  7890. string content(2000, 'R');
  7891. res.set_content(content, "text/plain");
  7892. });
  7893. },
  7894. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7895. DownloadProgress progress_callback) {
  7896. return cli.Get(endpoint, content_receiver, progress_callback);
  7897. },
  7898. "/download-receiver", 2000u);
  7899. }
  7900. TEST(StreamingTest, NoContentLengthStreaming) {
  7901. Server svr;
  7902. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7903. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7904. if (offset < 6) {
  7905. sink.os << (offset < 3 ? "a" : "b");
  7906. } else {
  7907. sink.done();
  7908. }
  7909. return true;
  7910. });
  7911. });
  7912. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7913. auto listen_se = detail::scope_exit([&] {
  7914. svr.stop();
  7915. listen_thread.join();
  7916. ASSERT_FALSE(svr.is_running());
  7917. });
  7918. svr.wait_until_ready();
  7919. Client client(HOST, PORT);
  7920. auto get_thread = std::thread([&client]() {
  7921. std::string s;
  7922. auto res =
  7923. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7924. s += std::string(data, len);
  7925. return true;
  7926. });
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(StatusCode::OK_200, res->status);
  7929. EXPECT_EQ("aaabbb", s);
  7930. });
  7931. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7932. // Give GET time to get a few messages.
  7933. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7934. }
  7935. TEST(MountTest, Unmount) {
  7936. Server svr;
  7937. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7938. auto se = detail::scope_exit([&] {
  7939. svr.stop();
  7940. listen_thread.join();
  7941. ASSERT_FALSE(svr.is_running());
  7942. });
  7943. svr.wait_until_ready();
  7944. Client cli("localhost", PORT);
  7945. svr.set_mount_point("/mount2", "./www2");
  7946. auto res = cli.Get("/");
  7947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7948. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7949. res = cli.Get("/mount2/dir/test.html");
  7950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7951. EXPECT_EQ(StatusCode::OK_200, res->status);
  7952. svr.set_mount_point("/", "./www");
  7953. res = cli.Get("/dir/");
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(StatusCode::OK_200, res->status);
  7956. svr.remove_mount_point("/");
  7957. res = cli.Get("/dir/");
  7958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7959. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7960. svr.remove_mount_point("/mount2");
  7961. res = cli.Get("/mount2/dir/test.html");
  7962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7963. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7964. }
  7965. TEST(MountTest, Redicect) {
  7966. Server svr;
  7967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7968. auto se = detail::scope_exit([&] {
  7969. svr.stop();
  7970. listen_thread.join();
  7971. ASSERT_FALSE(svr.is_running());
  7972. });
  7973. svr.set_mount_point("/", "./www");
  7974. svr.wait_until_ready();
  7975. Client cli("localhost", PORT);
  7976. auto res = cli.Get("/dir/");
  7977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7978. EXPECT_EQ(StatusCode::OK_200, res->status);
  7979. res = cli.Get("/dir");
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7982. res = cli.Get("/file");
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. res = cli.Get("/file/");
  7986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7987. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7988. cli.set_follow_location(true);
  7989. res = cli.Get("/dir");
  7990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7991. EXPECT_EQ(StatusCode::OK_200, res->status);
  7992. }
  7993. TEST(MountTest, MultibytesPathName) {
  7994. Server svr;
  7995. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7996. auto se = detail::scope_exit([&] {
  7997. svr.stop();
  7998. listen_thread.join();
  7999. ASSERT_FALSE(svr.is_running());
  8000. });
  8001. svr.set_mount_point("/", "./www");
  8002. svr.wait_until_ready();
  8003. Client cli("localhost", PORT);
  8004. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8006. EXPECT_EQ(StatusCode::OK_200, res->status);
  8007. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8008. }
  8009. #ifdef _WIN32
  8010. // Issue #2435: mmap::open() must succeed even when another handle holds
  8011. // the file open for writing (e.g. an active log file).
  8012. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8013. const char *path = "mmap_concurrent_writer_test.txt";
  8014. const char *content = "hello";
  8015. {
  8016. std::ofstream f(path, std::ios::binary);
  8017. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8018. }
  8019. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8020. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8021. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8022. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8023. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8024. detail::mmap m(path);
  8025. ASSERT_TRUE(m.is_open());
  8026. EXPECT_EQ(strlen(content), m.size());
  8027. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8028. }
  8029. #endif
  8030. #ifndef _WIN32
  8031. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8032. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8033. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8034. TEST(MmapTest, FailedMappingIsNotOpen) {
  8035. const char *path = "./mmap_failed_mapping_test_dir";
  8036. ASSERT_EQ(0, ::mkdir(path, 0755));
  8037. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8038. detail::mmap m(path);
  8039. EXPECT_FALSE(m.is_open());
  8040. EXPECT_EQ(0U, m.size());
  8041. EXPECT_NE(static_cast<const void *>(m.data()),
  8042. static_cast<const void *>(MAP_FAILED));
  8043. }
  8044. #endif
  8045. TEST(KeepAliveTest, ReadTimeout) {
  8046. Server svr;
  8047. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8048. std::this_thread::sleep_for(std::chrono::seconds(2));
  8049. res.set_content("a", "text/plain");
  8050. });
  8051. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8052. res.set_content("b", "text/plain");
  8053. });
  8054. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8055. auto se = detail::scope_exit([&] {
  8056. svr.stop();
  8057. listen_thread.join();
  8058. ASSERT_FALSE(svr.is_running());
  8059. });
  8060. svr.wait_until_ready();
  8061. Client cli("localhost", PORT);
  8062. cli.set_keep_alive(true);
  8063. cli.set_read_timeout(std::chrono::seconds(1));
  8064. auto resa = cli.Get("/a");
  8065. ASSERT_FALSE(resa);
  8066. EXPECT_EQ(Error::Read, resa.error());
  8067. auto resb = cli.Get("/b");
  8068. ASSERT_TRUE(resb);
  8069. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8070. EXPECT_EQ("b", resb->body);
  8071. }
  8072. TEST(KeepAliveTest, MaxCount) {
  8073. size_t keep_alive_max_count = 3;
  8074. Server svr;
  8075. svr.set_keep_alive_max_count(keep_alive_max_count);
  8076. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8077. res.set_content("Hello World!", "text/plain");
  8078. });
  8079. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8080. auto se = detail::scope_exit([&] {
  8081. svr.stop();
  8082. listen_thread.join();
  8083. ASSERT_FALSE(svr.is_running());
  8084. });
  8085. svr.wait_until_ready();
  8086. Client cli(HOST, PORT);
  8087. cli.set_keep_alive(true);
  8088. for (size_t i = 0; i < 5; i++) {
  8089. auto result = cli.Get("/hi");
  8090. ASSERT_TRUE(result);
  8091. EXPECT_EQ(StatusCode::OK_200, result->status);
  8092. if (i == keep_alive_max_count - 1) {
  8093. EXPECT_EQ("close", result->get_header_value("Connection"));
  8094. } else {
  8095. EXPECT_FALSE(result->has_header("Connection"));
  8096. }
  8097. }
  8098. }
  8099. TEST(KeepAliveTest, Issue1041) {
  8100. Server svr;
  8101. svr.set_keep_alive_timeout(3);
  8102. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8103. res.set_content("Hello World!", "text/plain");
  8104. });
  8105. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8106. auto se = detail::scope_exit([&] {
  8107. svr.stop();
  8108. listen_thread.join();
  8109. ASSERT_FALSE(svr.is_running());
  8110. });
  8111. svr.wait_until_ready();
  8112. Client cli(HOST, PORT);
  8113. cli.set_keep_alive(true);
  8114. auto result = cli.Get("/hi");
  8115. ASSERT_TRUE(result);
  8116. EXPECT_EQ(StatusCode::OK_200, result->status);
  8117. std::this_thread::sleep_for(std::chrono::seconds(5));
  8118. result = cli.Get("/hi");
  8119. ASSERT_TRUE(result);
  8120. EXPECT_EQ(StatusCode::OK_200, result->status);
  8121. }
  8122. TEST(KeepAliveTest, Issue1959) {
  8123. Server svr;
  8124. svr.set_keep_alive_timeout(5);
  8125. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8126. res.set_content("a", "text/plain");
  8127. });
  8128. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8129. auto se = detail::scope_exit([&] {
  8130. if (!svr.is_running()) return;
  8131. svr.stop();
  8132. listen_thread.join();
  8133. ASSERT_FALSE(svr.is_running());
  8134. });
  8135. svr.wait_until_ready();
  8136. Client cli("localhost", PORT);
  8137. cli.set_keep_alive(true);
  8138. using namespace std::chrono;
  8139. auto start = steady_clock::now();
  8140. cli.Get("/a");
  8141. svr.stop();
  8142. listen_thread.join();
  8143. auto end = steady_clock::now();
  8144. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8145. EXPECT_LT(elapsed, 5000);
  8146. }
  8147. #ifdef CPPHTTPLIB_SSL_ENABLED
  8148. TEST(KeepAliveTest, SSLClientReconnection) {
  8149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8150. ASSERT_TRUE(svr.is_valid());
  8151. svr.set_keep_alive_timeout(1);
  8152. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8153. res.set_content("Hello World!", "text/plain");
  8154. });
  8155. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8156. auto se = detail::scope_exit([&] {
  8157. svr.stop();
  8158. listen_thread.join();
  8159. ASSERT_FALSE(svr.is_running());
  8160. });
  8161. svr.wait_until_ready();
  8162. SSLClient cli(HOST, PORT);
  8163. cli.enable_server_certificate_verification(false);
  8164. cli.set_keep_alive(true);
  8165. auto result = cli.Get("/hi");
  8166. ASSERT_TRUE(result);
  8167. EXPECT_EQ(StatusCode::OK_200, result->status);
  8168. result = cli.Get("/hi");
  8169. ASSERT_TRUE(result);
  8170. EXPECT_EQ(StatusCode::OK_200, result->status);
  8171. std::this_thread::sleep_for(std::chrono::seconds(2));
  8172. // Recoonect
  8173. result = cli.Get("/hi");
  8174. ASSERT_TRUE(result);
  8175. EXPECT_EQ(StatusCode::OK_200, result->status);
  8176. result = cli.Get("/hi");
  8177. ASSERT_TRUE(result);
  8178. EXPECT_EQ(StatusCode::OK_200, result->status);
  8179. }
  8180. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8181. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8182. ASSERT_TRUE(svr.is_valid());
  8183. svr.set_keep_alive_timeout(1);
  8184. std::string content = "reconnect";
  8185. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8186. res.set_content("Hello World!", "text/plain");
  8187. });
  8188. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8189. auto se = detail::scope_exit([&] {
  8190. svr.stop();
  8191. listen_thread.join();
  8192. ASSERT_FALSE(svr.is_running());
  8193. });
  8194. svr.wait_until_ready();
  8195. SSLClient cli(HOST, PORT);
  8196. cli.enable_server_certificate_verification(false);
  8197. cli.set_keep_alive(true);
  8198. auto result = cli.Post(
  8199. "/hi", content.size(),
  8200. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8201. sink.write(content.c_str(), content.size());
  8202. return true;
  8203. },
  8204. "text/plain");
  8205. ASSERT_TRUE(result);
  8206. EXPECT_EQ(200, result->status);
  8207. std::this_thread::sleep_for(std::chrono::seconds(2));
  8208. // Recoonect
  8209. result = cli.Post(
  8210. "/hi", content.size(),
  8211. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8212. sink.write(content.c_str(), content.size());
  8213. return true;
  8214. },
  8215. "text/plain");
  8216. ASSERT_TRUE(result);
  8217. EXPECT_EQ(200, result->status);
  8218. result = cli.Post(
  8219. "/hi", content.size(),
  8220. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8221. sink.write(content.c_str(), content.size());
  8222. return true;
  8223. },
  8224. "text/plain");
  8225. ASSERT_TRUE(result);
  8226. EXPECT_EQ(200, result->status);
  8227. }
  8228. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8229. using namespace httplib::tls;
  8230. {
  8231. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8232. ASSERT_TRUE(svr.is_valid());
  8233. svr.Get("/sni", [&](const Request &req, Response &res) {
  8234. std::string expected = req.sni();
  8235. EXPECT_EQ(expected, req.get_param_value("expected"));
  8236. res.set_content("ok", "text/plain");
  8237. });
  8238. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8239. auto se = detail::scope_exit([&] {
  8240. svr.stop();
  8241. listen_thread.join();
  8242. ASSERT_FALSE(svr.is_running());
  8243. });
  8244. svr.wait_until_ready();
  8245. {
  8246. SSLClient cli("localhost", PORT);
  8247. cli.enable_server_certificate_verification(false);
  8248. auto res = cli.Get("/sni?expected=localhost");
  8249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8250. }
  8251. {
  8252. SSLClient cli("::1", PORT);
  8253. cli.enable_server_certificate_verification(false);
  8254. auto res = cli.Get("/sni?expected=");
  8255. // NOTE: This may fail if the server is listening on IPv4 only
  8256. // (e.g., when localhost resolves to 127.0.0.1 only)
  8257. if (res) {
  8258. EXPECT_EQ(StatusCode::OK_200, res->status);
  8259. } else {
  8260. EXPECT_EQ(Error::Connection, res.error());
  8261. }
  8262. }
  8263. }
  8264. }
  8265. #endif
  8266. TEST(ClientProblemDetectionTest, ContentProvider) {
  8267. Server svr;
  8268. size_t content_length = 1024 * 1024;
  8269. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8270. res.set_content_provider(
  8271. content_length, "text/plain",
  8272. [&](size_t offset, size_t length, DataSink &sink) {
  8273. auto out_len = std::min(length, static_cast<size_t>(1024));
  8274. std::string out(out_len, '@');
  8275. sink.write(out.data(), out_len);
  8276. return offset < 4096;
  8277. },
  8278. [](bool success) { ASSERT_FALSE(success); });
  8279. });
  8280. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8281. res.set_content_provider(
  8282. 0, "text/plain",
  8283. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8284. EXPECT_TRUE(false);
  8285. return true;
  8286. },
  8287. [](bool success) { ASSERT_FALSE(success); });
  8288. });
  8289. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8290. auto se = detail::scope_exit([&] {
  8291. svr.stop();
  8292. listen_thread.join();
  8293. ASSERT_FALSE(svr.is_running());
  8294. });
  8295. svr.wait_until_ready();
  8296. Client cli("localhost", PORT);
  8297. {
  8298. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8299. size_t /*data_length*/) { return false; });
  8300. ASSERT_FALSE(res);
  8301. }
  8302. {
  8303. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8304. size_t /*data_length*/) { return false; });
  8305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8306. }
  8307. }
  8308. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8309. Server svr;
  8310. svr.set_error_handler([](Request const &, Response &res) -> void {
  8311. res.set_chunked_content_provider(
  8312. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8313. sink.os << "hello";
  8314. sink.os << "world";
  8315. sink.done();
  8316. return true;
  8317. });
  8318. });
  8319. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8320. auto se = detail::scope_exit([&] {
  8321. svr.stop();
  8322. listen_thread.join();
  8323. ASSERT_FALSE(svr.is_running());
  8324. });
  8325. svr.wait_until_ready();
  8326. Client cli("localhost", PORT);
  8327. auto res = cli.Get("/");
  8328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8329. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8330. EXPECT_EQ("helloworld", res->body);
  8331. }
  8332. TEST(LongPollingTest, ClientCloseDetection) {
  8333. Server svr;
  8334. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8335. res.set_chunked_content_provider(
  8336. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8337. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8338. sink.os << "hello";
  8339. auto count = 10;
  8340. while (count > 0 && sink.is_writable()) {
  8341. this_thread::sleep_for(chrono::milliseconds(10));
  8342. count--;
  8343. }
  8344. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8345. return true;
  8346. });
  8347. });
  8348. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8349. auto se = detail::scope_exit([&] {
  8350. svr.stop();
  8351. listen_thread.join();
  8352. ASSERT_FALSE(svr.is_running());
  8353. });
  8354. svr.wait_until_ready();
  8355. Client cli("localhost", PORT);
  8356. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8357. EXPECT_EQ("hello", string(data, data_length));
  8358. return false; // close the socket immediately.
  8359. });
  8360. ASSERT_FALSE(res);
  8361. }
  8362. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8363. Server svr;
  8364. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8365. res.set_chunked_content_provider(
  8366. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8367. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8368. sink.os << "hello";
  8369. EXPECT_TRUE(sink.os.good());
  8370. // Wait for the client to close the connection
  8371. auto count = 10;
  8372. while (count > 0 && sink.is_writable()) {
  8373. this_thread::sleep_for(chrono::milliseconds(10));
  8374. count--;
  8375. }
  8376. // After client disconnect, write repeatedly until the socket
  8377. // write actually fails (small writes may be absorbed by the
  8378. // kernel buffer)
  8379. std::string chunk(1024, 'x');
  8380. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8381. sink.os << chunk;
  8382. }
  8383. EXPECT_TRUE(sink.os.fail());
  8384. return true;
  8385. });
  8386. });
  8387. auto port = svr.bind_to_any_port("localhost");
  8388. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8389. auto se = detail::scope_exit([&] {
  8390. svr.stop();
  8391. listen_thread.join();
  8392. ASSERT_FALSE(svr.is_running());
  8393. });
  8394. svr.wait_until_ready();
  8395. Client cli("localhost", port);
  8396. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8397. EXPECT_EQ("hello", string(data, data_length));
  8398. return false; // close the socket immediately.
  8399. });
  8400. ASSERT_FALSE(res);
  8401. }
  8402. TEST(GetWithParametersTest, GetWithParameters) {
  8403. Server svr;
  8404. svr.Get("/", [&](const Request &req, Response &) {
  8405. EXPECT_EQ("world", req.get_param_value("hello"));
  8406. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8407. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8408. });
  8409. svr.Get("/params", [&](const Request &req, Response &) {
  8410. EXPECT_EQ("world", req.get_param_value("hello"));
  8411. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8412. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8413. });
  8414. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8415. EXPECT_EQ("resource-id", req.matches[1]);
  8416. EXPECT_EQ("foo", req.get_param_value("param1"));
  8417. EXPECT_EQ("bar", req.get_param_value("param2"));
  8418. });
  8419. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8420. EXPECT_EQ("user-id", req.path_params.at("id"));
  8421. EXPECT_EQ("foo", req.get_param_value("param1"));
  8422. EXPECT_EQ("bar", req.get_param_value("param2"));
  8423. });
  8424. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8425. auto se = detail::scope_exit([&] {
  8426. svr.stop();
  8427. listen_thread.join();
  8428. ASSERT_FALSE(svr.is_running());
  8429. });
  8430. svr.wait_until_ready();
  8431. {
  8432. Client cli(HOST, PORT);
  8433. Params params;
  8434. params.emplace("hello", "world");
  8435. params.emplace("hello2", "world2");
  8436. params.emplace("hello3", "world3");
  8437. auto res = cli.Get("/", params, Headers{});
  8438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8439. EXPECT_EQ(StatusCode::OK_200, res->status);
  8440. }
  8441. {
  8442. Client cli(HOST, PORT);
  8443. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8445. EXPECT_EQ(StatusCode::OK_200, res->status);
  8446. }
  8447. {
  8448. Client cli(HOST, PORT);
  8449. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8451. EXPECT_EQ(StatusCode::OK_200, res->status);
  8452. }
  8453. {
  8454. Client cli(HOST, PORT);
  8455. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8457. EXPECT_EQ(StatusCode::OK_200, res->status);
  8458. }
  8459. }
  8460. TEST(GetWithParametersTest, GetWithParameters2) {
  8461. Server svr;
  8462. svr.Get("/", [&](const Request &req, Response &res) {
  8463. auto text = req.get_param_value("hello");
  8464. res.set_content(text, "text/plain");
  8465. });
  8466. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8467. auto se = detail::scope_exit([&] {
  8468. svr.stop();
  8469. listen_thread.join();
  8470. ASSERT_FALSE(svr.is_running());
  8471. });
  8472. svr.wait_until_ready();
  8473. Client cli("localhost", PORT);
  8474. Params params;
  8475. params.emplace("hello", "world");
  8476. std::string body;
  8477. auto res = cli.Get("/", params, Headers{},
  8478. [&](const char *data, size_t data_length) {
  8479. body.append(data, data_length);
  8480. return true;
  8481. });
  8482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8483. EXPECT_EQ(StatusCode::OK_200, res->status);
  8484. EXPECT_EQ("world", body);
  8485. }
  8486. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8487. Server svr;
  8488. svr.Get("/search", [&](const Request &req, Response &res) {
  8489. auto q = req.get_param_value("q");
  8490. res.set_content(q, "text/plain");
  8491. });
  8492. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8493. auto se = detail::scope_exit([&] {
  8494. svr.stop();
  8495. listen_thread.join();
  8496. ASSERT_FALSE(svr.is_running());
  8497. });
  8498. svr.wait_until_ready();
  8499. Client cli("localhost", PORT);
  8500. // Verify that Get(path, params) works without requiring Headers argument
  8501. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8503. EXPECT_EQ(StatusCode::OK_200, res->status);
  8504. EXPECT_EQ("cpp-httplib", res->body);
  8505. }
  8506. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8507. auto host = "httpbingo.org";
  8508. auto path = std::string{"/range/32"};
  8509. #ifdef CPPHTTPLIB_SSL_ENABLED
  8510. SSLClient cli(host);
  8511. #else
  8512. Client cli(host);
  8513. #endif
  8514. cli.set_default_headers({make_range_header({{1, 10}})});
  8515. cli.set_connection_timeout(5);
  8516. {
  8517. auto res = cli.Get(path);
  8518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8519. EXPECT_EQ("bcdefghijk", res->body);
  8520. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8521. }
  8522. {
  8523. auto res = cli.Get(path);
  8524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8525. EXPECT_EQ("bcdefghijk", res->body);
  8526. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8527. }
  8528. }
  8529. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8530. Server svr;
  8531. svr.set_default_headers({{"Hello", "World"}});
  8532. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8533. res.set_content("ok", "text/plain");
  8534. });
  8535. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8536. auto se = detail::scope_exit([&] {
  8537. svr.stop();
  8538. listen_thread.join();
  8539. ASSERT_FALSE(svr.is_running());
  8540. });
  8541. svr.wait_until_ready();
  8542. Client cli("localhost", PORT);
  8543. auto res = cli.Get("/");
  8544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8545. EXPECT_EQ(StatusCode::OK_200, res->status);
  8546. EXPECT_EQ("ok", res->body);
  8547. EXPECT_EQ("World", res->get_header_value("Hello"));
  8548. }
  8549. #ifdef CPPHTTPLIB_SSL_ENABLED
  8550. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8552. ASSERT_TRUE(svr.is_valid());
  8553. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8554. std::this_thread::sleep_for(std::chrono::seconds(2));
  8555. res.set_content("a", "text/plain");
  8556. });
  8557. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8558. res.set_content("b", "text/plain");
  8559. });
  8560. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8561. auto se = detail::scope_exit([&] {
  8562. svr.stop();
  8563. listen_thread.join();
  8564. ASSERT_FALSE(svr.is_running());
  8565. });
  8566. svr.wait_until_ready();
  8567. SSLClient cli("localhost", PORT);
  8568. cli.enable_server_certificate_verification(false);
  8569. cli.set_keep_alive(true);
  8570. cli.set_read_timeout(std::chrono::seconds(1));
  8571. auto resa = cli.Get("/a");
  8572. ASSERT_TRUE(!resa);
  8573. EXPECT_EQ(Error::Read, resa.error());
  8574. auto resb = cli.Get("/b");
  8575. ASSERT_TRUE(resb);
  8576. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8577. EXPECT_EQ("b", resb->body);
  8578. }
  8579. #endif
  8580. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8581. protected:
  8582. ServerTestWithAI_PASSIVE()
  8583. : cli_(HOST, PORT)
  8584. #ifdef CPPHTTPLIB_SSL_ENABLED
  8585. ,
  8586. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8587. #endif
  8588. {
  8589. #ifdef CPPHTTPLIB_SSL_ENABLED
  8590. cli_.enable_server_certificate_verification(false);
  8591. #endif
  8592. }
  8593. virtual void SetUp() {
  8594. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8595. res.set_content("Hello World!", "text/plain");
  8596. });
  8597. t_ = thread(
  8598. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8599. svr_.wait_until_ready();
  8600. }
  8601. virtual void TearDown() {
  8602. svr_.stop();
  8603. t_.join();
  8604. }
  8605. #ifdef CPPHTTPLIB_SSL_ENABLED
  8606. SSLClient cli_;
  8607. SSLServer svr_;
  8608. #else
  8609. Client cli_;
  8610. Server svr_;
  8611. #endif
  8612. thread t_;
  8613. };
  8614. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8615. auto res = cli_.Get("/hi");
  8616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8617. EXPECT_EQ(StatusCode::OK_200, res->status);
  8618. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8619. EXPECT_EQ("Hello World!", res->body);
  8620. }
  8621. class ServerUpDownTest : public ::testing::Test {
  8622. protected:
  8623. ServerUpDownTest() : cli_(HOST, PORT) {}
  8624. virtual void SetUp() {
  8625. t_ = thread([&]() {
  8626. svr_.bind_to_any_port(HOST);
  8627. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8628. ASSERT_TRUE(svr_.listen_after_bind());
  8629. });
  8630. svr_.wait_until_ready();
  8631. }
  8632. virtual void TearDown() {
  8633. svr_.stop();
  8634. t_.join();
  8635. }
  8636. Client cli_;
  8637. Server svr_;
  8638. thread t_;
  8639. };
  8640. TEST_F(ServerUpDownTest, QuickStartStop) {
  8641. // Should not crash, especially when run with
  8642. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8643. }
  8644. class PayloadMaxLengthTest : public ::testing::Test {
  8645. protected:
  8646. PayloadMaxLengthTest()
  8647. : cli_(HOST, PORT)
  8648. #ifdef CPPHTTPLIB_SSL_ENABLED
  8649. ,
  8650. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8651. #endif
  8652. {
  8653. #ifdef CPPHTTPLIB_SSL_ENABLED
  8654. cli_.enable_server_certificate_verification(false);
  8655. #endif
  8656. }
  8657. virtual void SetUp() {
  8658. svr_.set_payload_max_length(8);
  8659. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8660. res.set_content("test", "text/plain");
  8661. });
  8662. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8663. svr_.wait_until_ready();
  8664. }
  8665. virtual void TearDown() {
  8666. svr_.stop();
  8667. t_.join();
  8668. }
  8669. #ifdef CPPHTTPLIB_SSL_ENABLED
  8670. SSLClient cli_;
  8671. SSLServer svr_;
  8672. #else
  8673. Client cli_;
  8674. Server svr_;
  8675. #endif
  8676. thread t_;
  8677. };
  8678. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8679. auto res = cli_.Post("/test", "123456789", "text/plain");
  8680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8681. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8682. res = cli_.Post("/test", "12345678", "text/plain");
  8683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8684. EXPECT_EQ(StatusCode::OK_200, res->status);
  8685. }
  8686. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8687. // Test chunked encoding with payload exceeding the 8-byte limit
  8688. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8689. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8691. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8692. }
  8693. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8694. // Test chunked encoding with payload within the 8-byte limit
  8695. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8696. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8698. EXPECT_EQ(StatusCode::OK_200, res->status);
  8699. }
  8700. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8701. // Test using send_request to send chunked data exceeding payload limit
  8702. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8703. "Host: " +
  8704. std::string(HOST) + ":" + std::to_string(PORT) +
  8705. "\r\n"
  8706. "Transfer-Encoding: chunked\r\n"
  8707. "Connection: close\r\n"
  8708. "\r\n"
  8709. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8710. "0123456789\r\n"
  8711. "0\r\n" // End chunk
  8712. "\r\n";
  8713. std::string response;
  8714. bool result = send_request(1, chunked_request, &response);
  8715. if (!result) {
  8716. // If send_request fails, it might be because the server closed the
  8717. // connection due to payload limit enforcement, which is acceptable
  8718. SUCCEED()
  8719. << "Server rejected oversized chunked request (connection closed)";
  8720. } else {
  8721. // If we got a response, check if it's an error response or connection was
  8722. // closed early Short response length indicates connection was closed due to
  8723. // payload limit
  8724. if (response.length() <= 10) {
  8725. SUCCEED() << "Server closed connection for oversized chunked request";
  8726. } else {
  8727. // Check for error status codes
  8728. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8729. response.find("Payload Too Large") != std::string::npos ||
  8730. response.find("400") != std::string::npos);
  8731. }
  8732. }
  8733. }
  8734. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8735. // Test request without Content-Length header exceeding payload limit
  8736. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8737. "Host: " +
  8738. std::string(HOST) + ":" +
  8739. std::to_string(PORT) +
  8740. "\r\n"
  8741. "Connection: close\r\n"
  8742. "\r\n";
  8743. // Add payload exceeding the 8-byte limit
  8744. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8745. request_without_content_length += large_payload;
  8746. std::string response;
  8747. bool result = send_request(1, request_without_content_length, &response);
  8748. if (!result) {
  8749. // If send_request fails, server likely closed connection due to payload
  8750. // limit
  8751. SUCCEED() << "Server rejected oversized request without Content-Length "
  8752. "(connection closed)";
  8753. } else {
  8754. // Check if server responded with error or closed connection early
  8755. if (response.length() <= 10) {
  8756. SUCCEED() << "Server closed connection for oversized request without "
  8757. "Content-Length";
  8758. } else {
  8759. // Check for error status codes
  8760. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8761. response.find("Payload Too Large") != std::string::npos ||
  8762. response.find("400") != std::string::npos);
  8763. }
  8764. }
  8765. }
  8766. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8767. // Test request without Content-Length header within payload limit
  8768. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8769. "Host: " +
  8770. std::string(HOST) + ":" +
  8771. std::to_string(PORT) +
  8772. "\r\n"
  8773. "Connection: close\r\n"
  8774. "\r\n";
  8775. // Add payload within the 8-byte limit
  8776. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8777. request_without_content_length += small_payload;
  8778. std::string response;
  8779. bool result = send_request(1, request_without_content_length, &response);
  8780. // For requests without Content-Length, the server may have different behavior
  8781. // The key is that it should not reject due to payload limit for small
  8782. // payloads
  8783. if (result) {
  8784. // Check for any HTTP response (success or error, but not connection closed)
  8785. if (response.length() > 10) {
  8786. SUCCEED()
  8787. << "Server processed request without Content-Length within limit";
  8788. } else {
  8789. // Short response might indicate connection closed, which is acceptable
  8790. SUCCEED() << "Server closed connection for request without "
  8791. "Content-Length (acceptable behavior)";
  8792. }
  8793. } else {
  8794. // Connection failure might be due to protocol requirements
  8795. SUCCEED() << "Connection issue with request without Content-Length "
  8796. "(environment-specific)";
  8797. }
  8798. }
  8799. class LargePayloadMaxLengthTest : public ::testing::Test {
  8800. protected:
  8801. LargePayloadMaxLengthTest()
  8802. : cli_(HOST, PORT)
  8803. #ifdef CPPHTTPLIB_SSL_ENABLED
  8804. ,
  8805. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8806. #endif
  8807. {
  8808. #ifdef CPPHTTPLIB_SSL_ENABLED
  8809. cli_.enable_server_certificate_verification(false);
  8810. #endif
  8811. }
  8812. virtual void SetUp() {
  8813. // Set 10MB payload limit
  8814. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8815. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8816. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8817. res.set_content("Large payload test", "text/plain");
  8818. });
  8819. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8820. svr_.wait_until_ready();
  8821. }
  8822. virtual void TearDown() {
  8823. svr_.stop();
  8824. t_.join();
  8825. }
  8826. #ifdef CPPHTTPLIB_SSL_ENABLED
  8827. SSLClient cli_;
  8828. SSLServer svr_;
  8829. #else
  8830. Client cli_;
  8831. Server svr_;
  8832. #endif
  8833. thread t_;
  8834. };
  8835. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8836. // Test chunked encoding with payload within 10MB limit
  8837. std::string medium_payload(5 * 1024 * 1024,
  8838. 'A'); // 5MB payload, within 10MB limit
  8839. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8841. EXPECT_EQ(StatusCode::OK_200, res->status);
  8842. }
  8843. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8844. // Test chunked encoding with payload exceeding 10MB limit
  8845. std::string large_payload(12 * 1024 * 1024,
  8846. 'B'); // 12MB payload, exceeds 10MB limit
  8847. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8848. // Server may either return 413 or close the connection
  8849. if (res) {
  8850. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8851. } else {
  8852. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8853. }
  8854. }
  8855. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8856. // Test request without Content-Length header within 10MB limit
  8857. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8858. "Host: " +
  8859. std::string(HOST) + ":" +
  8860. std::to_string(PORT) +
  8861. "\r\n"
  8862. "Connection: close\r\n"
  8863. "\r\n";
  8864. // Add 1MB payload (within 10MB limit)
  8865. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8866. request_without_content_length += medium_payload;
  8867. std::string response;
  8868. bool result = send_request(5, request_without_content_length, &response);
  8869. if (result) {
  8870. // Should get a proper HTTP response for payloads within limit
  8871. if (response.length() > 10) {
  8872. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8873. "10MB limit";
  8874. } else {
  8875. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8876. "Content-Length)";
  8877. }
  8878. } else {
  8879. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8880. }
  8881. }
  8882. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8883. // Test request without Content-Length header exceeding 10MB limit
  8884. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8885. "Host: " +
  8886. std::string(HOST) + ":" +
  8887. std::to_string(PORT) +
  8888. "\r\n"
  8889. "Connection: close\r\n"
  8890. "\r\n";
  8891. // Add 12MB payload (exceeds 10MB limit)
  8892. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8893. request_without_content_length += large_payload;
  8894. std::string response;
  8895. bool result = send_request(10, request_without_content_length, &response);
  8896. if (!result) {
  8897. // Server should close connection due to payload limit
  8898. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8899. "(connection closed)";
  8900. } else {
  8901. // Check for error response
  8902. if (response.length() <= 10) {
  8903. SUCCEED()
  8904. << "Server closed connection for 12MB request exceeding 10MB limit";
  8905. } else {
  8906. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8907. response.find("Payload Too Large") != std::string::npos ||
  8908. response.find("400") != std::string::npos);
  8909. }
  8910. }
  8911. }
  8912. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8913. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8914. // path.
  8915. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8916. Server svr;
  8917. const size_t LIMIT = 64 * 1024; // 64KB
  8918. svr.set_payload_max_length(LIMIT);
  8919. size_t total = 0;
  8920. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8921. const ContentReader &content_reader) {
  8922. content_reader([&](const char * /*data*/, size_t len) {
  8923. total += len;
  8924. return true;
  8925. });
  8926. res.status = 200;
  8927. res.set_content("stream_ok", "text/plain");
  8928. });
  8929. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8930. auto se = detail::scope_exit([&] {
  8931. svr.stop();
  8932. thread.join();
  8933. ASSERT_FALSE(svr.is_running());
  8934. });
  8935. svr.wait_until_ready();
  8936. // Prepare 256KB raw data and gzip-compress it
  8937. std::string raw(256 * 1024, 'A');
  8938. std::string gz;
  8939. {
  8940. z_stream zs{};
  8941. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8942. Z_DEFAULT_STRATEGY);
  8943. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8944. zs.avail_in = static_cast<uInt>(raw.size());
  8945. char outbuf[4096];
  8946. int ret;
  8947. do {
  8948. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8949. zs.avail_out = sizeof(outbuf);
  8950. ret = deflate(&zs, Z_FINISH);
  8951. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8952. } while (ret != Z_STREAM_END);
  8953. deflateEnd(&zs);
  8954. }
  8955. Client cli(HOST, PORT);
  8956. cli.set_connection_timeout(std::chrono::seconds(5));
  8957. Headers headers = {{"Content-Encoding", "gzip"}};
  8958. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8959. "application/octet-stream");
  8960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8961. // Server must reject oversized decompressed payloads with 413.
  8962. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8963. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8964. EXPECT_LE(total, LIMIT);
  8965. }
  8966. #endif
  8967. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  8968. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  8969. // the payload must be passed through untouched instead of being rejected.
  8970. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  8971. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  8972. Server svr;
  8973. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  8974. res.set_content(body, "image/jpeg");
  8975. res.set_header("Content-Encoding", "UTF-8");
  8976. });
  8977. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  8978. res.set_content(body, "image/jpeg");
  8979. res.set_header("Content-Encoding", "identity");
  8980. });
  8981. svr.Post("/echo", [](const Request &req, Response &res) {
  8982. res.set_content(req.body, "image/jpeg");
  8983. });
  8984. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8985. auto se = detail::scope_exit([&] {
  8986. svr.stop();
  8987. t.join();
  8988. ASSERT_FALSE(svr.is_running());
  8989. });
  8990. svr.wait_until_ready();
  8991. Client cli(HOST, PORT);
  8992. {
  8993. auto res = cli.Get("/image");
  8994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8995. EXPECT_EQ(StatusCode::OK_200, res->status);
  8996. EXPECT_EQ(body, res->body);
  8997. }
  8998. {
  8999. auto res = cli.Get("/identity");
  9000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9001. EXPECT_EQ(StatusCode::OK_200, res->status);
  9002. EXPECT_EQ(body, res->body);
  9003. }
  9004. {
  9005. // The same applies to a request body reaching the server.
  9006. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9007. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9009. EXPECT_EQ(StatusCode::OK_200, res->status);
  9010. EXPECT_EQ(body, res->body);
  9011. }
  9012. }
  9013. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9014. // gzip-encoded response even when the build has no zlib support.
  9015. static const char GZIPPED_HELLO_WORLD[] = {
  9016. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9017. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9018. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9019. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9020. // A content coding cpp-httplib recognizes but was not built with must be
  9021. // reported as such. Handing the still-compressed payload back to the caller
  9022. // would silently corrupt it.
  9023. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9024. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9025. Server svr;
  9026. // "image/jpeg" keeps the server from applying a content coding of its own,
  9027. // so the hand-crafted Content-Encoding below survives.
  9028. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9029. res.set_content(gzipped, "image/jpeg");
  9030. res.set_header("Content-Encoding", "gzip");
  9031. });
  9032. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9033. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9034. res.set_content(gzipped, "image/jpeg");
  9035. res.set_header("Content-Encoding", "GZIP");
  9036. });
  9037. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9038. auto se = detail::scope_exit([&] {
  9039. svr.stop();
  9040. t.join();
  9041. ASSERT_FALSE(svr.is_running());
  9042. });
  9043. svr.wait_until_ready();
  9044. Client cli(HOST, PORT);
  9045. {
  9046. auto res = cli.Get("/gzipped");
  9047. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9049. EXPECT_EQ("Hello World!", res->body);
  9050. #else
  9051. ASSERT_FALSE(res);
  9052. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9053. #endif
  9054. }
  9055. {
  9056. // open_stream() must behave the same way.
  9057. auto handle = cli.open_stream("GET", "/gzipped");
  9058. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9059. ASSERT_TRUE(handle.is_valid());
  9060. std::string received;
  9061. char buf[256];
  9062. ssize_t n;
  9063. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9064. received.append(buf, static_cast<size_t>(n));
  9065. }
  9066. EXPECT_EQ("Hello World!", received);
  9067. #else
  9068. EXPECT_FALSE(handle.is_valid());
  9069. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9070. #endif
  9071. }
  9072. {
  9073. // A differently-cased coding must not be mistaken for an unknown one, or
  9074. // the body would be handed back still compressed.
  9075. auto res = cli.Get("/gzipped-uppercase");
  9076. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9078. EXPECT_EQ("Hello World!", res->body);
  9079. #else
  9080. ASSERT_FALSE(res);
  9081. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9082. #endif
  9083. }
  9084. }
  9085. // Regression test for DoS vulnerability: a malicious server sending a response
  9086. // without Content-Length header must not cause unbounded memory consumption on
  9087. // the client side. The client should stop reading after a reasonable limit,
  9088. // similar to the server-side set_payload_max_length protection.
  9089. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9090. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9091. #ifndef _WIN32
  9092. signal(SIGPIPE, SIG_IGN);
  9093. #endif
  9094. auto server_thread = std::thread([] {
  9095. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9096. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9097. default_socket_options(srv);
  9098. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9099. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9100. sockaddr_in addr{};
  9101. addr.sin_family = AF_INET;
  9102. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9103. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9104. int opt = 1;
  9105. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9106. #ifdef _WIN32
  9107. reinterpret_cast<const char *>(&opt),
  9108. #else
  9109. &opt,
  9110. #endif
  9111. sizeof(opt));
  9112. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9113. ::listen(srv, 1);
  9114. sockaddr_in cli_addr{};
  9115. socklen_t cli_len = sizeof(cli_addr);
  9116. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9117. if (cli != INVALID_SOCKET) {
  9118. char buf[4096];
  9119. ::recv(cli, buf, sizeof(buf), 0);
  9120. // Malicious response: no Content-Length, no chunked encoding
  9121. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9122. "Connection: close\r\n"
  9123. "\r\n";
  9124. ::send(cli,
  9125. #ifdef _WIN32
  9126. static_cast<const char *>(response_header.c_str()),
  9127. static_cast<int>(response_header.size()),
  9128. #else
  9129. response_header.c_str(), response_header.size(),
  9130. #endif
  9131. 0);
  9132. // Send 10MB of data
  9133. std::string chunk(64 * 1024, 'A');
  9134. size_t total_sent = 0;
  9135. while (total_sent < MALICIOUS_DATA_SIZE) {
  9136. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9137. auto sent = ::send(cli,
  9138. #ifdef _WIN32
  9139. static_cast<const char *>(chunk.c_str()),
  9140. static_cast<int>(to_send),
  9141. #else
  9142. chunk.c_str(), to_send,
  9143. #endif
  9144. 0);
  9145. if (sent <= 0) break;
  9146. total_sent += static_cast<size_t>(sent);
  9147. }
  9148. detail::close_socket(cli);
  9149. }
  9150. detail::close_socket(srv);
  9151. });
  9152. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9153. size_t total_read = 0;
  9154. {
  9155. Client cli("127.0.0.1", PORT + 2);
  9156. cli.set_read_timeout(5, 0);
  9157. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9158. auto stream = cli.open_stream("GET", "/malicious");
  9159. ASSERT_TRUE(stream.is_valid());
  9160. char buffer[64 * 1024];
  9161. ssize_t n;
  9162. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9163. total_read += static_cast<size_t>(n);
  9164. }
  9165. } // StreamHandle and Client destroyed here, closing the socket
  9166. server_thread.join();
  9167. // With set_payload_max_length, the client must stop reading before consuming
  9168. // all 10MB. The read loop should be cut off at or near the configured limit.
  9169. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9170. << "Client read " << total_read << " bytes, exceeding the configured "
  9171. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9172. }
  9173. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9174. // the entire response body without truncation.
  9175. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9176. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9177. #ifndef _WIN32
  9178. signal(SIGPIPE, SIG_IGN);
  9179. #endif
  9180. auto server_thread = std::thread([] {
  9181. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9182. default_socket_options(srv);
  9183. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9184. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9185. sockaddr_in addr{};
  9186. addr.sin_family = AF_INET;
  9187. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9188. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9189. int opt = 1;
  9190. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9191. #ifdef _WIN32
  9192. reinterpret_cast<const char *>(&opt),
  9193. #else
  9194. &opt,
  9195. #endif
  9196. sizeof(opt));
  9197. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9198. ::listen(srv, 1);
  9199. sockaddr_in cli_addr{};
  9200. socklen_t cli_len = sizeof(cli_addr);
  9201. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9202. if (cli != INVALID_SOCKET) {
  9203. char buf[4096];
  9204. ::recv(cli, buf, sizeof(buf), 0);
  9205. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9206. "Connection: close\r\n"
  9207. "\r\n";
  9208. ::send(cli,
  9209. #ifdef _WIN32
  9210. static_cast<const char *>(response_header.c_str()),
  9211. static_cast<int>(response_header.size()),
  9212. #else
  9213. response_header.c_str(), response_header.size(),
  9214. #endif
  9215. 0);
  9216. std::string chunk(64 * 1024, 'A');
  9217. size_t total_sent = 0;
  9218. while (total_sent < DATA_SIZE) {
  9219. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9220. auto sent = ::send(cli,
  9221. #ifdef _WIN32
  9222. static_cast<const char *>(chunk.c_str()),
  9223. static_cast<int>(to_send),
  9224. #else
  9225. chunk.c_str(), to_send,
  9226. #endif
  9227. 0);
  9228. if (sent <= 0) break;
  9229. total_sent += static_cast<size_t>(sent);
  9230. }
  9231. #ifdef _WIN32
  9232. ::shutdown(cli, SD_SEND);
  9233. #else
  9234. ::shutdown(cli, SHUT_WR);
  9235. #endif
  9236. // Drain until the client closes its end, ensuring all data is delivered
  9237. char drain[1024];
  9238. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9239. detail::close_socket(cli);
  9240. }
  9241. detail::close_socket(srv);
  9242. });
  9243. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9244. size_t total_read = 0;
  9245. {
  9246. Client cli("127.0.0.1", PORT + 2);
  9247. cli.set_read_timeout(5, 0);
  9248. cli.set_payload_max_length(0); // 0 means no limit
  9249. auto stream = cli.open_stream("GET", "/data");
  9250. ASSERT_TRUE(stream.is_valid());
  9251. char buffer[64 * 1024];
  9252. ssize_t n;
  9253. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9254. total_read += static_cast<size_t>(n);
  9255. }
  9256. }
  9257. server_thread.join();
  9258. EXPECT_EQ(total_read, DATA_SIZE)
  9259. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9260. << " bytes without truncation, but only read " << total_read << " bytes.";
  9261. }
  9262. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9263. // enormous Content-Length must not cause the client to pre-allocate a huge
  9264. // response body buffer. The reservation is capped at payload_max_length_, and
  9265. // the read itself fails when the body exceeds the limit.
  9266. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9267. #ifndef _WIN32
  9268. signal(SIGPIPE, SIG_IGN);
  9269. #endif
  9270. auto server_thread = std::thread([] {
  9271. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9272. default_socket_options(srv);
  9273. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9274. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9275. sockaddr_in addr{};
  9276. addr.sin_family = AF_INET;
  9277. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9278. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9279. int opt = 1;
  9280. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9281. #ifdef _WIN32
  9282. reinterpret_cast<const char *>(&opt),
  9283. #else
  9284. &opt,
  9285. #endif
  9286. sizeof(opt));
  9287. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9288. ::listen(srv, 1);
  9289. sockaddr_in cli_addr{};
  9290. socklen_t cli_len = sizeof(cli_addr);
  9291. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9292. if (cli != INVALID_SOCKET) {
  9293. char buf[4096];
  9294. ::recv(cli, buf, sizeof(buf), 0);
  9295. // Malicious response: claim a 20GB body but send only a tiny payload.
  9296. std::string response = "HTTP/1.1 200 OK\r\n"
  9297. "Content-Length: 20000000000\r\n"
  9298. "\r\n"
  9299. "abc";
  9300. ::send(cli,
  9301. #ifdef _WIN32
  9302. static_cast<const char *>(response.c_str()),
  9303. static_cast<int>(response.size()),
  9304. #else
  9305. response.c_str(), response.size(),
  9306. #endif
  9307. 0);
  9308. detail::close_socket(cli);
  9309. }
  9310. detail::close_socket(srv);
  9311. });
  9312. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9313. {
  9314. Client cli("127.0.0.1", PORT + 2);
  9315. cli.set_read_timeout(5, 0);
  9316. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9317. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9318. // (server claims more bytes than payload_max_length permits), but it must
  9319. // not exhaust memory before getting there.
  9320. auto res = cli.Get("/malicious");
  9321. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9322. }
  9323. server_thread.join();
  9324. }
  9325. // Verify that content_receiver bypasses the default payload_max_length,
  9326. // allowing streaming downloads larger than 100MB without requiring an explicit
  9327. // set_payload_max_length call.
  9328. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9329. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9330. #ifndef _WIN32
  9331. signal(SIGPIPE, SIG_IGN);
  9332. #endif
  9333. auto server_thread = std::thread([] {
  9334. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9335. default_socket_options(srv);
  9336. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9337. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9338. sockaddr_in addr{};
  9339. addr.sin_family = AF_INET;
  9340. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9341. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9342. int opt = 1;
  9343. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9344. #ifdef _WIN32
  9345. reinterpret_cast<const char *>(&opt),
  9346. #else
  9347. &opt,
  9348. #endif
  9349. sizeof(opt));
  9350. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9351. ::listen(srv, 1);
  9352. sockaddr_in cli_addr{};
  9353. socklen_t cli_len = sizeof(cli_addr);
  9354. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9355. if (cli != INVALID_SOCKET) {
  9356. char buf[4096];
  9357. ::recv(cli, buf, sizeof(buf), 0);
  9358. // Response with Content-Length larger than default 100MB limit
  9359. auto content_length = std::to_string(DATA_SIZE);
  9360. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9361. "Content-Length: " +
  9362. content_length +
  9363. "\r\n"
  9364. "Connection: close\r\n"
  9365. "\r\n";
  9366. ::send(cli,
  9367. #ifdef _WIN32
  9368. static_cast<const char *>(response_header.c_str()),
  9369. static_cast<int>(response_header.size()),
  9370. #else
  9371. response_header.c_str(), response_header.size(),
  9372. #endif
  9373. 0);
  9374. std::string chunk(64 * 1024, 'A');
  9375. size_t total_sent = 0;
  9376. while (total_sent < DATA_SIZE) {
  9377. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9378. auto sent = ::send(cli,
  9379. #ifdef _WIN32
  9380. static_cast<const char *>(chunk.c_str()),
  9381. static_cast<int>(to_send),
  9382. #else
  9383. chunk.c_str(), to_send,
  9384. #endif
  9385. 0);
  9386. if (sent <= 0) break;
  9387. total_sent += static_cast<size_t>(sent);
  9388. }
  9389. detail::close_socket(cli);
  9390. }
  9391. detail::close_socket(srv);
  9392. });
  9393. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9394. size_t total_received = 0;
  9395. {
  9396. Client cli("127.0.0.1", PORT + 2);
  9397. cli.set_read_timeout(10, 0);
  9398. // Do NOT call set_payload_max_length — use the default 100MB limit
  9399. auto res =
  9400. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9401. total_received += data_length;
  9402. return true;
  9403. });
  9404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9405. EXPECT_EQ(StatusCode::OK_200, res->status);
  9406. }
  9407. server_thread.join();
  9408. EXPECT_EQ(total_received, DATA_SIZE)
  9409. << "With content_receiver, the client should read all " << DATA_SIZE
  9410. << " bytes despite the default 100MB payload_max_length, but only read "
  9411. << total_received << " bytes.";
  9412. }
  9413. // Verify that an explicit set_payload_max_length smaller than the response is
  9414. // enforced even when a content_receiver is used.
  9415. TEST(ClientVulnerabilityTest,
  9416. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9417. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9418. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9419. #ifndef _WIN32
  9420. signal(SIGPIPE, SIG_IGN);
  9421. #endif
  9422. auto server_thread = std::thread([] {
  9423. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9424. default_socket_options(srv);
  9425. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9426. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9427. sockaddr_in addr{};
  9428. addr.sin_family = AF_INET;
  9429. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9430. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9431. int opt = 1;
  9432. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9433. #ifdef _WIN32
  9434. reinterpret_cast<const char *>(&opt),
  9435. #else
  9436. &opt,
  9437. #endif
  9438. sizeof(opt));
  9439. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9440. ::listen(srv, 1);
  9441. sockaddr_in cli_addr{};
  9442. socklen_t cli_len = sizeof(cli_addr);
  9443. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9444. if (cli != INVALID_SOCKET) {
  9445. char buf[4096];
  9446. ::recv(cli, buf, sizeof(buf), 0);
  9447. auto content_length = std::to_string(DATA_SIZE);
  9448. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9449. "Content-Length: " +
  9450. content_length +
  9451. "\r\n"
  9452. "Connection: close\r\n"
  9453. "\r\n";
  9454. ::send(cli,
  9455. #ifdef _WIN32
  9456. static_cast<const char *>(response_header.c_str()),
  9457. static_cast<int>(response_header.size()),
  9458. #else
  9459. response_header.c_str(), response_header.size(),
  9460. #endif
  9461. 0);
  9462. std::string chunk(64 * 1024, 'A');
  9463. size_t total_sent = 0;
  9464. while (total_sent < DATA_SIZE) {
  9465. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9466. auto sent = ::send(cli,
  9467. #ifdef _WIN32
  9468. static_cast<const char *>(chunk.c_str()),
  9469. static_cast<int>(to_send),
  9470. #else
  9471. chunk.c_str(), to_send,
  9472. #endif
  9473. 0);
  9474. if (sent <= 0) break;
  9475. total_sent += static_cast<size_t>(sent);
  9476. }
  9477. detail::close_socket(cli);
  9478. }
  9479. detail::close_socket(srv);
  9480. });
  9481. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9482. size_t total_received = 0;
  9483. {
  9484. Client cli("127.0.0.1", PORT + 2);
  9485. cli.set_read_timeout(10, 0);
  9486. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9487. auto res =
  9488. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9489. total_received += data_length;
  9490. return true;
  9491. });
  9492. // Should fail because 200MB exceeds the explicit 150MB limit
  9493. EXPECT_FALSE(res);
  9494. }
  9495. server_thread.join();
  9496. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9497. << "Client with content_receiver should respect the explicit "
  9498. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9499. << total_received << " bytes.";
  9500. }
  9501. // Verify that an explicit set_payload_max_length larger than the response
  9502. // allows the content_receiver to read all data successfully.
  9503. TEST(ClientVulnerabilityTest,
  9504. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9505. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9506. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9507. #ifndef _WIN32
  9508. signal(SIGPIPE, SIG_IGN);
  9509. #endif
  9510. auto server_thread = std::thread([] {
  9511. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9512. default_socket_options(srv);
  9513. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9514. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9515. sockaddr_in addr{};
  9516. addr.sin_family = AF_INET;
  9517. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9518. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9519. int opt = 1;
  9520. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9521. #ifdef _WIN32
  9522. reinterpret_cast<const char *>(&opt),
  9523. #else
  9524. &opt,
  9525. #endif
  9526. sizeof(opt));
  9527. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9528. ::listen(srv, 1);
  9529. sockaddr_in cli_addr{};
  9530. socklen_t cli_len = sizeof(cli_addr);
  9531. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9532. if (cli != INVALID_SOCKET) {
  9533. char buf[4096];
  9534. ::recv(cli, buf, sizeof(buf), 0);
  9535. auto content_length = std::to_string(DATA_SIZE);
  9536. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9537. "Content-Length: " +
  9538. content_length +
  9539. "\r\n"
  9540. "Connection: close\r\n"
  9541. "\r\n";
  9542. ::send(cli,
  9543. #ifdef _WIN32
  9544. static_cast<const char *>(response_header.c_str()),
  9545. static_cast<int>(response_header.size()),
  9546. #else
  9547. response_header.c_str(), response_header.size(),
  9548. #endif
  9549. 0);
  9550. std::string chunk(64 * 1024, 'A');
  9551. size_t total_sent = 0;
  9552. while (total_sent < DATA_SIZE) {
  9553. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9554. auto sent = ::send(cli,
  9555. #ifdef _WIN32
  9556. static_cast<const char *>(chunk.c_str()),
  9557. static_cast<int>(to_send),
  9558. #else
  9559. chunk.c_str(), to_send,
  9560. #endif
  9561. 0);
  9562. if (sent <= 0) break;
  9563. total_sent += static_cast<size_t>(sent);
  9564. }
  9565. #ifdef _WIN32
  9566. ::shutdown(cli, SD_SEND);
  9567. #else
  9568. ::shutdown(cli, SHUT_WR);
  9569. #endif
  9570. char drain[1024];
  9571. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9572. detail::close_socket(cli);
  9573. }
  9574. detail::close_socket(srv);
  9575. });
  9576. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9577. size_t total_received = 0;
  9578. {
  9579. Client cli("127.0.0.1", PORT + 2);
  9580. cli.set_read_timeout(10, 0);
  9581. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9582. auto res =
  9583. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9584. total_received += data_length;
  9585. return true;
  9586. });
  9587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9588. EXPECT_EQ(StatusCode::OK_200, res->status);
  9589. }
  9590. server_thread.join();
  9591. EXPECT_EQ(total_received, DATA_SIZE)
  9592. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9593. << " bytes (larger than " << DATA_SIZE
  9594. << " bytes response), content_receiver should read all data, but only "
  9595. "read "
  9596. << total_received << " bytes.";
  9597. }
  9598. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9599. // Regression test for "zip bomb" attack on the client side: a malicious server
  9600. // sends a small gzip-compressed response that decompresses to a huge payload.
  9601. // The client must enforce payload_max_length on the decompressed size.
  9602. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9603. constexpr size_t DECOMPRESSED_SIZE =
  9604. 10 * 1024 * 1024; // 10MB after decompression
  9605. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9606. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9607. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9608. std::string compressed;
  9609. {
  9610. httplib::detail::gzip_compressor compressor;
  9611. bool ok =
  9612. compressor.compress(uncompressed.data(), uncompressed.size(),
  9613. /*last=*/true, [&](const char *buf, size_t len) {
  9614. compressed.append(buf, len);
  9615. return true;
  9616. });
  9617. ASSERT_TRUE(ok);
  9618. }
  9619. // Sanity: compressed data should be much smaller than the decompressed size
  9620. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9621. #ifndef _WIN32
  9622. signal(SIGPIPE, SIG_IGN);
  9623. #endif
  9624. // Set up the listening socket in the main thread so the server is guaranteed
  9625. // to be ready before the client connects (eliminates race condition).
  9626. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9627. default_socket_options(srv);
  9628. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9629. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9630. sockaddr_in addr{};
  9631. addr.sin_family = AF_INET;
  9632. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9633. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9634. int opt = 1;
  9635. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9636. #ifdef _WIN32
  9637. reinterpret_cast<const char *>(&opt),
  9638. #else
  9639. &opt,
  9640. #endif
  9641. sizeof(opt));
  9642. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9643. ASSERT_EQ(0, ::listen(srv, 1));
  9644. auto server_thread = std::thread([&compressed, srv] {
  9645. sockaddr_in cli_addr{};
  9646. socklen_t cli_len = sizeof(cli_addr);
  9647. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9648. if (cli != INVALID_SOCKET) {
  9649. // Read the full HTTP request (until \r\n\r\n)
  9650. char buf[4096];
  9651. size_t total = 0;
  9652. while (total < sizeof(buf)) {
  9653. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9654. if (n <= 0) break;
  9655. total += static_cast<size_t>(n);
  9656. // Check for end of headers
  9657. if (total >= 4) {
  9658. std::string req(buf, total);
  9659. if (req.find("\r\n\r\n") != std::string::npos) break;
  9660. }
  9661. }
  9662. // Malicious response: gzip-compressed body, no Content-Length
  9663. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9664. "Content-Encoding: gzip\r\n"
  9665. "Connection: close\r\n"
  9666. "\r\n";
  9667. ::send(cli,
  9668. #ifdef _WIN32
  9669. static_cast<const char *>(response_header.c_str()),
  9670. static_cast<int>(response_header.size()),
  9671. #else
  9672. response_header.c_str(), response_header.size(),
  9673. #endif
  9674. 0);
  9675. // Send the compressed payload (small on the wire, huge when decompressed)
  9676. size_t total_sent = 0;
  9677. while (total_sent < compressed.size()) {
  9678. auto to_send = std::min(compressed.size() - total_sent,
  9679. static_cast<size_t>(64 * 1024));
  9680. auto sent =
  9681. ::send(cli,
  9682. #ifdef _WIN32
  9683. static_cast<const char *>(compressed.c_str() + total_sent),
  9684. static_cast<int>(to_send),
  9685. #else
  9686. compressed.c_str() + total_sent, to_send,
  9687. #endif
  9688. 0);
  9689. if (sent <= 0) break;
  9690. total_sent += static_cast<size_t>(sent);
  9691. }
  9692. detail::close_socket(cli);
  9693. }
  9694. });
  9695. auto se = detail::scope_exit([&] {
  9696. detail::close_socket(srv);
  9697. server_thread.join();
  9698. });
  9699. size_t total_decompressed = 0;
  9700. {
  9701. Client cli("127.0.0.1", PORT + 3);
  9702. cli.set_read_timeout(5, 0);
  9703. cli.set_decompress(true);
  9704. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9705. auto stream = cli.open_stream("GET", "/zipbomb");
  9706. ASSERT_TRUE(stream.is_valid());
  9707. char buffer[64 * 1024];
  9708. ssize_t n;
  9709. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9710. total_decompressed += static_cast<size_t>(n);
  9711. }
  9712. }
  9713. // The decompressed size must be capped by payload_max_length. Without
  9714. // protection, the client would decompress the full 10MB from a tiny
  9715. // compressed payload, enabling a zip bomb DoS attack.
  9716. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9717. << "Client decompressed " << total_decompressed
  9718. << " bytes from a gzip response. The decompressed size should be "
  9719. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9720. }
  9721. #endif
  9722. TEST(HostAndPortPropertiesTest, NoSSL) {
  9723. httplib::Client cli("www.google.com", 1234);
  9724. ASSERT_EQ("www.google.com", cli.host());
  9725. ASSERT_EQ(1234, cli.port());
  9726. }
  9727. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9728. httplib::Client cli("www.google.com:1234");
  9729. ASSERT_EQ("www.google.com", cli.host());
  9730. ASSERT_EQ(1234, cli.port());
  9731. }
  9732. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9733. // Port number that overflows int — should not crash, client becomes invalid
  9734. httplib::Client cli("http://www.google.com:99999999999999999999");
  9735. ASSERT_FALSE(cli.is_valid());
  9736. }
  9737. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9738. // Port 99999 exceeds valid range (1-65535) — should not crash
  9739. httplib::Client cli("http://www.google.com:99999");
  9740. ASSERT_FALSE(cli.is_valid());
  9741. }
  9742. #ifdef CPPHTTPLIB_SSL_ENABLED
  9743. TEST(HostAndPortPropertiesTest, SSL) {
  9744. httplib::SSLClient cli("www.google.com");
  9745. ASSERT_EQ("www.google.com", cli.host());
  9746. ASSERT_EQ(443, cli.port());
  9747. }
  9748. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9749. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9750. std::string cert;
  9751. read_file(CA_CERT_FILE, cert);
  9752. httplib::SSLClient httplib_client("www.google.com");
  9753. // Load CA store first time
  9754. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9755. // Load CA store second time (update)
  9756. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9757. // Verify client is still valid and can make connections
  9758. httplib_client.enable_server_certificate_verification(true);
  9759. auto res = httplib_client.Get("/");
  9760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9761. // Google may return 200 or 301 depending on various factors
  9762. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9763. res->status == StatusCode::MovedPermanently_301);
  9764. }
  9765. TEST(SSLClientTest, ServerNameIndication_Online) {
  9766. auto host = "httpbingo.org";
  9767. auto path = std::string{"/get"};
  9768. SSLClient cli(host, 443);
  9769. auto res = cli.Get(path);
  9770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9771. ASSERT_EQ(StatusCode::OK_200, res->status);
  9772. }
  9773. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9774. // Use a site that will cause SSL verification failure due to self-signed cert
  9775. SSLClient cli("self-signed.badssl.com", 443);
  9776. cli.enable_server_certificate_verification(true);
  9777. auto res = cli.Get("/");
  9778. ASSERT_TRUE(!res);
  9779. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9780. // Verify backend error is captured for SSLServerVerification
  9781. // This occurs when certificate verification fails
  9782. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9783. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9784. EXPECT_NE(0UL, res.ssl_backend_error());
  9785. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9786. // For OpenSSL, ssl_error is 0 for verification errors
  9787. EXPECT_EQ(0, res.ssl_error());
  9788. #if !defined(_WIN32) || \
  9789. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9790. // On non-Windows or when Windows Schannel is disabled, the error comes
  9791. // from OpenSSL's verification
  9792. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9793. res.ssl_backend_error());
  9794. #endif
  9795. #endif
  9796. }
  9797. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9798. // Use a site where hostname doesn't match the certificate
  9799. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9800. SSLClient cli("wrong.host.badssl.com", 443);
  9801. cli.enable_server_certificate_verification(true);
  9802. cli.enable_server_hostname_verification(true);
  9803. auto res = cli.Get("/");
  9804. ASSERT_TRUE(!res);
  9805. // The error type depends on when hostname verification occurs:
  9806. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9807. // - Mbed TLS: SSLServerVerification (during handshake)
  9808. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9809. res.error() == Error::SSLServerVerification);
  9810. // Verify backend error is captured for hostname verification failure
  9811. EXPECT_NE(0UL, res.ssl_backend_error());
  9812. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9813. // For OpenSSL, ssl_error is 0 for verification errors
  9814. EXPECT_EQ(0, res.ssl_error());
  9815. #if !defined(_WIN32) || \
  9816. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9817. // On non-Windows or when Windows Schannel is disabled, the error comes
  9818. // from OpenSSL's hostname verification
  9819. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9820. res.ssl_backend_error());
  9821. #endif
  9822. #endif
  9823. }
  9824. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9825. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9826. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9827. SSLClient cli("www.google.com", 443);
  9828. cli.enable_server_certificate_verification(true);
  9829. auto res = cli.Get("/");
  9830. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9831. }
  9832. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9833. SSLClient cli("www.google.com", 443);
  9834. cli.enable_server_certificate_verification(true);
  9835. cli.enable_windows_certificate_verification(false);
  9836. auto res = cli.Get("/");
  9837. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9838. }
  9839. #endif
  9840. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9841. Client cli("https://google.com");
  9842. auto res = cli.Get("/");
  9843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9844. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9845. }
  9846. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9847. SSLClient cli("google.com");
  9848. cli.set_ca_cert_path(CA_CERT_FILE);
  9849. auto res = cli.Get("/");
  9850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9851. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9852. }
  9853. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9854. SSLClient cli("google.com");
  9855. cli.enable_server_certificate_verification(true);
  9856. cli.set_ca_cert_path("hello");
  9857. auto res = cli.Get("/");
  9858. ASSERT_TRUE(!res);
  9859. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9860. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9861. // should be set
  9862. EXPECT_EQ(0, res.ssl_error());
  9863. // Verify backend error is captured for SSLLoadingCerts
  9864. // This error occurs when loading CA certificates fails
  9865. EXPECT_NE(0UL, res.ssl_backend_error());
  9866. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9867. // OpenSSL specific error codes:
  9868. // > openssl errstr 0x80000002
  9869. // error:80000002:system library::No such file or directory
  9870. // > openssl errstr 0xA000126
  9871. // error:0A000126:SSL routines::unexpected eof while reading
  9872. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9873. res.ssl_backend_error() == 0xA000126);
  9874. #endif
  9875. }
  9876. TEST(SSLClientTest, ServerCertificateVerification4) {
  9877. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9878. ASSERT_TRUE(svr.is_valid());
  9879. svr.Get("/test", [&](const Request &, Response &res) {
  9880. res.set_content("test", "text/plain");
  9881. svr.stop();
  9882. ASSERT_TRUE(true);
  9883. });
  9884. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9885. auto se = detail::scope_exit([&] {
  9886. t.join();
  9887. ASSERT_FALSE(svr.is_running());
  9888. });
  9889. svr.wait_until_ready();
  9890. SSLClient cli("127.0.0.1", PORT);
  9891. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9892. cli.enable_server_certificate_verification(true);
  9893. cli.set_connection_timeout(30);
  9894. auto res = cli.Get("/test");
  9895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9896. ASSERT_EQ(StatusCode::OK_200, res->status);
  9897. }
  9898. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9899. std::string cert;
  9900. read_file(CA_CERT_FILE, cert);
  9901. SSLClient cli("google.com");
  9902. cli.load_ca_cert_store(cert.data(), cert.size());
  9903. const auto res = cli.Get("/");
  9904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9905. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9906. }
  9907. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9908. // clang-format off
  9909. static constexpr char cert[] =
  9910. "GlobalSign Root CA\n"
  9911. "==================\n"
  9912. "-----BEGIN CERTIFICATE-----\n"
  9913. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9914. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9915. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9916. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9917. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9918. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9919. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9920. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9921. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9922. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9923. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9924. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9925. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9926. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9927. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9928. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9929. "-----END CERTIFICATE-----\n";
  9930. // clang-format on
  9931. SSLClient cli("google.com");
  9932. cli.load_ca_cert_store(cert, sizeof(cert));
  9933. const auto res = cli.Get("/");
  9934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9935. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9936. }
  9937. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9938. SSLClient cli("www.youtube.com");
  9939. cli.set_ca_cert_path(CA_CERT_FILE);
  9940. cli.enable_server_certificate_verification(true);
  9941. cli.set_follow_location(true);
  9942. auto res = cli.Get("/");
  9943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9944. ASSERT_EQ(StatusCode::OK_200, res->status);
  9945. }
  9946. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9947. SSLClient cli("wWw.YouTube.Com");
  9948. cli.set_ca_cert_path(CA_CERT_FILE);
  9949. cli.enable_server_certificate_verification(true);
  9950. cli.enable_server_hostname_verification(true);
  9951. cli.set_follow_location(true);
  9952. auto res = cli.Get("/");
  9953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9954. ASSERT_EQ(StatusCode::OK_200, res->status);
  9955. }
  9956. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9957. SSLClient cli("gOoGlE.COm");
  9958. cli.enable_server_certificate_verification(true);
  9959. cli.enable_server_hostname_verification(true);
  9960. cli.set_follow_location(true);
  9961. auto res = cli.Get("/");
  9962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9963. ASSERT_EQ(StatusCode::OK_200, res->status);
  9964. }
  9965. TEST(SSLClientTest, Issue2004_Online) {
  9966. Client client("https://google.com");
  9967. client.set_follow_location(true);
  9968. auto res = client.Get("/");
  9969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9970. ASSERT_EQ(StatusCode::OK_200, res->status);
  9971. auto body = res->body;
  9972. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9973. }
  9974. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9975. // Create SSLClient with invalid cert/key to make is_valid() return false
  9976. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9977. "nonexistent_key.pem");
  9978. // is_valid() should be false due to cert loading failure
  9979. ASSERT_FALSE(cli.is_valid());
  9980. auto res = cli.Get("/");
  9981. ASSERT_FALSE(res);
  9982. EXPECT_EQ(Error::SSLConnection, res.error());
  9983. }
  9984. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9985. // Test for Issue #2251: SSL error not properly reported when client cert
  9986. // and key paths are swapped or mismatched
  9987. // This simulates the scenario where user accidentally swaps the cert and key
  9988. // files
  9989. // Using client cert file as private key and vice versa (completely wrong)
  9990. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9991. // Should fail validation due to cert/key mismatch
  9992. ASSERT_FALSE(cli.is_valid());
  9993. // Attempt to make a request should fail with proper error
  9994. auto res = cli.Get("/");
  9995. ASSERT_FALSE(res);
  9996. EXPECT_EQ(Error::SSLConnection, res.error());
  9997. // SSL error should be recorded in the Result object (this is the key fix for
  9998. // Issue #2251)
  9999. auto backend_error = res.ssl_backend_error();
  10000. EXPECT_NE(0u, backend_error);
  10001. }
  10002. // Tests cert/key mismatch detection at the TLS context level
  10003. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10004. // Test that using mismatched cert/key causes connection failure.
  10005. // We verify this at the SSLClient level rather than through internal
  10006. // TLS API functions.
  10007. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10008. cli.enable_server_certificate_verification(false);
  10009. cli.set_connection_timeout(2);
  10010. // The mismatch should cause a connection or handshake error
  10011. auto res = cli.Get("/test");
  10012. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10013. // Either way, the request should fail
  10014. EXPECT_FALSE(res);
  10015. }
  10016. #endif
  10017. #if 0
  10018. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10019. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10020. ASSERT_TRUE(cli != nullptr);
  10021. cli->set_address_family(AF_INET6);
  10022. cli->set_interface("en0");
  10023. auto res = cli->Get("/get");
  10024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10025. ASSERT_EQ(StatusCode::OK_200, res->status);
  10026. }
  10027. #endif
  10028. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10029. #ifdef CPPHTTPLIB_SSL_ENABLED
  10030. void ClientCertPresent(
  10031. const std::string &client_cert_file,
  10032. const std::string &client_private_key_file,
  10033. const std::string &client_encrypted_private_key_pass = std::string()) {
  10034. using namespace httplib::tls;
  10035. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10036. CLIENT_CA_CERT_DIR);
  10037. ASSERT_TRUE(svr.is_valid());
  10038. svr.Get("/test", [&](const Request &req, Response &res) {
  10039. res.set_content("test", "text/plain");
  10040. auto cert = req.peer_cert();
  10041. ASSERT_TRUE(static_cast<bool>(cert));
  10042. std::string common_name = cert.subject_cn();
  10043. EXPECT_EQ("Common Name", common_name);
  10044. });
  10045. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10046. auto se = detail::scope_exit([&] {
  10047. svr.stop();
  10048. t.join();
  10049. ASSERT_FALSE(svr.is_running());
  10050. });
  10051. svr.wait_until_ready();
  10052. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10053. client_encrypted_private_key_pass);
  10054. cli.enable_server_certificate_verification(false);
  10055. cli.set_connection_timeout(30);
  10056. auto res = cli.Get("/test");
  10057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10058. ASSERT_EQ(StatusCode::OK_200, res->status);
  10059. }
  10060. TEST(SSLClientServerTest, ClientCertPresent) {
  10061. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10062. }
  10063. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10064. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10065. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10066. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10067. }
  10068. // PEM memory-based constructor tests (works with all TLS backends)
  10069. void PemMemoryClientCertPresent(
  10070. const std::string &client_cert_file,
  10071. const std::string &client_private_key_file,
  10072. const std::string &client_encrypted_private_key_pass = std::string()) {
  10073. // Read PEM files into memory
  10074. std::string server_cert_pem, server_key_pem;
  10075. std::string client_ca_pem;
  10076. std::string client_cert_pem, client_key_pem;
  10077. read_file(SERVER_CERT_FILE, server_cert_pem);
  10078. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10079. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10080. read_file(client_cert_file, client_cert_pem);
  10081. read_file(client_private_key_file, client_key_pem);
  10082. // Create server with PEM memory
  10083. SSLServer::PemMemory server_pem = {
  10084. server_cert_pem.c_str(),
  10085. server_cert_pem.size(),
  10086. server_key_pem.c_str(),
  10087. server_key_pem.size(),
  10088. client_ca_pem.c_str(),
  10089. client_ca_pem.size(),
  10090. nullptr // no password for server key
  10091. };
  10092. SSLServer svr(server_pem);
  10093. ASSERT_TRUE(svr.is_valid());
  10094. svr.Get("/test", [&](const Request &, Response &res) {
  10095. res.set_content("test", "text/plain");
  10096. });
  10097. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10098. auto se = detail::scope_exit([&] {
  10099. svr.stop();
  10100. t.join();
  10101. ASSERT_FALSE(svr.is_running());
  10102. });
  10103. svr.wait_until_ready();
  10104. // Create client with PEM memory
  10105. const char *password = client_encrypted_private_key_pass.empty()
  10106. ? nullptr
  10107. : client_encrypted_private_key_pass.c_str();
  10108. SSLClient::PemMemory client_pem = {
  10109. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10110. client_key_pem.size(), password};
  10111. SSLClient cli(HOST, PORT, client_pem);
  10112. cli.enable_server_certificate_verification(false);
  10113. cli.set_connection_timeout(30);
  10114. auto res = cli.Get("/test");
  10115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10116. ASSERT_EQ(StatusCode::OK_200, res->status);
  10117. }
  10118. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10119. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10120. }
  10121. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10122. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10123. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10124. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10125. }
  10126. TEST(SSLClientServerTest, ClientCertMissing) {
  10127. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10128. CLIENT_CA_CERT_DIR);
  10129. ASSERT_TRUE(svr.is_valid());
  10130. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10131. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10132. auto se = detail::scope_exit([&] {
  10133. svr.stop();
  10134. t.join();
  10135. ASSERT_FALSE(svr.is_running());
  10136. });
  10137. svr.wait_until_ready();
  10138. SSLClient cli(HOST, PORT);
  10139. cli.set_connection_timeout(30);
  10140. auto res = cli.Get("/test");
  10141. ASSERT_TRUE(!res);
  10142. // When client cert is missing and server requires it, connection fails
  10143. // Error type depends on backend implementation
  10144. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10145. res.error() == Error::SSLConnection);
  10146. // Verify backend error is captured
  10147. // Note: This test may have different error codes depending on the exact
  10148. // verification failure
  10149. EXPECT_NE(0UL, res.ssl_backend_error());
  10150. }
  10151. TEST(SSLClientServerTest, TrustDirOptional) {
  10152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10153. ASSERT_TRUE(svr.is_valid());
  10154. svr.Get("/test", [&](const Request &, Response &res) {
  10155. res.set_content("test", "text/plain");
  10156. });
  10157. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10158. auto se = detail::scope_exit([&] {
  10159. svr.stop();
  10160. t.join();
  10161. ASSERT_FALSE(svr.is_running());
  10162. });
  10163. svr.wait_until_ready();
  10164. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10165. cli.enable_server_certificate_verification(false);
  10166. cli.set_connection_timeout(30);
  10167. auto res = cli.Get("/test");
  10168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10169. ASSERT_EQ(StatusCode::OK_200, res->status);
  10170. }
  10171. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10172. class NoListenSSLServer : public SSLServer {
  10173. public:
  10174. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10175. const char *client_ca_cert_file_path,
  10176. const char *client_ca_cert_dir_path = nullptr)
  10177. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10178. client_ca_cert_dir_path),
  10179. stop_(false) {}
  10180. std::atomic_bool stop_;
  10181. private:
  10182. bool process_and_close_socket(socket_t /*sock*/) override {
  10183. // Don't create SSL context
  10184. while (!stop_.load()) {
  10185. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10186. }
  10187. return true;
  10188. }
  10189. };
  10190. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10191. CLIENT_CA_CERT_FILE);
  10192. ASSERT_TRUE(svr.is_valid());
  10193. svr.Get("/test", [&](const Request &, Response &res) {
  10194. res.set_content("test", "text/plain");
  10195. });
  10196. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10197. auto se = detail::scope_exit([&] {
  10198. svr.stop_ = true;
  10199. svr.stop();
  10200. t.join();
  10201. ASSERT_FALSE(svr.is_running());
  10202. });
  10203. svr.wait_until_ready();
  10204. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10205. cli.enable_server_certificate_verification(false);
  10206. cli.set_connection_timeout(1);
  10207. auto res = cli.Get("/test");
  10208. ASSERT_TRUE(!res);
  10209. EXPECT_EQ(Error::SSLConnection, res.error());
  10210. // Timeout results in WantRead error code (maps to backend-specific value)
  10211. EXPECT_NE(0, res.ssl_error());
  10212. }
  10213. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10214. // Test SSLServer with client certificate verification using the standard
  10215. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10216. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10217. CLIENT_CA_CERT_DIR);
  10218. ASSERT_TRUE(svr.is_valid());
  10219. svr.Get("/test", [&](const Request &req, Response &res) {
  10220. res.set_content("test", "text/plain");
  10221. auto cert = req.peer_cert();
  10222. ASSERT_TRUE(static_cast<bool>(cert));
  10223. auto common_name = cert.subject_cn();
  10224. EXPECT_EQ("Common Name", common_name);
  10225. });
  10226. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10227. auto se = detail::scope_exit([&] {
  10228. svr.stop();
  10229. t.join();
  10230. ASSERT_FALSE(svr.is_running());
  10231. });
  10232. svr.wait_until_ready();
  10233. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10234. cli.enable_server_certificate_verification(false);
  10235. cli.set_connection_timeout(30);
  10236. auto res = cli.Get("/test");
  10237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10238. ASSERT_EQ(StatusCode::OK_200, res->status);
  10239. }
  10240. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10241. // Verifies that wildcard matching and exact matching work consistently
  10242. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10243. using namespace httplib::tls;
  10244. // We need a running server to test against
  10245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10246. ASSERT_TRUE(svr.is_valid());
  10247. svr.Get("/test", [](const Request &, Response &res) {
  10248. res.set_content("ok", "text/plain");
  10249. });
  10250. thread t([&]() { svr.listen(HOST, PORT); });
  10251. auto se = detail::scope_exit([&] {
  10252. svr.stop();
  10253. t.join();
  10254. });
  10255. svr.wait_until_ready();
  10256. bool verify_callback_called = false;
  10257. bool verify_result_wrong = false;
  10258. SSLClient cli(HOST, PORT);
  10259. cli.enable_server_certificate_verification(true);
  10260. cli.set_ca_cert_path(CA_CERT_FILE);
  10261. cli.set_connection_timeout(5);
  10262. // Note: Test certificate has CN="Common Name", not "localhost"
  10263. bool verify_result_cn = false;
  10264. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10265. verify_callback_called = true;
  10266. if (!ctx.cert) return false;
  10267. // Test 1: "Common Name" should match (our test server cert CN)
  10268. verify_result_cn = ctx.check_hostname("Common Name");
  10269. // Test 2: wrong hostname should not match
  10270. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10271. return true; // Accept for the purpose of this test
  10272. });
  10273. auto res = cli.Get("/test");
  10274. // The request may succeed or fail depending on cert configuration
  10275. // but the callback should have been called
  10276. ASSERT_TRUE(verify_callback_called)
  10277. << "Verify callback should have been called";
  10278. // CN="Common Name" should match our test certificate
  10279. //
  10280. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10281. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10282. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10283. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10284. // <openssl/base.h>, which is included transitively when
  10285. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10286. #if defined(OPENSSL_IS_BORINGSSL)
  10287. EXPECT_FALSE(verify_result_cn)
  10288. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10289. #else
  10290. EXPECT_TRUE(verify_result_cn)
  10291. << "verify_hostname should match 'Common Name' (certificate CN)";
  10292. #endif
  10293. // Wrong hostname should not match
  10294. EXPECT_FALSE(verify_result_wrong)
  10295. << "verify_hostname should not match 'wronghost.example.com'";
  10296. }
  10297. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10298. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10299. // X509_check_ip behavior and must hold for every backend.
  10300. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10301. using namespace httplib::tls;
  10302. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10303. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10304. ASSERT_TRUE(svr.is_valid());
  10305. svr.Get("/test", [](const Request &, Response &res) {
  10306. res.set_content("ok", "text/plain");
  10307. });
  10308. thread t([&]() { svr.listen(HOST, PORT); });
  10309. auto se = detail::scope_exit([&] {
  10310. svr.stop();
  10311. t.join();
  10312. });
  10313. svr.wait_until_ready();
  10314. bool verify_callback_called = false;
  10315. bool ip_matched_via_cn = true;
  10316. SSLClient cli(HOST, PORT);
  10317. cli.enable_server_certificate_verification(true);
  10318. cli.set_ca_cert_path(CA_CERT_FILE);
  10319. cli.set_connection_timeout(5);
  10320. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10321. verify_callback_called = true;
  10322. if (!ctx.cert) return false;
  10323. // The IP appears only in the CN, so it must NOT be accepted.
  10324. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10325. return true; // Accept for the purpose of this test
  10326. });
  10327. cli.Get("/test");
  10328. ASSERT_TRUE(verify_callback_called)
  10329. << "Verify callback should have been called";
  10330. EXPECT_FALSE(ip_matched_via_cn)
  10331. << "An IP host must not be authenticated via the certificate CN";
  10332. }
  10333. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10334. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10335. using namespace httplib::tls;
  10336. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10337. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10338. ASSERT_TRUE(svr.is_valid());
  10339. svr.Get("/test", [](const Request &, Response &res) {
  10340. res.set_content("ok", "text/plain");
  10341. });
  10342. thread t([&]() { svr.listen(HOST, PORT); });
  10343. auto se = detail::scope_exit([&] {
  10344. svr.stop();
  10345. t.join();
  10346. });
  10347. svr.wait_until_ready();
  10348. bool verify_callback_called = false;
  10349. bool san_matched = false;
  10350. bool wrong_ipv6_matched = true;
  10351. bool cn_ipv6_matched = true;
  10352. SSLClient cli(HOST, PORT);
  10353. cli.enable_server_certificate_verification(true);
  10354. cli.set_ca_cert_path(CA_CERT_FILE);
  10355. cli.set_connection_timeout(5);
  10356. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10357. verify_callback_called = true;
  10358. if (!ctx.cert) return false;
  10359. // Matches the IPv6 iPAddress SAN.
  10360. san_matched = ctx.check_hostname("2001:db8::1");
  10361. // A different IPv6 address must not match.
  10362. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10363. // "::1" lives only in the CN, so it must not be accepted.
  10364. cn_ipv6_matched = ctx.check_hostname("::1");
  10365. return true; // Accept for the purpose of this test
  10366. });
  10367. cli.Get("/test");
  10368. ASSERT_TRUE(verify_callback_called)
  10369. << "Verify callback should have been called";
  10370. EXPECT_TRUE(san_matched)
  10371. << "verify_hostname should match an IPv6 iPAddress SAN";
  10372. EXPECT_FALSE(wrong_ipv6_matched)
  10373. << "verify_hostname should not match a non-matching IPv6 address";
  10374. EXPECT_FALSE(cn_ipv6_matched)
  10375. << "An IPv6 host must not be authenticated via the certificate CN";
  10376. }
  10377. #endif
  10378. // mbedTLS-specific callback constructor test
  10379. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10380. #ifdef CPPHTTPLIB_SSL_ENABLED
  10381. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10382. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10383. ASSERT_TRUE(svr.is_valid());
  10384. // Set up a handler to verify client certificate is present
  10385. bool client_cert_verified = false;
  10386. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10387. // Verify that client certificate was provided
  10388. client_cert_verified = true;
  10389. res.set_content("success", "text/plain");
  10390. });
  10391. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10392. auto se = detail::scope_exit([&] {
  10393. svr.stop();
  10394. t.join();
  10395. ASSERT_FALSE(svr.is_running());
  10396. });
  10397. svr.wait_until_ready();
  10398. // Client with certificate
  10399. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10400. cli.enable_server_certificate_verification(false);
  10401. cli.set_connection_timeout(30);
  10402. auto res = cli.Get("/test");
  10403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10404. ASSERT_EQ(StatusCode::OK_200, res->status);
  10405. ASSERT_TRUE(client_cert_verified);
  10406. EXPECT_EQ("success", res->body);
  10407. }
  10408. #endif
  10409. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10410. // backends
  10411. #ifdef CPPHTTPLIB_SSL_ENABLED
  10412. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10413. using namespace httplib::tls;
  10414. // Test that when client CA cert file is provided,
  10415. // the server properly requests and validates client certificates
  10416. // Create a server with client authentication
  10417. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10418. ASSERT_TRUE(svr.is_valid());
  10419. bool handler_called = false;
  10420. svr.Get("/test", [&](const Request &req, Response &res) {
  10421. handler_called = true;
  10422. // Verify that a client certificate was provided
  10423. auto cert = req.peer_cert();
  10424. ASSERT_TRUE(static_cast<bool>(cert));
  10425. // Get the issuer name
  10426. std::string issuer_str = cert.issuer_name();
  10427. ASSERT_FALSE(issuer_str.empty());
  10428. // The client certificate should be issued by our test CA
  10429. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10430. res.set_content("authenticated", "text/plain");
  10431. });
  10432. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10433. auto se = detail::scope_exit([&] {
  10434. svr.stop();
  10435. t.join();
  10436. ASSERT_FALSE(svr.is_running());
  10437. });
  10438. svr.wait_until_ready();
  10439. // Connect with a client certificate issued by the CA
  10440. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10441. cli.enable_server_certificate_verification(false);
  10442. cli.set_connection_timeout(30);
  10443. auto res = cli.Get("/test");
  10444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10445. ASSERT_EQ(StatusCode::OK_200, res->status);
  10446. ASSERT_TRUE(handler_called);
  10447. EXPECT_EQ("authenticated", res->body);
  10448. }
  10449. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10450. using namespace httplib::tls;
  10451. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10452. ASSERT_TRUE(svr.is_valid());
  10453. svr.Get("/test", [](const Request &, Response &res) {
  10454. res.set_content("ok", "text/plain");
  10455. });
  10456. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10457. auto se = detail::scope_exit([&] {
  10458. svr.stop();
  10459. t.join();
  10460. });
  10461. svr.wait_until_ready();
  10462. SSLClient cli(HOST, PORT);
  10463. cli.enable_server_certificate_verification(false);
  10464. cli.set_connection_timeout(30);
  10465. bool cert_checked = false;
  10466. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10467. if (ctx.cert) {
  10468. auto sans = ctx.sans();
  10469. // Test certificate may or may not have SANs - just verify the API
  10470. // works If SANs exist, verify the types are valid
  10471. for (const auto &san : sans) {
  10472. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10473. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10474. san.type == SanType::OTHER);
  10475. EXPECT_FALSE(san.value.empty());
  10476. }
  10477. cert_checked = true;
  10478. }
  10479. return true;
  10480. });
  10481. auto res = cli.Get("/test");
  10482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10483. EXPECT_TRUE(cert_checked);
  10484. }
  10485. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10486. using namespace httplib::tls;
  10487. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10488. ASSERT_TRUE(svr.is_valid());
  10489. svr.Get("/test", [](const Request &, Response &res) {
  10490. res.set_content("ok", "text/plain");
  10491. });
  10492. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10493. auto se = detail::scope_exit([&] {
  10494. svr.stop();
  10495. t.join();
  10496. });
  10497. svr.wait_until_ready();
  10498. SSLClient cli(HOST, PORT);
  10499. cli.enable_server_certificate_verification(false);
  10500. cli.set_connection_timeout(30);
  10501. bool validity_checked = false;
  10502. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10503. if (ctx.cert) {
  10504. time_t not_before = 0, not_after = 0;
  10505. bool result = ctx.validity(not_before, not_after);
  10506. EXPECT_TRUE(result);
  10507. // Verify that not_before < now < not_after for a valid cert
  10508. time_t now = time(nullptr);
  10509. EXPECT_LT(not_before, now);
  10510. EXPECT_GT(not_after, now);
  10511. validity_checked = true;
  10512. }
  10513. return true;
  10514. });
  10515. auto res = cli.Get("/test");
  10516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10517. EXPECT_TRUE(validity_checked);
  10518. }
  10519. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10520. using namespace httplib::tls;
  10521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10522. ASSERT_TRUE(svr.is_valid());
  10523. svr.Get("/test", [](const Request &, Response &res) {
  10524. res.set_content("ok", "text/plain");
  10525. });
  10526. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10527. auto se = detail::scope_exit([&] {
  10528. svr.stop();
  10529. t.join();
  10530. });
  10531. svr.wait_until_ready();
  10532. SSLClient cli(HOST, PORT);
  10533. cli.enable_server_certificate_verification(false);
  10534. cli.set_connection_timeout(30);
  10535. bool serial_checked = false;
  10536. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10537. if (ctx.cert) {
  10538. std::string serial = ctx.serial();
  10539. EXPECT_FALSE(serial.empty());
  10540. // Serial should be a hex string
  10541. for (char c : serial) {
  10542. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10543. (c >= 'a' && c <= 'f'));
  10544. }
  10545. serial_checked = true;
  10546. }
  10547. return true;
  10548. });
  10549. auto res = cli.Get("/test");
  10550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10551. EXPECT_TRUE(serial_checked);
  10552. }
  10553. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10554. // Test 1: Valid CA file - no error should be recorded
  10555. {
  10556. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10557. CLIENT_CA_CERT_FILE);
  10558. ASSERT_TRUE(svr.is_valid());
  10559. // With valid setup, last_ssl_error should be 0
  10560. EXPECT_EQ(0, svr.ssl_last_error());
  10561. }
  10562. // Test 2: Invalid CA file content
  10563. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10564. {
  10565. // Create a temporary file with completely invalid content
  10566. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10567. {
  10568. std::ofstream ofs(temp_invalid_ca);
  10569. ofs << "This is not a certificate file at all\n";
  10570. ofs << "Just plain text content\n";
  10571. }
  10572. // Create server with invalid CA file
  10573. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10574. // Clean up temporary file
  10575. std::remove(temp_invalid_ca);
  10576. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10577. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10578. // Note: SSL_CTX_load_verify_locations typically fails first,
  10579. // but our error handling code path is still exercised
  10580. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10581. }
  10582. }
  10583. TEST(VerifyCallbackTest, VerifyContextFields) {
  10584. using namespace httplib::tls;
  10585. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10586. ASSERT_TRUE(svr.is_valid());
  10587. svr.Get("/test", [](const Request &, Response &res) {
  10588. res.set_content("ok", "text/plain");
  10589. });
  10590. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10591. auto se = detail::scope_exit([&] {
  10592. svr.stop();
  10593. t.join();
  10594. });
  10595. svr.wait_until_ready();
  10596. SSLClient cli(HOST, PORT);
  10597. cli.enable_server_certificate_verification(false);
  10598. cli.set_connection_timeout(30);
  10599. int callback_count = 0;
  10600. bool saw_leaf_cert = false;
  10601. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10602. if (ctx.cert) {
  10603. callback_count++;
  10604. // We should see at least one certificate (the leaf)
  10605. std::string cn = ctx.subject_cn();
  10606. if (!cn.empty()) { saw_leaf_cert = true; }
  10607. // Verify context fields are populated
  10608. EXPECT_NE(ctx.session, nullptr);
  10609. EXPECT_GE(ctx.depth, 0);
  10610. }
  10611. return true;
  10612. });
  10613. auto res = cli.Get("/test");
  10614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10615. EXPECT_GT(callback_count, 0);
  10616. EXPECT_TRUE(saw_leaf_cert);
  10617. }
  10618. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10619. using httplib::tls::TlsError;
  10620. // Test that verify_error_to_string returns empty for success
  10621. std::string success_str = TlsError::verify_error_to_string(0);
  10622. EXPECT_TRUE(success_str.empty());
  10623. // Test that verify_error_to_string returns non-empty for error codes
  10624. // Using a common error code (certificate expired)
  10625. std::string error_str =
  10626. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10627. EXPECT_FALSE(error_str.empty());
  10628. }
  10629. TEST(SessionVerifierTest, CertificateAccepted) {
  10630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10631. ASSERT_TRUE(svr.is_valid());
  10632. svr.Get("/test", [](const Request &, Response &res) {
  10633. res.set_content("ok", "text/plain");
  10634. });
  10635. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10636. auto se = detail::scope_exit([&] {
  10637. svr.stop();
  10638. t.join();
  10639. });
  10640. svr.wait_until_ready();
  10641. SSLClient cli(HOST, PORT);
  10642. cli.enable_server_certificate_verification(false);
  10643. cli.set_connection_timeout(30);
  10644. bool callback_called = false;
  10645. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10646. EXPECT_NE(session, nullptr);
  10647. callback_called = true;
  10648. return SSLVerifierResponse::CertificateAccepted;
  10649. });
  10650. auto res = cli.Get("/test");
  10651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10652. EXPECT_EQ(200, res->status);
  10653. EXPECT_TRUE(callback_called);
  10654. }
  10655. TEST(SessionVerifierTest, CertificateRejected) {
  10656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10657. ASSERT_TRUE(svr.is_valid());
  10658. svr.Get("/test", [](const Request &, Response &res) {
  10659. res.set_content("ok", "text/plain");
  10660. });
  10661. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10662. auto se = detail::scope_exit([&] {
  10663. svr.stop();
  10664. t.join();
  10665. });
  10666. svr.wait_until_ready();
  10667. SSLClient cli(HOST, PORT);
  10668. cli.enable_server_certificate_verification(false);
  10669. cli.set_connection_timeout(30);
  10670. bool callback_called = false;
  10671. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10672. EXPECT_NE(session, nullptr);
  10673. callback_called = true;
  10674. return SSLVerifierResponse::CertificateRejected;
  10675. });
  10676. auto res = cli.Get("/test");
  10677. EXPECT_FALSE(res);
  10678. EXPECT_TRUE(callback_called);
  10679. }
  10680. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10682. ASSERT_TRUE(svr.is_valid());
  10683. svr.Get("/test", [](const Request &, Response &res) {
  10684. res.set_content("ok", "text/plain");
  10685. });
  10686. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10687. auto se = detail::scope_exit([&] {
  10688. svr.stop();
  10689. t.join();
  10690. });
  10691. svr.wait_until_ready();
  10692. // NoDecisionMade with verification disabled should succeed (no default check)
  10693. SSLClient cli(HOST, PORT);
  10694. cli.enable_server_certificate_verification(false);
  10695. cli.set_connection_timeout(30);
  10696. bool callback_called = false;
  10697. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10698. EXPECT_NE(session, nullptr);
  10699. callback_called = true;
  10700. return SSLVerifierResponse::NoDecisionMade;
  10701. });
  10702. auto res = cli.Get("/test");
  10703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10704. EXPECT_EQ(200, res->status);
  10705. EXPECT_TRUE(callback_called);
  10706. }
  10707. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10709. ASSERT_TRUE(svr.is_valid());
  10710. svr.Get("/test", [](const Request &, Response &res) {
  10711. res.set_content("ok", "text/plain");
  10712. });
  10713. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10714. auto se = detail::scope_exit([&] {
  10715. svr.stop();
  10716. t.join();
  10717. });
  10718. svr.wait_until_ready();
  10719. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10720. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10721. // so we only check that the request fails, not whether the callback was
  10722. // called.
  10723. SSLClient cli(HOST, PORT);
  10724. cli.enable_server_certificate_verification(true);
  10725. cli.set_connection_timeout(30);
  10726. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10727. EXPECT_NE(session, nullptr);
  10728. return SSLVerifierResponse::NoDecisionMade;
  10729. });
  10730. auto res = cli.Get("/test");
  10731. EXPECT_FALSE(res);
  10732. }
  10733. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10734. // Test SSL server using PemMemory constructor with client CA certificates
  10735. // Read PEM files
  10736. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10737. read_file(SERVER_CERT_FILE, server_cert_pem);
  10738. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10739. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10740. // Create SSLServer with PemMemory constructor including client CA
  10741. SSLServer::PemMemory server_pem = {
  10742. server_cert_pem.c_str(),
  10743. server_cert_pem.size(),
  10744. server_key_pem.c_str(),
  10745. server_key_pem.size(),
  10746. client_ca_pem.c_str(),
  10747. client_ca_pem.size(),
  10748. nullptr // no password for server key
  10749. };
  10750. SSLServer svr(server_pem);
  10751. ASSERT_TRUE(svr.is_valid());
  10752. // No SSL error should be recorded for valid setup
  10753. EXPECT_EQ(0, svr.ssl_last_error());
  10754. // Set up server endpoints
  10755. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10756. res.set_content("ok", "text/plain");
  10757. });
  10758. // Start server in a thread
  10759. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10760. svr.wait_until_ready();
  10761. // Connect with client certificate (using constructor with paths)
  10762. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10763. cli.enable_server_certificate_verification(false);
  10764. auto res = cli.Get("/test-pem-ca");
  10765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10766. EXPECT_EQ(200, res->status);
  10767. EXPECT_EQ("ok", res->body);
  10768. svr.stop();
  10769. server_thread.join();
  10770. }
  10771. #endif
  10772. #ifdef _WIN32
  10773. TEST(CleanupTest, WSACleanup) {
  10774. int ret = WSACleanup();
  10775. ASSERT_EQ(0, ret);
  10776. }
  10777. #endif
  10778. #ifndef CPPHTTPLIB_SSL_ENABLED
  10779. TEST(NoSSLSupport, SimpleInterface) {
  10780. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10781. }
  10782. #endif
  10783. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10784. TEST(InvalidScheme, SimpleInterface) {
  10785. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10786. }
  10787. #endif
  10788. TEST(NoScheme, SimpleInterface) {
  10789. Client cli("yahoo.com:80");
  10790. ASSERT_TRUE(cli.is_valid());
  10791. }
  10792. TEST(SendAPI, SimpleInterface_Online) {
  10793. Client cli("http://yahoo.com");
  10794. Request req;
  10795. req.method = "GET";
  10796. req.path = "/";
  10797. auto res = cli.send(req);
  10798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10799. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10800. }
  10801. TEST(SendAPI, WithParamsInRequest) {
  10802. Server svr;
  10803. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10804. EXPECT_TRUE(req.has_param("test"));
  10805. EXPECT_EQ("test_value", req.get_param_value("test"));
  10806. });
  10807. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10808. auto se = detail::scope_exit([&] {
  10809. svr.stop();
  10810. t.join();
  10811. ASSERT_FALSE(svr.is_running());
  10812. });
  10813. svr.wait_until_ready();
  10814. Client cli(HOST, PORT);
  10815. {
  10816. Request req;
  10817. req.method = "GET";
  10818. req.path = "/";
  10819. req.params.emplace("test", "test_value");
  10820. auto res = cli.send(req);
  10821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10822. }
  10823. {
  10824. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10826. }
  10827. }
  10828. TEST(ClientImplMethods, GetSocketTest) {
  10829. httplib::Server svr;
  10830. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10831. res.status = StatusCode::OK_200;
  10832. });
  10833. auto port = svr.bind_to_any_port("127.0.0.1");
  10834. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10835. auto se = detail::scope_exit([&] {
  10836. svr.stop();
  10837. thread.join();
  10838. ASSERT_FALSE(svr.is_running());
  10839. });
  10840. svr.wait_until_ready();
  10841. {
  10842. httplib::Client cli("127.0.0.1", port);
  10843. cli.set_keep_alive(true);
  10844. // Use the behavior of cpp-httplib of opening the connection
  10845. // only when the first request happens. If that changes,
  10846. // this test would be obsolete.
  10847. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10848. // This also implicitly tests the server. But other tests would fail much
  10849. // earlier than this one to be considered.
  10850. auto res = cli.Get("/");
  10851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10852. EXPECT_EQ(StatusCode::OK_200, res->status);
  10853. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10854. }
  10855. }
  10856. #ifdef CPPHTTPLIB_SSL_ENABLED
  10857. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10858. Client cli("http://yahoo.com");
  10859. auto res = cli.Get("/");
  10860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10861. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10862. cli.set_follow_location(true);
  10863. res = cli.Get("/");
  10864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10865. EXPECT_EQ(StatusCode::OK_200, res->status);
  10866. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10867. }
  10868. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10869. Client cli("https://yahoo.com");
  10870. auto res = cli.Get("/");
  10871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10872. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10873. cli.set_follow_location(true);
  10874. res = cli.Get("/");
  10875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10876. EXPECT_EQ(StatusCode::OK_200, res->status);
  10877. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10878. }
  10879. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10880. Client cli("https://yahoo.com");
  10881. auto res = cli.Get("/");
  10882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10883. ASSERT_FALSE(!res);
  10884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10885. ASSERT_FALSE(res == nullptr);
  10886. ASSERT_TRUE(res != nullptr);
  10887. EXPECT_EQ(Error::Success, res.error());
  10888. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10889. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10890. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10891. cli.set_follow_location(true);
  10892. res = cli.Get("/");
  10893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10894. EXPECT_EQ(Error::Success, res.error());
  10895. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10896. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10897. EXPECT_EQ(StatusCode::OK_200, res->status);
  10898. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10899. }
  10900. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10901. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10902. Client cli("https://cdnjs.cloudflare.com");
  10903. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10904. Headers{{"Accept-Encoding", "br"}});
  10905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10906. EXPECT_EQ(StatusCode::OK_200, res->status);
  10907. EXPECT_EQ(287630U, res->body.size());
  10908. EXPECT_EQ("application/javascript; charset=utf-8",
  10909. res->get_header_value("Content-Type"));
  10910. }
  10911. #endif
  10912. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10913. #undef REDIR_HOST // Silence compiler warning
  10914. #define REDIR_HOST "https://httpbingo.org"
  10915. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10916. Client cli(REDIR_HOST);
  10917. cli.set_follow_location(true);
  10918. auto res =
  10919. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10921. EXPECT_EQ(StatusCode::OK_200, res->status);
  10922. }
  10923. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10924. Client cli(REDIR_HOST);
  10925. cli.set_follow_location(true);
  10926. Params params;
  10927. params.emplace("url", "http://example.com");
  10928. params.emplace("status_code", "302");
  10929. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10931. EXPECT_EQ(StatusCode::OK_200, res->status);
  10932. }
  10933. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10934. Client cli(REDIR_HOST);
  10935. cli.set_follow_location(true);
  10936. Params params;
  10937. params.emplace("url", "http://example.com");
  10938. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10940. EXPECT_EQ(StatusCode::OK_200, res->status);
  10941. }
  10942. TEST(HttpToHttpsRedirectTest, CertFile) {
  10943. auto ssl_port = PORT + 1;
  10944. Server svr;
  10945. ASSERT_TRUE(svr.is_valid());
  10946. svr.Get("/index", [&](const Request &, Response &res) {
  10947. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10948. "/index");
  10949. svr.stop();
  10950. });
  10951. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10952. ASSERT_TRUE(ssl_svr.is_valid());
  10953. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10954. res.set_content("test", "text/plain");
  10955. ssl_svr.stop();
  10956. });
  10957. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10958. thread t2 =
  10959. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10960. auto se = detail::scope_exit([&] {
  10961. t2.join();
  10962. t.join();
  10963. ASSERT_FALSE(svr.is_running());
  10964. });
  10965. svr.wait_until_ready();
  10966. ssl_svr.wait_until_ready();
  10967. Client cli("127.0.0.1", PORT);
  10968. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10969. cli.enable_server_certificate_verification(true);
  10970. cli.set_follow_location(true);
  10971. cli.set_connection_timeout(30);
  10972. auto res = cli.Get("/index");
  10973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10974. ASSERT_EQ(StatusCode::OK_200, res->status);
  10975. }
  10976. TEST(SSLClientRedirectTest, CertFile) {
  10977. auto ssl_port = PORT + 1;
  10978. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10979. ASSERT_TRUE(ssl_svr1.is_valid());
  10980. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10981. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10982. "/index");
  10983. ssl_svr1.stop();
  10984. });
  10985. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10986. ASSERT_TRUE(ssl_svr2.is_valid());
  10987. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10988. res.set_content("test", "text/plain");
  10989. ssl_svr2.stop();
  10990. });
  10991. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10992. thread t2 =
  10993. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10994. auto se = detail::scope_exit([&] {
  10995. t2.join();
  10996. t.join();
  10997. ASSERT_FALSE(ssl_svr1.is_running());
  10998. });
  10999. ssl_svr1.wait_until_ready();
  11000. ssl_svr2.wait_until_ready();
  11001. SSLClient cli("127.0.0.1", PORT);
  11002. std::string cert;
  11003. read_file(SERVER_CERT2_FILE, cert);
  11004. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11005. cli.enable_server_certificate_verification(true);
  11006. cli.set_follow_location(true);
  11007. cli.set_connection_timeout(30);
  11008. auto res = cli.Get("/index");
  11009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11010. ASSERT_EQ(StatusCode::OK_200, res->status);
  11011. }
  11012. #endif
  11013. #ifdef CPPHTTPLIB_SSL_ENABLED
  11014. // Test that set_ca_cert_store() skips system certs (consistent with
  11015. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11016. // should be trusted - system certs should NOT be loaded.
  11017. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11018. // Load a specific cert that is NOT a system CA cert
  11019. std::string cert;
  11020. read_file(SERVER_CERT2_FILE, cert);
  11021. SSLClient cli("google.com");
  11022. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11023. cli.enable_server_certificate_verification(true);
  11024. // This should FAIL because:
  11025. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11026. // 2. System certs should NOT be loaded when custom store is set
  11027. // If system certs WERE loaded, this would succeed
  11028. auto res = cli.Get("/");
  11029. ASSERT_FALSE(res);
  11030. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11031. }
  11032. // Same as above, but through the native store handle path. Regression test:
  11033. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11034. // merged system certs into the user-provided store.
  11035. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11036. std::string cert;
  11037. read_file(SERVER_CERT2_FILE, cert);
  11038. SSLClient cli("google.com");
  11039. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11040. cli.enable_server_certificate_verification(true);
  11041. auto res = cli.Get("/");
  11042. ASSERT_FALSE(res);
  11043. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11044. }
  11045. // A custom store set via the native handle must still verify a server whose
  11046. // cert it does contain.
  11047. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11048. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11049. ASSERT_TRUE(svr.is_valid());
  11050. svr.Get("/test", [&](const Request &, Response &res) {
  11051. res.set_content("test", "text/plain");
  11052. });
  11053. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11054. auto se = detail::scope_exit([&] {
  11055. svr.stop();
  11056. t.join();
  11057. ASSERT_FALSE(svr.is_running());
  11058. });
  11059. svr.wait_until_ready();
  11060. SSLClient cli("127.0.0.1", PORT);
  11061. std::string cert;
  11062. read_file(SERVER_CERT2_FILE, cert);
  11063. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11064. cli.enable_server_certificate_verification(true);
  11065. cli.set_connection_timeout(30);
  11066. auto res = cli.Get("/test");
  11067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11068. ASSERT_EQ(StatusCode::OK_200, res->status);
  11069. }
  11070. // CA certs loaded through the universal Client must be transferred to the
  11071. // client created internally for following an HTTPS redirect. Regression test:
  11072. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11073. // the CA data for redirect transfer.
  11074. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11075. auto ssl_port = PORT + 1;
  11076. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11077. ASSERT_TRUE(ssl_svr1.is_valid());
  11078. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11079. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11080. "/index");
  11081. });
  11082. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11083. ASSERT_TRUE(ssl_svr2.is_valid());
  11084. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11085. res.set_content("test", "text/plain");
  11086. });
  11087. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11088. thread t2 =
  11089. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11090. auto se = detail::scope_exit([&] {
  11091. ssl_svr2.stop();
  11092. ssl_svr1.stop();
  11093. t2.join();
  11094. t.join();
  11095. ASSERT_FALSE(ssl_svr1.is_running());
  11096. });
  11097. ssl_svr1.wait_until_ready();
  11098. ssl_svr2.wait_until_ready();
  11099. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11100. std::string cert;
  11101. read_file(SERVER_CERT2_FILE, cert);
  11102. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11103. cli.enable_server_certificate_verification(true);
  11104. cli.set_follow_location(true);
  11105. cli.set_connection_timeout(30);
  11106. auto res = cli.Get("/index");
  11107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11108. ASSERT_EQ(StatusCode::OK_200, res->status);
  11109. }
  11110. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11111. // so a host signed by a system CA verifies even though a custom CA is set
  11112. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11113. std::string cert;
  11114. read_file(SERVER_CERT2_FILE, cert);
  11115. SSLClient cli("google.com");
  11116. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11117. cli.enable_system_ca(true);
  11118. cli.enable_server_certificate_verification(true);
  11119. auto res = cli.Get("/");
  11120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11121. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11122. }
  11123. // The custom CA remains effective when combined with the system CA
  11124. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11125. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11126. ASSERT_TRUE(svr.is_valid());
  11127. svr.Get("/test", [&](const Request &, Response &res) {
  11128. res.set_content("test", "text/plain");
  11129. });
  11130. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11131. auto se = detail::scope_exit([&] {
  11132. svr.stop();
  11133. t.join();
  11134. ASSERT_FALSE(svr.is_running());
  11135. });
  11136. svr.wait_until_ready();
  11137. SSLClient cli("127.0.0.1", PORT);
  11138. std::string cert;
  11139. read_file(SERVER_CERT2_FILE, cert);
  11140. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11141. cli.enable_system_ca(true);
  11142. cli.enable_server_certificate_verification(true);
  11143. cli.set_connection_timeout(30);
  11144. auto res = cli.Get("/test");
  11145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11146. ASSERT_EQ(StatusCode::OK_200, res->status);
  11147. }
  11148. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11149. // skip chain verification entirely (only the certificate identity was
  11150. // checked), so a server presenting an untrusted certificate with a matching
  11151. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11152. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11153. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11154. ASSERT_TRUE(svr.is_valid());
  11155. svr.Get("/test", [&](const Request &, Response &res) {
  11156. res.set_content("test", "text/plain");
  11157. });
  11158. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11159. auto se = detail::scope_exit([&] {
  11160. svr.stop();
  11161. t.join();
  11162. ASSERT_FALSE(svr.is_running());
  11163. });
  11164. svr.wait_until_ready();
  11165. SSLClient cli("127.0.0.1", PORT);
  11166. std::string cert;
  11167. // A trusted CA that did not sign the server certificate. The server cert
  11168. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11169. // this connection.
  11170. read_file(CLIENT_CA_CERT_FILE, cert);
  11171. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11172. cli.enable_server_certificate_verification(true);
  11173. cli.set_connection_timeout(30);
  11174. auto res = cli.Get("/test");
  11175. ASSERT_FALSE(res);
  11176. }
  11177. // enable_system_ca(false) prevents system CA loading entirely
  11178. TEST(SSLClientTest, DisableSystemCa_Online) {
  11179. SSLClient cli("google.com");
  11180. cli.enable_system_ca(false);
  11181. cli.enable_server_certificate_verification(true);
  11182. auto res = cli.Get("/");
  11183. ASSERT_FALSE(res);
  11184. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11185. // itself when the CA chain is empty
  11186. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11187. res.error() == Error::SSLConnection);
  11188. }
  11189. // The universal Client forwards enable_system_ca()
  11190. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11191. std::string cert;
  11192. read_file(SERVER_CERT2_FILE, cert);
  11193. Client cli("https://google.com");
  11194. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11195. cli.enable_system_ca(true);
  11196. cli.enable_server_certificate_verification(true);
  11197. auto res = cli.Get("/");
  11198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11199. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11200. }
  11201. // The system CA policy must carry over to the client created internally for
  11202. // following a cross-host HTTPS redirect
  11203. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11204. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11205. ASSERT_TRUE(svr.is_valid());
  11206. svr.Get("/index", [&](const Request &, Response &res) {
  11207. res.set_redirect("https://www.google.com/");
  11208. });
  11209. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11210. auto se = detail::scope_exit([&] {
  11211. svr.stop();
  11212. t.join();
  11213. ASSERT_FALSE(svr.is_running());
  11214. });
  11215. svr.wait_until_ready();
  11216. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11217. std::string cert;
  11218. read_file(SERVER_CERT2_FILE, cert);
  11219. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11220. cli.enable_system_ca(true);
  11221. cli.enable_server_certificate_verification(true);
  11222. cli.set_follow_location(true);
  11223. cli.set_connection_timeout(30);
  11224. // Receiving any response proves the redirect client completed the TLS
  11225. // handshake with a system-CA-signed host
  11226. auto res = cli.Get("/index");
  11227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11228. }
  11229. TEST(MultipartFormDataTest, LargeData) {
  11230. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11231. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11232. const ContentReader &content_reader) {
  11233. if (req.is_multipart_form_data()) {
  11234. std::vector<FormData> items;
  11235. content_reader(
  11236. [&](const FormData &file) {
  11237. items.push_back(file);
  11238. return true;
  11239. },
  11240. [&](const char *data, size_t data_length) {
  11241. items.back().content.append(data, data_length);
  11242. return true;
  11243. });
  11244. EXPECT_TRUE(std::string(items[0].name) == "document");
  11245. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11246. EXPECT_TRUE(items[0].filename == "2MB_data");
  11247. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11248. EXPECT_TRUE(items[1].name == "hello");
  11249. EXPECT_TRUE(items[1].content == "world");
  11250. EXPECT_TRUE(items[1].filename == "");
  11251. EXPECT_TRUE(items[1].content_type == "");
  11252. } else {
  11253. std::string body;
  11254. content_reader([&](const char *data, size_t data_length) {
  11255. body.append(data, data_length);
  11256. return true;
  11257. });
  11258. }
  11259. });
  11260. auto port = svr.bind_to_any_port(HOST);
  11261. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11262. auto se = detail::scope_exit([&] {
  11263. svr.stop();
  11264. t.join();
  11265. ASSERT_FALSE(svr.is_running());
  11266. });
  11267. svr.wait_until_ready();
  11268. {
  11269. std::string data(1024 * 1024 * 2, '.');
  11270. std::stringstream buffer;
  11271. buffer << data;
  11272. SSLClient cli(HOST, port);
  11273. cli.enable_server_certificate_verification(false);
  11274. UploadFormDataItems items{
  11275. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11276. {"hello", "world", "", ""},
  11277. };
  11278. auto res = cli.Post("/post", items);
  11279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11280. ASSERT_EQ(StatusCode::OK_200, res->status);
  11281. }
  11282. }
  11283. TEST(MultipartFormDataTest, DataProviderItems) {
  11284. std::random_device seed_gen;
  11285. std::mt19937 random(seed_gen());
  11286. std::string rand1;
  11287. rand1.resize(1000);
  11288. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11289. std::string rand2;
  11290. rand2.resize(3000);
  11291. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11292. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11293. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11294. const ContentReader &content_reader) {
  11295. ASSERT_FALSE(req.is_multipart_form_data());
  11296. std::string body;
  11297. content_reader([&](const char *data, size_t data_length) {
  11298. body.append(data, data_length);
  11299. return true;
  11300. });
  11301. EXPECT_EQ(body, "");
  11302. });
  11303. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11304. const ContentReader &content_reader) {
  11305. ASSERT_TRUE(req.is_multipart_form_data());
  11306. std::vector<FormData> items;
  11307. content_reader(
  11308. [&](const FormData &file) {
  11309. items.push_back(file);
  11310. return true;
  11311. },
  11312. [&](const char *data, size_t data_length) {
  11313. items.back().content.append(data, data_length);
  11314. return true;
  11315. });
  11316. ASSERT_TRUE(items.size() == 2);
  11317. EXPECT_EQ(std::string(items[0].name), "name1");
  11318. EXPECT_EQ(items[0].content, "Testing123");
  11319. EXPECT_EQ(items[0].filename, "filename1");
  11320. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11321. EXPECT_EQ(items[1].name, "name2");
  11322. EXPECT_EQ(items[1].content, "Testing456");
  11323. EXPECT_EQ(items[1].filename, "");
  11324. EXPECT_EQ(items[1].content_type, "");
  11325. });
  11326. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11327. const ContentReader &content_reader) {
  11328. ASSERT_TRUE(req.is_multipart_form_data());
  11329. std::vector<FormData> items;
  11330. content_reader(
  11331. [&](const FormData &file) {
  11332. items.push_back(file);
  11333. return true;
  11334. },
  11335. [&](const char *data, size_t data_length) {
  11336. items.back().content.append(data, data_length);
  11337. return true;
  11338. });
  11339. ASSERT_TRUE(items.size() == 2);
  11340. EXPECT_EQ(items[0].name, "name3");
  11341. EXPECT_EQ(items[0].content, rand1);
  11342. EXPECT_EQ(items[0].filename, "filename3");
  11343. EXPECT_EQ(items[0].content_type, "");
  11344. EXPECT_EQ(items[1].name, "name4");
  11345. EXPECT_EQ(items[1].content, rand2);
  11346. EXPECT_EQ(items[1].filename, "filename4");
  11347. EXPECT_EQ(items[1].content_type, "");
  11348. });
  11349. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11350. const ContentReader &content_reader) {
  11351. ASSERT_TRUE(req.is_multipart_form_data());
  11352. std::vector<FormData> items;
  11353. content_reader(
  11354. [&](const FormData &file) {
  11355. items.push_back(file);
  11356. return true;
  11357. },
  11358. [&](const char *data, size_t data_length) {
  11359. items.back().content.append(data, data_length);
  11360. return true;
  11361. });
  11362. ASSERT_TRUE(items.size() == 4);
  11363. EXPECT_EQ(std::string(items[0].name), "name1");
  11364. EXPECT_EQ(items[0].content, "Testing123");
  11365. EXPECT_EQ(items[0].filename, "filename1");
  11366. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11367. EXPECT_EQ(items[1].name, "name2");
  11368. EXPECT_EQ(items[1].content, "Testing456");
  11369. EXPECT_EQ(items[1].filename, "");
  11370. EXPECT_EQ(items[1].content_type, "");
  11371. EXPECT_EQ(items[2].name, "name3");
  11372. EXPECT_EQ(items[2].content, rand1);
  11373. EXPECT_EQ(items[2].filename, "filename3");
  11374. EXPECT_EQ(items[2].content_type, "");
  11375. EXPECT_EQ(items[3].name, "name4");
  11376. EXPECT_EQ(items[3].content, rand2);
  11377. EXPECT_EQ(items[3].filename, "filename4");
  11378. EXPECT_EQ(items[3].content_type, "");
  11379. });
  11380. auto port = svr.bind_to_any_port("localhost");
  11381. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11382. auto se = detail::scope_exit([&] {
  11383. svr.stop();
  11384. t.join();
  11385. ASSERT_FALSE(svr.is_running());
  11386. });
  11387. svr.wait_until_ready();
  11388. {
  11389. SSLClient cli("localhost", port);
  11390. cli.enable_server_certificate_verification(false);
  11391. UploadFormDataItems items{
  11392. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11393. {"name2", "Testing456", "", ""}, // not a file
  11394. };
  11395. {
  11396. auto res = cli.Post("/post-none", {}, {}, {});
  11397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11398. ASSERT_EQ(StatusCode::OK_200, res->status);
  11399. }
  11400. FormDataProviderItems providers;
  11401. {
  11402. auto res =
  11403. cli.Post("/post-items", {}, items, providers); // empty providers
  11404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11405. ASSERT_EQ(StatusCode::OK_200, res->status);
  11406. }
  11407. providers.push_back({"name3",
  11408. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11409. // test the offset is given correctly at each step
  11410. if (!offset)
  11411. sink.os.write(rand1.data(), 30);
  11412. else if (offset == 30)
  11413. sink.os.write(rand1.data() + 30, 300);
  11414. else if (offset == 330)
  11415. sink.os.write(rand1.data() + 330, 670);
  11416. else if (offset == rand1.size())
  11417. sink.done();
  11418. return true;
  11419. },
  11420. "filename3",
  11421. {}});
  11422. providers.push_back({"name4",
  11423. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11424. // test the offset is given correctly at each step
  11425. if (!offset)
  11426. sink.os.write(rand2.data(), 2000);
  11427. else if (offset == 2000)
  11428. sink.os.write(rand2.data() + 2000, 1);
  11429. else if (offset == 2001)
  11430. sink.os.write(rand2.data() + 2001, 999);
  11431. else if (offset == rand2.size())
  11432. sink.done();
  11433. return true;
  11434. },
  11435. "filename4",
  11436. {}});
  11437. {
  11438. auto res = cli.Post("/post-providers", {}, {}, providers);
  11439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11440. ASSERT_EQ(StatusCode::OK_200, res->status);
  11441. }
  11442. {
  11443. auto res = cli.Post("/post-both", {}, items, providers);
  11444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11445. ASSERT_EQ(StatusCode::OK_200, res->status);
  11446. }
  11447. }
  11448. }
  11449. TEST(MultipartFormDataTest, BadHeader) {
  11450. Server svr;
  11451. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11452. res.set_content("ok", "text/plain");
  11453. });
  11454. thread t = thread([&] { svr.listen(HOST, PORT); });
  11455. auto se = detail::scope_exit([&] {
  11456. svr.stop();
  11457. t.join();
  11458. ASSERT_FALSE(svr.is_running());
  11459. });
  11460. svr.wait_until_ready();
  11461. const std::string body =
  11462. "This is the preamble. It is to be ignored, though it\r\n"
  11463. "is a handy place for composition agents to include an\r\n"
  11464. "explanatory note to non-MIME conformant readers.\r\n"
  11465. "\r\n"
  11466. "\r\n"
  11467. "--simple boundary\r\n"
  11468. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11469. ": BAD...\r\n"
  11470. "\r\n"
  11471. "value1\r\n"
  11472. "--simple boundary\r\n"
  11473. "Content-Disposition: form-data; name=\"field2\"; "
  11474. "filename=\"example.txt\"\r\n"
  11475. "\r\n"
  11476. "value2\r\n"
  11477. "--simple boundary--\r\n"
  11478. "This is the epilogue. It is also to be ignored.\r\n";
  11479. std::string content_type =
  11480. R"(multipart/form-data; boundary="simple boundary")";
  11481. Client cli(HOST, PORT);
  11482. auto res = cli.Post("/post", body, content_type.c_str());
  11483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11484. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11485. }
  11486. TEST(MultipartFormDataTest, WithPreamble) {
  11487. Server svr;
  11488. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11489. res.set_content("ok", "text/plain");
  11490. });
  11491. thread t = thread([&] { svr.listen(HOST, PORT); });
  11492. auto se = detail::scope_exit([&] {
  11493. svr.stop();
  11494. t.join();
  11495. ASSERT_FALSE(svr.is_running());
  11496. });
  11497. svr.wait_until_ready();
  11498. const std::string body =
  11499. "This is the preamble. It is to be ignored, though it\r\n"
  11500. "is a handy place for composition agents to include an\r\n"
  11501. "explanatory note to non-MIME conformant readers.\r\n"
  11502. "\r\n"
  11503. "\r\n"
  11504. "--simple boundary\r\n"
  11505. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11506. "\r\n"
  11507. "value1\r\n"
  11508. "--simple boundary\r\n"
  11509. "Content-Disposition: form-data; name=\"field2\"; "
  11510. "filename=\"example.txt\"\r\n"
  11511. "\r\n"
  11512. "value2\r\n"
  11513. "--simple boundary--\r\n"
  11514. "This is the epilogue. It is also to be ignored.\r\n";
  11515. std::string content_type =
  11516. R"(multipart/form-data; boundary="simple boundary")";
  11517. Client cli(HOST, PORT);
  11518. auto res = cli.Post("/post", body, content_type.c_str());
  11519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11520. EXPECT_EQ(StatusCode::OK_200, res->status);
  11521. }
  11522. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11524. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11525. const ContentReader &content_reader) {
  11526. if (req.is_multipart_form_data()) {
  11527. std::vector<FormData> items;
  11528. content_reader(
  11529. [&](const FormData &file) {
  11530. items.push_back(file);
  11531. return true;
  11532. },
  11533. [&](const char *data, size_t data_length) {
  11534. items.back().content.append(data, data_length);
  11535. return true;
  11536. });
  11537. EXPECT_TRUE(std::string(items[0].name) == "document");
  11538. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11539. EXPECT_TRUE(items[0].filename == "2MB_data");
  11540. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11541. EXPECT_TRUE(items[1].name == "hello");
  11542. EXPECT_TRUE(items[1].content == "world");
  11543. EXPECT_TRUE(items[1].filename == "");
  11544. EXPECT_TRUE(items[1].content_type == "");
  11545. } else {
  11546. std::string body;
  11547. content_reader([&](const char *data, size_t data_length) {
  11548. body.append(data, data_length);
  11549. return true;
  11550. });
  11551. }
  11552. });
  11553. auto port = svr.bind_to_any_port("localhost");
  11554. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11555. auto se = detail::scope_exit([&] {
  11556. svr.stop();
  11557. t.join();
  11558. ASSERT_FALSE(svr.is_running());
  11559. });
  11560. svr.wait_until_ready();
  11561. {
  11562. std::string data(1024 * 1024 * 2, '.');
  11563. std::stringstream buffer;
  11564. buffer << data;
  11565. SSLClient cli("localhost", port);
  11566. cli.enable_server_certificate_verification(false);
  11567. UploadFormDataItems items{
  11568. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11569. {"hello", "world", "", ""},
  11570. };
  11571. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11573. ASSERT_EQ(StatusCode::OK_200, res->status);
  11574. }
  11575. }
  11576. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11577. std::string data(1024 * 1024 * 2, '&');
  11578. std::stringstream buffer;
  11579. buffer << data;
  11580. Client cli("https://localhost:8080");
  11581. UploadFormDataItems items{
  11582. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11583. {"hello", "world", "", ""},
  11584. };
  11585. for (const char &c : " \t\r\n") {
  11586. auto res =
  11587. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11588. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11589. ASSERT_FALSE(res);
  11590. }
  11591. }
  11592. TEST(MultipartFormDataTest, PutFormData) {
  11593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11594. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11595. const ContentReader &content_reader) {
  11596. if (req.is_multipart_form_data()) {
  11597. std::vector<FormData> items;
  11598. content_reader(
  11599. [&](const FormData &file) {
  11600. items.push_back(file);
  11601. return true;
  11602. },
  11603. [&](const char *data, size_t data_length) {
  11604. items.back().content.append(data, data_length);
  11605. return true;
  11606. });
  11607. EXPECT_TRUE(std::string(items[0].name) == "document");
  11608. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11609. EXPECT_TRUE(items[0].filename == "2MB_data");
  11610. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11611. EXPECT_TRUE(items[1].name == "hello");
  11612. EXPECT_TRUE(items[1].content == "world");
  11613. EXPECT_TRUE(items[1].filename == "");
  11614. EXPECT_TRUE(items[1].content_type == "");
  11615. } else {
  11616. std::string body;
  11617. content_reader([&](const char *data, size_t data_length) {
  11618. body.append(data, data_length);
  11619. return true;
  11620. });
  11621. }
  11622. });
  11623. auto port = svr.bind_to_any_port("localhost");
  11624. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11625. auto se = detail::scope_exit([&] {
  11626. svr.stop();
  11627. t.join();
  11628. ASSERT_FALSE(svr.is_running());
  11629. });
  11630. svr.wait_until_ready();
  11631. {
  11632. std::string data(1024 * 1024 * 2, '&');
  11633. std::stringstream buffer;
  11634. buffer << data;
  11635. SSLClient cli("localhost", port);
  11636. cli.enable_server_certificate_verification(false);
  11637. UploadFormDataItems items{
  11638. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11639. {"hello", "world", "", ""},
  11640. };
  11641. auto res = cli.Put("/put", items);
  11642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11643. ASSERT_EQ(StatusCode::OK_200, res->status);
  11644. }
  11645. }
  11646. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11647. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11648. svr.Put("/put_customboundary",
  11649. [&](const Request &req, const Response & /*res*/,
  11650. const ContentReader &content_reader) {
  11651. if (req.is_multipart_form_data()) {
  11652. std::vector<FormData> items;
  11653. content_reader(
  11654. [&](const FormData &file) {
  11655. items.push_back(file);
  11656. return true;
  11657. },
  11658. [&](const char *data, size_t data_length) {
  11659. items.back().content.append(data, data_length);
  11660. return true;
  11661. });
  11662. EXPECT_TRUE(std::string(items[0].name) == "document");
  11663. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11664. EXPECT_TRUE(items[0].filename == "2MB_data");
  11665. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11666. EXPECT_TRUE(items[1].name == "hello");
  11667. EXPECT_TRUE(items[1].content == "world");
  11668. EXPECT_TRUE(items[1].filename == "");
  11669. EXPECT_TRUE(items[1].content_type == "");
  11670. } else {
  11671. std::string body;
  11672. content_reader([&](const char *data, size_t data_length) {
  11673. body.append(data, data_length);
  11674. return true;
  11675. });
  11676. }
  11677. });
  11678. auto port = svr.bind_to_any_port("localhost");
  11679. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11680. auto se = detail::scope_exit([&] {
  11681. svr.stop();
  11682. t.join();
  11683. ASSERT_FALSE(svr.is_running());
  11684. });
  11685. svr.wait_until_ready();
  11686. {
  11687. std::string data(1024 * 1024 * 2, '&');
  11688. std::stringstream buffer;
  11689. buffer << data;
  11690. SSLClient cli("localhost", port);
  11691. cli.enable_server_certificate_verification(false);
  11692. UploadFormDataItems items{
  11693. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11694. {"hello", "world", "", ""},
  11695. };
  11696. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11698. ASSERT_EQ(StatusCode::OK_200, res->status);
  11699. }
  11700. }
  11701. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11702. std::string data(1024 * 1024 * 2, '&');
  11703. std::stringstream buffer;
  11704. buffer << data;
  11705. Client cli("https://localhost:8080");
  11706. cli.enable_server_certificate_verification(false);
  11707. UploadFormDataItems items{
  11708. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11709. {"hello", "world", "", ""},
  11710. };
  11711. for (const char &c : " \t\r\n") {
  11712. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11713. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11714. ASSERT_FALSE(res);
  11715. }
  11716. }
  11717. TEST(MultipartFormDataTest, AlternateFilename) {
  11718. auto handled = false;
  11719. Server svr;
  11720. svr.Post("/test", [&](const Request &req, Response &res) {
  11721. ASSERT_EQ(2u, req.form.files.size());
  11722. ASSERT_EQ(1u, req.form.fields.size());
  11723. // Test files
  11724. const auto &file1 = req.form.get_file("file1");
  11725. ASSERT_EQ("file1", file1.name);
  11726. ASSERT_EQ("A.txt", file1.filename);
  11727. ASSERT_EQ("text/plain", file1.content_type);
  11728. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11729. const auto &file2 = req.form.get_file("file2");
  11730. ASSERT_EQ("file2", file2.name);
  11731. ASSERT_EQ("a.html", file2.filename);
  11732. ASSERT_EQ("text/html", file2.content_type);
  11733. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11734. file2.content);
  11735. // Test text field
  11736. const auto &text = req.form.get_field("text");
  11737. ASSERT_EQ("text default", text);
  11738. res.set_content("ok", "text/plain");
  11739. handled = true;
  11740. });
  11741. thread t = thread([&] { svr.listen(HOST, PORT); });
  11742. auto se = detail::scope_exit([&] {
  11743. svr.stop();
  11744. t.join();
  11745. ASSERT_FALSE(svr.is_running());
  11746. ASSERT_TRUE(handled);
  11747. });
  11748. svr.wait_until_ready();
  11749. auto req = "POST /test HTTP/1.1\r\n"
  11750. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11751. "Content-Length: 399\r\n"
  11752. "\r\n"
  11753. "----------\r\n"
  11754. "Content-Disposition: form-data; name=\"text\"\r\n"
  11755. "\r\n"
  11756. "text default\r\n"
  11757. "----------\r\n"
  11758. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11759. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11760. "Content-Type: text/plain\r\n"
  11761. "\r\n"
  11762. "Content of a.txt.\r\n"
  11763. "\r\n"
  11764. "----------\r\n"
  11765. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11766. "\"a.html\"\r\n"
  11767. "Content-Type: text/html\r\n"
  11768. "\r\n"
  11769. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11770. "\r\n"
  11771. "------------\r\n";
  11772. ASSERT_TRUE(send_request(1, req));
  11773. }
  11774. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11775. auto handled = false;
  11776. Server svr;
  11777. svr.Post("/test", [&](const Request &req, Response &res) {
  11778. // Case-insensitive "utf-8''" prefix with a long value
  11779. const auto &file = req.form.get_file("file1");
  11780. ASSERT_EQ("file1", file.name);
  11781. // 8000 chars exercises both the Content-Disposition parser and the
  11782. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11783. // Prior to the fix, std::regex_match on this header would cause O(N)
  11784. // stack recursion in libstdc++, leading to SIGSEGV.
  11785. std::string expected_filename(8000, 'A');
  11786. ASSERT_EQ(expected_filename, file.filename);
  11787. res.set_content("ok", "text/plain");
  11788. handled = true;
  11789. });
  11790. thread t = thread([&] { svr.listen(HOST, PORT); });
  11791. auto se = detail::scope_exit([&] {
  11792. svr.stop();
  11793. t.join();
  11794. ASSERT_FALSE(svr.is_running());
  11795. ASSERT_TRUE(handled);
  11796. });
  11797. svr.wait_until_ready();
  11798. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11799. // Regression test for GHSA-qq6v-r583-3h69
  11800. std::string long_filename(8000, 'A');
  11801. std::string body = "----------\r\n"
  11802. "Content-Disposition: form-data; name=\"file1\"; "
  11803. "filename*=\"Utf-8''" +
  11804. long_filename +
  11805. "\"\r\n"
  11806. "\r\n"
  11807. "hello\r\n"
  11808. "------------\r\n";
  11809. auto req = "POST /test HTTP/1.1\r\n"
  11810. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11811. "Content-Length: " +
  11812. std::to_string(body.size()) + "\r\n\r\n" + body;
  11813. ASSERT_TRUE(send_request(1, req));
  11814. }
  11815. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11816. auto handled = false;
  11817. Server svr;
  11818. svr.Post("/test", [&](const Request &req, Response &) {
  11819. ASSERT_EQ(2u, req.form.fields.size());
  11820. const auto &text1 = req.form.get_field("text1");
  11821. ASSERT_EQ("text1", text1);
  11822. const auto &text2 = req.form.get_field("text2");
  11823. ASSERT_EQ("text2", text2);
  11824. handled = true;
  11825. });
  11826. thread t = thread([&] { svr.listen(HOST, PORT); });
  11827. auto se = detail::scope_exit([&] {
  11828. svr.stop();
  11829. t.join();
  11830. ASSERT_FALSE(svr.is_running());
  11831. ASSERT_TRUE(handled);
  11832. });
  11833. svr.wait_until_ready();
  11834. auto req = "POST /test HTTP/1.1\r\n"
  11835. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11836. "Content-Length: 146\r\n"
  11837. "\r\n----------\r\n"
  11838. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11839. "\r\n"
  11840. "text1"
  11841. "\r\n----------\r\n"
  11842. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11843. "\r\n"
  11844. "text2"
  11845. "\r\n------------";
  11846. std::string response;
  11847. ASSERT_TRUE(send_request(1, req, &response));
  11848. ASSERT_EQ("200", response.substr(9, 3));
  11849. }
  11850. TEST(MultipartFormDataTest, ContentLength) {
  11851. auto handled = false;
  11852. Server svr;
  11853. svr.Post("/test", [&](const Request &req, Response &) {
  11854. ASSERT_EQ(2u, req.form.fields.size());
  11855. const auto &text1 = req.form.get_field("text1");
  11856. ASSERT_EQ("text1", text1);
  11857. const auto &text2 = req.form.get_field("text2");
  11858. ASSERT_EQ("text2", text2);
  11859. handled = true;
  11860. });
  11861. thread t = thread([&] { svr.listen(HOST, PORT); });
  11862. auto se = detail::scope_exit([&] {
  11863. svr.stop();
  11864. t.join();
  11865. ASSERT_FALSE(svr.is_running());
  11866. ASSERT_TRUE(handled);
  11867. });
  11868. svr.wait_until_ready();
  11869. auto req = "POST /test HTTP/1.1\r\n"
  11870. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11871. "Content-Length: 167\r\n"
  11872. "\r\n----------\r\n"
  11873. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11874. "Content-Length: 5\r\n"
  11875. "\r\n"
  11876. "text1"
  11877. "\r\n----------\r\n"
  11878. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11879. "\r\n"
  11880. "text2"
  11881. "\r\n------------\r\n";
  11882. std::string response;
  11883. ASSERT_TRUE(send_request(1, req, &response));
  11884. ASSERT_EQ("200", response.substr(9, 3));
  11885. }
  11886. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11887. auto handled = false;
  11888. Server svr;
  11889. svr.Post("/test", [&](const Request &req, Response &) {
  11890. ASSERT_EQ(2u, req.form.fields.size());
  11891. const auto &text1 = req.form.get_field("text1");
  11892. ASSERT_EQ("text1", text1);
  11893. // TODO: Add header access for text fields if needed
  11894. const auto &text2 = req.form.get_field("text2");
  11895. ASSERT_EQ("text2", text2);
  11896. // TODO: Header access for text fields needs to be implemented
  11897. // auto &headers = it->second.headers;
  11898. // ASSERT_EQ(3U, headers.size());
  11899. // auto custom_header = headers.find("x-whatever");
  11900. // ASSERT_TRUE(custom_header != headers.end());
  11901. // ASSERT_NE("customvalue", custom_header->second);
  11902. // ASSERT_EQ("CustomValue", custom_header->second);
  11903. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11904. handled = true;
  11905. });
  11906. thread t = thread([&] { svr.listen(HOST, PORT); });
  11907. auto se = detail::scope_exit([&] {
  11908. svr.stop();
  11909. t.join();
  11910. ASSERT_FALSE(svr.is_running());
  11911. ASSERT_TRUE(handled);
  11912. });
  11913. svr.wait_until_ready();
  11914. auto req = "POST /test HTTP/1.1\r\n"
  11915. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11916. "Content-Length: 232\r\n"
  11917. "\r\n----------\r\n"
  11918. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11919. "Content-Length: 5\r\n"
  11920. "X-Test: 1\r\n"
  11921. "\r\n"
  11922. "text1"
  11923. "\r\n----------\r\n"
  11924. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11925. "Content-Type: text/plain\r\n"
  11926. "X-Whatever: CustomValue\r\n"
  11927. "\r\n"
  11928. "text2"
  11929. "\r\n------------\r\n"
  11930. "That should be disregarded. Not even read";
  11931. std::string response;
  11932. ASSERT_TRUE(send_request(1, req, &response));
  11933. ASSERT_EQ("200", response.substr(9, 3));
  11934. }
  11935. TEST(MultipartFormDataTest, LargeHeader) {
  11936. auto handled = false;
  11937. Server svr;
  11938. svr.Post("/test", [&](const Request &req, Response &) {
  11939. ASSERT_EQ(1u, req.form.fields.size());
  11940. const auto &text = req.form.get_field("name1");
  11941. ASSERT_EQ("text1", text);
  11942. handled = true;
  11943. });
  11944. thread t = thread([&] { svr.listen(HOST, PORT); });
  11945. auto se = detail::scope_exit([&] {
  11946. svr.stop();
  11947. t.join();
  11948. ASSERT_FALSE(svr.is_running());
  11949. ASSERT_TRUE(handled);
  11950. });
  11951. svr.wait_until_ready();
  11952. auto boundary = std::string("cpp-httplib-multipart-data");
  11953. std::string content = "--" + boundary +
  11954. "\r\n"
  11955. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11956. "\r\n"
  11957. "text1\r\n"
  11958. "--" +
  11959. boundary + "--\r\n";
  11960. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11961. "Content-Type: multipart/form-data;boundary=" +
  11962. boundary +
  11963. "\r\n"
  11964. "Content-Length: " +
  11965. std::to_string(content.size()) +
  11966. "\r\n"
  11967. "Dummy-Header: ";
  11968. std::string header_suffix = "\r\n"
  11969. "\r\n";
  11970. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11971. size_t header_dummy_size =
  11972. read_buff_size -
  11973. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11974. auto header_dummy = std::string(header_dummy_size, '@');
  11975. auto req = header_prefix + header_dummy + header_suffix + content;
  11976. std::string response;
  11977. ASSERT_TRUE(send_request(1, req, &response));
  11978. ASSERT_EQ("200", response.substr(9, 3));
  11979. }
  11980. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11981. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11982. // (not chunked Transfer-Encoding) after the streaming refactor.
  11983. auto handled = false;
  11984. Server svr;
  11985. svr.Post("/upload", [&](const Request &req, Response &res) {
  11986. auto cl_it = req.headers.find("Content-Length");
  11987. EXPECT_TRUE(cl_it != req.headers.end());
  11988. auto te_it = req.headers.find("Transfer-Encoding");
  11989. EXPECT_TRUE(te_it == req.headers.end());
  11990. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11991. res.set_content("ok", "text/plain");
  11992. handled = true;
  11993. });
  11994. auto port = svr.bind_to_any_port(HOST);
  11995. auto t = thread([&] { svr.listen_after_bind(); });
  11996. auto se = detail::scope_exit([&] {
  11997. svr.stop();
  11998. t.join();
  11999. ASSERT_FALSE(svr.is_running());
  12000. ASSERT_TRUE(handled);
  12001. });
  12002. svr.wait_until_ready();
  12003. UploadFormDataItems items = {
  12004. {"field1", "hello", "", "text/plain"},
  12005. {"file1", "world", "test.txt", "application/octet-stream"},
  12006. };
  12007. Client cli(HOST, port);
  12008. auto res = cli.Post("/upload", {}, items);
  12009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12010. EXPECT_EQ(StatusCode::OK_200, res->status);
  12011. }
  12012. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12013. // Verify that make_multipart_content_provider coalesces many small segments
  12014. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12015. constexpr size_t kItemCount = 1000;
  12016. UploadFormDataItems items;
  12017. items.reserve(kItemCount);
  12018. for (size_t i = 0; i < kItemCount; i++) {
  12019. items.push_back(
  12020. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12021. }
  12022. const std::string boundary = "----test-boundary";
  12023. auto content_length = detail::get_multipart_content_length(items, boundary);
  12024. auto provider = detail::make_multipart_content_provider(items, boundary);
  12025. // Drive the provider the same way write_content_with_progress does
  12026. size_t write_count = 0;
  12027. size_t total_bytes = 0;
  12028. DataSink sink;
  12029. size_t offset = 0;
  12030. sink.write = [&](const char *d, size_t l) -> bool {
  12031. (void)d;
  12032. write_count++;
  12033. total_bytes += l;
  12034. offset += l;
  12035. return true;
  12036. };
  12037. sink.is_writable = []() -> bool { return true; };
  12038. while (offset < content_length) {
  12039. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12040. }
  12041. EXPECT_EQ(content_length, total_bytes);
  12042. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12043. // With buffering into 64KB blocks, write_count should be much smaller.
  12044. auto segment_count = 3 * kItemCount + 1;
  12045. EXPECT_LT(write_count, segment_count / 10);
  12046. }
  12047. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12048. // Integration test: send many UploadFormDataItems and verify the server
  12049. // receives all of them correctly (#2410).
  12050. constexpr size_t kItemCount = 500;
  12051. auto handled = false;
  12052. Server svr;
  12053. svr.Post("/upload", [&](const Request &req, Response &res) {
  12054. EXPECT_EQ(kItemCount, req.form.fields.size());
  12055. for (size_t i = 0; i < kItemCount; i++) {
  12056. auto key = "field" + std::to_string(i);
  12057. auto val = "value" + std::to_string(i);
  12058. auto it = req.form.fields.find(key);
  12059. if (it != req.form.fields.end()) {
  12060. EXPECT_EQ(val, it->second.content);
  12061. } else {
  12062. ADD_FAILURE() << "Missing field: " << key;
  12063. }
  12064. }
  12065. res.set_content("ok", "text/plain");
  12066. handled = true;
  12067. });
  12068. auto port = svr.bind_to_any_port(HOST);
  12069. auto t = thread([&] { svr.listen_after_bind(); });
  12070. auto se = detail::scope_exit([&] {
  12071. svr.stop();
  12072. t.join();
  12073. ASSERT_FALSE(svr.is_running());
  12074. ASSERT_TRUE(handled);
  12075. });
  12076. svr.wait_until_ready();
  12077. UploadFormDataItems items;
  12078. items.reserve(kItemCount);
  12079. for (size_t i = 0; i < kItemCount; i++) {
  12080. items.push_back(
  12081. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12082. }
  12083. Client cli(HOST, port);
  12084. auto res = cli.Post("/upload", items);
  12085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12086. EXPECT_EQ(StatusCode::OK_200, res->status);
  12087. }
  12088. TEST(MultipartFormDataTest, MakeFileProvider) {
  12089. // Verify make_file_provider sends a file's contents correctly.
  12090. const std::string file_content(4096, 'Z');
  12091. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12092. {
  12093. std::ofstream ofs(tmp_path, std::ios::binary);
  12094. ofs.write(file_content.data(),
  12095. static_cast<std::streamsize>(file_content.size()));
  12096. }
  12097. auto handled = false;
  12098. Server svr;
  12099. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12100. const ContentReader &content_reader) {
  12101. ASSERT_TRUE(req.is_multipart_form_data());
  12102. std::vector<FormData> items;
  12103. content_reader(
  12104. [&](const FormData &file) {
  12105. items.push_back(file);
  12106. return true;
  12107. },
  12108. [&](const char *data, size_t data_length) {
  12109. items.back().content.append(data, data_length);
  12110. return true;
  12111. });
  12112. ASSERT_EQ(1u, items.size());
  12113. EXPECT_EQ("myfile", items[0].name);
  12114. EXPECT_EQ("data.bin", items[0].filename);
  12115. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12116. EXPECT_EQ(file_content, items[0].content);
  12117. handled = true;
  12118. });
  12119. auto port = svr.bind_to_any_port(HOST);
  12120. auto t = thread([&] { svr.listen_after_bind(); });
  12121. auto se = detail::scope_exit([&] {
  12122. svr.stop();
  12123. t.join();
  12124. ASSERT_FALSE(svr.is_running());
  12125. ASSERT_TRUE(handled);
  12126. std::remove(tmp_path.c_str());
  12127. });
  12128. svr.wait_until_ready();
  12129. FormDataProviderItems providers;
  12130. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12131. "application/octet-stream"));
  12132. Client cli(HOST, port);
  12133. auto res = cli.Post("/upload", {}, {}, providers);
  12134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12135. EXPECT_EQ(StatusCode::OK_200, res->status);
  12136. }
  12137. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12138. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12139. // (100) headers is rejected with a 400 Bad Request response.
  12140. Server svr;
  12141. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12142. res.set_content("ok", "text/plain");
  12143. });
  12144. thread t = thread([&] { svr.listen(HOST, PORT); });
  12145. auto se = detail::scope_exit([&] {
  12146. svr.stop();
  12147. t.join();
  12148. ASSERT_FALSE(svr.is_running());
  12149. });
  12150. svr.wait_until_ready();
  12151. // Build a multipart part with 101 custom headers (exceeding
  12152. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12153. std::stringstream body;
  12154. body << "--simpleboundary\r\n"
  12155. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12156. for (int i = 0; i < 101; i++) {
  12157. body << "X-Custom-Header-" << i << ": value\r\n";
  12158. }
  12159. body << "\r\n"
  12160. << "value1\r\n"
  12161. << "--simpleboundary--\r\n";
  12162. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12163. Client cli(HOST, PORT);
  12164. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12166. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12167. }
  12168. TEST(MakeFileBodyTest, Basic) {
  12169. const std::string file_content(4096, 'Z');
  12170. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12171. {
  12172. std::ofstream ofs(tmp_path, std::ios::binary);
  12173. ofs.write(file_content.data(),
  12174. static_cast<std::streamsize>(file_content.size()));
  12175. }
  12176. auto handled = false;
  12177. Server svr;
  12178. svr.Post("/upload", [&](const Request &req, Response &res) {
  12179. EXPECT_EQ(file_content, req.body);
  12180. handled = true;
  12181. res.status = StatusCode::OK_200;
  12182. });
  12183. auto port = svr.bind_to_any_port(HOST);
  12184. auto t = thread([&] { svr.listen_after_bind(); });
  12185. auto se = detail::scope_exit([&] {
  12186. svr.stop();
  12187. t.join();
  12188. ASSERT_FALSE(svr.is_running());
  12189. ASSERT_TRUE(handled);
  12190. std::remove(tmp_path.c_str());
  12191. });
  12192. svr.wait_until_ready();
  12193. auto fb = make_file_body(tmp_path);
  12194. ASSERT_GT(fb.first, 0u);
  12195. Client cli(HOST, port);
  12196. auto res =
  12197. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12199. EXPECT_EQ(StatusCode::OK_200, res->status);
  12200. }
  12201. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12202. static constexpr unsigned int number_of_tasks{1000000};
  12203. std::atomic_uint count{0};
  12204. std::unique_ptr<TaskQueue> task_queue{
  12205. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12206. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12207. auto queued = task_queue->enqueue(
  12208. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12209. EXPECT_TRUE(queued);
  12210. }
  12211. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12212. task_queue->shutdown();
  12213. #else
  12214. EXPECT_NO_THROW(task_queue->shutdown());
  12215. #endif
  12216. EXPECT_EQ(number_of_tasks, count.load());
  12217. }
  12218. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12219. static constexpr unsigned int number_of_tasks{1000000};
  12220. static constexpr unsigned int qlimit{2};
  12221. unsigned int queued_count{0};
  12222. std::atomic_uint count{0};
  12223. std::unique_ptr<TaskQueue> task_queue{
  12224. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12225. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12226. if (task_queue->enqueue(
  12227. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12228. queued_count++;
  12229. }
  12230. }
  12231. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12232. task_queue->shutdown();
  12233. #else
  12234. EXPECT_NO_THROW(task_queue->shutdown());
  12235. #endif
  12236. EXPECT_EQ(queued_count, count.load());
  12237. EXPECT_TRUE(queued_count <= number_of_tasks);
  12238. EXPECT_TRUE(queued_count >= qlimit);
  12239. }
  12240. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12241. // Use a short idle timeout so a dynamic thread spawns, times out and
  12242. // exits during the test, and the pool keeps working afterwards.
  12243. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12244. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12245. /*idle_timeout_sec=*/1}};
  12246. std::atomic_uint count{0};
  12247. std::condition_variable cv;
  12248. std::mutex mtx;
  12249. bool release = false;
  12250. // Block the base thread so the second task spawns a dynamic thread.
  12251. EXPECT_TRUE(task_queue->enqueue([&] {
  12252. std::unique_lock<std::mutex> lock(mtx);
  12253. while (!release) {
  12254. cv.wait(lock);
  12255. }
  12256. count++;
  12257. }));
  12258. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12259. // Let the dynamic thread finish its task and exceed the idle timeout.
  12260. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12261. {
  12262. std::unique_lock<std::mutex> lock(mtx);
  12263. release = true;
  12264. }
  12265. cv.notify_all();
  12266. // The pool must still accept and run tasks after the dynamic thread exited.
  12267. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12268. task_queue->shutdown();
  12269. EXPECT_EQ(3u, count.load());
  12270. }
  12271. TEST(TaskQueueTest, MaxQueuedRequests) {
  12272. static constexpr unsigned int qlimit{3};
  12273. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12274. std::condition_variable sem_cv;
  12275. std::mutex sem_mtx;
  12276. int credits = 0;
  12277. bool queued;
  12278. /* Fill up the queue with tasks that will block until we give them credits to
  12279. * complete. */
  12280. for (unsigned int n = 0; n <= qlimit;) {
  12281. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12282. std::unique_lock<std::mutex> lock(sem_mtx);
  12283. while (credits <= 0) {
  12284. sem_cv.wait(lock);
  12285. }
  12286. /* Consume the credit and signal the test code if they are all gone. */
  12287. if (--credits == 0) { sem_cv.notify_one(); }
  12288. });
  12289. if (n < qlimit) {
  12290. /* The first qlimit enqueues must succeed. */
  12291. EXPECT_TRUE(queued);
  12292. } else {
  12293. /* The last one will succeed only when the worker thread
  12294. * starts and dequeues the first blocking task. Although
  12295. * not necessary for the correctness of this test, we sleep for
  12296. * a short while to avoid busy waiting. */
  12297. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12298. }
  12299. if (queued) { n++; }
  12300. }
  12301. /* Further enqueues must fail since the queue is full. */
  12302. for (auto i = 0; i < 4; i++) {
  12303. queued = task_queue->enqueue([] {});
  12304. EXPECT_FALSE(queued);
  12305. }
  12306. /* Give the credits to allow the previous tasks to complete. */
  12307. {
  12308. std::unique_lock<std::mutex> lock(sem_mtx);
  12309. credits += qlimit + 1;
  12310. }
  12311. sem_cv.notify_all();
  12312. /* Wait for all the credits to be consumed. */
  12313. {
  12314. std::unique_lock<std::mutex> lock(sem_mtx);
  12315. while (credits > 0) {
  12316. sem_cv.wait(lock);
  12317. }
  12318. }
  12319. /* Check that we are able again to enqueue at least qlimit tasks. */
  12320. for (unsigned int i = 0; i < qlimit; i++) {
  12321. queued = task_queue->enqueue([] {});
  12322. EXPECT_TRUE(queued);
  12323. }
  12324. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12325. task_queue->shutdown();
  12326. #else
  12327. EXPECT_NO_THROW(task_queue->shutdown());
  12328. #endif
  12329. }
  12330. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12331. Server svr;
  12332. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12333. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12334. });
  12335. svr.Get("/hello", [](const Request &req, Response &res) {
  12336. res.set_content(req.get_param_value("key"), "text/plain");
  12337. });
  12338. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12339. auto se = detail::scope_exit([&] {
  12340. svr.stop();
  12341. thread.join();
  12342. ASSERT_FALSE(svr.is_running());
  12343. });
  12344. svr.wait_until_ready();
  12345. {
  12346. Client cli(HOST, PORT);
  12347. cli.set_follow_location(true);
  12348. auto res = cli.Get("/");
  12349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12350. EXPECT_EQ(StatusCode::OK_200, res->status);
  12351. EXPECT_EQ("val&key2=val2", res->body);
  12352. }
  12353. }
  12354. #endif
  12355. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12356. Server svr;
  12357. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12358. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12359. });
  12360. svr.Get("/hello", [](const Request &req, Response &res) {
  12361. res.set_content(req.get_param_value("key"), "text/plain");
  12362. });
  12363. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12364. auto se = detail::scope_exit([&] {
  12365. svr.stop();
  12366. thread.join();
  12367. ASSERT_FALSE(svr.is_running());
  12368. });
  12369. svr.wait_until_ready();
  12370. {
  12371. Client cli(HOST, PORT);
  12372. cli.set_follow_location(true);
  12373. auto res = cli.Get("/");
  12374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12375. EXPECT_EQ(StatusCode::OK_200, res->status);
  12376. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12377. }
  12378. }
  12379. TEST(RedirectTest, RedirectWithPlusInPath) {
  12380. Server svr;
  12381. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12382. res.set_redirect("/a+b");
  12383. });
  12384. // Route pattern uses regex; escape + as \\+
  12385. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12386. res.set_content(req.path, "text/plain");
  12387. });
  12388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12389. auto se = detail::scope_exit([&] {
  12390. svr.stop();
  12391. thread.join();
  12392. ASSERT_FALSE(svr.is_running());
  12393. });
  12394. svr.wait_until_ready();
  12395. {
  12396. Client cli(HOST, PORT);
  12397. cli.set_follow_location(true);
  12398. auto res = cli.Get("/");
  12399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12400. EXPECT_EQ(StatusCode::OK_200, res->status);
  12401. EXPECT_EQ("/a+b", res->body);
  12402. }
  12403. }
  12404. #ifdef CPPHTTPLIB_SSL_ENABLED
  12405. TEST(RedirectTest, Issue2185_Online) {
  12406. SSLClient client("github.com");
  12407. client.set_follow_location(true);
  12408. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12409. "Coollab-Windows.zip");
  12410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12411. EXPECT_EQ(StatusCode::OK_200, res->status);
  12412. EXPECT_EQ(9920427U, res->body.size());
  12413. }
  12414. #endif
  12415. TEST(VulnerabilityTest, CRLFInjection) {
  12416. Server svr;
  12417. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12418. res.set_content("Hello 1", "text/plain");
  12419. });
  12420. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12421. res.set_content("Hello 2", "text/plain");
  12422. });
  12423. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12424. res.set_content("Hello 3", "text/plain");
  12425. });
  12426. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12427. res.set_content("Hello 4", "text/plain");
  12428. });
  12429. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12430. for (const auto &x : req.headers) {
  12431. auto key = x.first;
  12432. EXPECT_STRNE("evil", key.c_str());
  12433. }
  12434. });
  12435. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12436. auto se = detail::scope_exit([&] {
  12437. svr.stop();
  12438. thread.join();
  12439. ASSERT_FALSE(svr.is_running());
  12440. });
  12441. svr.wait_until_ready();
  12442. {
  12443. Client cli(HOST, PORT);
  12444. cli.Post("/test1", "A=B",
  12445. "application/x-www-form-urlencoded\r\nevil: hello1");
  12446. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12447. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12448. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12449. }
  12450. }
  12451. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12452. auto server_thread = std::thread([] {
  12453. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12454. default_socket_options(srv);
  12455. sockaddr_in addr{};
  12456. addr.sin_family = AF_INET;
  12457. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12458. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12459. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12460. ::listen(srv, 1);
  12461. sockaddr_in cli_addr{};
  12462. socklen_t cli_len = sizeof(cli_addr);
  12463. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12464. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12465. std::string buf_all;
  12466. char buf[2048];
  12467. ssize_t n;
  12468. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12469. buf_all.append(buf, static_cast<size_t>(n));
  12470. size_t pos;
  12471. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12472. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12473. auto e = request_block.find("\r\n");
  12474. if (e != std::string::npos) {
  12475. auto request_line = request_block.substr(0, e);
  12476. std::string msg =
  12477. "CRLF injection detected in request line: '" + request_line + "'";
  12478. EXPECT_FALSE(true) << msg;
  12479. }
  12480. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12481. ::send(cli,
  12482. #ifdef _WIN32
  12483. static_cast<const char *>(resp.c_str()),
  12484. static_cast<int>(resp.size()),
  12485. #else
  12486. resp.c_str(), resp.size(),
  12487. #endif
  12488. 0);
  12489. buf_all.erase(0, pos + 4);
  12490. }
  12491. }
  12492. detail::close_socket(cli);
  12493. detail::close_socket(srv);
  12494. });
  12495. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12496. auto cli = Client("127.0.0.1", PORT + 1);
  12497. auto headers = Headers{
  12498. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12499. {"Connection", "keep-alive"}};
  12500. auto res = cli.Get("/hi", headers);
  12501. EXPECT_FALSE(res);
  12502. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12503. server_thread.join();
  12504. }
  12505. TEST(PathParamsTest, StaticMatch) {
  12506. const auto pattern = "/users/all";
  12507. detail::PathParamsMatcher matcher(pattern);
  12508. Request request;
  12509. request.path = "/users/all";
  12510. ASSERT_TRUE(matcher.match(request));
  12511. std::unordered_map<std::string, std::string> expected_params = {};
  12512. EXPECT_EQ(request.path_params, expected_params);
  12513. }
  12514. TEST(PathParamsTest, StaticMismatch) {
  12515. const auto pattern = "/users/all";
  12516. detail::PathParamsMatcher matcher(pattern);
  12517. Request request;
  12518. request.path = "/users/1";
  12519. ASSERT_FALSE(matcher.match(request));
  12520. }
  12521. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12522. const auto pattern = "/users/:id/subscriptions";
  12523. detail::PathParamsMatcher matcher(pattern);
  12524. Request request;
  12525. request.path = "/users/42/subscriptions";
  12526. ASSERT_TRUE(matcher.match(request));
  12527. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12528. EXPECT_EQ(request.path_params, expected_params);
  12529. }
  12530. TEST(PathParamsTest, SingleParamInTheEnd) {
  12531. const auto pattern = "/users/:id";
  12532. detail::PathParamsMatcher matcher(pattern);
  12533. Request request;
  12534. request.path = "/users/24";
  12535. ASSERT_TRUE(matcher.match(request));
  12536. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12537. EXPECT_EQ(request.path_params, expected_params);
  12538. }
  12539. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12540. const auto pattern = "/users/:id/";
  12541. detail::PathParamsMatcher matcher(pattern);
  12542. Request request;
  12543. request.path = "/users/42/";
  12544. ASSERT_TRUE(matcher.match(request));
  12545. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12546. EXPECT_EQ(request.path_params, expected_params);
  12547. }
  12548. TEST(PathParamsTest, EmptyParam) {
  12549. const auto pattern = "/users/:id/";
  12550. detail::PathParamsMatcher matcher(pattern);
  12551. Request request;
  12552. request.path = "/users//";
  12553. ASSERT_TRUE(matcher.match(request));
  12554. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12555. EXPECT_EQ(request.path_params, expected_params);
  12556. }
  12557. TEST(PathParamsTest, FragmentMismatch) {
  12558. const auto pattern = "/users/:id/";
  12559. detail::PathParamsMatcher matcher(pattern);
  12560. Request request;
  12561. request.path = "/admins/24/";
  12562. ASSERT_FALSE(matcher.match(request));
  12563. }
  12564. TEST(PathParamsTest, ExtraFragments) {
  12565. const auto pattern = "/users/:id";
  12566. detail::PathParamsMatcher matcher(pattern);
  12567. Request request;
  12568. request.path = "/users/42/subscriptions";
  12569. ASSERT_FALSE(matcher.match(request));
  12570. }
  12571. TEST(PathParamsTest, MissingTrailingParam) {
  12572. const auto pattern = "/users/:id";
  12573. detail::PathParamsMatcher matcher(pattern);
  12574. Request request;
  12575. request.path = "/users";
  12576. ASSERT_FALSE(matcher.match(request));
  12577. }
  12578. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12579. const auto pattern = "/users/:id/subscriptions";
  12580. detail::PathParamsMatcher matcher(pattern);
  12581. Request request;
  12582. request.path = "/users/subscriptions";
  12583. ASSERT_FALSE(matcher.match(request));
  12584. }
  12585. TEST(PathParamsTest, MultipleParams) {
  12586. const auto pattern = "/users/:userid/subscriptions/:subid";
  12587. detail::PathParamsMatcher matcher(pattern);
  12588. Request request;
  12589. request.path = "/users/42/subscriptions/2";
  12590. ASSERT_TRUE(matcher.match(request));
  12591. std::unordered_map<std::string, std::string> expected_params = {
  12592. {"userid", "42"}, {"subid", "2"}};
  12593. EXPECT_EQ(request.path_params, expected_params);
  12594. }
  12595. TEST(PathParamsTest, SequenceOfParams) {
  12596. const auto pattern = "/values/:x/:y/:z";
  12597. detail::PathParamsMatcher matcher(pattern);
  12598. Request request;
  12599. request.path = "/values/1/2/3";
  12600. ASSERT_TRUE(matcher.match(request));
  12601. std::unordered_map<std::string, std::string> expected_params = {
  12602. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12603. EXPECT_EQ(request.path_params, expected_params);
  12604. }
  12605. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12606. const auto pattern = "/prefix:suffix";
  12607. detail::PathParamsMatcher matcher(pattern);
  12608. Request request;
  12609. request.path = "/prefix:suffix";
  12610. ASSERT_TRUE(matcher.match(request));
  12611. const std::unordered_map<std::string, std::string> expected_params = {};
  12612. EXPECT_EQ(request.path_params, expected_params);
  12613. }
  12614. TEST(ParseUrlTest, VariousPatterns) {
  12615. {
  12616. detail::UrlComponents uc;
  12617. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12618. EXPECT_EQ("http", uc.scheme);
  12619. EXPECT_EQ("example.com", uc.host);
  12620. EXPECT_EQ("8080", uc.port);
  12621. EXPECT_EQ("/path", uc.path);
  12622. EXPECT_EQ("?q=1", uc.query);
  12623. }
  12624. {
  12625. detail::UrlComponents uc;
  12626. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12627. EXPECT_EQ("https", uc.scheme);
  12628. EXPECT_EQ("example.com", uc.host);
  12629. EXPECT_TRUE(uc.port.empty());
  12630. EXPECT_EQ("/path", uc.path);
  12631. }
  12632. {
  12633. detail::UrlComponents uc;
  12634. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12635. EXPECT_EQ("::1", uc.host);
  12636. EXPECT_EQ("8080", uc.port);
  12637. EXPECT_EQ("/path", uc.path);
  12638. }
  12639. {
  12640. detail::UrlComponents uc;
  12641. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12642. }
  12643. {
  12644. detail::UrlComponents uc;
  12645. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12646. EXPECT_TRUE(uc.scheme.empty());
  12647. EXPECT_EQ("example.com", uc.host);
  12648. EXPECT_EQ("/path", uc.path);
  12649. EXPECT_EQ("?q=1", uc.query);
  12650. }
  12651. {
  12652. detail::UrlComponents uc;
  12653. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12654. EXPECT_TRUE(uc.host.empty());
  12655. EXPECT_EQ("/path", uc.path);
  12656. EXPECT_EQ("?q=1", uc.query);
  12657. }
  12658. {
  12659. detail::UrlComponents uc;
  12660. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12661. EXPECT_EQ("example.com", uc.host);
  12662. EXPECT_EQ("8080", uc.port);
  12663. }
  12664. {
  12665. // Unix socket path — must not be parsed as host
  12666. detail::UrlComponents uc;
  12667. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12668. EXPECT_TRUE(uc.host.empty());
  12669. }
  12670. {
  12671. detail::UrlComponents uc;
  12672. ASSERT_TRUE(detail::parse_url("", uc));
  12673. EXPECT_TRUE(uc.host.empty());
  12674. EXPECT_TRUE(uc.path.empty());
  12675. }
  12676. {
  12677. detail::UrlComponents uc;
  12678. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12679. }
  12680. {
  12681. detail::UrlComponents uc;
  12682. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12683. }
  12684. {
  12685. // Accepted by parse_url; callers restrict to http/https
  12686. detail::UrlComponents uc;
  12687. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12688. EXPECT_EQ("ftp", uc.scheme);
  12689. }
  12690. {
  12691. detail::UrlComponents uc;
  12692. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12693. }
  12694. {
  12695. detail::UrlComponents uc;
  12696. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12697. }
  12698. }
  12699. TEST(ParseUrlTest, FragmentHandling) {
  12700. {
  12701. detail::UrlComponents uc;
  12702. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12703. EXPECT_EQ("/path", uc.path);
  12704. EXPECT_TRUE(uc.query.empty());
  12705. }
  12706. {
  12707. detail::UrlComponents uc;
  12708. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12709. EXPECT_TRUE(uc.path.empty());
  12710. EXPECT_TRUE(uc.query.empty());
  12711. }
  12712. }
  12713. TEST(ParseUrlTest, UserinfoHandling) {
  12714. // Userinfo with @ but no colon — host includes @
  12715. detail::UrlComponents uc;
  12716. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12717. EXPECT_EQ("user@host.com", uc.host);
  12718. EXPECT_EQ("/path", uc.path);
  12719. }
  12720. TEST(ParseUrlTest, IPv6EdgeCases) {
  12721. {
  12722. detail::UrlComponents uc;
  12723. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12724. EXPECT_TRUE(uc.scheme.empty());
  12725. EXPECT_EQ("::1", uc.host);
  12726. EXPECT_EQ("8080", uc.port);
  12727. }
  12728. {
  12729. // Zone ID '%25' is not in [a-fA-F0-9:]
  12730. detail::UrlComponents uc;
  12731. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12732. }
  12733. }
  12734. TEST(ParseUrlTest, SchemeEdgeCases) {
  12735. {
  12736. detail::UrlComponents uc;
  12737. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12738. }
  12739. {
  12740. detail::UrlComponents uc;
  12741. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12742. }
  12743. {
  12744. detail::UrlComponents uc;
  12745. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12746. }
  12747. }
  12748. TEST(ParseUrlTest, PortEdgeCases) {
  12749. {
  12750. detail::UrlComponents uc;
  12751. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12752. EXPECT_TRUE(uc.port.empty());
  12753. EXPECT_EQ("/path", uc.path);
  12754. }
  12755. {
  12756. // parse_url accepts any port string; validation is done by parse_port
  12757. detail::UrlComponents uc;
  12758. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12759. EXPECT_EQ("abc", uc.port);
  12760. }
  12761. }
  12762. TEST(ParseUrlTest, WebSocketPatterns) {
  12763. {
  12764. detail::UrlComponents uc;
  12765. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12766. EXPECT_EQ("ws", uc.scheme);
  12767. EXPECT_EQ("echo.example.com", uc.host);
  12768. EXPECT_EQ("8080", uc.port);
  12769. EXPECT_EQ("/ws", uc.path);
  12770. }
  12771. {
  12772. detail::UrlComponents uc;
  12773. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12774. EXPECT_EQ("wss", uc.scheme);
  12775. EXPECT_EQ("echo.example.com", uc.host);
  12776. EXPECT_TRUE(uc.port.empty());
  12777. EXPECT_EQ("/ws", uc.path);
  12778. }
  12779. }
  12780. TEST(ParseUrlTest, QueryOnly) {
  12781. detail::UrlComponents uc;
  12782. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12783. EXPECT_TRUE(uc.host.empty());
  12784. EXPECT_TRUE(uc.path.empty());
  12785. EXPECT_EQ("?q=1&r=2", uc.query);
  12786. }
  12787. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12788. detail::UrlComponents uc;
  12789. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12790. EXPECT_TRUE(uc.scheme.empty());
  12791. EXPECT_EQ("example.com", uc.host);
  12792. EXPECT_EQ("443", uc.port);
  12793. EXPECT_EQ("/path", uc.path);
  12794. }
  12795. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12796. // If ipv6 regex working, regex match codepath is taken.
  12797. // else port will default to 80 in Client impl
  12798. int clientImplMagicPort = 80;
  12799. int port = 4321;
  12800. // above ports must be different to avoid false negative
  12801. EXPECT_NE(clientImplMagicPort, port);
  12802. std::string ipV6TestURL = "http://[ff06::c3]";
  12803. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12804. CLIENT_PRIVATE_KEY_FILE);
  12805. EXPECT_EQ(cli.port(), port);
  12806. }
  12807. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12808. auto file_path = "./www/dir/index.html";
  12809. auto dir_path = "./www/dir";
  12810. detail::FileStat stat_file(file_path);
  12811. EXPECT_TRUE(stat_file.is_file());
  12812. EXPECT_FALSE(stat_file.is_dir());
  12813. detail::FileStat stat_dir(dir_path);
  12814. EXPECT_FALSE(stat_dir.is_file());
  12815. EXPECT_TRUE(stat_dir.is_dir());
  12816. }
  12817. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12818. // IPv4 with default HTTP port (80)
  12819. EXPECT_EQ("example.com",
  12820. detail::make_host_and_port_string("example.com", 80, false));
  12821. // IPv4 with default HTTPS port (443)
  12822. EXPECT_EQ("example.com",
  12823. detail::make_host_and_port_string("example.com", 443, true));
  12824. // IPv4 with non-default HTTP port
  12825. EXPECT_EQ("example.com:8080",
  12826. detail::make_host_and_port_string("example.com", 8080, false));
  12827. // IPv4 with non-default HTTPS port
  12828. EXPECT_EQ("example.com:8443",
  12829. detail::make_host_and_port_string("example.com", 8443, true));
  12830. // IPv6 with default HTTP port (80)
  12831. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12832. // IPv6 with default HTTPS port (443)
  12833. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12834. // IPv6 with non-default HTTP port
  12835. EXPECT_EQ("[::1]:8080",
  12836. detail::make_host_and_port_string("::1", 8080, false));
  12837. // IPv6 with non-default HTTPS port
  12838. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12839. // IPv6 full address with default port
  12840. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12841. detail::make_host_and_port_string(
  12842. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12843. // IPv6 full address with non-default port
  12844. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12845. detail::make_host_and_port_string(
  12846. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12847. // IPv6 localhost with non-default port
  12848. EXPECT_EQ("[::1]:3000",
  12849. detail::make_host_and_port_string("::1", 3000, false));
  12850. // IPv6 with zone ID (link-local address) with default port
  12851. EXPECT_EQ("[fe80::1%eth0]",
  12852. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12853. // IPv6 with zone ID (link-local address) with non-default port
  12854. EXPECT_EQ("[fe80::1%eth0]:8080",
  12855. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12856. // Edge case: Port 443 with is_ssl=false (should add port)
  12857. EXPECT_EQ("example.com:443",
  12858. detail::make_host_and_port_string("example.com", 443, false));
  12859. // Edge case: Port 80 with is_ssl=true (should add port)
  12860. EXPECT_EQ("example.com:80",
  12861. detail::make_host_and_port_string("example.com", 80, true));
  12862. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12863. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12864. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12865. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12866. // Security fix: Already bracketed IPv6 should not get double brackets
  12867. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12868. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12869. EXPECT_EQ("[::1]:8080",
  12870. detail::make_host_and_port_string("[::1]", 8080, false));
  12871. EXPECT_EQ("[2001:db8::1]:8080",
  12872. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12873. EXPECT_EQ("[fe80::1%eth0]",
  12874. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12875. EXPECT_EQ("[fe80::1%eth0]:8080",
  12876. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12877. // Edge case: Empty host (should return as-is)
  12878. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12879. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12880. // This is a known limitation but shouldn't crash
  12881. EXPECT_EQ("[host:name]",
  12882. detail::make_host_and_port_string("host:name", 80, false));
  12883. // Port number edge cases (no validation, but should not crash)
  12884. EXPECT_EQ("example.com:0",
  12885. detail::make_host_and_port_string("example.com", 0, false));
  12886. EXPECT_EQ("example.com:-1",
  12887. detail::make_host_and_port_string("example.com", -1, false));
  12888. EXPECT_EQ("example.com:65535",
  12889. detail::make_host_and_port_string("example.com", 65535, false));
  12890. EXPECT_EQ("example.com:65536",
  12891. detail::make_host_and_port_string("example.com", 65536, false));
  12892. }
  12893. #ifdef CPPHTTPLIB_SSL_ENABLED
  12894. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12895. httplib::SSLClient cli("roblox.com", 443);
  12896. cli.set_follow_location(true);
  12897. auto res = cli.Get("/");
  12898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12899. EXPECT_EQ(StatusCode::OK_200, res->status);
  12900. }
  12901. #endif
  12902. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12903. Server svr;
  12904. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12905. EXPECT_EQ(res.status, 400);
  12906. });
  12907. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12908. auto se = detail::scope_exit([&] {
  12909. svr.stop();
  12910. thread.join();
  12911. ASSERT_FALSE(svr.is_running());
  12912. });
  12913. svr.wait_until_ready();
  12914. Client cli(HOST, PORT);
  12915. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12916. }
  12917. TEST(InvalidHeaderCharsTest, is_field_name) {
  12918. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12919. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12920. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12921. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12922. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12923. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12924. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12925. EXPECT_FALSE(detail::fields::is_field_name(""));
  12926. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12927. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12928. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12929. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12930. }
  12931. TEST(InvalidHeaderCharsTest, is_field_value) {
  12932. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12933. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12934. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12935. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12936. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12937. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12938. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12939. EXPECT_TRUE(detail::fields::is_field_value(""));
  12940. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12941. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12942. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12943. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12944. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12945. }
  12946. TEST(InvalidHeaderCharsTest, OnServer) {
  12947. Server svr;
  12948. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12949. std::string header = "Not Set";
  12950. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12951. res.set_header(header, "value");
  12952. res.set_content("Page Content Page Content", "text/plain");
  12953. });
  12954. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12955. std::string header = "Not Set";
  12956. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12957. res.set_header("X-Test", header);
  12958. res.set_content("Page Content Page Content", "text/plain");
  12959. });
  12960. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12961. auto se = detail::scope_exit([&] {
  12962. svr.stop();
  12963. thread.join();
  12964. ASSERT_FALSE(svr.is_running());
  12965. });
  12966. svr.wait_until_ready();
  12967. Client cli(HOST, PORT);
  12968. {
  12969. auto res = cli.Get(
  12970. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12972. EXPECT_EQ("Page Content Page Content", res->body);
  12973. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12974. }
  12975. {
  12976. auto res = cli.Get(
  12977. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12979. EXPECT_EQ("Page Content Page Content", res->body);
  12980. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12981. }
  12982. }
  12983. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12984. auto handled = false;
  12985. Server svr;
  12986. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12987. thread t = thread([&] { svr.listen(HOST, PORT); });
  12988. auto se = detail::scope_exit([&] {
  12989. svr.stop();
  12990. t.join();
  12991. ASSERT_FALSE(svr.is_running());
  12992. ASSERT_FALSE(handled);
  12993. });
  12994. svr.wait_until_ready();
  12995. auto req = "POST /test HTTP/1.1\r\n"
  12996. "Content-Length: x\r\n"
  12997. "\r\n";
  12998. std::string response;
  12999. ASSERT_TRUE(send_request(1, req, &response));
  13000. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13001. response.substr(0, response.find("\r\n")));
  13002. }
  13003. #ifndef _WIN32
  13004. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13005. static constexpr char reject[] = "Unauthorized";
  13006. static constexpr char accept[] = "Upload accepted";
  13007. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13008. Server svr;
  13009. svr.set_expect_100_continue_handler(
  13010. [](const Request & /*req*/, Response &res) {
  13011. res.status = StatusCode::Unauthorized_401;
  13012. res.set_content(reject, "text/plain");
  13013. return res.status;
  13014. });
  13015. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13016. res.set_content(accept, "text/plain");
  13017. });
  13018. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13019. auto se = detail::scope_exit([&] {
  13020. svr.stop();
  13021. thread.join();
  13022. ASSERT_FALSE(svr.is_running());
  13023. });
  13024. svr.wait_until_ready();
  13025. {
  13026. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13027. curl_easy_init(), &curl_easy_cleanup};
  13028. ASSERT_NE(curl, nullptr);
  13029. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13030. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13031. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13032. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13033. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13034. &curl_slist_free_all};
  13035. ASSERT_NE(list, nullptr);
  13036. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13037. struct read_data {
  13038. size_t read_size;
  13039. size_t total_size;
  13040. } data = {0, total_size};
  13041. using read_callback_t =
  13042. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13043. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13044. void *userdata) -> size_t {
  13045. read_data *d = (read_data *)userdata;
  13046. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13047. std::fill_n(ptr, size * nmemb, 'A');
  13048. d->read_size += size * nmemb;
  13049. return size * nmemb;
  13050. };
  13051. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13052. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13053. std::vector<char> buffer;
  13054. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13055. using write_callback_t =
  13056. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13057. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13058. void *userdata) -> size_t {
  13059. std::vector<char> *buf = (std::vector<char> *)userdata;
  13060. buf->reserve(buf->size() + size * nmemb + 1);
  13061. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13062. return size * nmemb;
  13063. };
  13064. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13065. {
  13066. const auto res = curl_easy_perform(curl.get());
  13067. ASSERT_EQ(res, CURLE_OK);
  13068. }
  13069. {
  13070. auto response_code = long{};
  13071. const auto res =
  13072. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13073. ASSERT_EQ(res, CURLE_OK);
  13074. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13075. }
  13076. {
  13077. auto dl = curl_off_t{};
  13078. const auto res =
  13079. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13080. ASSERT_EQ(res, CURLE_OK);
  13081. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13082. }
  13083. {
  13084. buffer.push_back('\0');
  13085. ASSERT_STRCASEEQ(buffer.data(), reject);
  13086. }
  13087. }
  13088. }
  13089. #endif
  13090. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13091. // Regression test for #2458.
  13092. //
  13093. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13094. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13095. // ticket can make the client socket spuriously readable during the
  13096. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13097. // the client withholds the body and then blocks reading a response that never
  13098. // comes, failing with `Failed to read connection`.
  13099. //
  13100. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13101. // within the timeout. This raw OpenSSL server deliberately never sends
  13102. // `100 Continue`; the client must still deliver the body and receive 200.
  13103. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13104. signal(SIGPIPE, SIG_IGN);
  13105. const auto port = PORT + 4;
  13106. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13107. ASSERT_NE(srv, INVALID_SOCKET);
  13108. int opt = 1;
  13109. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13110. sockaddr_in addr{};
  13111. addr.sin_family = AF_INET;
  13112. addr.sin_port = htons(static_cast<uint16_t>(port));
  13113. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13114. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13115. ASSERT_EQ(0, ::listen(srv, 1));
  13116. std::atomic<size_t> server_body_bytes{0};
  13117. auto server_thread = std::thread([&] {
  13118. sockaddr_in cli_addr{};
  13119. socklen_t cli_len = sizeof(cli_addr);
  13120. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13121. if (cli == INVALID_SOCKET) { return; }
  13122. // Bound the lifetime of the server side so a buggy client (which never
  13123. // sends the body) cannot make this thread block forever on join.
  13124. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13125. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13126. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13127. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13128. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13129. SSL *ssl = SSL_new(ctx);
  13130. SSL_set_fd(ssl, static_cast<int>(cli));
  13131. if (SSL_accept(ssl) > 0) {
  13132. // Read the request headers. Reading here also flushes the TLS 1.3
  13133. // session tickets to the client. Deliberately do NOT send
  13134. // `100 Continue`.
  13135. std::string buf;
  13136. char tmp[1024];
  13137. while (buf.find("\r\n\r\n") == std::string::npos) {
  13138. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13139. if (n <= 0) { break; }
  13140. buf.append(tmp, static_cast<size_t>(n));
  13141. }
  13142. // A correct client sends the body now; count what arrives.
  13143. auto pos = buf.find("\r\n\r\n");
  13144. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13145. while (body < 4096) {
  13146. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13147. if (n <= 0) { break; }
  13148. body += static_cast<size_t>(n);
  13149. }
  13150. server_body_bytes = body;
  13151. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13152. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13153. SSL_shutdown(ssl);
  13154. }
  13155. SSL_free(ssl);
  13156. detail::close_socket(cli);
  13157. SSL_CTX_free(ctx);
  13158. });
  13159. auto se = detail::scope_exit([&] {
  13160. server_thread.join();
  13161. detail::close_socket(srv);
  13162. });
  13163. SSLClient cli("127.0.0.1", port);
  13164. cli.enable_server_certificate_verification(false);
  13165. cli.set_connection_timeout(5, 0);
  13166. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13167. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13168. std::string body(4096, 'A');
  13169. auto res = cli.Put("/api/test", body, "application/json");
  13170. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13171. EXPECT_EQ(StatusCode::OK_200, res->status);
  13172. EXPECT_EQ(body.size(), server_body_bytes.load());
  13173. }
  13174. #endif
  13175. template <typename S, typename C>
  13176. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13177. svr.Get("/stream", [&](const Request &, Response &res) {
  13178. auto data = new std::string("01234567890123456789");
  13179. res.set_content_provider(
  13180. data->size(), "text/plain",
  13181. [&, data](size_t offset, size_t length, DataSink &sink) {
  13182. const size_t DATA_CHUNK_SIZE = 4;
  13183. const auto &d = *data;
  13184. std::this_thread::sleep_for(std::chrono::seconds(1));
  13185. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13186. return true;
  13187. },
  13188. [data](bool success) {
  13189. EXPECT_FALSE(success);
  13190. delete data;
  13191. });
  13192. });
  13193. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13194. auto i = new size_t(0);
  13195. res.set_content_provider(
  13196. "text/plain",
  13197. [i](size_t, DataSink &sink) {
  13198. if (*i < 5) {
  13199. std::this_thread::sleep_for(std::chrono::seconds(1));
  13200. sink.write("abcd", 4);
  13201. (*i)++;
  13202. } else {
  13203. sink.done();
  13204. }
  13205. return true;
  13206. },
  13207. [i](bool success) {
  13208. EXPECT_FALSE(success);
  13209. delete i;
  13210. });
  13211. });
  13212. svr.Get("/chunked", [&](const Request &, Response &res) {
  13213. auto i = new size_t(0);
  13214. res.set_chunked_content_provider(
  13215. "text/plain",
  13216. [i](size_t, DataSink &sink) {
  13217. if (*i < 5) {
  13218. std::this_thread::sleep_for(std::chrono::seconds(1));
  13219. sink.os << "abcd";
  13220. (*i)++;
  13221. } else {
  13222. sink.done();
  13223. }
  13224. return true;
  13225. },
  13226. [i](bool success) {
  13227. EXPECT_FALSE(success);
  13228. delete i;
  13229. });
  13230. });
  13231. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13232. auto se = detail::scope_exit([&] {
  13233. svr.stop();
  13234. listen_thread.join();
  13235. ASSERT_FALSE(svr.is_running());
  13236. });
  13237. svr.wait_until_ready();
  13238. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13239. {
  13240. auto start = std::chrono::steady_clock::now();
  13241. auto res = cli.Get("/stream");
  13242. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13243. std::chrono::steady_clock::now() - start)
  13244. .count();
  13245. ASSERT_FALSE(res);
  13246. EXPECT_EQ(Error::Read, res.error());
  13247. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13248. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13249. }
  13250. {
  13251. auto start = std::chrono::steady_clock::now();
  13252. auto res = cli.Get("/stream_without_length");
  13253. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13254. std::chrono::steady_clock::now() - start)
  13255. .count();
  13256. ASSERT_FALSE(res);
  13257. EXPECT_EQ(Error::Read, res.error());
  13258. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13259. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13260. }
  13261. {
  13262. auto start = std::chrono::steady_clock::now();
  13263. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13264. EXPECT_EQ("abcd", string(data, data_length));
  13265. return true;
  13266. });
  13267. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13268. std::chrono::steady_clock::now() - start)
  13269. .count();
  13270. ASSERT_FALSE(res);
  13271. EXPECT_EQ(Error::Read, res.error());
  13272. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13273. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13274. }
  13275. }
  13276. TEST(MaxTimeoutTest, ContentStream) {
  13277. time_t timeout = 2000;
  13278. time_t threshold = 200;
  13279. Server svr;
  13280. Client cli("localhost", PORT);
  13281. max_timeout_test(svr, cli, timeout, threshold);
  13282. }
  13283. #ifdef CPPHTTPLIB_SSL_ENABLED
  13284. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13285. time_t timeout = 2000;
  13286. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13287. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13288. SSLClient cli("localhost", PORT);
  13289. cli.enable_server_certificate_verification(false);
  13290. max_timeout_test(svr, cli, timeout, threshold);
  13291. }
  13292. #endif
  13293. class EventDispatcher {
  13294. public:
  13295. EventDispatcher() {}
  13296. bool wait_event(DataSink *sink) {
  13297. unique_lock<mutex> lk(m_);
  13298. int id = id_;
  13299. // Wait with timeout to prevent hanging if client disconnects
  13300. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13301. [&] { return cid_ == id; })) {
  13302. return false; // Timeout occurred
  13303. }
  13304. sink->write(message_.data(), message_.size());
  13305. return true;
  13306. }
  13307. void send_event(const string &message) {
  13308. lock_guard<mutex> lk(m_);
  13309. cid_ = id_++;
  13310. message_ = message;
  13311. cv_.notify_all();
  13312. }
  13313. private:
  13314. mutex m_;
  13315. condition_variable cv_;
  13316. atomic_int id_{0};
  13317. atomic_int cid_{-1};
  13318. string message_;
  13319. };
  13320. TEST(ClientInThreadTest, Issue2068) {
  13321. EventDispatcher ed;
  13322. Server svr;
  13323. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13324. res.set_chunked_content_provider("text/event-stream",
  13325. [&](size_t /*offset*/, DataSink &sink) {
  13326. return ed.wait_event(&sink);
  13327. });
  13328. });
  13329. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13330. svr.wait_until_ready();
  13331. thread event_thread([&] {
  13332. int id = 0;
  13333. while (svr.is_running()) {
  13334. this_thread::sleep_for(chrono::milliseconds(500));
  13335. std::stringstream ss;
  13336. ss << "data: " << id << "\n\n";
  13337. ed.send_event(ss.str());
  13338. id++;
  13339. }
  13340. });
  13341. auto se = detail::scope_exit([&] {
  13342. svr.stop();
  13343. listen_thread.join();
  13344. event_thread.join();
  13345. ASSERT_FALSE(svr.is_running());
  13346. });
  13347. {
  13348. auto client = detail::make_unique<Client>(HOST, PORT);
  13349. client->set_read_timeout(std::chrono::minutes(10));
  13350. std::atomic<bool> stop{false};
  13351. std::thread t([&] {
  13352. client->Get("/event1",
  13353. [&](const char *, size_t) -> bool { return !stop; });
  13354. });
  13355. std::this_thread::sleep_for(std::chrono::seconds(2));
  13356. stop = true;
  13357. client->stop();
  13358. t.join();
  13359. // Reset client after thread has finished
  13360. client.reset();
  13361. }
  13362. }
  13363. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13364. auto handled = false;
  13365. Server svr;
  13366. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13367. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13368. auto se = detail::scope_exit([&] {
  13369. svr.stop();
  13370. t.join();
  13371. ASSERT_FALSE(svr.is_running());
  13372. ASSERT_FALSE(handled);
  13373. });
  13374. svr.wait_until_ready();
  13375. // Two Content-Length headers with different values — must be rejected
  13376. auto req = "POST /test HTTP/1.1\r\n"
  13377. "Content-Length: 5\r\n"
  13378. "Content-Length: 10\r\n"
  13379. "\r\n"
  13380. "hello";
  13381. std::string response;
  13382. ASSERT_TRUE(send_request(1, req, &response));
  13383. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13384. response.substr(0, response.find("\r\n")));
  13385. }
  13386. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13387. auto handled = false;
  13388. Server svr;
  13389. svr.Post("/test", [&](const Request &, Response &res) {
  13390. handled = true;
  13391. res.set_content("ok", "text/plain");
  13392. });
  13393. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13394. auto se = detail::scope_exit([&] {
  13395. svr.stop();
  13396. t.join();
  13397. ASSERT_FALSE(svr.is_running());
  13398. ASSERT_TRUE(handled);
  13399. });
  13400. svr.wait_until_ready();
  13401. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13402. auto req = "POST /test HTTP/1.1\r\n"
  13403. "Content-Length: 5\r\n"
  13404. "Content-Length: 5\r\n"
  13405. "\r\n"
  13406. "hello";
  13407. std::string response;
  13408. ASSERT_TRUE(send_request(1, req, &response));
  13409. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13410. }
  13411. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13412. Server svr;
  13413. svr.Get("/", [](const Request &req, Response &res) {
  13414. EXPECT_EQ(2U, req.trailers.size());
  13415. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13416. // Denied
  13417. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13418. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13419. // Accepted
  13420. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13421. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13422. EXPECT_TRUE(req.has_trailer("X-World"));
  13423. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13424. res.set_content("ok", "text/plain");
  13425. });
  13426. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13427. auto se = detail::scope_exit([&] {
  13428. svr.stop();
  13429. t.join();
  13430. ASSERT_FALSE(svr.is_running());
  13431. });
  13432. svr.wait_until_ready();
  13433. const std::string req = "GET / HTTP/1.1\r\n"
  13434. "Transfer-Encoding: chunked\r\n"
  13435. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13436. "\r\n"
  13437. "0\r\n"
  13438. "Content-Length: 10\r\n"
  13439. "Host: internal.local\r\n"
  13440. "Content-Type: malicious/content\r\n"
  13441. "Cookie: any\r\n"
  13442. "Set-Cookie: any\r\n"
  13443. "X-Forwarded-For: attacker.com\r\n"
  13444. "X-Real-Ip: 1.1.1.1\r\n"
  13445. "X-Hello: hello\r\n"
  13446. "X-World: world\r\n"
  13447. "\r\n";
  13448. std::string res;
  13449. ASSERT_TRUE(send_request(1, req, &res));
  13450. }
  13451. // A direct client that is not listed in trusted_proxies must not be able to
  13452. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13453. // the peer address on the actual TCP connection determines whether the
  13454. // header is honored.
  13455. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13456. Server svr;
  13457. // Deliberately does NOT include the loopback address the test client
  13458. // actually connects from, so the direct connection is not a trusted proxy.
  13459. svr.set_trusted_proxies({"203.0.113.66"});
  13460. std::string observed_remote_addr;
  13461. svr.Get("/ip", [&](const Request &req, Response &res) {
  13462. observed_remote_addr = req.remote_addr;
  13463. res.set_content("ok", "text/plain");
  13464. });
  13465. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13466. auto se = detail::scope_exit([&] {
  13467. svr.stop();
  13468. t.join();
  13469. ASSERT_FALSE(svr.is_running());
  13470. });
  13471. svr.wait_until_ready();
  13472. Client cli(HOST, PORT);
  13473. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13475. EXPECT_EQ(StatusCode::OK_200, res->status);
  13476. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13477. // ignored entirely and the real connection-level address retained.
  13478. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13479. observed_remote_addr == "127.0.0.1");
  13480. }
  13481. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13482. Server svr;
  13483. std::string observed_remote_addr;
  13484. std::string observed_xff;
  13485. svr.Get("/ip", [&](const Request &req, Response &res) {
  13486. observed_remote_addr = req.remote_addr;
  13487. observed_xff = req.get_header_value("X-Forwarded-For");
  13488. res.set_content("ok", "text/plain");
  13489. });
  13490. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13491. auto se = detail::scope_exit([&] {
  13492. svr.stop();
  13493. t.join();
  13494. ASSERT_FALSE(svr.is_running());
  13495. });
  13496. svr.wait_until_ready();
  13497. Client cli(HOST, PORT);
  13498. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13500. EXPECT_EQ(StatusCode::OK_200, res->status);
  13501. EXPECT_EQ(observed_xff, "203.0.113.66");
  13502. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13503. observed_remote_addr == "127.0.0.1");
  13504. }
  13505. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13506. Server svr;
  13507. svr.set_trusted_proxies({"203.0.113.66"});
  13508. std::string observed_remote_addr;
  13509. std::string observed_xff;
  13510. svr.Get("/ip", [&](const Request &req, Response &res) {
  13511. observed_remote_addr = req.remote_addr;
  13512. observed_xff = req.get_header_value("X-Forwarded-For");
  13513. res.set_content("ok", "text/plain");
  13514. });
  13515. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13516. auto se = detail::scope_exit([&] {
  13517. svr.stop();
  13518. t.join();
  13519. ASSERT_FALSE(svr.is_running());
  13520. });
  13521. svr.wait_until_ready();
  13522. Client cli(HOST, PORT);
  13523. auto res = cli.Get("/ip");
  13524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13525. EXPECT_EQ(StatusCode::OK_200, res->status);
  13526. EXPECT_EQ(observed_xff, "");
  13527. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13528. observed_remote_addr == "127.0.0.1");
  13529. }
  13530. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13531. Server svr;
  13532. // Include the loopback address the test client actually connects from, so
  13533. // the direct connection itself is recognized as the trusted proxy hop.
  13534. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13535. std::string observed_remote_addr;
  13536. std::string observed_xff;
  13537. svr.Get("/ip", [&](const Request &req, Response &res) {
  13538. observed_remote_addr = req.remote_addr;
  13539. observed_xff = req.get_header_value("X-Forwarded-For");
  13540. res.set_content("ok", "text/plain");
  13541. });
  13542. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13543. auto se = detail::scope_exit([&] {
  13544. svr.stop();
  13545. t.join();
  13546. ASSERT_FALSE(svr.is_running());
  13547. });
  13548. svr.wait_until_ready();
  13549. Client cli(HOST, PORT);
  13550. auto res = cli.Get(
  13551. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13553. EXPECT_EQ(StatusCode::OK_200, res->status);
  13554. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13555. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13556. }
  13557. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13558. Server svr;
  13559. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13560. std::string observed_remote_addr;
  13561. std::string observed_xff;
  13562. svr.Get("/ip", [&](const Request &req, Response &res) {
  13563. observed_remote_addr = req.remote_addr;
  13564. observed_xff = req.get_header_value("X-Forwarded-For");
  13565. res.set_content("ok", "text/plain");
  13566. });
  13567. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13568. auto se = detail::scope_exit([&] {
  13569. svr.stop();
  13570. t.join();
  13571. ASSERT_FALSE(svr.is_running());
  13572. });
  13573. svr.wait_until_ready();
  13574. Client cli(HOST, PORT);
  13575. auto res = cli.Get(
  13576. "/ip",
  13577. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13579. EXPECT_EQ(StatusCode::OK_200, res->status);
  13580. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13581. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13582. }
  13583. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13584. Server svr;
  13585. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13586. std::string observed_remote_addr;
  13587. std::string observed_xff;
  13588. svr.Get("/ip", [&](const Request &req, Response &res) {
  13589. observed_remote_addr = req.remote_addr;
  13590. observed_xff = req.get_header_value("X-Forwarded-For");
  13591. res.set_content("ok", "text/plain");
  13592. });
  13593. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13594. auto se = detail::scope_exit([&] {
  13595. svr.stop();
  13596. t.join();
  13597. ASSERT_FALSE(svr.is_running());
  13598. });
  13599. svr.wait_until_ready();
  13600. Client cli(HOST, PORT);
  13601. auto res = cli.Get(
  13602. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13604. EXPECT_EQ(StatusCode::OK_200, res->status);
  13605. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13606. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13607. // and must not be selected.
  13608. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13609. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13610. }
  13611. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13612. Server svr;
  13613. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13614. std::string observed_remote_addr;
  13615. svr.Get("/ip", [&](const Request &req, Response &res) {
  13616. observed_remote_addr = req.remote_addr;
  13617. res.set_content("ok", "text/plain");
  13618. });
  13619. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13620. auto se = detail::scope_exit([&] {
  13621. svr.stop();
  13622. t.join();
  13623. ASSERT_FALSE(svr.is_running());
  13624. });
  13625. svr.wait_until_ready();
  13626. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13627. // a forged address and the trusted proxy's own address; the forged value must
  13628. // not win over the address the trusted proxy actually recorded.
  13629. Client cli(HOST, PORT);
  13630. auto res = cli.Get(
  13631. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13633. EXPECT_EQ(StatusCode::OK_200, res->status);
  13634. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13635. }
  13636. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13637. Server svr;
  13638. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13639. std::string observed_remote_addr;
  13640. std::string observed_xff;
  13641. svr.Get("/ip", [&](const Request &req, Response &res) {
  13642. observed_remote_addr = req.remote_addr;
  13643. observed_xff = req.get_header_value("X-Forwarded-For");
  13644. res.set_content("ok", "text/plain");
  13645. });
  13646. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13647. auto se = detail::scope_exit([&] {
  13648. svr.stop();
  13649. t.join();
  13650. ASSERT_FALSE(svr.is_running());
  13651. });
  13652. svr.wait_until_ready();
  13653. Client cli(HOST, PORT);
  13654. auto res = cli.Get(
  13655. "/ip",
  13656. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13658. EXPECT_EQ(StatusCode::OK_200, res->status);
  13659. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13660. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13661. }
  13662. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13663. Server svr;
  13664. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13665. std::string observed_remote_addr;
  13666. std::string observed_xff;
  13667. svr.Get("/ip", [&](const Request &req, Response &res) {
  13668. observed_remote_addr = req.remote_addr;
  13669. observed_xff = req.get_header_value("X-Forwarded-For");
  13670. res.set_content("ok", "text/plain");
  13671. });
  13672. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13673. auto se = detail::scope_exit([&] {
  13674. svr.stop();
  13675. t.join();
  13676. ASSERT_FALSE(svr.is_running());
  13677. });
  13678. svr.wait_until_ready();
  13679. std::string raw_req =
  13680. "GET /ip HTTP/1.1\r\n"
  13681. "Host: localhost\r\n"
  13682. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13683. "Connection: close\r\n"
  13684. "\r\n";
  13685. std::string out;
  13686. ASSERT_TRUE(send_request(5, raw_req, &out));
  13687. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13688. // Header parser trims surrounding whitespace of the header value
  13689. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13690. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13691. }
  13692. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13693. // crash the server (it used to call front() on an empty vector inside
  13694. // get_client_ip). The connection-level remote address must be retained instead.
  13695. static void run_malformed_xff_test(const std::string &xff_value) {
  13696. Server svr;
  13697. svr.set_trusted_proxies({"192.0.2.45"});
  13698. std::string observed_remote_addr;
  13699. svr.Get("/ip", [&](const Request &req, Response &res) {
  13700. observed_remote_addr = req.remote_addr;
  13701. res.set_content("ok", "text/plain");
  13702. });
  13703. int port = 0;
  13704. thread t = thread([&]() {
  13705. port = svr.bind_to_any_port(HOST);
  13706. svr.listen_after_bind();
  13707. });
  13708. auto se = detail::scope_exit([&] {
  13709. svr.stop();
  13710. t.join();
  13711. ASSERT_FALSE(svr.is_running());
  13712. });
  13713. svr.wait_until_ready();
  13714. Client cli(HOST, port);
  13715. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13717. EXPECT_EQ(StatusCode::OK_200, res->status);
  13718. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13719. observed_remote_addr == "127.0.0.1");
  13720. }
  13721. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13722. run_malformed_xff_test("");
  13723. }
  13724. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13725. run_malformed_xff_test(",");
  13726. }
  13727. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13728. run_malformed_xff_test(", , ,");
  13729. }
  13730. #ifndef _WIN32
  13731. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13732. Server svr;
  13733. svr.Post("/post", [&](const Request &req, Response &res) {
  13734. res.set_content(req.body, "text/plain");
  13735. });
  13736. svr.Put("/put", [&](const Request &req, Response &res) {
  13737. res.set_content(req.body, "text/plain");
  13738. });
  13739. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13740. res.set_content(req.body, "text/plain");
  13741. });
  13742. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13743. res.set_content(req.body, "text/plain");
  13744. });
  13745. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13746. auto se = detail::scope_exit([&] {
  13747. svr.stop();
  13748. t.join();
  13749. ASSERT_FALSE(svr.is_running());
  13750. });
  13751. svr.wait_until_ready();
  13752. std::string resp;
  13753. // POST without Content-Length
  13754. ASSERT_TRUE(send_request(5,
  13755. "POST /post HTTP/1.1\r\n"
  13756. "Host: localhost\r\n"
  13757. "Connection: close\r\n"
  13758. "\r\n",
  13759. &resp));
  13760. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13761. // PUT without Content-Length
  13762. resp.clear();
  13763. ASSERT_TRUE(send_request(5,
  13764. "PUT /put HTTP/1.1\r\n"
  13765. "Host: localhost\r\n"
  13766. "Connection: close\r\n"
  13767. "\r\n",
  13768. &resp));
  13769. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13770. // PATCH without Content-Length
  13771. resp.clear();
  13772. ASSERT_TRUE(send_request(5,
  13773. "PATCH /patch HTTP/1.1\r\n"
  13774. "Host: localhost\r\n"
  13775. "Connection: close\r\n"
  13776. "\r\n",
  13777. &resp));
  13778. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13779. // DELETE without Content-Length
  13780. resp.clear();
  13781. ASSERT_TRUE(send_request(5,
  13782. "DELETE /delete HTTP/1.1\r\n"
  13783. "Host: localhost\r\n"
  13784. "Connection: close\r\n"
  13785. "\r\n",
  13786. &resp));
  13787. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13788. }
  13789. #endif
  13790. //==============================================================================
  13791. // open_stream() Tests
  13792. //==============================================================================
  13793. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13794. std::string result;
  13795. char buf[8192];
  13796. ssize_t n;
  13797. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13798. result.append(buf, static_cast<size_t>(n));
  13799. }
  13800. return result;
  13801. }
  13802. // Mock stream for unit tests
  13803. class MockStream : public Stream {
  13804. public:
  13805. std::string data;
  13806. size_t pos = 0;
  13807. ssize_t error_after = -1; // -1 = no error
  13808. explicit MockStream(const std::string &d, ssize_t err = -1)
  13809. : data(d), error_after(err) {}
  13810. bool is_readable() const override { return true; }
  13811. bool wait_readable() const override { return true; }
  13812. bool wait_writable() const override { return true; }
  13813. ssize_t read(char *ptr, size_t size) override {
  13814. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13815. if (pos >= data.size()) return 0;
  13816. size_t limit =
  13817. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13818. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13819. std::memcpy(ptr, data.data() + pos, to_read);
  13820. pos += to_read;
  13821. return static_cast<ssize_t>(to_read);
  13822. }
  13823. ssize_t write(const char *, size_t) override { return -1; }
  13824. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13825. ip = "127.0.0.1";
  13826. port = 0;
  13827. }
  13828. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13829. ip = "127.0.0.1";
  13830. port = 0;
  13831. }
  13832. socket_t socket() const override { return INVALID_SOCKET; }
  13833. time_t duration() const override { return 0; }
  13834. };
  13835. TEST(StreamHandleTest, Basic) {
  13836. ClientImpl::StreamHandle handle;
  13837. EXPECT_FALSE(handle.is_valid());
  13838. handle.response = detail::make_unique<Response>();
  13839. handle.error = Error::Connection;
  13840. EXPECT_FALSE(handle.is_valid());
  13841. handle.error = Error::Success;
  13842. EXPECT_TRUE(handle.is_valid());
  13843. }
  13844. TEST(BodyReaderTest, Basic) {
  13845. MockStream stream("Hello, World!");
  13846. detail::BodyReader reader;
  13847. reader.stream = &stream;
  13848. reader.content_length = 13;
  13849. char buf[32];
  13850. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13851. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13852. EXPECT_TRUE(reader.eof);
  13853. }
  13854. TEST(BodyReaderTest, NoStream) {
  13855. detail::BodyReader reader;
  13856. char buf[32];
  13857. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13858. EXPECT_EQ(Error::Connection, reader.last_error);
  13859. }
  13860. TEST(BodyReaderTest, Error) {
  13861. MockStream stream("Hello, World!", 5);
  13862. detail::BodyReader reader;
  13863. reader.stream = &stream;
  13864. reader.content_length = 13;
  13865. char buf[32];
  13866. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13867. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13868. EXPECT_EQ(Error::Read, reader.last_error);
  13869. }
  13870. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13871. // Mock-based StreamHandle tests relying on private internals are removed.
  13872. class OpenStreamTest : public ::testing::Test {
  13873. protected:
  13874. void SetUp() override {
  13875. svr_.Get("/hello", [](const Request &, Response &res) {
  13876. res.set_content("Hello World!", "text/plain");
  13877. });
  13878. svr_.Get("/large", [](const Request &, Response &res) {
  13879. res.set_content(std::string(10000, 'X'), "text/plain");
  13880. });
  13881. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  13882. res.set_content("Hello World!", "image/jpeg");
  13883. res.set_header("Content-Encoding", "UTF-8");
  13884. });
  13885. svr_.Get("/chunked", [](const Request &, Response &res) {
  13886. res.set_chunked_content_provider("text/plain",
  13887. [](size_t offset, DataSink &sink) {
  13888. if (offset < 15) {
  13889. sink.write("chunk", 5);
  13890. return true;
  13891. }
  13892. sink.done();
  13893. return true;
  13894. });
  13895. });
  13896. svr_.Get("/compressible", [](const Request &, Response &res) {
  13897. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13898. DataSink &sink) {
  13899. if (offset < 100 * 1024) {
  13900. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13901. sink.write(chunk.data(), chunk.size());
  13902. return true;
  13903. }
  13904. sink.done();
  13905. return true;
  13906. });
  13907. });
  13908. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13909. [](const Request & /*req*/, Response &res) {
  13910. auto i = new int(0);
  13911. res.set_header("Trailer", "Content-Length, X-Allowed");
  13912. res.set_chunked_content_provider(
  13913. "text/plain",
  13914. [i](size_t /*offset*/, DataSink &sink) {
  13915. switch (*i) {
  13916. case 0: sink.os << "123"; break;
  13917. case 1: sink.os << "456"; break;
  13918. case 2: sink.os << "789"; break;
  13919. case 3: {
  13920. sink.done_with_trailer(
  13921. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13922. } break;
  13923. }
  13924. (*i)++;
  13925. return true;
  13926. },
  13927. [i](bool success) {
  13928. EXPECT_TRUE(success);
  13929. delete i;
  13930. });
  13931. });
  13932. // Echo headers endpoint for header-related tests
  13933. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13934. std::string body;
  13935. for (const auto &h : req.headers) {
  13936. body.append(h.first);
  13937. body.push_back(':');
  13938. body.append(h.second);
  13939. body.push_back('\n');
  13940. }
  13941. res.set_content(body, "text/plain");
  13942. });
  13943. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13944. std::string body;
  13945. for (const auto &h : req.headers) {
  13946. body.append(h.first);
  13947. body.push_back(':');
  13948. body.append(h.second);
  13949. body.push_back('\n');
  13950. }
  13951. res.set_content(body, "text/plain");
  13952. });
  13953. port_ = svr_.bind_to_any_port("127.0.0.1");
  13954. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13955. svr_.wait_until_ready();
  13956. }
  13957. void TearDown() override {
  13958. svr_.stop();
  13959. if (thread_.joinable()) thread_.join();
  13960. }
  13961. Server svr_;
  13962. std::thread thread_;
  13963. int port_ = 0;
  13964. };
  13965. TEST_F(OpenStreamTest, Basic) {
  13966. Client cli("127.0.0.1", port_);
  13967. auto handle = cli.open_stream("GET", "/hello");
  13968. EXPECT_TRUE(handle.is_valid());
  13969. EXPECT_EQ("Hello World!", read_all(handle));
  13970. }
  13971. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  13972. Client cli("127.0.0.1", port_);
  13973. auto handle = cli.open_stream("GET", "/unknown-encoding");
  13974. ASSERT_TRUE(handle.is_valid());
  13975. EXPECT_EQ("Hello World!", read_all(handle));
  13976. }
  13977. TEST_F(OpenStreamTest, SmallBuffer) {
  13978. Client cli("127.0.0.1", port_);
  13979. auto handle = cli.open_stream("GET", "/hello");
  13980. std::string result;
  13981. char buf[4];
  13982. ssize_t n;
  13983. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13984. result.append(buf, static_cast<size_t>(n));
  13985. EXPECT_EQ("Hello World!", result);
  13986. }
  13987. TEST_F(OpenStreamTest, DefaultHeaders) {
  13988. Client cli("127.0.0.1", port_);
  13989. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13990. {
  13991. auto handle = cli.open_stream("GET", "/echo-headers");
  13992. ASSERT_TRUE(handle.is_valid());
  13993. auto body = read_all(handle);
  13994. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13995. std::string::npos);
  13996. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13997. std::string::npos);
  13998. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13999. }
  14000. // open_stream POST with body and no explicit content_type should NOT add
  14001. // text/plain Content-Type (behavior differs from non-streaming path), but
  14002. // should include Content-Length
  14003. {
  14004. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14005. ASSERT_TRUE(handle.is_valid());
  14006. auto body = read_all(handle);
  14007. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14008. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14009. }
  14010. // open_stream POST with explicit Content-Type should preserve it
  14011. {
  14012. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14013. {{"Content-Type", "application/custom"}},
  14014. "{}", "application/custom");
  14015. ASSERT_TRUE(handle.is_valid());
  14016. auto body = read_all(handle);
  14017. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14018. }
  14019. // User-specified User-Agent must not be overwritten for stream API
  14020. {
  14021. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14022. {{"User-Agent", "MyAgent/1.2"}});
  14023. ASSERT_TRUE(handle.is_valid());
  14024. auto body = read_all(handle);
  14025. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14026. }
  14027. }
  14028. TEST_F(OpenStreamTest, Large) {
  14029. Client cli("127.0.0.1", port_);
  14030. auto handle = cli.open_stream("GET", "/large");
  14031. EXPECT_EQ(10000u, read_all(handle).size());
  14032. }
  14033. TEST_F(OpenStreamTest, ConnectionError) {
  14034. Client cli("127.0.0.1", 9999);
  14035. auto handle = cli.open_stream("GET", "/hello");
  14036. EXPECT_FALSE(handle.is_valid());
  14037. }
  14038. TEST_F(OpenStreamTest, Chunked) {
  14039. Client cli("127.0.0.1", port_);
  14040. auto handle = cli.open_stream("GET", "/chunked");
  14041. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14042. "Transfer-Encoding") == "chunked");
  14043. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14044. }
  14045. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14046. Client cli("127.0.0.1", port_);
  14047. auto handle =
  14048. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14049. ASSERT_TRUE(handle.is_valid());
  14050. // Consume body to allow trailers to be received/parsed
  14051. auto body = read_all(handle);
  14052. // Explicitly parse trailers (ensure trailers are available for assertion)
  14053. handle.parse_trailers_if_needed();
  14054. EXPECT_EQ(std::string("123456789"), body);
  14055. // The response should include a Trailer header declaring both names
  14056. ASSERT_TRUE(handle.response);
  14057. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14058. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14059. handle.response->get_header_value("Trailer"));
  14060. // Prohibited trailer must not be present
  14061. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14062. // Allowed trailer should be present
  14063. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14064. EXPECT_EQ(std::string("yes"),
  14065. handle.response->get_trailer_value("X-Allowed"));
  14066. // Verify trailers are NOT present as regular headers
  14067. EXPECT_EQ(std::string(""),
  14068. handle.response->get_header_value("Content-Length"));
  14069. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14070. }
  14071. static std::thread serve_single_response(std::promise<int> &port_promise,
  14072. const std::string &response) {
  14073. return std::thread([&port_promise, response] {
  14074. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14075. default_socket_options(srv);
  14076. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14077. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14078. sockaddr_in addr{};
  14079. addr.sin_family = AF_INET;
  14080. addr.sin_port = htons(0); // Let OS assign a free port
  14081. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14082. int opt = 1;
  14083. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14084. #ifdef _WIN32
  14085. reinterpret_cast<const char *>(&opt),
  14086. #else
  14087. &opt,
  14088. #endif
  14089. sizeof(opt));
  14090. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14091. ::listen(srv, 1) != 0) {
  14092. port_promise.set_value(-1);
  14093. detail::close_socket(srv);
  14094. return;
  14095. }
  14096. socklen_t addr_len = sizeof(addr);
  14097. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14098. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14099. sockaddr_in cli_addr{};
  14100. socklen_t cli_len = sizeof(cli_addr);
  14101. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14102. if (cli != INVALID_SOCKET) {
  14103. // Read the complete HTTP request (until the blank line that terminates
  14104. // headers) before sending the response. If the server closes the socket
  14105. // while the client's request data is still unread in the kernel receive
  14106. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14107. // connection on both sides: it discards the client's receive buffer
  14108. // (which already holds our response) and causes any in-progress write on
  14109. // the client to fail with ECONNRESET. Reading all request data first
  14110. // ensures close() emits a graceful FIN.
  14111. {
  14112. char rbuf[256];
  14113. std::string req;
  14114. while (req.find("\r\n\r\n") == std::string::npos) {
  14115. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14116. if (n <= 0) { break; }
  14117. req.append(rbuf, static_cast<size_t>(n));
  14118. }
  14119. }
  14120. ::send(cli,
  14121. #ifdef _WIN32
  14122. static_cast<const char *>(response.c_str()),
  14123. static_cast<int>(response.size()),
  14124. #else
  14125. response.c_str(), response.size(),
  14126. #endif
  14127. 0);
  14128. detail::close_socket(cli);
  14129. }
  14130. detail::close_socket(srv);
  14131. });
  14132. }
  14133. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14134. #ifndef _WIN32
  14135. signal(SIGPIPE, SIG_IGN);
  14136. #endif
  14137. std::promise<int> port_promise;
  14138. auto port_future = port_promise.get_future();
  14139. auto server_thread =
  14140. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14141. "Content-Type: text/plain\r\n"
  14142. "Content-Length: not-a-number\r\n"
  14143. "Connection: close\r\n"
  14144. "\r\n"
  14145. "hello");
  14146. auto port = port_future.get();
  14147. ASSERT_GT(port, 0);
  14148. Client cli("127.0.0.1", port);
  14149. auto handle = cli.open_stream("GET", "/");
  14150. EXPECT_FALSE(handle.is_valid());
  14151. server_thread.join();
  14152. }
  14153. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14154. #ifndef _WIN32
  14155. signal(SIGPIPE, SIG_IGN);
  14156. #endif
  14157. std::promise<int> port_promise;
  14158. auto port_future = port_promise.get_future();
  14159. auto server_thread = serve_single_response(
  14160. port_promise, "HTTP/1.1 200 OK\r\n"
  14161. "Content-Type: text/plain\r\n"
  14162. "Content-Length: 99999999999999999999999999\r\n"
  14163. "Connection: close\r\n"
  14164. "\r\n"
  14165. "hello");
  14166. auto port = port_future.get();
  14167. ASSERT_GT(port, 0);
  14168. // Historically std::stoull would throw std::out_of_range here and crash
  14169. // the process, then parsing silently clamped to a bogus framing length and
  14170. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14171. // so the stream fails to open, matching the not-a-number case above. The
  14172. // process still must NOT terminate.
  14173. Client cli("127.0.0.1", port);
  14174. auto handle = cli.open_stream("GET", "/");
  14175. EXPECT_FALSE(handle.is_valid());
  14176. server_thread.join();
  14177. }
  14178. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14179. TEST_F(OpenStreamTest, Gzip) {
  14180. Client cli("127.0.0.1", port_);
  14181. auto handle = cli.open_stream("GET", "/compressible", {},
  14182. {{"Accept-Encoding", "gzip"}});
  14183. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14184. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14185. }
  14186. #endif
  14187. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14188. TEST_F(OpenStreamTest, Brotli) {
  14189. Client cli("127.0.0.1", port_);
  14190. auto handle =
  14191. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14192. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14193. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14194. }
  14195. #endif
  14196. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14197. TEST_F(OpenStreamTest, Zstd) {
  14198. Client cli("127.0.0.1", port_);
  14199. auto handle = cli.open_stream("GET", "/compressible", {},
  14200. {{"Accept-Encoding", "zstd"}});
  14201. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14202. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14203. }
  14204. #endif
  14205. #ifdef CPPHTTPLIB_SSL_ENABLED
  14206. class SSLOpenStreamTest : public ::testing::Test {
  14207. protected:
  14208. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14209. void SetUp() override {
  14210. svr_.Get("/hello", [](const Request &, Response &res) {
  14211. res.set_content("Hello SSL World!", "text/plain");
  14212. });
  14213. svr_.Get("/chunked", [](const Request &, Response &res) {
  14214. res.set_chunked_content_provider("text/plain",
  14215. [](size_t offset, DataSink &sink) {
  14216. if (offset < 15) {
  14217. sink.write("chunk", 5);
  14218. return true;
  14219. }
  14220. sink.done();
  14221. return true;
  14222. });
  14223. });
  14224. svr_.Post("/echo", [](const Request &req, Response &res) {
  14225. res.set_content(req.body, req.get_header_value("Content-Type"));
  14226. });
  14227. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14228. std::string body = req.body;
  14229. res.set_chunked_content_provider(
  14230. "text/plain", [body](size_t offset, DataSink &sink) {
  14231. if (offset < body.size()) {
  14232. sink.write(body.data() + offset, body.size() - offset);
  14233. }
  14234. sink.done();
  14235. return true;
  14236. });
  14237. });
  14238. port_ = svr_.bind_to_any_port("127.0.0.1");
  14239. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14240. svr_.wait_until_ready();
  14241. }
  14242. void TearDown() override {
  14243. svr_.stop();
  14244. if (thread_.joinable()) thread_.join();
  14245. }
  14246. SSLServer svr_;
  14247. std::thread thread_;
  14248. int port_ = 0;
  14249. };
  14250. TEST_F(SSLOpenStreamTest, Basic) {
  14251. SSLClient cli("127.0.0.1", port_);
  14252. cli.enable_server_certificate_verification(false);
  14253. auto handle = cli.open_stream("GET", "/hello");
  14254. ASSERT_TRUE(handle.is_valid());
  14255. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14256. }
  14257. TEST_F(SSLOpenStreamTest, Chunked) {
  14258. SSLClient cli("127.0.0.1", port_);
  14259. cli.enable_server_certificate_verification(false);
  14260. auto handle = cli.open_stream("GET", "/chunked");
  14261. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14262. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14263. "Transfer-Encoding") == "chunked");
  14264. auto body = read_all(handle);
  14265. EXPECT_EQ("chunkchunkchunk", body);
  14266. }
  14267. TEST_F(SSLOpenStreamTest, Post) {
  14268. SSLClient cli("127.0.0.1", port_);
  14269. cli.enable_server_certificate_verification(false);
  14270. auto handle =
  14271. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14272. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14273. EXPECT_EQ(200, handle.response->status);
  14274. auto body = read_all(handle);
  14275. EXPECT_EQ("Hello SSL POST", body);
  14276. }
  14277. TEST_F(SSLOpenStreamTest, PostChunked) {
  14278. SSLClient cli("127.0.0.1", port_);
  14279. cli.enable_server_certificate_verification(false);
  14280. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14281. "Chunked SSL Data", "text/plain");
  14282. ASSERT_TRUE(handle.is_valid());
  14283. EXPECT_EQ(200, handle.response->status);
  14284. auto body = read_all(handle);
  14285. EXPECT_EQ("Chunked SSL Data", body);
  14286. }
  14287. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14288. // Content-Length is terminated by the server closing the connection. When the
  14289. // SSL peer sends a close_notify after the body, the client must treat it as a
  14290. // clean EOF and return a successful response rather than an error.
  14291. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14292. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14293. ASSERT_TRUE(svr.is_valid());
  14294. svr.set_keep_alive_max_count(1);
  14295. const std::string expected_body = "Hello from connection-close response!";
  14296. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14297. res.set_content_provider("text/plain",
  14298. [&](size_t offset, DataSink &sink) -> bool {
  14299. if (offset < expected_body.size()) {
  14300. sink.write(expected_body.data() + offset,
  14301. expected_body.size() - offset);
  14302. }
  14303. sink.done();
  14304. return true;
  14305. });
  14306. });
  14307. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14308. auto se = detail::scope_exit([&] {
  14309. svr.stop();
  14310. listen_thread.join();
  14311. ASSERT_FALSE(svr.is_running());
  14312. });
  14313. svr.wait_until_ready();
  14314. SSLClient cli(HOST, PORT);
  14315. cli.enable_server_certificate_verification(false);
  14316. auto res = cli.Get("/no-content-length");
  14317. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14318. EXPECT_EQ(StatusCode::OK_200, res->status);
  14319. EXPECT_EQ(expected_body, res->body);
  14320. }
  14321. #endif // CPPHTTPLIB_SSL_ENABLED
  14322. //==============================================================================
  14323. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14324. // results for various scenarios.
  14325. //==============================================================================
  14326. TEST(ParityTest, GetVsOpenStream) {
  14327. Server svr;
  14328. const std::string path = "/parity";
  14329. const std::string content = "Parity test content: hello world";
  14330. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14331. res.set_content(content, "text/plain");
  14332. });
  14333. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14334. auto se = detail::scope_exit([&] {
  14335. svr.stop();
  14336. t.join();
  14337. ASSERT_FALSE(svr.is_running());
  14338. });
  14339. svr.wait_until_ready();
  14340. Client cli(HOST, PORT);
  14341. // Non-stream path
  14342. auto r1 = cli.Get(path);
  14343. ASSERT_TRUE(r1);
  14344. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14345. // Stream path
  14346. auto h = cli.open_stream("GET", path);
  14347. ASSERT_TRUE(h.is_valid());
  14348. EXPECT_EQ(r1->body, read_all(h));
  14349. }
  14350. // Helper to compress data with provided compressor type T
  14351. template <typename Compressor>
  14352. static std::string compress_payload_for_parity(const std::string &in) {
  14353. std::string out;
  14354. Compressor compressor;
  14355. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14356. [&](const char *data, size_t n) {
  14357. out.append(data, n);
  14358. return true;
  14359. });
  14360. EXPECT_TRUE(ok);
  14361. return out;
  14362. }
  14363. // Helper function for compression parity tests
  14364. template <typename Compressor>
  14365. static void test_compression_parity(const std::string &original,
  14366. const std::string &path,
  14367. const std::string &encoding) {
  14368. const std::string compressed =
  14369. compress_payload_for_parity<Compressor>(original);
  14370. Server svr;
  14371. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14372. res.set_content(compressed, "application/octet-stream");
  14373. res.set_header("Content-Encoding", encoding);
  14374. });
  14375. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14376. auto se = detail::scope_exit([&] {
  14377. svr.stop();
  14378. t.join();
  14379. ASSERT_FALSE(svr.is_running());
  14380. });
  14381. svr.wait_until_ready();
  14382. Client cli(HOST, PORT);
  14383. // Non-streaming
  14384. {
  14385. auto res = cli.Get(path);
  14386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14387. EXPECT_EQ(StatusCode::OK_200, res->status);
  14388. EXPECT_EQ(original, res->body);
  14389. }
  14390. // Streaming
  14391. {
  14392. auto h = cli.open_stream("GET", path);
  14393. ASSERT_TRUE(h.is_valid());
  14394. EXPECT_EQ(original, read_all(h));
  14395. }
  14396. }
  14397. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14398. TEST(ParityTest, Gzip) {
  14399. test_compression_parity<detail::gzip_compressor>(
  14400. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14401. }
  14402. #endif
  14403. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14404. TEST(ParityTest, Brotli) {
  14405. test_compression_parity<detail::brotli_compressor>(
  14406. "Hello, brotli parity test payload", "/parity-br", "br");
  14407. }
  14408. #endif
  14409. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14410. TEST(ParityTest, Zstd) {
  14411. test_compression_parity<detail::zstd_compressor>(
  14412. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14413. }
  14414. #endif
  14415. //==============================================================================
  14416. // New Stream API Tests
  14417. //==============================================================================
  14418. inline std::string read_body(httplib::stream::Result &result) {
  14419. std::string body;
  14420. while (result.next()) {
  14421. body.append(result.data(), result.size());
  14422. }
  14423. return body;
  14424. }
  14425. TEST(ClientConnectionTest, Basic) {
  14426. httplib::ClientConnection conn;
  14427. EXPECT_FALSE(conn.is_open());
  14428. conn.sock = 1;
  14429. EXPECT_TRUE(conn.is_open());
  14430. httplib::ClientConnection conn2(std::move(conn));
  14431. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14432. conn2.sock = INVALID_SOCKET;
  14433. }
  14434. // Unified test server for all stream::* tests
  14435. class StreamApiTest : public ::testing::Test {
  14436. protected:
  14437. void SetUp() override {
  14438. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14439. res.set_content("Hello World!", "text/plain");
  14440. });
  14441. svr_.Get("/echo-params",
  14442. [](const httplib::Request &req, httplib::Response &res) {
  14443. std::string r;
  14444. for (const auto &p : req.params) {
  14445. if (!r.empty()) r += "&";
  14446. r += p.first + "=" + p.second;
  14447. }
  14448. res.set_content(r, "text/plain");
  14449. });
  14450. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14451. res.set_content(req.body, req.get_header_value("Content-Type"));
  14452. });
  14453. svr_.Post("/echo-headers",
  14454. [](const httplib::Request &req, httplib::Response &res) {
  14455. std::string r;
  14456. for (const auto &h : req.headers)
  14457. r += h.first + ": " + h.second + "\n";
  14458. res.set_content(r, "text/plain");
  14459. });
  14460. svr_.Post("/echo-params",
  14461. [](const httplib::Request &req, httplib::Response &res) {
  14462. std::string r = "params:";
  14463. for (const auto &p : req.params)
  14464. r += p.first + "=" + p.second + ";";
  14465. res.set_content(r + " body:" + req.body, "text/plain");
  14466. });
  14467. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14468. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14469. });
  14470. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14471. res.set_content("PUT:" + req.body, "text/plain");
  14472. });
  14473. svr_.Patch("/echo",
  14474. [](const httplib::Request &req, httplib::Response &res) {
  14475. res.set_content("PATCH:" + req.body, "text/plain");
  14476. });
  14477. svr_.Delete(
  14478. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14479. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14480. "text/plain");
  14481. });
  14482. svr_.Get("/head-test",
  14483. [](const httplib::Request &, httplib::Response &res) {
  14484. res.set_content("body for HEAD", "text/plain");
  14485. });
  14486. svr_.Options("/options",
  14487. [](const httplib::Request &, httplib::Response &res) {
  14488. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14489. });
  14490. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14491. svr_.wait_until_ready();
  14492. }
  14493. void TearDown() override {
  14494. svr_.stop();
  14495. if (thread_.joinable()) thread_.join();
  14496. }
  14497. httplib::Server svr_;
  14498. std::thread thread_;
  14499. };
  14500. // stream::Get tests
  14501. TEST_F(StreamApiTest, GetBasic) {
  14502. httplib::Client cli(HOST, PORT);
  14503. auto result = httplib::stream::Get(cli, "/hello");
  14504. ASSERT_TRUE(result.is_valid());
  14505. EXPECT_EQ(200, result.status());
  14506. EXPECT_EQ("Hello World!", read_body(result));
  14507. }
  14508. TEST_F(StreamApiTest, GetWithParams) {
  14509. httplib::Client cli(HOST, PORT);
  14510. httplib::Params params{{"foo", "bar"}};
  14511. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14512. ASSERT_TRUE(result.is_valid());
  14513. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14514. }
  14515. TEST_F(StreamApiTest, GetConnectionError) {
  14516. httplib::Client cli(HOST, 9999);
  14517. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14518. }
  14519. TEST_F(StreamApiTest, Get404) {
  14520. httplib::Client cli(HOST, PORT);
  14521. auto result = httplib::stream::Get(cli, "/nonexistent");
  14522. EXPECT_TRUE(result.is_valid());
  14523. EXPECT_EQ(404, result.status());
  14524. }
  14525. // stream::Post tests
  14526. TEST_F(StreamApiTest, PostBasic) {
  14527. httplib::Client cli(HOST, PORT);
  14528. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14529. "application/json");
  14530. ASSERT_TRUE(result.is_valid());
  14531. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14532. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14533. }
  14534. TEST_F(StreamApiTest, PostWithHeaders) {
  14535. httplib::Client cli(HOST, PORT);
  14536. httplib::Headers headers{{"X-Custom", "value"}};
  14537. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14538. "text/plain");
  14539. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14540. }
  14541. TEST_F(StreamApiTest, PostWithParams) {
  14542. httplib::Client cli(HOST, PORT);
  14543. httplib::Params params{{"k", "v"}};
  14544. auto result =
  14545. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14546. auto body = read_body(result);
  14547. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14548. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14549. }
  14550. TEST_F(StreamApiTest, PostLarge) {
  14551. httplib::Client cli(HOST, PORT);
  14552. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14553. size_t total = 0;
  14554. while (result.next()) {
  14555. total += result.size();
  14556. }
  14557. EXPECT_EQ(100u * 1024u, total);
  14558. }
  14559. // stream::Put/Patch tests
  14560. TEST_F(StreamApiTest, PutAndPatch) {
  14561. httplib::Client cli(HOST, PORT);
  14562. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14563. EXPECT_EQ("PUT:test", read_body(put));
  14564. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14565. EXPECT_EQ("PATCH:test", read_body(patch));
  14566. }
  14567. // stream::Delete tests
  14568. TEST_F(StreamApiTest, Delete) {
  14569. httplib::Client cli(HOST, PORT);
  14570. auto del1 = httplib::stream::Delete(cli, "/resource");
  14571. EXPECT_EQ("Deleted", read_body(del1));
  14572. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14573. EXPECT_EQ("Deleted:data", read_body(del2));
  14574. }
  14575. // stream::Head/Options tests
  14576. TEST_F(StreamApiTest, HeadAndOptions) {
  14577. httplib::Client cli(HOST, PORT);
  14578. auto head = httplib::stream::Head(cli, "/head-test");
  14579. EXPECT_TRUE(head.is_valid());
  14580. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14581. auto opts = httplib::stream::Options(cli, "/options");
  14582. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14583. }
  14584. // SSL stream::* tests
  14585. #ifdef CPPHTTPLIB_SSL_ENABLED
  14586. class SSLStreamApiTest : public ::testing::Test {
  14587. protected:
  14588. void SetUp() override {
  14589. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14590. res.set_content("Hello SSL!", "text/plain");
  14591. });
  14592. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14593. res.set_content(req.body, "text/plain");
  14594. });
  14595. port_ = svr_.bind_to_any_port("127.0.0.1");
  14596. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14597. svr_.wait_until_ready();
  14598. }
  14599. void TearDown() override {
  14600. svr_.stop();
  14601. if (thread_.joinable()) thread_.join();
  14602. }
  14603. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14604. std::thread thread_;
  14605. int port_ = 0;
  14606. };
  14607. TEST_F(SSLStreamApiTest, GetAndPost) {
  14608. httplib::SSLClient cli("127.0.0.1", port_);
  14609. cli.enable_server_certificate_verification(false);
  14610. auto get = httplib::stream::Get(cli, "/hello");
  14611. EXPECT_EQ("Hello SSL!", read_body(get));
  14612. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14613. EXPECT_EQ("test", read_body(post));
  14614. }
  14615. #endif
  14616. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14617. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14618. // BodyReader
  14619. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14620. // Test that read timeout during streaming is detected
  14621. // Use a large content-length response where server delays mid-stream
  14622. Server svr;
  14623. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14624. // Send a large response with delay in the middle
  14625. res.set_content_provider(
  14626. 1000, // content_length
  14627. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14628. if (offset < 100) {
  14629. // Send first 100 bytes immediately
  14630. std::string data(100, 'A');
  14631. sink.write(data.c_str(), data.size());
  14632. return true;
  14633. }
  14634. // Then delay longer than client timeout
  14635. std::this_thread::sleep_for(std::chrono::seconds(3));
  14636. std::string data(900, 'B');
  14637. sink.write(data.c_str(), data.size());
  14638. return true;
  14639. });
  14640. });
  14641. auto port = 8091;
  14642. std::thread t([&]() { svr.listen("localhost", port); });
  14643. svr.wait_until_ready();
  14644. Client cli("localhost", port);
  14645. cli.set_read_timeout(1, 0); // 1 second timeout
  14646. auto handle = cli.open_stream("GET", "/slow-stream");
  14647. ASSERT_TRUE(handle.is_valid());
  14648. char buf[256];
  14649. ssize_t total = 0;
  14650. ssize_t n;
  14651. bool got_error = false;
  14652. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14653. total += n;
  14654. }
  14655. if (n < 0) {
  14656. got_error = true;
  14657. // Should be timeout or read error
  14658. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14659. handle.get_read_error() == Error::Read)
  14660. << "Actual error: " << to_string(handle.get_read_error());
  14661. }
  14662. // Either we got an error, or we got less data than expected
  14663. EXPECT_TRUE(got_error || total < 1000)
  14664. << "Expected timeout but got all " << total << " bytes";
  14665. svr.stop();
  14666. t.join();
  14667. }
  14668. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14669. // Test connection closed detection via BodyReader
  14670. Server svr;
  14671. std::atomic<bool> close_now{false};
  14672. svr.Get("/will-close", [&](const Request &, Response &res) {
  14673. res.set_content_provider(
  14674. 10000, // Large content_length that we won't fully send
  14675. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14676. if (offset < 100) {
  14677. std::string data(100, 'X');
  14678. sink.write(data.c_str(), data.size());
  14679. return true;
  14680. }
  14681. // Wait for signal then abort
  14682. while (!close_now) {
  14683. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14684. }
  14685. return false; // Abort - server will close connection
  14686. });
  14687. });
  14688. auto port = 8092;
  14689. std::thread t([&]() { svr.listen("localhost", port); });
  14690. svr.wait_until_ready();
  14691. Client cli("localhost", port);
  14692. auto handle = cli.open_stream("GET", "/will-close");
  14693. ASSERT_TRUE(handle.is_valid());
  14694. char buf[256];
  14695. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14696. EXPECT_GT(n, 0) << "First read should succeed";
  14697. // Signal server to close
  14698. close_now = true;
  14699. // Keep reading until error or EOF
  14700. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14701. // Keep reading
  14702. }
  14703. // Should get an error since content_length wasn't satisfied
  14704. if (n < 0) {
  14705. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14706. handle.get_read_error() == Error::Read)
  14707. << "Actual error: " << to_string(handle.get_read_error());
  14708. }
  14709. svr.stop();
  14710. t.join();
  14711. }
  14712. #ifdef CPPHTTPLIB_SSL_ENABLED
  14713. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14714. // Test that read timeout during SSL streaming is detected
  14715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14716. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14717. res.set_content_provider(
  14718. 1000, "text/plain",
  14719. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14720. if (offset < 100) {
  14721. std::string data(100, 'A');
  14722. sink.write(data.c_str(), data.size());
  14723. return true;
  14724. }
  14725. std::this_thread::sleep_for(std::chrono::seconds(3));
  14726. std::string data(900, 'B');
  14727. sink.write(data.c_str(), data.size());
  14728. return true;
  14729. });
  14730. });
  14731. auto port = 8093;
  14732. std::thread t([&]() { svr.listen("localhost", port); });
  14733. svr.wait_until_ready();
  14734. SSLClient cli("localhost", port);
  14735. cli.enable_server_certificate_verification(false);
  14736. cli.set_read_timeout(1, 0); // 1 second timeout
  14737. auto handle = cli.open_stream("GET", "/slow-stream");
  14738. ASSERT_TRUE(handle.is_valid());
  14739. char buf[256];
  14740. ssize_t total = 0;
  14741. ssize_t n;
  14742. bool got_error = false;
  14743. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14744. total += n;
  14745. }
  14746. if (n < 0) {
  14747. got_error = true;
  14748. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14749. handle.get_read_error() == Error::Read)
  14750. << "Actual error: " << to_string(handle.get_read_error());
  14751. }
  14752. EXPECT_TRUE(got_error || total < 1000)
  14753. << "Expected timeout but got all " << total << " bytes";
  14754. svr.stop();
  14755. t.join();
  14756. }
  14757. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14758. // Test SSL connection closed detection
  14759. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14760. std::atomic<bool> close_now{false};
  14761. svr.Get("/will-close", [&](const Request &, Response &res) {
  14762. res.set_content_provider(
  14763. 10000, "text/plain",
  14764. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14765. if (offset < 100) {
  14766. std::string data(100, 'X');
  14767. sink.write(data.c_str(), data.size());
  14768. return true;
  14769. }
  14770. while (!close_now) {
  14771. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14772. }
  14773. return false;
  14774. });
  14775. });
  14776. auto port = 8094;
  14777. std::thread t([&]() { svr.listen("localhost", port); });
  14778. svr.wait_until_ready();
  14779. SSLClient cli("localhost", port);
  14780. cli.enable_server_certificate_verification(false);
  14781. auto handle = cli.open_stream("GET", "/will-close");
  14782. ASSERT_TRUE(handle.is_valid());
  14783. char buf[256];
  14784. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14785. EXPECT_GT(n, 0);
  14786. // Signal server to close
  14787. close_now = true;
  14788. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14789. // Keep reading
  14790. }
  14791. if (n < 0) {
  14792. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14793. handle.get_read_error() == Error::Read)
  14794. << "Actual error: " << to_string(handle.get_read_error());
  14795. }
  14796. svr.stop();
  14797. t.join();
  14798. }
  14799. #endif
  14800. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14801. using namespace httplib;
  14802. // Create a test file
  14803. const char *fname = "etag_testfile.txt";
  14804. const char *content = "etag-content";
  14805. {
  14806. std::ofstream ofs(fname);
  14807. ofs << content;
  14808. ASSERT_TRUE(ofs.good());
  14809. }
  14810. Server svr;
  14811. svr.set_mount_point("/static", ".");
  14812. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14813. svr.wait_until_ready();
  14814. Client cli(HOST, PORT);
  14815. // First request: should get 200 with ETag header
  14816. auto res1 = cli.Get("/static/etag_testfile.txt");
  14817. ASSERT_TRUE(res1);
  14818. ASSERT_EQ(200, res1->status);
  14819. ASSERT_TRUE(res1->has_header("ETag"));
  14820. std::string etag = res1->get_header_value("ETag");
  14821. EXPECT_FALSE(etag.empty());
  14822. // Verify ETag format: W/"hex-hex"
  14823. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14824. EXPECT_EQ('W', etag[0]);
  14825. EXPECT_EQ('/', etag[1]);
  14826. EXPECT_EQ('"', etag[2]);
  14827. EXPECT_EQ('"', etag.back());
  14828. // Exact match: expect 304 Not Modified
  14829. Headers h2 = {{"If-None-Match", etag}};
  14830. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14831. ASSERT_TRUE(res2);
  14832. EXPECT_EQ(304, res2->status);
  14833. // Wildcard match: expect 304 Not Modified
  14834. Headers h3 = {{"If-None-Match", "*"}};
  14835. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14836. ASSERT_TRUE(res3);
  14837. EXPECT_EQ(304, res3->status);
  14838. // Non-matching ETag: expect 200
  14839. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14840. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14841. ASSERT_TRUE(res4);
  14842. EXPECT_EQ(200, res4->status);
  14843. // Multiple ETags with one matching: expect 304
  14844. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14845. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14846. ASSERT_TRUE(res5);
  14847. EXPECT_EQ(304, res5->status);
  14848. svr.stop();
  14849. t.join();
  14850. std::remove(fname);
  14851. }
  14852. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14853. using namespace httplib;
  14854. Server svr;
  14855. svr.set_mount_point("/static", ".");
  14856. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14857. svr.wait_until_ready();
  14858. Client cli(HOST, PORT);
  14859. // Send If-None-Match: * to a non-existent file
  14860. Headers h = {{"If-None-Match", "*"}};
  14861. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14863. EXPECT_EQ(404, res->status);
  14864. svr.stop();
  14865. t.join();
  14866. }
  14867. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14868. using namespace httplib;
  14869. // Create a test file
  14870. const char *fname = "etag_boundary_testfile.txt";
  14871. const char *content = "boundary-test";
  14872. {
  14873. std::ofstream ofs(fname);
  14874. ofs << content;
  14875. ASSERT_TRUE(ofs.good());
  14876. }
  14877. Server svr;
  14878. svr.set_mount_point("/static", ".");
  14879. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14880. svr.wait_until_ready();
  14881. Client cli(HOST, PORT);
  14882. // Get the actual ETag
  14883. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14884. ASSERT_TRUE(res1);
  14885. ASSERT_EQ(200, res1->status);
  14886. ASSERT_TRUE(res1->has_header("ETag"));
  14887. std::string etag = res1->get_header_value("ETag");
  14888. // Test 1: Very long ETag value (longer than actual ETag)
  14889. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14890. Headers h1 = {{"If-None-Match", "W/"
  14891. "\"very-long-etag-value-that-is-much-longer-"
  14892. "than-the-actual-etag-value\""}};
  14893. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14894. ASSERT_TRUE(res2);
  14895. EXPECT_EQ(200, res2->status); // Should not match
  14896. // Test 2: Long string followed by wildcard
  14897. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14898. // string)
  14899. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14900. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14901. ASSERT_TRUE(res3);
  14902. EXPECT_EQ(304, res3->status); // Should match on "*"
  14903. // Test 3: Wildcard followed by long string
  14904. // Should match on "*" immediately and return 304
  14905. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14906. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14907. ASSERT_TRUE(res4);
  14908. EXPECT_EQ(304, res4->status); // Should match on "*"
  14909. // Test 4: Multiple long non-matching values
  14910. // Should NOT match and return 200 (test that all comparisons are safe)
  14911. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14912. "W/\"second-long-non-matching-value\", "
  14913. "W/\"third-long-non-matching-value\""}};
  14914. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14915. ASSERT_TRUE(res5);
  14916. EXPECT_EQ(200, res5->status); // Should not match
  14917. // Test 5: Single character that is not "*" (edge case)
  14918. Headers h5 = {{"If-None-Match", "X"}};
  14919. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14920. ASSERT_TRUE(res6);
  14921. EXPECT_EQ(200, res6->status); // Should not match
  14922. svr.stop();
  14923. t.join();
  14924. std::remove(fname);
  14925. }
  14926. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14927. using namespace httplib;
  14928. // Create a test file
  14929. const char *fname = "ims_testfile.txt";
  14930. const char *content = "if-modified-since-test";
  14931. {
  14932. std::ofstream ofs(fname);
  14933. ofs << content;
  14934. ASSERT_TRUE(ofs.good());
  14935. }
  14936. Server svr;
  14937. svr.set_mount_point("/static", ".");
  14938. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14939. svr.wait_until_ready();
  14940. Client cli(HOST, PORT);
  14941. // First request: should get 200 with Last-Modified header
  14942. auto res1 = cli.Get("/static/ims_testfile.txt");
  14943. ASSERT_TRUE(res1);
  14944. ASSERT_EQ(200, res1->status);
  14945. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14946. std::string last_modified = res1->get_header_value("Last-Modified");
  14947. EXPECT_FALSE(last_modified.empty());
  14948. // If-Modified-Since with same time: expect 304
  14949. Headers h2 = {{"If-Modified-Since", last_modified}};
  14950. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14951. ASSERT_TRUE(res2);
  14952. EXPECT_EQ(304, res2->status);
  14953. // If-Modified-Since with future time: expect 304
  14954. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14955. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14956. ASSERT_TRUE(res3);
  14957. EXPECT_EQ(304, res3->status);
  14958. // If-Modified-Since with past time: expect 200
  14959. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14960. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14961. ASSERT_TRUE(res4);
  14962. EXPECT_EQ(200, res4->status);
  14963. // If-None-Match takes precedence over If-Modified-Since
  14964. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14965. ASSERT_TRUE(res1->has_header("ETag"));
  14966. std::string etag = res1->get_header_value("ETag");
  14967. Headers h5 = {{"If-None-Match", etag},
  14968. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14969. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14970. ASSERT_TRUE(res5);
  14971. EXPECT_EQ(304, res5->status);
  14972. svr.stop();
  14973. t.join();
  14974. std::remove(fname);
  14975. }
  14976. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14977. using namespace httplib;
  14978. Server svr;
  14979. // Endpoint that returns compressible content
  14980. svr.Get("/compressible", [](const Request &, Response &res) {
  14981. // Return a large enough body to trigger compression
  14982. std::string body(1000, 'a');
  14983. res.set_content(body, "text/plain");
  14984. });
  14985. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14986. svr.wait_until_ready();
  14987. Client cli(HOST, PORT);
  14988. // Request with gzip support: should get Vary header when compressed
  14989. cli.set_compress(true);
  14990. auto res1 = cli.Get("/compressible");
  14991. ASSERT_TRUE(res1);
  14992. EXPECT_EQ(200, res1->status);
  14993. // If Content-Encoding is set, Vary should also be set
  14994. if (res1->has_header("Content-Encoding")) {
  14995. EXPECT_TRUE(res1->has_header("Vary"));
  14996. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14997. }
  14998. // Request without Accept-Encoding header: should not have compression
  14999. Headers h_no_compress;
  15000. auto res2 = cli.Get("/compressible", h_no_compress);
  15001. ASSERT_TRUE(res2);
  15002. EXPECT_EQ(200, res2->status);
  15003. // Verify Vary header is present when compression is applied
  15004. // (the exact behavior depends on server configuration)
  15005. svr.stop();
  15006. t.join();
  15007. }
  15008. TEST(ETagTest, IfRangeWithETag) {
  15009. using namespace httplib;
  15010. // Create a test file with known content
  15011. const char *fname = "if_range_testfile.txt";
  15012. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15013. {
  15014. std::ofstream ofs(fname);
  15015. ofs << content;
  15016. ASSERT_TRUE(ofs.good());
  15017. }
  15018. Server svr;
  15019. svr.set_mount_point("/static", ".");
  15020. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15021. svr.wait_until_ready();
  15022. Client cli(HOST, PORT);
  15023. // First request: get ETag
  15024. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15025. ASSERT_TRUE(res1);
  15026. ASSERT_EQ(200, res1->status);
  15027. ASSERT_TRUE(res1->has_header("ETag"));
  15028. std::string etag = res1->get_header_value("ETag");
  15029. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15030. // Since our server generates weak ETags (W/"..."), If-Range with our
  15031. // ETag should NOT result in partial content - it should return full content.
  15032. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15033. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15034. ASSERT_TRUE(res2);
  15035. // Weak ETag in If-Range -> full content (200), not partial (206)
  15036. EXPECT_EQ(200, res2->status);
  15037. EXPECT_EQ(content, res2->body);
  15038. EXPECT_FALSE(res2->has_header("Content-Range"));
  15039. // Range request with non-matching If-Range (ETag): should get 200 (full
  15040. // content)
  15041. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15042. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15043. ASSERT_TRUE(res3);
  15044. EXPECT_EQ(200, res3->status);
  15045. EXPECT_EQ(content, res3->body);
  15046. EXPECT_FALSE(res3->has_header("Content-Range"));
  15047. // Range request with strong ETag (hypothetical - our server doesn't generate
  15048. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15049. // should return full content)
  15050. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15051. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15052. ASSERT_TRUE(res4);
  15053. EXPECT_EQ(200, res4->status);
  15054. EXPECT_EQ(content, res4->body);
  15055. EXPECT_FALSE(res4->has_header("Content-Range"));
  15056. svr.stop();
  15057. t.join();
  15058. std::remove(fname);
  15059. }
  15060. TEST(ETagTest, IfRangeWithDate) {
  15061. using namespace httplib;
  15062. // Create a test file
  15063. const char *fname = "if_range_date_testfile.txt";
  15064. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15065. {
  15066. std::ofstream ofs(fname);
  15067. ofs << content;
  15068. ASSERT_TRUE(ofs.good());
  15069. }
  15070. Server svr;
  15071. svr.set_mount_point("/static", ".");
  15072. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15073. svr.wait_until_ready();
  15074. Client cli(HOST, PORT);
  15075. // First request: get Last-Modified
  15076. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15077. ASSERT_TRUE(res1);
  15078. ASSERT_EQ(200, res1->status);
  15079. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15080. std::string last_modified = res1->get_header_value("Last-Modified");
  15081. // Range request with matching If-Range (date): should get 206
  15082. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15083. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15084. ASSERT_TRUE(res2);
  15085. EXPECT_EQ(206, res2->status);
  15086. EXPECT_EQ("FGHIJ", res2->body);
  15087. // Range request with old If-Range date: should get 200 (full content)
  15088. Headers h3 = {{"Range", "bytes=5-9"},
  15089. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15090. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15091. ASSERT_TRUE(res3);
  15092. EXPECT_EQ(200, res3->status);
  15093. EXPECT_EQ(content, res3->body);
  15094. // Range request with future If-Range date: should get 206
  15095. Headers h4 = {{"Range", "bytes=0-4"},
  15096. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15097. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15098. ASSERT_TRUE(res4);
  15099. EXPECT_EQ(206, res4->status);
  15100. EXPECT_EQ("ABCDE", res4->body);
  15101. svr.stop();
  15102. t.join();
  15103. std::remove(fname);
  15104. }
  15105. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15106. using namespace httplib;
  15107. const char *fname = "etag_malformed.txt";
  15108. const char *content = "malformed-etag";
  15109. {
  15110. std::ofstream ofs(fname);
  15111. ofs << content;
  15112. ASSERT_TRUE(ofs.good());
  15113. }
  15114. Server svr;
  15115. svr.set_mount_point("/static", ".");
  15116. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15117. svr.wait_until_ready();
  15118. Client cli(HOST, PORT);
  15119. // baseline: should get 200 and an ETag
  15120. auto res1 = cli.Get("/static/etag_malformed.txt");
  15121. ASSERT_TRUE(res1);
  15122. ASSERT_EQ(200, res1->status);
  15123. ASSERT_TRUE(res1->has_header("ETag"));
  15124. // Malformed ETag value (missing quotes) should be treated as non-matching
  15125. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15126. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15127. ASSERT_TRUE(res_bad);
  15128. EXPECT_EQ(200, res_bad->status);
  15129. // Whitespace-only header value should be considered invalid / non-matching
  15130. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15131. "Host: localhost\r\n"
  15132. "If-None-Match: \r\n"
  15133. "Connection: close\r\n"
  15134. "\r\n";
  15135. std::string out;
  15136. ASSERT_TRUE(send_request(5, raw_req, &out));
  15137. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15138. svr.stop();
  15139. t.join();
  15140. std::remove(fname);
  15141. }
  15142. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15143. using namespace httplib;
  15144. const char *fname = "ims_invalid_format.txt";
  15145. const char *content = "ims-bad-format";
  15146. {
  15147. std::ofstream ofs(fname);
  15148. ofs << content;
  15149. ASSERT_TRUE(ofs.good());
  15150. }
  15151. Server svr;
  15152. svr.set_mount_point("/static", ".");
  15153. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15154. svr.wait_until_ready();
  15155. Client cli(HOST, PORT);
  15156. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15157. ASSERT_TRUE(res1);
  15158. ASSERT_EQ(200, res1->status);
  15159. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15160. // If-Modified-Since with invalid format should not result in 304
  15161. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15162. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15163. ASSERT_TRUE(res_bad);
  15164. EXPECT_EQ(200, res_bad->status);
  15165. // If-Range with invalid date format should be treated as mismatch -> full
  15166. // content (200)
  15167. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15168. {"If-Range", "invalid-date"}};
  15169. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15170. ASSERT_TRUE(res_ifrange);
  15171. EXPECT_EQ(200, res_ifrange->status);
  15172. svr.stop();
  15173. t.join();
  15174. std::remove(fname);
  15175. }
  15176. TEST(ETagTest, IfRangeWithMalformedETag) {
  15177. using namespace httplib;
  15178. const char *fname = "ifrange_malformed.txt";
  15179. const std::string content = "0123456789";
  15180. {
  15181. std::ofstream ofs(fname);
  15182. ofs << content;
  15183. ASSERT_TRUE(ofs.good());
  15184. }
  15185. Server svr;
  15186. svr.set_mount_point("/static", ".");
  15187. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15188. svr.wait_until_ready();
  15189. Client cli(HOST, PORT);
  15190. // First request: get ETag
  15191. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15192. ASSERT_TRUE(res1);
  15193. ASSERT_EQ(200, res1->status);
  15194. ASSERT_TRUE(res1->has_header("ETag"));
  15195. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15196. // full content (200)
  15197. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15198. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15199. ASSERT_TRUE(res2);
  15200. EXPECT_EQ(200, res2->status);
  15201. EXPECT_EQ(content, res2->body);
  15202. svr.stop();
  15203. t.join();
  15204. std::remove(fname);
  15205. }
  15206. TEST(ETagTest, ExtremeLargeDateValues) {
  15207. using namespace httplib;
  15208. const char *fname = "ims_extreme_date.txt";
  15209. const char *content = "ims-extreme-date";
  15210. {
  15211. std::ofstream ofs(fname);
  15212. ofs << content;
  15213. ASSERT_TRUE(ofs.good());
  15214. }
  15215. Server svr;
  15216. svr.set_mount_point("/static", ".");
  15217. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15218. svr.wait_until_ready();
  15219. Client cli(HOST, PORT);
  15220. auto res1 = cli.Get(std::string("/static/") + fname);
  15221. ASSERT_TRUE(res1);
  15222. ASSERT_EQ(200, res1->status);
  15223. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15224. // Extremely large year that may overflow date parsing routines.
  15225. Headers h_large_date = {
  15226. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15227. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15228. ASSERT_TRUE(res_bad);
  15229. // Expect server to treat this as invalid/mismatch and return full content
  15230. EXPECT_EQ(200, res_bad->status);
  15231. // If-Range with extremely large date should be treated as mismatch -> full
  15232. // content (200)
  15233. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15234. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15235. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15236. ASSERT_TRUE(res_ifrange);
  15237. EXPECT_EQ(200, res_ifrange->status);
  15238. svr.stop();
  15239. t.join();
  15240. std::remove(fname);
  15241. }
  15242. TEST(ETagTest, NegativeFileModificationTime) {
  15243. using namespace httplib;
  15244. const char *fname = "ims_negative_mtime.txt";
  15245. const std::string content = "negative-mtime";
  15246. {
  15247. std::ofstream ofs(fname);
  15248. ofs << content;
  15249. ASSERT_TRUE(ofs.good());
  15250. }
  15251. // Try to set file mtime to a negative value. This may fail on some
  15252. // platforms/filesystems; if it fails, the test will still verify server
  15253. // behaves safely by performing a regular conditional request.
  15254. #if defined(__APPLE__) || defined(__linux__)
  15255. bool set_negative = false;
  15256. do {
  15257. struct timeval times[2];
  15258. // access time: now
  15259. times[0].tv_sec = time(nullptr);
  15260. times[0].tv_usec = 0;
  15261. // modification time: negative (e.g., -1)
  15262. times[1].tv_sec = -1;
  15263. times[1].tv_usec = 0;
  15264. if (utimes(fname, times) == 0) { set_negative = true; }
  15265. } while (0);
  15266. #else
  15267. bool set_negative = false;
  15268. #endif
  15269. Server svr;
  15270. svr.set_mount_point("/static", ".");
  15271. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15272. svr.wait_until_ready();
  15273. Client cli(HOST, PORT);
  15274. auto res1 = cli.Get(std::string("/static/") + fname);
  15275. ASSERT_TRUE(res1);
  15276. ASSERT_EQ(200, res1->status);
  15277. bool has_last_modified = res1->has_header("Last-Modified");
  15278. std::string last_modified;
  15279. if (has_last_modified) {
  15280. last_modified = res1->get_header_value("Last-Modified");
  15281. }
  15282. if (set_negative) {
  15283. // If we successfully set a negative mtime, ensure server returns a
  15284. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15285. // with an old date and ensure server handles it without crash.
  15286. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15287. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15288. ASSERT_TRUE(res2);
  15289. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15290. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15291. } else {
  15292. // Could not set negative mtime on this platform; fall back to verifying
  15293. // that normal invalid/malformed dates are treated safely (non-304).
  15294. Headers h_bad_date = {
  15295. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15296. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15297. ASSERT_TRUE(res_bad);
  15298. EXPECT_EQ(200, res_bad->status);
  15299. }
  15300. svr.stop();
  15301. t.join();
  15302. std::remove(fname);
  15303. }
  15304. //==============================================================================
  15305. // SSE Parsing Tests
  15306. //==============================================================================
  15307. class SSEParsingTest : public ::testing::Test {
  15308. protected:
  15309. // Test helper that mimics SSE parsing behavior
  15310. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15311. int &retry_ms) {
  15312. // Blank line signals end of event
  15313. if (line.empty() || line == "\r") { return true; }
  15314. // Lines starting with ':' are comments (ignored)
  15315. if (!line.empty() && line[0] == ':') { return false; }
  15316. // Find the colon separator
  15317. auto colon_pos = line.find(':');
  15318. if (colon_pos == std::string::npos) {
  15319. // Line with no colon is treated as field name with empty value
  15320. return false;
  15321. }
  15322. std::string field = line.substr(0, colon_pos);
  15323. std::string value;
  15324. // Value starts after colon, skip optional single space
  15325. if (colon_pos + 1 < line.size()) {
  15326. size_t value_start = colon_pos + 1;
  15327. if (line[value_start] == ' ') { value_start++; }
  15328. value = line.substr(value_start);
  15329. // Remove trailing \r if present
  15330. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15331. }
  15332. // Handle known fields
  15333. if (field == "event") {
  15334. msg.event = value;
  15335. } else if (field == "data") {
  15336. // Multiple data lines are concatenated with newlines
  15337. if (!msg.data.empty()) { msg.data += "\n"; }
  15338. msg.data += value;
  15339. } else if (field == "id") {
  15340. // Empty id is valid (clears the last event ID)
  15341. msg.id = value;
  15342. } else if (field == "retry") {
  15343. // Parse retry interval in milliseconds
  15344. {
  15345. int v = 0;
  15346. auto res =
  15347. detail::from_chars(value.data(), value.data() + value.size(), v);
  15348. if (res.ec == std::errc{}) { retry_ms = v; }
  15349. }
  15350. }
  15351. // Unknown fields are ignored per SSE spec
  15352. return false;
  15353. }
  15354. };
  15355. // Test: Single-line data
  15356. TEST_F(SSEParsingTest, SingleLineData) {
  15357. sse::SSEMessage msg;
  15358. int retry_ms = 3000;
  15359. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15360. EXPECT_EQ(msg.data, "hello");
  15361. EXPECT_EQ(msg.event, "message");
  15362. // Blank line ends event
  15363. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15364. }
  15365. // Test: Multi-line data
  15366. TEST_F(SSEParsingTest, MultiLineData) {
  15367. sse::SSEMessage msg;
  15368. int retry_ms = 3000;
  15369. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15370. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15371. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15372. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15373. }
  15374. // Test: Custom event types
  15375. TEST_F(SSEParsingTest, CustomEventType) {
  15376. sse::SSEMessage msg;
  15377. int retry_ms = 3000;
  15378. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15379. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15380. EXPECT_EQ(msg.event, "update");
  15381. EXPECT_EQ(msg.data, "payload");
  15382. }
  15383. // Test: Event ID handling
  15384. TEST_F(SSEParsingTest, EventIdHandling) {
  15385. sse::SSEMessage msg;
  15386. int retry_ms = 3000;
  15387. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15388. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15389. EXPECT_EQ(msg.id, "12345");
  15390. }
  15391. // Test: Empty event ID (clears last event ID)
  15392. TEST_F(SSEParsingTest, EmptyEventId) {
  15393. sse::SSEMessage msg;
  15394. msg.id = "previous";
  15395. int retry_ms = 3000;
  15396. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15397. EXPECT_EQ(msg.id, "");
  15398. }
  15399. // Test: Retry field parsing
  15400. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15401. sse::SSEMessage msg;
  15402. int retry_ms = 3000;
  15403. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15404. EXPECT_EQ(retry_ms, 5000);
  15405. }
  15406. // Test: Invalid retry value
  15407. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15408. sse::SSEMessage msg;
  15409. int retry_ms = 3000;
  15410. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15411. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15412. }
  15413. // Test: Comments (lines starting with :)
  15414. TEST_F(SSEParsingTest, CommentsIgnored) {
  15415. sse::SSEMessage msg;
  15416. int retry_ms = 3000;
  15417. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15418. EXPECT_EQ(msg.data, "");
  15419. EXPECT_EQ(msg.event, "message");
  15420. }
  15421. // Test: Colon in value
  15422. TEST_F(SSEParsingTest, ColonInValue) {
  15423. sse::SSEMessage msg;
  15424. int retry_ms = 3000;
  15425. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15426. EXPECT_EQ(msg.data, "hello:world:test");
  15427. }
  15428. // Test: Line with no colon (field name only)
  15429. TEST_F(SSEParsingTest, FieldNameOnly) {
  15430. sse::SSEMessage msg;
  15431. int retry_ms = 3000;
  15432. // According to SSE spec, this is treated as field name with empty value
  15433. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15434. // Since we don't recognize "data" without colon, data should be empty
  15435. EXPECT_EQ(msg.data, "");
  15436. }
  15437. // Test: Trailing \r handling
  15438. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15439. sse::SSEMessage msg;
  15440. int retry_ms = 3000;
  15441. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15442. EXPECT_EQ(msg.data, "hello");
  15443. }
  15444. // Test: Unknown fields ignored
  15445. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15446. sse::SSEMessage msg;
  15447. int retry_ms = 3000;
  15448. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15449. EXPECT_EQ(msg.data, "");
  15450. EXPECT_EQ(msg.event, "message");
  15451. }
  15452. // Test: Space after colon is optional
  15453. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15454. sse::SSEMessage msg1, msg2;
  15455. int retry_ms = 3000;
  15456. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15457. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15458. EXPECT_EQ(msg1.data, "hello");
  15459. EXPECT_EQ(msg2.data, "hello");
  15460. }
  15461. // Test: SSEMessage clear
  15462. TEST_F(SSEParsingTest, MessageClear) {
  15463. sse::SSEMessage msg;
  15464. msg.event = "custom";
  15465. msg.data = "some data";
  15466. msg.id = "123";
  15467. msg.clear();
  15468. EXPECT_EQ(msg.event, "message");
  15469. EXPECT_EQ(msg.data, "");
  15470. EXPECT_EQ(msg.id, "");
  15471. }
  15472. // Test: Complete event parsing
  15473. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15474. sse::SSEMessage msg;
  15475. int retry_ms = 3000;
  15476. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15477. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15478. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15479. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15480. // Blank line ends event
  15481. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15482. EXPECT_EQ(msg.event, "notification");
  15483. EXPECT_EQ(msg.id, "evt-42");
  15484. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15485. EXPECT_EQ(retry_ms, 1000);
  15486. }
  15487. //==============================================================================
  15488. // Integration Tests with Server
  15489. //==============================================================================
  15490. class SSEIntegrationTest : public ::testing::Test {
  15491. protected:
  15492. void SetUp() override {
  15493. stop_server_.store(false);
  15494. events_.clear();
  15495. server_ = httplib::detail::make_unique<Server>();
  15496. setup_server();
  15497. start_server();
  15498. }
  15499. void TearDown() override {
  15500. stop_server_.store(true);
  15501. event_cv_.notify_all();
  15502. server_->stop();
  15503. if (server_thread_.joinable()) { server_thread_.join(); }
  15504. }
  15505. void setup_server() {
  15506. // Simple SSE endpoint
  15507. server_->Get("/events", [this](const Request &req, Response &res) {
  15508. auto last_id = req.get_header_value("Last-Event-ID");
  15509. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15510. res.set_chunked_content_provider(
  15511. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15512. std::unique_lock<std::mutex> lock(event_mutex_);
  15513. if (event_cv_.wait_for(
  15514. lock, std::chrono::milliseconds(200), [this] {
  15515. return !events_.empty() || stop_server_.load();
  15516. })) {
  15517. if (stop_server_.load()) { return false; }
  15518. if (!events_.empty()) {
  15519. std::string event = events_.front();
  15520. events_.erase(events_.begin());
  15521. sink.write(event.data(), event.size());
  15522. return true;
  15523. }
  15524. }
  15525. return !stop_server_.load();
  15526. });
  15527. });
  15528. // Endpoint that returns error
  15529. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15530. res.status = 500;
  15531. res.set_content("Internal Server Error", "text/plain");
  15532. });
  15533. // Endpoint for custom event types
  15534. server_->Get("/custom-events", [](const Request &, Response &res) {
  15535. res.set_chunked_content_provider(
  15536. "text/event-stream", [](size_t offset, DataSink &sink) {
  15537. if (offset == 0) {
  15538. std::string event = "event: update\ndata: updated\n\n"
  15539. "event: delete\ndata: deleted\n\n";
  15540. sink.write(event.data(), event.size());
  15541. }
  15542. return false; // End stream after sending
  15543. });
  15544. });
  15545. }
  15546. void start_server() {
  15547. port_ = server_->bind_to_any_port(HOST);
  15548. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15549. // Wait for server to start
  15550. while (!server_->is_running()) {
  15551. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15552. }
  15553. }
  15554. int get_port() const { return port_; }
  15555. void send_event(const std::string &event) {
  15556. std::lock_guard<std::mutex> lock(event_mutex_);
  15557. events_.push_back(event);
  15558. event_cv_.notify_all();
  15559. }
  15560. std::unique_ptr<Server> server_;
  15561. std::thread server_thread_;
  15562. std::mutex event_mutex_;
  15563. std::condition_variable event_cv_;
  15564. std::vector<std::string> events_;
  15565. std::atomic<bool> stop_server_{false};
  15566. std::string last_received_event_id_;
  15567. int port_ = 0;
  15568. };
  15569. // Test: Successful connection and on_open callback
  15570. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15571. // Add a simple endpoint that sends one event and closes
  15572. server_->Get("/simple-event", [](const Request &, Response &res) {
  15573. res.set_chunked_content_provider(
  15574. "text/event-stream", [](size_t offset, DataSink &sink) {
  15575. if (offset == 0) {
  15576. std::string event = "data: hello\n\n";
  15577. sink.write(event.data(), event.size());
  15578. }
  15579. return false; // Close stream after sending
  15580. });
  15581. });
  15582. Client client("localhost", get_port());
  15583. sse::SSEClient sse(client, "/simple-event");
  15584. std::atomic<bool> open_called{false};
  15585. std::atomic<bool> message_received{false};
  15586. sse.on_open([&open_called]() { open_called.store(true); });
  15587. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15588. if (msg.data == "hello") { message_received.store(true); }
  15589. });
  15590. sse.set_reconnect_interval(100);
  15591. sse.set_max_reconnect_attempts(1);
  15592. // Start async
  15593. sse.start_async();
  15594. // Wait for message to be processed
  15595. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15596. sse.stop();
  15597. EXPECT_TRUE(open_called.load());
  15598. EXPECT_TRUE(message_received.load());
  15599. }
  15600. // Test: on_message callback
  15601. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15602. // Endpoint that sends multiple events then closes
  15603. server_->Get("/multi-event", [](const Request &, Response &res) {
  15604. res.set_chunked_content_provider(
  15605. "text/event-stream", [](size_t offset, DataSink &sink) {
  15606. if (offset == 0) {
  15607. std::string events = "data: message1\n\ndata: message2\n\n";
  15608. sink.write(events.data(), events.size());
  15609. }
  15610. return false;
  15611. });
  15612. });
  15613. Client client("localhost", get_port());
  15614. sse::SSEClient sse(client, "/multi-event");
  15615. std::vector<std::string> received_messages;
  15616. std::mutex messages_mutex;
  15617. sse.on_message([&](const sse::SSEMessage &msg) {
  15618. std::lock_guard<std::mutex> lock(messages_mutex);
  15619. received_messages.push_back(msg.data);
  15620. });
  15621. sse.set_reconnect_interval(100);
  15622. sse.set_max_reconnect_attempts(1);
  15623. sse.start_async();
  15624. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15625. sse.stop();
  15626. std::lock_guard<std::mutex> lock(messages_mutex);
  15627. EXPECT_GE(received_messages.size(), 2u);
  15628. if (received_messages.size() >= 2) {
  15629. EXPECT_EQ(received_messages[0], "message1");
  15630. EXPECT_EQ(received_messages[1], "message2");
  15631. }
  15632. }
  15633. // Test: on_event for specific types
  15634. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15635. Client client("localhost", get_port());
  15636. sse::SSEClient sse(client, "/custom-events");
  15637. std::atomic<bool> update_received{false};
  15638. std::atomic<bool> delete_received{false};
  15639. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15640. if (msg.data == "updated") { update_received.store(true); }
  15641. });
  15642. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15643. if (msg.data == "deleted") { delete_received.store(true); }
  15644. });
  15645. sse.set_max_reconnect_attempts(1);
  15646. sse.start_async();
  15647. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15648. sse.stop();
  15649. EXPECT_TRUE(update_received.load());
  15650. EXPECT_TRUE(delete_received.load());
  15651. }
  15652. // Test: on_error callback on connection failure
  15653. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15654. // Connect to a non-existent port
  15655. Client client("localhost", 59999);
  15656. sse::SSEClient sse(client, "/events");
  15657. std::atomic<bool> error_called{false};
  15658. Error received_error = Error::Success;
  15659. sse.on_error([&](Error err) {
  15660. error_called.store(true);
  15661. received_error = err;
  15662. });
  15663. sse.set_reconnect_interval(50);
  15664. sse.set_max_reconnect_attempts(1);
  15665. sse.start_async();
  15666. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15667. sse.stop();
  15668. EXPECT_TRUE(error_called.load());
  15669. EXPECT_NE(received_error, Error::Success);
  15670. }
  15671. // Test: Last-Event-ID header sent on reconnect
  15672. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15673. // Endpoint that sends event with ID
  15674. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15675. res.set_chunked_content_provider(
  15676. "text/event-stream", [](size_t offset, DataSink &sink) {
  15677. if (offset == 0) {
  15678. std::string event = "id: evt-123\ndata: test\n\n";
  15679. sink.write(event.data(), event.size());
  15680. }
  15681. return false;
  15682. });
  15683. });
  15684. Client client("localhost", get_port());
  15685. sse::SSEClient sse(client, "/event-with-id");
  15686. std::atomic<bool> id_received{false};
  15687. sse.on_message([&](const sse::SSEMessage &msg) {
  15688. if (!msg.id.empty()) { id_received.store(true); }
  15689. });
  15690. sse.set_reconnect_interval(100);
  15691. sse.set_max_reconnect_attempts(1);
  15692. sse.start_async();
  15693. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15694. sse.stop();
  15695. EXPECT_TRUE(id_received.load());
  15696. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15697. }
  15698. // Test: Manual stop
  15699. TEST_F(SSEIntegrationTest, ManualStop) {
  15700. // Endpoint that sends one event and stays open briefly
  15701. std::atomic<bool> handler_running{true};
  15702. server_->Get("/stay-open", [&handler_running](const Request &,
  15703. Response &res) {
  15704. res.set_chunked_content_provider(
  15705. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15706. if (offset == 0) {
  15707. std::string event = "data: connected\n\n";
  15708. sink.write(event.data(), event.size());
  15709. }
  15710. // Keep connection open while handler_running is true
  15711. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15712. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15713. }
  15714. return false;
  15715. });
  15716. });
  15717. Client client("localhost", get_port());
  15718. sse::SSEClient sse(client, "/stay-open");
  15719. std::atomic<bool> connected{false};
  15720. sse.on_open([&connected]() { connected.store(true); });
  15721. sse.set_reconnect_interval(100);
  15722. sse.set_max_reconnect_attempts(1);
  15723. sse.start_async();
  15724. // Wait for connection to establish
  15725. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15726. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15727. }
  15728. EXPECT_TRUE(connected.load());
  15729. EXPECT_TRUE(sse.is_connected());
  15730. // Signal handler to stop
  15731. handler_running.store(false);
  15732. // Stop SSE client
  15733. sse.stop();
  15734. EXPECT_FALSE(sse.is_connected());
  15735. }
  15736. // Test: SSEClient with custom headers
  15737. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15738. // Setup a server endpoint that checks for custom header
  15739. std::atomic<bool> header_received{false};
  15740. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15741. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15742. header_received.store(true);
  15743. }
  15744. res.set_chunked_content_provider("text/event-stream",
  15745. [](size_t, DataSink &) { return false; });
  15746. });
  15747. Client client("localhost", get_port());
  15748. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15749. sse::SSEClient sse(client, "/header-check", headers);
  15750. sse.set_max_reconnect_attempts(1);
  15751. sse.start_async();
  15752. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15753. sse.stop();
  15754. EXPECT_TRUE(header_received.load());
  15755. }
  15756. // Test: Reconnect interval configuration
  15757. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15758. Client client("localhost", get_port());
  15759. sse::SSEClient sse(client, "/events");
  15760. auto &result = sse.set_reconnect_interval(500);
  15761. // Builder pattern should return reference to self
  15762. EXPECT_EQ(&result, &sse);
  15763. }
  15764. // Test: Max reconnect attempts
  15765. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15766. // Connect to non-existent port to force reconnects
  15767. Client client("localhost", 59998);
  15768. sse::SSEClient sse(client, "/events");
  15769. std::atomic<int> error_count{0};
  15770. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15771. sse.set_reconnect_interval(50);
  15772. sse.set_max_reconnect_attempts(2);
  15773. auto start = std::chrono::steady_clock::now();
  15774. sse.start(); // Blocking call
  15775. auto end = std::chrono::steady_clock::now();
  15776. // Should have stopped after 2 failed attempts
  15777. EXPECT_GE(error_count.load(), 2);
  15778. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15779. auto duration =
  15780. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15781. #ifdef _WIN32
  15782. // Windows is much slower for socket connection failures
  15783. EXPECT_LT(duration.count(), 7000);
  15784. #else
  15785. EXPECT_LT(duration.count(), 1000);
  15786. #endif
  15787. }
  15788. // Test: Multi-line data in integration
  15789. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15790. // Endpoint with multi-line data
  15791. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15792. res.set_chunked_content_provider(
  15793. "text/event-stream", [](size_t offset, DataSink &sink) {
  15794. if (offset == 0) {
  15795. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15796. sink.write(event.data(), event.size());
  15797. }
  15798. return false;
  15799. });
  15800. });
  15801. Client client("localhost", get_port());
  15802. sse::SSEClient sse(client, "/multiline-data");
  15803. std::string received_data;
  15804. std::mutex data_mutex;
  15805. sse.on_message([&](const sse::SSEMessage &msg) {
  15806. std::lock_guard<std::mutex> lock(data_mutex);
  15807. received_data = msg.data;
  15808. });
  15809. sse.set_reconnect_interval(100);
  15810. sse.set_max_reconnect_attempts(1);
  15811. sse.start_async();
  15812. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15813. sse.stop();
  15814. std::lock_guard<std::mutex> lock(data_mutex);
  15815. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15816. }
  15817. // Test: Auto-reconnect after server disconnection
  15818. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15819. std::atomic<int> connection_count{0};
  15820. std::atomic<int> message_count{0};
  15821. // Endpoint that sends one event and closes, forcing reconnect
  15822. server_->Get("/reconnect-test",
  15823. [&connection_count](const Request &, Response &res) {
  15824. connection_count.fetch_add(1);
  15825. res.set_chunked_content_provider(
  15826. "text/event-stream", [](size_t offset, DataSink &sink) {
  15827. if (offset == 0) {
  15828. std::string event = "data: hello\n\n";
  15829. sink.write(event.data(), event.size());
  15830. }
  15831. return false; // Close connection after sending
  15832. });
  15833. });
  15834. Client client("localhost", get_port());
  15835. sse::SSEClient sse(client, "/reconnect-test");
  15836. sse.on_message([&message_count](const sse::SSEMessage &) {
  15837. message_count.fetch_add(1);
  15838. });
  15839. sse.set_reconnect_interval(100);
  15840. sse.set_max_reconnect_attempts(3);
  15841. sse.start_async();
  15842. // Wait long enough for multiple reconnects
  15843. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15844. sse.stop();
  15845. // Should have connected multiple times (initial + reconnects)
  15846. EXPECT_GE(connection_count.load(), 2);
  15847. // Should have received messages from multiple connections
  15848. EXPECT_GE(message_count.load(), 2);
  15849. }
  15850. // Test: Last-Event-ID sent on reconnect
  15851. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15852. std::atomic<int> connection_count{0};
  15853. std::vector<std::string> received_last_event_ids;
  15854. std::mutex id_mutex;
  15855. // Endpoint that checks Last-Event-ID header and sends event with ID
  15856. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15857. int conn = connection_count.fetch_add(1);
  15858. // Capture the Last-Event-ID header from each connection
  15859. {
  15860. std::lock_guard<std::mutex> lock(id_mutex);
  15861. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15862. }
  15863. res.set_chunked_content_provider(
  15864. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15865. if (offset == 0) {
  15866. std::string event =
  15867. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15868. sink.write(event.data(), event.size());
  15869. }
  15870. return false;
  15871. });
  15872. });
  15873. Client client("localhost", get_port());
  15874. sse::SSEClient sse(client, "/reconnect-with-id");
  15875. sse.set_reconnect_interval(100);
  15876. sse.set_max_reconnect_attempts(3);
  15877. sse.start_async();
  15878. // Wait for at least 2 connections
  15879. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15880. sse.stop();
  15881. // Verify behavior
  15882. std::lock_guard<std::mutex> lock(id_mutex);
  15883. EXPECT_GE(received_last_event_ids.size(), 2u);
  15884. // First connection should have no Last-Event-ID
  15885. if (!received_last_event_ids.empty()) {
  15886. EXPECT_EQ(received_last_event_ids[0], "");
  15887. }
  15888. // Second connection should have Last-Event-ID from first connection
  15889. if (received_last_event_ids.size() >= 2) {
  15890. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15891. }
  15892. }
  15893. // Test: set_headers updates headers used on reconnect
  15894. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15895. std::vector<std::string> received_tokens;
  15896. std::mutex token_mutex;
  15897. // Endpoint that captures Authorization header
  15898. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15899. {
  15900. std::lock_guard<std::mutex> lock(token_mutex);
  15901. received_tokens.push_back(req.get_header_value("Authorization"));
  15902. }
  15903. res.set_chunked_content_provider(
  15904. "text/event-stream", [](size_t offset, DataSink &sink) {
  15905. if (offset == 0) {
  15906. std::string event = "data: hello\n\n";
  15907. sink.write(event.data(), event.size());
  15908. }
  15909. return false; // Close connection to trigger reconnect
  15910. });
  15911. });
  15912. Client client("localhost", get_port());
  15913. Headers headers = {{"Authorization", "Bearer old-token"}};
  15914. sse::SSEClient sse(client, "/auth-check", headers);
  15915. // Update headers on each successful connection
  15916. sse.on_open(
  15917. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15918. sse.set_reconnect_interval(100);
  15919. sse.set_max_reconnect_attempts(3);
  15920. sse.start_async();
  15921. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15922. sse.stop();
  15923. std::lock_guard<std::mutex> lock(token_mutex);
  15924. ASSERT_GE(received_tokens.size(), 2u);
  15925. // First connection uses original header
  15926. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15927. // Second connection uses updated header from set_headers
  15928. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15929. }
  15930. // Test: 401 allows reconnection (so on_error can refresh headers)
  15931. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15932. std::atomic<int> connection_count{0};
  15933. // Endpoint: returns 401 on first attempt, 200 on second
  15934. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15935. int conn = connection_count.fetch_add(1);
  15936. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15937. res.status = StatusCode::Unauthorized_401;
  15938. res.set_content("Unauthorized", "text/plain");
  15939. return;
  15940. }
  15941. res.set_chunked_content_provider(
  15942. "text/event-stream", [](size_t offset, DataSink &sink) {
  15943. if (offset == 0) {
  15944. std::string event = "data: authenticated\n\n";
  15945. sink.write(event.data(), event.size());
  15946. }
  15947. return false;
  15948. });
  15949. });
  15950. Client client("localhost", get_port());
  15951. Headers headers = {{"Authorization", "Bearer expired"}};
  15952. sse::SSEClient sse(client, "/auth-retry", headers);
  15953. std::atomic<bool> message_received{false};
  15954. // Refresh token on error
  15955. sse.on_error(
  15956. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15957. sse.on_message([&](const sse::SSEMessage &msg) {
  15958. if (msg.data == "authenticated") { message_received.store(true); }
  15959. });
  15960. sse.set_reconnect_interval(100);
  15961. sse.set_max_reconnect_attempts(3);
  15962. sse.start_async();
  15963. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15964. sse.stop();
  15965. // Should have reconnected after 401 and succeeded with new token
  15966. EXPECT_GE(connection_count.load(), 2);
  15967. EXPECT_TRUE(message_received.load());
  15968. }
  15969. TEST(Issue2318Test, EmptyHostString) {
  15970. {
  15971. httplib::Client cli_empty("", PORT);
  15972. auto res = cli_empty.Get("/");
  15973. ASSERT_FALSE(res);
  15974. EXPECT_EQ(httplib::Error::Connection, res.error());
  15975. }
  15976. {
  15977. httplib::Client cli(" ", PORT);
  15978. auto res = cli.Get("/");
  15979. ASSERT_FALSE(res);
  15980. EXPECT_EQ(httplib::Error::Connection, res.error());
  15981. }
  15982. }
  15983. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15984. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15985. Server svr;
  15986. // Set a small payload limit (1KB)
  15987. svr.set_payload_max_length(1024);
  15988. svr.Post("/test", [&](const Request &req, Response &res) {
  15989. res.set_content("Body size: " + std::to_string(req.body.size()),
  15990. "text/plain");
  15991. });
  15992. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15993. auto se = detail::scope_exit([&] {
  15994. svr.stop();
  15995. listen_thread.join();
  15996. });
  15997. svr.wait_until_ready();
  15998. // Create data that compresses well but exceeds limit when decompressed
  15999. // 8KB of repeated null bytes compresses to a very small size
  16000. std::string original_data(8 * 1024, '\0');
  16001. // Compress the data using gzip
  16002. std::string compressed_data;
  16003. detail::gzip_compressor compressor;
  16004. compressor.compress(original_data.data(), original_data.size(), true,
  16005. [&](const char *data, size_t size) {
  16006. compressed_data.append(data, size);
  16007. return true;
  16008. });
  16009. // Verify compression worked (compressed should be much smaller)
  16010. ASSERT_LT(compressed_data.size(), original_data.size());
  16011. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16012. // Send compressed data with Content-Encoding: gzip
  16013. Client cli(HOST, PORT);
  16014. Headers headers = {{"Content-Encoding", "gzip"}};
  16015. auto res =
  16016. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16017. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16019. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16020. }
  16021. #endif
  16022. // ============================================================================
  16023. // OpenSSL-Specific Tests
  16024. // ============================================================================
  16025. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16026. X509 *readCertificate(const std::string &strFileName) {
  16027. std::ifstream inStream(strFileName);
  16028. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16029. std::istreambuf_iterator<char>());
  16030. if (strCertPEM.empty()) return (nullptr);
  16031. BIO *pbCert = BIO_new(BIO_s_mem());
  16032. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16033. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16034. BIO_free(pbCert);
  16035. return (pCert);
  16036. }
  16037. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16038. std::ifstream inStream(strFileName);
  16039. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16040. std::istreambuf_iterator<char>());
  16041. if (strPrivateKeyPEM.empty()) return (nullptr);
  16042. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16043. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16044. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16045. BIO_free(pbPrivKey);
  16046. return (pPrivateKey);
  16047. }
  16048. TEST(BindServerTest, UpdateCerts) {
  16049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16050. int port = svr.bind_to_any_port("0.0.0.0");
  16051. ASSERT_TRUE(svr.is_valid());
  16052. ASSERT_TRUE(port > 0);
  16053. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16054. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16055. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16056. ASSERT_TRUE(cert != nullptr);
  16057. ASSERT_TRUE(ca_cert != nullptr);
  16058. ASSERT_TRUE(key != nullptr);
  16059. X509_STORE *cert_store = X509_STORE_new();
  16060. X509_STORE_add_cert(cert_store, ca_cert);
  16061. // svr.update_certs(cert, key, cert_store); // deprecated
  16062. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16063. CLIENT_CA_CERT_FILE);
  16064. ASSERT_TRUE(svr.is_valid());
  16065. svr.stop();
  16066. X509_STORE_free(cert_store);
  16067. X509_free(cert);
  16068. X509_free(ca_cert);
  16069. EVP_PKEY_free(key);
  16070. }
  16071. // Test that update_certs() updates client CA list correctly
  16072. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16073. // Start with file-based constructor
  16074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16075. ASSERT_TRUE(svr.is_valid());
  16076. // Initially no client CA list should be set
  16077. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16078. ASSERT_TRUE(ssl_ctx != nullptr);
  16079. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16080. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16081. EXPECT_EQ(0, count_before);
  16082. // Now update with client CA (PEM string)
  16083. std::string cert_pem, key_pem, ca_pem;
  16084. read_file(SERVER_CERT_FILE, cert_pem);
  16085. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16086. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16087. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16088. ASSERT_TRUE(svr.is_valid());
  16089. // Now client CA list should be set
  16090. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16091. ASSERT_TRUE(ca_list_after != nullptr);
  16092. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16093. }
  16094. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16095. // Test that the file-path SSLServer constructor properly sets the client CA
  16096. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16098. ASSERT_TRUE(svr.is_valid());
  16099. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16100. ASSERT_TRUE(ssl_ctx != nullptr);
  16101. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16102. ASSERT_TRUE(ca_list != nullptr);
  16103. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16104. }
  16105. #endif
  16106. // ============================================================================
  16107. // MbedTLS-Specific Tests
  16108. // ============================================================================
  16109. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16110. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16111. using namespace httplib::tls;
  16112. // Track if callback was invoked
  16113. bool callback_invoked = false;
  16114. // The callback receives void* ctx which is actually MbedTlsContext*
  16115. // We can access the mbedtls_ssl_config via the context
  16116. auto setup_callback = [&callback_invoked](void *ctx) {
  16117. callback_invoked = true;
  16118. // Cast to MbedTlsContext* to access the ssl config
  16119. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16120. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16121. // Use static variables to hold certificate data (simplified for test)
  16122. static mbedtls_x509_crt own_cert;
  16123. static mbedtls_pk_context own_key;
  16124. static mbedtls_x509_crt ca_chain;
  16125. static bool initialized = false;
  16126. if (!initialized) {
  16127. mbedtls_x509_crt_init(&own_cert);
  16128. mbedtls_pk_init(&own_key);
  16129. mbedtls_x509_crt_init(&ca_chain);
  16130. // Load server certificate
  16131. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16132. return false;
  16133. }
  16134. // Load server private key.
  16135. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16136. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16137. #if MBEDTLS_VERSION_MAJOR == 3
  16138. ,
  16139. mbedtls_ctr_drbg_random, nullptr
  16140. #endif
  16141. ) != 0) {
  16142. return false;
  16143. }
  16144. // Load CA chain for client verification
  16145. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16146. return false;
  16147. }
  16148. initialized = true;
  16149. }
  16150. // Configure the SSL config
  16151. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16152. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16153. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16154. // Set minimum TLS version using mbedTLS native API
  16155. #if MBEDTLS_VERSION_MAJOR >= 3
  16156. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16157. #else
  16158. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16159. MBEDTLS_SSL_MINOR_VERSION_3);
  16160. #endif
  16161. return true;
  16162. };
  16163. SSLServer svr(setup_callback);
  16164. ASSERT_TRUE(svr.is_valid());
  16165. ASSERT_TRUE(callback_invoked);
  16166. svr.Get("/test", [&](const Request &req, Response &res) {
  16167. res.set_content("test", "text/plain");
  16168. auto cert = req.peer_cert();
  16169. ASSERT_TRUE(static_cast<bool>(cert));
  16170. auto common_name = cert.subject_cn();
  16171. EXPECT_EQ("Common Name", common_name);
  16172. });
  16173. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16174. auto se = detail::scope_exit([&] {
  16175. svr.stop();
  16176. t.join();
  16177. ASSERT_FALSE(svr.is_running());
  16178. });
  16179. svr.wait_until_ready();
  16180. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16181. cli.enable_server_certificate_verification(false);
  16182. cli.set_connection_timeout(30);
  16183. auto res = cli.Get("/test");
  16184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16185. ASSERT_EQ(StatusCode::OK_200, res->status);
  16186. }
  16187. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16188. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16189. // keep-alive SSL session, which reads through that config in
  16190. // mbedtls_ssl_close_notify.
  16191. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16192. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16193. ASSERT_TRUE(svr.is_valid());
  16194. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16195. res.set_content("test", "text/plain");
  16196. });
  16197. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16198. auto se = detail::scope_exit([&] {
  16199. svr.stop();
  16200. t.join();
  16201. ASSERT_FALSE(svr.is_running());
  16202. });
  16203. svr.wait_until_ready();
  16204. {
  16205. SSLClient cli(HOST, PORT);
  16206. cli.enable_server_certificate_verification(false);
  16207. cli.set_keep_alive(true);
  16208. auto res = cli.Get("/test");
  16209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16210. ASSERT_EQ(StatusCode::OK_200, res->status);
  16211. // cli is destructed here with the keep-alive SSL session still open.
  16212. }
  16213. }
  16214. #endif
  16215. // WebSocket Tests
  16216. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16217. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16218. // defining the meaning of these bits has been negotiated.
  16219. auto make_frame = [](uint8_t first_byte) {
  16220. std::string frame;
  16221. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16222. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16223. frame += "Hello";
  16224. return frame;
  16225. };
  16226. // RSV1 set (0x40)
  16227. {
  16228. detail::BufferStream strm;
  16229. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16230. ws::Opcode opcode;
  16231. std::string payload;
  16232. bool fin;
  16233. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16234. false, 1024));
  16235. }
  16236. // RSV2 set (0x20)
  16237. {
  16238. detail::BufferStream strm;
  16239. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16240. ws::Opcode opcode;
  16241. std::string payload;
  16242. bool fin;
  16243. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16244. false, 1024));
  16245. }
  16246. // RSV3 set (0x10)
  16247. {
  16248. detail::BufferStream strm;
  16249. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16250. ws::Opcode opcode;
  16251. std::string payload;
  16252. bool fin;
  16253. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16254. false, 1024));
  16255. }
  16256. // No RSV bits set - should succeed
  16257. {
  16258. detail::BufferStream strm;
  16259. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16260. ws::Opcode opcode;
  16261. std::string payload;
  16262. bool fin;
  16263. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16264. false, 1024));
  16265. EXPECT_EQ(ws::Opcode::Text, opcode);
  16266. EXPECT_EQ("Hello", payload);
  16267. EXPECT_TRUE(fin);
  16268. }
  16269. }
  16270. TEST(WebSocketTest, ControlFrameValidation) {
  16271. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16272. // payload length <= 125.
  16273. // Ping with FIN=0 - must be rejected
  16274. {
  16275. detail::BufferStream strm;
  16276. std::string frame;
  16277. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16278. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16279. strm.write(frame.data(), frame.size());
  16280. ws::Opcode opcode;
  16281. std::string payload;
  16282. bool fin;
  16283. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16284. false, 1024));
  16285. }
  16286. // Close with FIN=0 - must be rejected
  16287. {
  16288. detail::BufferStream strm;
  16289. std::string frame;
  16290. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16291. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16292. strm.write(frame.data(), frame.size());
  16293. ws::Opcode opcode;
  16294. std::string payload;
  16295. bool fin;
  16296. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16297. false, 1024));
  16298. }
  16299. // Ping with payload_len=126 (extended length) - must be rejected
  16300. {
  16301. detail::BufferStream strm;
  16302. std::string frame;
  16303. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16304. frame += static_cast<char>(126); // payload_len=126 (>125)
  16305. frame += static_cast<char>(0x00); // extended length high byte
  16306. frame += static_cast<char>(126); // extended length low byte
  16307. frame += std::string(126, 'x');
  16308. strm.write(frame.data(), frame.size());
  16309. ws::Opcode opcode;
  16310. std::string payload;
  16311. bool fin;
  16312. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16313. false, 1024));
  16314. }
  16315. // Ping with FIN=1 and payload_len=125 - should succeed
  16316. {
  16317. detail::BufferStream strm;
  16318. std::string frame;
  16319. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16320. frame += static_cast<char>(125); // payload_len=125
  16321. frame += std::string(125, 'x');
  16322. strm.write(frame.data(), frame.size());
  16323. ws::Opcode opcode;
  16324. std::string payload;
  16325. bool fin;
  16326. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16327. false, 1024));
  16328. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16329. EXPECT_EQ(125u, payload.size());
  16330. EXPECT_TRUE(fin);
  16331. }
  16332. }
  16333. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16334. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16335. // length MUST be 0.
  16336. // MSB set - must be rejected
  16337. {
  16338. detail::BufferStream strm;
  16339. std::string frame;
  16340. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16341. frame += static_cast<char>(127); // 64-bit extended length
  16342. frame += static_cast<char>(0x80); // MSB set (invalid)
  16343. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16344. strm.write(frame.data(), frame.size());
  16345. ws::Opcode opcode;
  16346. std::string payload;
  16347. bool fin;
  16348. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16349. false, 1024));
  16350. }
  16351. // MSB clear - should pass length parsing (will be rejected by max_len,
  16352. // but that's a different check; use a small length to verify)
  16353. {
  16354. detail::BufferStream strm;
  16355. std::string frame;
  16356. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16357. frame += static_cast<char>(127); // 64-bit extended length
  16358. frame += std::string(7, '\0'); // high bytes = 0
  16359. frame += static_cast<char>(0x03); // length = 3
  16360. frame += "abc";
  16361. strm.write(frame.data(), frame.size());
  16362. ws::Opcode opcode;
  16363. std::string payload;
  16364. bool fin;
  16365. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16366. false, 1024));
  16367. EXPECT_EQ(ws::Opcode::Text, opcode);
  16368. EXPECT_EQ("abc", payload);
  16369. }
  16370. }
  16371. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16372. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16373. // Valid UTF-8
  16374. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16375. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16376. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16377. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16378. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16379. // Invalid UTF-8
  16380. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16381. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16382. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16383. EXPECT_FALSE(
  16384. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16385. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16386. }
  16387. TEST(WebSocketTest, ConnectAndDisconnect) {
  16388. Server svr;
  16389. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16390. std::string msg;
  16391. while (ws.read(msg)) {}
  16392. });
  16393. auto port = svr.bind_to_any_port(HOST);
  16394. std::thread t([&]() { svr.listen_after_bind(); });
  16395. svr.wait_until_ready();
  16396. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16397. ASSERT_TRUE(client.connect());
  16398. EXPECT_TRUE(client.is_open());
  16399. client.close();
  16400. EXPECT_FALSE(client.is_open());
  16401. svr.stop();
  16402. t.join();
  16403. }
  16404. TEST(WebSocketTest, ValidURL) {
  16405. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16406. EXPECT_TRUE(ws1.is_valid());
  16407. ws::WebSocketClient ws2("ws://example.com/path");
  16408. EXPECT_TRUE(ws2.is_valid());
  16409. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16410. EXPECT_TRUE(ws3.is_valid());
  16411. #ifdef CPPHTTPLIB_SSL_ENABLED
  16412. ws::WebSocketClient wss1("wss://example.com/path");
  16413. EXPECT_TRUE(wss1.is_valid());
  16414. ws::WebSocketClient wss2("wss://example.com:443/path");
  16415. EXPECT_TRUE(wss2.is_valid());
  16416. #endif
  16417. }
  16418. TEST(WebSocketTest, InvalidURL) {
  16419. // No scheme
  16420. ws::WebSocketClient ws1("localhost:8080/path");
  16421. EXPECT_FALSE(ws1.is_valid());
  16422. // No path
  16423. ws::WebSocketClient ws2("ws://localhost:8080");
  16424. EXPECT_FALSE(ws2.is_valid());
  16425. // Empty string
  16426. ws::WebSocketClient ws3("");
  16427. EXPECT_FALSE(ws3.is_valid());
  16428. // Missing host
  16429. ws::WebSocketClient ws4("ws://:8080/path");
  16430. EXPECT_FALSE(ws4.is_valid());
  16431. // Port number overflow — should not crash
  16432. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16433. EXPECT_FALSE(ws5.is_valid());
  16434. // Port out of range
  16435. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16436. EXPECT_FALSE(ws6.is_valid());
  16437. }
  16438. TEST(WebSocketTest, UnsupportedScheme) {
  16439. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16440. ws::WebSocketClient ws1("http://localhost:8080/path");
  16441. EXPECT_FALSE(ws1.is_valid());
  16442. ws::WebSocketClient ws2("https://localhost:8080/path");
  16443. EXPECT_FALSE(ws2.is_valid());
  16444. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16445. EXPECT_FALSE(ws3.is_valid());
  16446. #else
  16447. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16448. std::invalid_argument);
  16449. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16450. std::invalid_argument);
  16451. #endif
  16452. }
  16453. TEST(WebSocketTest, ConnectWhenInvalid) {
  16454. ws::WebSocketClient ws("not a valid url");
  16455. EXPECT_FALSE(ws.is_valid());
  16456. EXPECT_FALSE(ws.connect());
  16457. }
  16458. TEST(WebSocketTest, DefaultPort) {
  16459. ws::WebSocketClient ws1("ws://example.com/path");
  16460. EXPECT_TRUE(ws1.is_valid());
  16461. // ws:// defaults to port 80 (verified by successful parse)
  16462. #ifdef CPPHTTPLIB_SSL_ENABLED
  16463. ws::WebSocketClient ws2("wss://example.com/path");
  16464. EXPECT_TRUE(ws2.is_valid());
  16465. // wss:// defaults to port 443 (verified by successful parse)
  16466. #endif
  16467. }
  16468. TEST(WebSocketTest, IPv6LiteralAddress) {
  16469. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16470. EXPECT_TRUE(ws1.is_valid());
  16471. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16472. EXPECT_TRUE(ws2.is_valid());
  16473. }
  16474. TEST(WebSocketTest, ComplexPath) {
  16475. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16476. EXPECT_TRUE(ws1.is_valid());
  16477. ws::WebSocketClient ws2("ws://localhost:8080/");
  16478. EXPECT_TRUE(ws2.is_valid());
  16479. }
  16480. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16481. Server svr;
  16482. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16483. std::string msg;
  16484. while (ws.read(msg)) {}
  16485. });
  16486. auto port = svr.bind_to_any_port(HOST);
  16487. std::thread t([&]() { svr.listen_after_bind(); });
  16488. svr.wait_until_ready();
  16489. auto another_host = "example.com";
  16490. auto wrong_ip = "192.0.2.1";
  16491. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16492. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16493. ASSERT_TRUE(client.connect());
  16494. EXPECT_TRUE(client.is_open());
  16495. client.close();
  16496. svr.stop();
  16497. t.join();
  16498. }
  16499. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16500. Server svr;
  16501. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16502. std::string msg;
  16503. while (ws.read(msg)) {}
  16504. });
  16505. auto port = svr.bind_to_any_port(HOST);
  16506. std::thread t([&]() { svr.listen_after_bind(); });
  16507. svr.wait_until_ready();
  16508. auto wrong_ip = "192.0.2.1";
  16509. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16510. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16511. client.set_connection_timeout(1);
  16512. client.set_read_timeout(1);
  16513. client.set_write_timeout(1);
  16514. EXPECT_FALSE(client.connect());
  16515. EXPECT_FALSE(client.is_open());
  16516. svr.stop();
  16517. t.join();
  16518. }
  16519. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16520. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16521. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16522. // (RFC 6761) is only a map key and the Host header value.
  16523. auto host = "target.invalid";
  16524. Server svr;
  16525. std::string received_host;
  16526. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16527. received_host = req.get_header_value("Host");
  16528. std::string msg;
  16529. while (ws.read(msg)) {}
  16530. });
  16531. auto port = svr.bind_to_any_port(HOST);
  16532. std::thread t([&]() { svr.listen_after_bind(); });
  16533. // ASSERT_* below returns from the test body, which would leave t joinable
  16534. // and make ~thread call std::terminate.
  16535. auto se = detail::scope_exit([&] {
  16536. svr.stop();
  16537. if (t.joinable()) { t.join(); }
  16538. });
  16539. svr.wait_until_ready();
  16540. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16541. std::to_string(port) + "/ws");
  16542. client.set_hostname_addr_map({{host, HOST}});
  16543. ASSERT_TRUE(client.connect());
  16544. EXPECT_TRUE(client.is_open());
  16545. client.close();
  16546. svr.stop();
  16547. t.join();
  16548. // The mapping only redirects the connection; the identity stays host_.
  16549. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16550. }
  16551. class WebSocketIntegrationTest : public ::testing::Test {
  16552. protected:
  16553. void SetUp() override {
  16554. server_ = httplib::detail::make_unique<Server>();
  16555. setup_server();
  16556. start_server();
  16557. }
  16558. void TearDown() override {
  16559. server_->stop();
  16560. if (server_thread_.joinable()) { server_thread_.join(); }
  16561. }
  16562. void setup_server() {
  16563. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16564. std::string msg;
  16565. ws::ReadResult ret;
  16566. while ((ret = ws.read(msg))) {
  16567. if (ret == ws::Binary) {
  16568. ws.send(msg.data(), msg.size());
  16569. } else {
  16570. ws.send(msg);
  16571. }
  16572. }
  16573. });
  16574. server_->WebSocket("/ws-echo-string",
  16575. [](const Request &, ws::WebSocket &ws) {
  16576. std::string msg;
  16577. while (ws.read(msg)) {
  16578. ws.send("echo: " + msg);
  16579. }
  16580. });
  16581. server_->WebSocket(
  16582. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16583. // Echo back request metadata
  16584. ws.send("path:" + req.path);
  16585. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16586. std::string msg;
  16587. while (ws.read(msg)) {}
  16588. });
  16589. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16590. std::string msg;
  16591. ws.read(msg); // wait for a message
  16592. ws.close();
  16593. });
  16594. server_->WebSocket("/ws-close-status",
  16595. [](const Request &, ws::WebSocket &ws) {
  16596. std::string msg;
  16597. ws.read(msg); // wait for a message
  16598. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16599. });
  16600. server_->WebSocket(
  16601. "/ws-subprotocol",
  16602. [](const Request &, ws::WebSocket &ws) {
  16603. std::string msg;
  16604. while (ws.read(msg)) {
  16605. ws.send(msg);
  16606. }
  16607. },
  16608. [](const std::vector<std::string> &protocols) -> std::string {
  16609. for (const auto &p : protocols) {
  16610. if (p == "graphql-ws") { return p; }
  16611. }
  16612. return "";
  16613. });
  16614. }
  16615. void start_server() {
  16616. port_ = server_->bind_to_any_port(HOST);
  16617. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16618. server_->wait_until_ready();
  16619. }
  16620. std::unique_ptr<Server> server_;
  16621. std::thread server_thread_;
  16622. int port_ = 0;
  16623. };
  16624. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16625. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16626. "/ws-echo");
  16627. ASSERT_TRUE(client.connect());
  16628. ASSERT_TRUE(client.is_open());
  16629. ASSERT_TRUE(client.send("Hello WebSocket"));
  16630. std::string msg;
  16631. EXPECT_EQ(ws::Text, client.read(msg));
  16632. EXPECT_EQ("Hello WebSocket", msg);
  16633. client.close();
  16634. }
  16635. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16636. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16637. "/ws-echo");
  16638. ASSERT_TRUE(client.connect());
  16639. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16640. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16641. std::string msg;
  16642. EXPECT_EQ(ws::Binary, client.read(msg));
  16643. EXPECT_EQ(binary_data, msg);
  16644. client.close();
  16645. }
  16646. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16647. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16648. "/ws-echo");
  16649. ASSERT_TRUE(client.connect());
  16650. for (int i = 0; i < 10; i++) {
  16651. auto text = "message " + std::to_string(i);
  16652. ASSERT_TRUE(client.send(text));
  16653. std::string msg;
  16654. ASSERT_TRUE(client.read(msg));
  16655. EXPECT_EQ(text, msg);
  16656. }
  16657. client.close();
  16658. }
  16659. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16660. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16661. "/ws-close");
  16662. ASSERT_TRUE(client.connect());
  16663. // Send a message to trigger the server to close
  16664. ASSERT_TRUE(client.send("trigger close"));
  16665. // The server will close, so read should return false
  16666. std::string msg;
  16667. EXPECT_FALSE(client.read(msg));
  16668. EXPECT_FALSE(client.is_open());
  16669. }
  16670. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16671. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16672. "/ws-echo");
  16673. ASSERT_TRUE(client.connect());
  16674. // 128KB message
  16675. std::string large_data(128 * 1024, 'X');
  16676. ASSERT_TRUE(client.send(large_data));
  16677. std::string msg;
  16678. ASSERT_TRUE(client.read(msg));
  16679. EXPECT_EQ(large_data, msg);
  16680. client.close();
  16681. }
  16682. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16683. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16684. "/ws-echo");
  16685. ASSERT_TRUE(client.connect());
  16686. const int num_threads = 4;
  16687. std::vector<std::thread> threads;
  16688. std::atomic<int> send_count{0};
  16689. for (int t = 0; t < num_threads; t++) {
  16690. threads.emplace_back([&client, &send_count, t]() {
  16691. for (int i = 0; i < 5; i++) {
  16692. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16693. if (client.send(text)) { send_count++; }
  16694. }
  16695. });
  16696. }
  16697. for (auto &th : threads) {
  16698. th.join();
  16699. }
  16700. int received = 0;
  16701. std::string msg;
  16702. while (received < send_count.load()) {
  16703. if (!client.read(msg)) { break; }
  16704. received++;
  16705. }
  16706. EXPECT_EQ(send_count.load(), received);
  16707. client.close();
  16708. }
  16709. TEST_F(WebSocketIntegrationTest, ReadString) {
  16710. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16711. "/ws-echo-string");
  16712. ASSERT_TRUE(client.connect());
  16713. ASSERT_TRUE(client.send("hello"));
  16714. std::string msg;
  16715. ASSERT_TRUE(client.read(msg));
  16716. EXPECT_EQ("echo: hello", msg);
  16717. ASSERT_TRUE(client.send("world"));
  16718. ASSERT_TRUE(client.read(msg));
  16719. EXPECT_EQ("echo: world", msg);
  16720. client.close();
  16721. }
  16722. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16723. Headers headers = {{"X-Test-Header", "test-value"}};
  16724. ws::WebSocketClient client(
  16725. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16726. ASSERT_TRUE(client.connect());
  16727. std::string msg;
  16728. ASSERT_TRUE(client.read(msg));
  16729. EXPECT_EQ("path:/ws-request-info", msg);
  16730. ASSERT_TRUE(client.read(msg));
  16731. EXPECT_EQ("header:test-value", msg);
  16732. client.close();
  16733. }
  16734. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16735. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16736. "/ws-echo");
  16737. client.set_read_timeout(1, 0); // 1 second
  16738. ASSERT_TRUE(client.connect());
  16739. // Don't send anything — server echo handler waits for a message,
  16740. // so read() should time out and return false.
  16741. std::string msg;
  16742. EXPECT_FALSE(client.read(msg));
  16743. }
  16744. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16745. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16746. "/ws-echo");
  16747. client.set_read_timeout(5, 0);
  16748. ASSERT_TRUE(client.connect());
  16749. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16750. // The server should reject it and close the connection.
  16751. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16752. client.send(oversized);
  16753. // The server's read() should have failed due to payload limit,
  16754. // so our read() should return false (connection closed).
  16755. std::string msg;
  16756. EXPECT_FALSE(client.read(msg));
  16757. }
  16758. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16760. "/ws-echo");
  16761. client.set_read_timeout(10, 0);
  16762. ASSERT_TRUE(client.connect());
  16763. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16764. // This should succeed.
  16765. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16766. ASSERT_TRUE(client.send(at_limit));
  16767. std::string msg;
  16768. ASSERT_TRUE(client.read(msg));
  16769. EXPECT_EQ(at_limit.size(), msg.size());
  16770. client.close();
  16771. }
  16772. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16773. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16774. "/nonexistent");
  16775. EXPECT_FALSE(client.connect());
  16776. EXPECT_FALSE(client.is_open());
  16777. }
  16778. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16779. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16780. "/ws-echo");
  16781. ASSERT_TRUE(client.connect());
  16782. ASSERT_TRUE(client.send(""));
  16783. std::string msg;
  16784. EXPECT_EQ(ws::Text, client.read(msg));
  16785. EXPECT_EQ("", msg);
  16786. client.close();
  16787. }
  16788. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16789. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16790. "/ws-echo");
  16791. // First connection
  16792. ASSERT_TRUE(client.connect());
  16793. ASSERT_TRUE(client.send("first"));
  16794. std::string msg;
  16795. ASSERT_TRUE(client.read(msg));
  16796. EXPECT_EQ("first", msg);
  16797. client.close();
  16798. EXPECT_FALSE(client.is_open());
  16799. // Reconnect using the same client object
  16800. ASSERT_TRUE(client.connect());
  16801. ASSERT_TRUE(client.is_open());
  16802. ASSERT_TRUE(client.send("second"));
  16803. ASSERT_TRUE(client.read(msg));
  16804. EXPECT_EQ("second", msg);
  16805. client.close();
  16806. }
  16807. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16808. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16809. "/ws-close-status");
  16810. ASSERT_TRUE(client.connect());
  16811. // Trigger the server to close with GoingAway status
  16812. ASSERT_TRUE(client.send("trigger"));
  16813. // read() should return false after receiving the close frame
  16814. std::string msg;
  16815. EXPECT_FALSE(client.read(msg));
  16816. EXPECT_FALSE(client.is_open());
  16817. }
  16818. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16819. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16820. "/ws-echo");
  16821. ASSERT_TRUE(client.connect());
  16822. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16823. EXPECT_FALSE(client.is_open());
  16824. }
  16825. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16826. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16827. ws::WebSocketClient client(
  16828. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16829. ASSERT_TRUE(client.connect());
  16830. // Server should have selected graphql-ws
  16831. EXPECT_EQ("graphql-ws", client.subprotocol());
  16832. client.close();
  16833. }
  16834. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16835. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16836. ws::WebSocketClient client(
  16837. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16838. ASSERT_TRUE(client.connect());
  16839. // Server should not have selected any subprotocol
  16840. EXPECT_TRUE(client.subprotocol().empty());
  16841. client.close();
  16842. }
  16843. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16844. // Connect without requesting any subprotocol
  16845. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16846. "/ws-subprotocol");
  16847. ASSERT_TRUE(client.connect());
  16848. EXPECT_TRUE(client.subprotocol().empty());
  16849. client.close();
  16850. }
  16851. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16852. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16853. "/ws-echo");
  16854. client.set_tcp_nodelay(true);
  16855. client.set_connection_timeout(3, 0);
  16856. bool socket_options_called = false;
  16857. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16858. ASSERT_TRUE(client.connect());
  16859. ASSERT_TRUE(client.is_open());
  16860. EXPECT_TRUE(socket_options_called);
  16861. ASSERT_TRUE(client.send("hello"));
  16862. std::string msg;
  16863. auto result = client.read(msg);
  16864. EXPECT_EQ(result, ws::ReadResult::Text);
  16865. EXPECT_EQ(msg, "hello");
  16866. client.close();
  16867. }
  16868. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16869. Server svr;
  16870. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16871. if (!req.has_header("Authorization")) {
  16872. res.status = StatusCode::Unauthorized_401;
  16873. res.set_content("Unauthorized", "text/plain");
  16874. return Server::HandlerResponse::Handled;
  16875. }
  16876. return Server::HandlerResponse::Unhandled;
  16877. });
  16878. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16879. std::string msg;
  16880. while (ws.read(msg)) {
  16881. ws.send(msg);
  16882. }
  16883. });
  16884. auto port = svr.bind_to_any_port("localhost");
  16885. std::thread t([&]() { svr.listen_after_bind(); });
  16886. svr.wait_until_ready();
  16887. // Without Authorization header - should be rejected before upgrade
  16888. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16889. EXPECT_FALSE(client1.connect());
  16890. // With Authorization header - should succeed
  16891. Headers headers = {{"Authorization", "Bearer token123"}};
  16892. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16893. headers);
  16894. ASSERT_TRUE(client2.connect());
  16895. ASSERT_TRUE(client2.send("hello"));
  16896. std::string msg;
  16897. ASSERT_TRUE(client2.read(msg));
  16898. EXPECT_EQ("hello", msg);
  16899. client2.close();
  16900. svr.stop();
  16901. t.join();
  16902. }
  16903. TEST(WebSocketTest, QueryStringInHandshake) {
  16904. Server svr;
  16905. std::mutex mtx;
  16906. std::string received_target;
  16907. std::string received_token;
  16908. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16909. {
  16910. std::lock_guard<std::mutex> lock(mtx);
  16911. received_target = req.target;
  16912. if (req.has_param("token")) {
  16913. received_token = req.get_param_value("token");
  16914. }
  16915. }
  16916. std::string msg;
  16917. while (ws.read(msg)) {
  16918. ws.send(msg);
  16919. }
  16920. });
  16921. auto port = svr.bind_to_any_port("localhost");
  16922. std::thread t([&]() { svr.listen_after_bind(); });
  16923. svr.wait_until_ready();
  16924. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16925. "/ws?token=ABC&session=123");
  16926. ASSERT_TRUE(client.connect());
  16927. // Round-trip ensures the handler has run and captured the request.
  16928. ASSERT_TRUE(client.send("hello"));
  16929. std::string msg;
  16930. ASSERT_TRUE(client.read(msg));
  16931. EXPECT_EQ("hello", msg);
  16932. client.close();
  16933. {
  16934. std::lock_guard<std::mutex> lock(mtx);
  16935. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16936. EXPECT_EQ("ABC", received_token);
  16937. }
  16938. svr.stop();
  16939. t.join();
  16940. }
  16941. // Run a handshake against a throwaway server and hand the request the server
  16942. // received back to the caller, so tests can assert on the headers the client
  16943. // actually put on the wire.
  16944. static void capture_websocket_handshake_request(
  16945. const Headers &client_headers,
  16946. std::function<void(const Request &, int port)> verify) {
  16947. Server svr;
  16948. std::mutex mtx;
  16949. Request received;
  16950. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16951. {
  16952. std::lock_guard<std::mutex> lock(mtx);
  16953. received = req;
  16954. }
  16955. std::string msg;
  16956. while (ws.read(msg)) {
  16957. ws.send(msg);
  16958. }
  16959. });
  16960. auto port = svr.bind_to_any_port("localhost");
  16961. std::thread t([&]() { svr.listen_after_bind(); });
  16962. auto se = detail::scope_exit([&] {
  16963. svr.stop();
  16964. t.join();
  16965. });
  16966. svr.wait_until_ready();
  16967. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  16968. client_headers);
  16969. ASSERT_TRUE(client.connect());
  16970. ASSERT_TRUE(client.send("hello"));
  16971. std::string msg;
  16972. ASSERT_TRUE(client.read(msg));
  16973. client.close();
  16974. {
  16975. std::lock_guard<std::mutex> lock(mtx);
  16976. verify(received, port);
  16977. }
  16978. }
  16979. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  16980. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  16981. // Non-default port must be present in the Host header. Default ports
  16982. // (80/443) are omitted; that logic is covered by
  16983. // MakeHostAndPortStringTest.
  16984. EXPECT_EQ("localhost:" + std::to_string(port),
  16985. req.get_header_value("Host"));
  16986. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  16987. req.get_header_value("User-Agent"));
  16988. EXPECT_FALSE(req.has_header("Accept"));
  16989. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  16990. EXPECT_FALSE(req.has_header("Content-Length"));
  16991. });
  16992. }
  16993. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  16994. capture_websocket_handshake_request(
  16995. {{"Host", "example.com"},
  16996. {"User-Agent", "custom-agent"},
  16997. {"X-Custom", "value"}},
  16998. [](const Request &req, int) {
  16999. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17000. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17001. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17002. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17003. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17004. });
  17005. }
  17006. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17007. capture_websocket_handshake_request(
  17008. {{"Upgrade", "bogus"},
  17009. {"Connection", "close"},
  17010. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17011. {"Sec-WebSocket-Version", "8"}},
  17012. [](const Request &req, int) {
  17013. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17014. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17015. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17016. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17017. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17018. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17019. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17020. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17021. req.get_header_value("Sec-WebSocket-Key"));
  17022. });
  17023. }
  17024. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17025. // A header the client refuses to send must abort the handshake before any
  17026. // part of it reaches the wire; a lone request line would otherwise sit in
  17027. // the peer's buffer as a truncated request.
  17028. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17029. ASSERT_NE(INVALID_SOCKET, srv);
  17030. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17031. sockaddr_in addr{};
  17032. addr.sin_family = AF_INET;
  17033. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17034. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17035. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17036. ASSERT_EQ(0, ::listen(srv, 1));
  17037. sockaddr_in bound{};
  17038. socklen_t bound_len = sizeof(bound);
  17039. ASSERT_EQ(
  17040. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17041. auto port = ntohs(bound.sin_port);
  17042. ssize_t received = -1;
  17043. std::thread t([&] {
  17044. // Bound every blocking call so a regression fails the test with a bad
  17045. // value instead of hanging the suite.
  17046. fd_set rfds;
  17047. FD_ZERO(&rfds);
  17048. FD_SET(srv, &rfds);
  17049. timeval tv{5, 0};
  17050. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17051. 0) {
  17052. return;
  17053. }
  17054. sockaddr_in cli_addr{};
  17055. socklen_t cli_len = sizeof(cli_addr);
  17056. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17057. if (cli == INVALID_SOCKET) { return; }
  17058. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17059. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17060. char buf[4096];
  17061. received = ::recv(cli, buf, sizeof(buf), 0);
  17062. });
  17063. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17064. // connect() has already shut the socket down by the time it returns false,
  17065. // so the peer sees EOF without waiting for the client to be destroyed.
  17066. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17067. {{"X-Bad", "a\r\nInjected: 1"}});
  17068. EXPECT_FALSE(client.connect());
  17069. t.join();
  17070. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17071. EXPECT_EQ(0, received);
  17072. }
  17073. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17074. // The socket path doubles as the URL host, so it must not contain '/'.
  17075. const char *shard = getenv("GTEST_SHARD_INDEX");
  17076. const std::string sock_path =
  17077. shard ? std::string("httplib-ws-") + shard + ".sock"
  17078. : std::string("httplib-ws.sock");
  17079. std::remove(sock_path.c_str());
  17080. Server svr;
  17081. std::mutex mtx;
  17082. std::string received_host;
  17083. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17084. {
  17085. std::lock_guard<std::mutex> lock(mtx);
  17086. received_host = req.get_header_value("Host");
  17087. }
  17088. std::string msg;
  17089. while (ws.read(msg)) {
  17090. ws.send(msg);
  17091. }
  17092. });
  17093. svr.set_address_family(AF_UNIX);
  17094. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17095. auto se = detail::scope_exit([&] {
  17096. svr.stop();
  17097. t.join();
  17098. std::remove(sock_path.c_str());
  17099. });
  17100. svr.wait_until_ready();
  17101. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17102. client.set_address_family(AF_UNIX);
  17103. ASSERT_TRUE(client.connect());
  17104. ASSERT_TRUE(client.send("hello"));
  17105. std::string msg;
  17106. ASSERT_TRUE(client.read(msg));
  17107. client.close();
  17108. {
  17109. std::lock_guard<std::mutex> lock(mtx);
  17110. // There is no host:port for a Unix socket, so the same "localhost"
  17111. // placeholder the HTTP client uses is expected.
  17112. EXPECT_EQ("localhost", received_host);
  17113. }
  17114. }
  17115. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17116. class WebSocketSSLIntegrationTest : public ::testing::Test {
  17117. protected:
  17118. void SetUp() override {
  17119. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  17120. SERVER_PRIVATE_KEY_FILE);
  17121. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17122. std::string msg;
  17123. ws::ReadResult ret;
  17124. while ((ret = ws.read(msg))) {
  17125. if (ret == ws::Binary) {
  17126. ws.send(msg.data(), msg.size());
  17127. } else {
  17128. ws.send(msg);
  17129. }
  17130. }
  17131. });
  17132. port_ = server_->bind_to_any_port(HOST);
  17133. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17134. server_->wait_until_ready();
  17135. }
  17136. void TearDown() override {
  17137. server_->stop();
  17138. if (server_thread_.joinable()) { server_thread_.join(); }
  17139. }
  17140. std::unique_ptr<SSLServer> server_;
  17141. std::thread server_thread_;
  17142. int port_ = 0;
  17143. };
  17144. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17145. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17146. "/ws-echo");
  17147. client.enable_server_certificate_verification(false);
  17148. ASSERT_TRUE(client.connect());
  17149. ASSERT_TRUE(client.is_open());
  17150. ASSERT_TRUE(client.send("Hello WSS"));
  17151. std::string msg;
  17152. EXPECT_EQ(ws::Text, client.read(msg));
  17153. EXPECT_EQ("Hello WSS", msg);
  17154. client.close();
  17155. }
  17156. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17157. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17158. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17159. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17160. // client (without calling close() first) is the only path that runs
  17161. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17162. // bug exactly.
  17163. //
  17164. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17165. // when linked against an instrumented libssl; run under Valgrind to catch it
  17166. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17167. // suite (the freed session otherwise stalls on the close handshake) — this test
  17168. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17169. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17170. {
  17171. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17172. "/ws-echo");
  17173. client.enable_server_certificate_verification(false);
  17174. client.set_read_timeout(2, 0);
  17175. client.set_write_timeout(2, 0);
  17176. ASSERT_TRUE(client.connect());
  17177. ASSERT_TRUE(client.is_open());
  17178. ASSERT_TRUE(client.send("still open"));
  17179. // Intentionally do NOT call client.close(): leaving scope runs
  17180. // shutdown_and_close() with the WebSocket still open, which must send the
  17181. // close frame while the TLS session is still alive.
  17182. }
  17183. }
  17184. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17185. // shutdown_and_close() at the start of connect(), reproducing the same
  17186. // use-after-free within the test body rather than at scope exit. The second
  17187. // connect must succeed and echo, proving the close handshake ran over a live
  17188. // session. See the note above about memory-tool requirements.
  17189. TEST_F(WebSocketSSLIntegrationTest,
  17190. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17191. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17192. "/ws-echo");
  17193. client.enable_server_certificate_verification(false);
  17194. client.set_read_timeout(2, 0);
  17195. client.set_write_timeout(2, 0);
  17196. ASSERT_TRUE(client.connect());
  17197. ASSERT_TRUE(client.is_open());
  17198. ASSERT_TRUE(client.send("still open"));
  17199. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17200. // the still-open connection, which must not touch a freed TLS session.
  17201. ASSERT_TRUE(client.connect());
  17202. ASSERT_TRUE(client.is_open());
  17203. ASSERT_TRUE(client.send("after reconnect"));
  17204. std::string msg;
  17205. EXPECT_EQ(ws::Text, client.read(msg));
  17206. EXPECT_EQ("after reconnect", msg);
  17207. client.close();
  17208. }
  17209. #endif
  17210. #ifdef CPPHTTPLIB_SSL_ENABLED
  17211. class WebSocketSSLCATest : public ::testing::Test {
  17212. protected:
  17213. void SetUp() override {
  17214. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17215. SERVER_PRIVATE_KEY_FILE);
  17216. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17217. std::string msg;
  17218. while (ws.read(msg)) {
  17219. ws.send(msg);
  17220. }
  17221. });
  17222. port_ = server_->bind_to_any_port("127.0.0.1");
  17223. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17224. server_->wait_until_ready();
  17225. }
  17226. void TearDown() override {
  17227. server_->stop();
  17228. if (server_thread_.joinable()) { server_thread_.join(); }
  17229. }
  17230. std::string url() const {
  17231. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17232. }
  17233. std::unique_ptr<SSLServer> server_;
  17234. std::thread server_thread_;
  17235. int port_ = 0;
  17236. };
  17237. // A custom CA loaded as PEM verifies the server with full certificate
  17238. // verification enabled
  17239. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17240. ws::WebSocketClient client(url());
  17241. std::string cert;
  17242. read_file(SERVER_CERT2_FILE, cert);
  17243. client.load_ca_cert_store(cert.c_str(), cert.size());
  17244. ASSERT_TRUE(client.connect());
  17245. ASSERT_TRUE(client.send("hello"));
  17246. std::string msg;
  17247. EXPECT_EQ(ws::Text, client.read(msg));
  17248. EXPECT_EQ("hello", msg);
  17249. client.close();
  17250. }
  17251. // A custom CA that does not cover the server must fail verification (the
  17252. // custom CA is exclusive; system certs are not loaded alongside it)
  17253. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17254. ws::WebSocketClient client(url());
  17255. std::string cert;
  17256. read_file(CLIENT_CA_CERT_FILE, cert);
  17257. client.load_ca_cert_store(cert.c_str(), cert.size());
  17258. ASSERT_FALSE(client.connect());
  17259. }
  17260. // Regression test: reconnecting with a native custom CA store used to reuse
  17261. // a store handle the previous TLS context had already freed (use-after-free
  17262. // under the OpenSSL backend). The context now lives as long as the client.
  17263. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17264. ws::WebSocketClient client(url());
  17265. std::string cert;
  17266. read_file(SERVER_CERT2_FILE, cert);
  17267. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17268. ASSERT_TRUE(client.connect());
  17269. client.close();
  17270. ASSERT_TRUE(client.connect());
  17271. ASSERT_TRUE(client.send("again"));
  17272. std::string msg;
  17273. EXPECT_EQ(ws::Text, client.read(msg));
  17274. EXPECT_EQ("again", msg);
  17275. client.close();
  17276. }
  17277. // Regression test: a certificate with a trusted chain but no identity match
  17278. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17279. // verification entirely for IP hosts, so this connection succeeded there.
  17280. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17281. // chain verification while the identity check must still fail.
  17282. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17284. ASSERT_TRUE(svr.is_valid());
  17285. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17286. std::string msg;
  17287. while (ws.read(msg)) {
  17288. ws.send(msg);
  17289. }
  17290. });
  17291. auto port = svr.bind_to_any_port("127.0.0.1");
  17292. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17293. auto se = detail::scope_exit([&] {
  17294. svr.stop();
  17295. t.join();
  17296. });
  17297. svr.wait_until_ready();
  17298. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17299. "/echo");
  17300. std::string cert;
  17301. read_file(SERVER_CERT_FILE, cert);
  17302. client.load_ca_cert_store(cert.c_str(), cert.size());
  17303. ASSERT_FALSE(client.connect());
  17304. }
  17305. #endif
  17306. #if !defined(_WIN32)
  17307. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17308. auto secret_dir = std::string("./symlink_test_secret");
  17309. auto served_dir = std::string("./symlink_test_served");
  17310. auto secret_file = secret_dir + "/secret.txt";
  17311. auto symlink_path = served_dir + "/escape";
  17312. // Setup: create directories and files
  17313. mkdir(secret_dir.c_str(), 0755);
  17314. mkdir(served_dir.c_str(), 0755);
  17315. {
  17316. std::ofstream ofs(secret_file);
  17317. ofs << "SECRET_DATA";
  17318. }
  17319. // Create symlink using absolute path so it resolves correctly
  17320. #ifdef PATH_MAX
  17321. char abs_secret[PATH_MAX];
  17322. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17323. #else
  17324. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17325. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17326. ASSERT_NE(nullptr, abs_secret);
  17327. #endif
  17328. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17329. auto se = detail::scope_exit([&] {
  17330. unlink(symlink_path.c_str());
  17331. unlink(secret_file.c_str());
  17332. rmdir(served_dir.c_str());
  17333. rmdir(secret_dir.c_str());
  17334. });
  17335. Server svr;
  17336. svr.set_mount_point("/", served_dir);
  17337. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17338. auto se2 = detail::scope_exit([&] {
  17339. svr.stop();
  17340. listen_thread.join();
  17341. });
  17342. svr.wait_until_ready();
  17343. Client cli("localhost", PORT);
  17344. // Symlink pointing outside base dir should be blocked
  17345. auto res = cli.Get("/escape/secret.txt");
  17346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17347. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17348. }
  17349. #endif
  17350. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17351. // A GET request with Content-Length to a static file handler must have its
  17352. // body drained before the keep-alive connection is reused. Otherwise the
  17353. // unread body bytes are interpreted as the next HTTP request.
  17354. //
  17355. // The body is sent AFTER receiving the first response (as in the original
  17356. // PoC) so that the stream_line_reader cannot buffer it together with the
  17357. // headers of the first request.
  17358. Server svr;
  17359. svr.set_mount_point("/", "./www");
  17360. std::atomic<int> smuggled_count(0);
  17361. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17362. smuggled_count++;
  17363. res.set_content("oops", "text/plain");
  17364. });
  17365. auto port = svr.bind_to_any_port("localhost");
  17366. thread t = thread([&] { svr.listen_after_bind(); });
  17367. auto se = detail::scope_exit([&] {
  17368. svr.stop();
  17369. t.join();
  17370. });
  17371. svr.wait_until_ready();
  17372. auto error = Error::Success;
  17373. auto sock = detail::create_client_socket(
  17374. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17375. /*connection_timeout_sec=*/2, 0,
  17376. /*read_timeout_sec=*/2, 0,
  17377. /*write_timeout_sec=*/2, 0, std::string(), error);
  17378. ASSERT_NE(INVALID_SOCKET, sock);
  17379. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17380. // The "smuggled" request will be sent as the body of the outer GET
  17381. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17382. "Host: localhost\r\n"
  17383. "Connection: close\r\n"
  17384. "\r\n";
  17385. // Step 1: Send only the outer request headers (no body yet)
  17386. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17387. "Host: localhost\r\n"
  17388. "Content-Length: " +
  17389. std::to_string(smuggled.size()) +
  17390. "\r\n"
  17391. "\r\n";
  17392. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17393. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17394. // Step 2: Read the first response (server serves file without reading body)
  17395. std::string first_response;
  17396. char buf[4096];
  17397. for (;;) {
  17398. auto n = recv(sock, buf, sizeof(buf), 0);
  17399. if (n <= 0) break;
  17400. first_response.append(buf, static_cast<size_t>(n));
  17401. // Stop once we have a complete response (headers + body)
  17402. auto hdr_end = first_response.find("\r\n\r\n");
  17403. if (hdr_end != std::string::npos) {
  17404. // Check for Content-Length to know when the body is complete
  17405. auto cl_pos = first_response.find("Content-Length:");
  17406. if (cl_pos != std::string::npos) {
  17407. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17408. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17409. auto cl = std::stoul(
  17410. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17411. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17412. } else {
  17413. break; // No Content-Length, assume headers-only response
  17414. }
  17415. }
  17416. }
  17417. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17418. // Step 3: Now send the body, which looks like a new HTTP request.
  17419. // On a vulnerable server the keep-alive loop reads this as a second request.
  17420. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17421. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17422. // Step 4: Try to read a second response (should NOT exist after fix)
  17423. std::string second_response;
  17424. for (;;) {
  17425. auto n = recv(sock, buf, sizeof(buf), 0);
  17426. if (n <= 0) break;
  17427. second_response.append(buf, static_cast<size_t>(n));
  17428. }
  17429. // The smuggled request must NOT have been processed
  17430. EXPECT_EQ(0, smuggled_count.load());
  17431. }
  17432. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17433. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17434. // must be rejected with 400 Bad Request.
  17435. Server svr;
  17436. svr.Post("/test", [&](const Request &, Response &res) {
  17437. res.set_content("ok", "text/plain");
  17438. });
  17439. thread t = thread([&] { svr.listen(HOST, PORT); });
  17440. auto se = detail::scope_exit([&] {
  17441. svr.stop();
  17442. t.join();
  17443. ASSERT_FALSE(svr.is_running());
  17444. });
  17445. svr.wait_until_ready();
  17446. // Exact "chunked"
  17447. {
  17448. auto req = "POST /test HTTP/1.1\r\n"
  17449. "Host: localhost\r\n"
  17450. "Content-Length: 5\r\n"
  17451. "Transfer-Encoding: chunked\r\n"
  17452. "Connection: close\r\n"
  17453. "\r\n"
  17454. "hello";
  17455. std::string response;
  17456. ASSERT_TRUE(send_request(1, req, &response));
  17457. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17458. response.substr(0, response.find("\r\n")));
  17459. }
  17460. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17461. {
  17462. auto req = "POST /test HTTP/1.1\r\n"
  17463. "Host: localhost\r\n"
  17464. "Content-Length: 5\r\n"
  17465. "Transfer-Encoding: gzip, chunked\r\n"
  17466. "Connection: close\r\n"
  17467. "\r\n"
  17468. "hello";
  17469. std::string response;
  17470. ASSERT_TRUE(send_request(1, req, &response));
  17471. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17472. response.substr(0, response.find("\r\n")));
  17473. }
  17474. }
  17475. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  17476. Server svr;
  17477. svr.Post("/test", [&](const Request &, Response &res) {
  17478. res.set_content("ok", "text/plain");
  17479. });
  17480. thread t = thread([&] { svr.listen(HOST, PORT); });
  17481. auto se = detail::scope_exit([&] {
  17482. svr.stop();
  17483. t.join();
  17484. ASSERT_FALSE(svr.is_running());
  17485. });
  17486. svr.wait_until_ready();
  17487. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  17488. // length cannot be determined, so the server must answer 400 and close
  17489. // rather than treat the request as bodyless and leave the body in the
  17490. // socket for the next request to pick up.
  17491. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  17492. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  17493. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  17494. std::string response;
  17495. ASSERT_TRUE(send_request(1, req, &response));
  17496. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17497. response.substr(0, response.find("\r\n")))
  17498. << transfer_encoding;
  17499. }
  17500. // RFC 9110 5.3: the codings may also be split across several
  17501. // Transfer-Encoding lines, which combine in the order they were received.
  17502. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  17503. // just like the single-line "chunked, gzip" above.
  17504. {
  17505. auto req = "POST /test HTTP/1.1\r\n"
  17506. "Host: localhost\r\n"
  17507. "Transfer-Encoding: chunked\r\n"
  17508. "Transfer-Encoding: gzip\r\n"
  17509. "\r\n"
  17510. "0\r\n\r\n";
  17511. std::string response;
  17512. ASSERT_TRUE(send_request(1, req, &response));
  17513. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17514. response.substr(0, response.find("\r\n")));
  17515. }
  17516. // A sequence ending in chunked stays valid.
  17517. auto req = "POST /test HTTP/1.1\r\n"
  17518. "Host: localhost\r\n"
  17519. "Transfer-Encoding: gzip, chunked\r\n"
  17520. "Connection: close\r\n"
  17521. "\r\n"
  17522. "0\r\n\r\n";
  17523. std::string response;
  17524. ASSERT_TRUE(send_request(1, req, &response));
  17525. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17526. // ...including when it is spread over several lines.
  17527. auto split_req = "POST /test HTTP/1.1\r\n"
  17528. "Host: localhost\r\n"
  17529. "Transfer-Encoding: gzip\r\n"
  17530. "Transfer-Encoding: chunked\r\n"
  17531. "Connection: close\r\n"
  17532. "\r\n"
  17533. "0\r\n\r\n";
  17534. std::string split_response;
  17535. ASSERT_TRUE(send_request(1, split_req, &split_response));
  17536. EXPECT_EQ("HTTP/1.1 200 OK",
  17537. split_response.substr(0, split_response.find("\r\n")));
  17538. }
  17539. // Regression for issue #2450: a DELETE without Content-Length on a
  17540. // keep-alive connection must not let the post-response drain consume the
  17541. // next request's bytes.
  17542. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17543. Server svr;
  17544. std::atomic<int> delete_count(0);
  17545. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17546. delete_count++;
  17547. res.status = StatusCode::NoContent_204;
  17548. });
  17549. auto port = svr.bind_to_any_port(HOST);
  17550. thread t = thread([&] { svr.listen_after_bind(); });
  17551. auto se = detail::scope_exit([&] {
  17552. svr.stop();
  17553. t.join();
  17554. });
  17555. svr.wait_until_ready();
  17556. auto error = Error::Success;
  17557. auto sock = detail::create_client_socket(
  17558. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17559. /*connection_timeout_sec=*/2, 0,
  17560. /*read_timeout_sec=*/2, 0,
  17561. /*write_timeout_sec=*/2, 0, std::string(), error);
  17562. ASSERT_NE(INVALID_SOCKET, sock);
  17563. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17564. auto send_request_and_read_response = [&](const std::string &req,
  17565. std::string &out) -> bool {
  17566. auto sent = send(sock, req.data(), req.size(), 0);
  17567. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17568. char buf[4096];
  17569. for (;;) {
  17570. auto n = recv(sock, buf, sizeof(buf), 0);
  17571. if (n <= 0) { return !out.empty(); }
  17572. out.append(buf, static_cast<size_t>(n));
  17573. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17574. }
  17575. };
  17576. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17577. "Host: localhost\r\n"
  17578. "\r\n";
  17579. std::string resp1;
  17580. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17581. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17582. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17583. "Host: localhost\r\n"
  17584. "Connection: close\r\n"
  17585. "\r\n";
  17586. std::string resp2;
  17587. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17588. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17589. EXPECT_EQ(2, delete_count.load());
  17590. }
  17591. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17592. Server svr;
  17593. svr.Post("/ingest", [&](const Request &, Response &res,
  17594. const ContentReader &content_reader) {
  17595. auto consumed = content_reader([](const char *, size_t) { return false; });
  17596. EXPECT_FALSE(consumed);
  17597. res.status = StatusCode::Conflict_409;
  17598. res.set_header("Connection", "close");
  17599. });
  17600. auto port = svr.bind_to_any_port(HOST);
  17601. thread t = thread([&] { svr.listen_after_bind(); });
  17602. auto se = detail::scope_exit([&] {
  17603. svr.stop();
  17604. t.join();
  17605. });
  17606. svr.wait_until_ready();
  17607. auto error = Error::Success;
  17608. auto sock = detail::create_client_socket(
  17609. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17610. /*connection_timeout_sec=*/2, 0,
  17611. /*read_timeout_sec=*/1, 0,
  17612. /*write_timeout_sec=*/2, 0, std::string(), error);
  17613. ASSERT_NE(INVALID_SOCKET, sock);
  17614. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17615. std::string request = "POST /ingest HTTP/1.1\r\n"
  17616. "Host: localhost\r\n"
  17617. "Transfer-Encoding: chunked\r\n"
  17618. "\r\n"
  17619. "4\r\n"
  17620. "data\r\n";
  17621. auto sent = send(sock, request.data(), request.size(), 0);
  17622. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17623. std::string response;
  17624. ssize_t received = 0;
  17625. do {
  17626. char buf[4096];
  17627. received = recv(sock, buf, sizeof(buf), 0);
  17628. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17629. } while (received > 0);
  17630. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17631. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17632. EXPECT_EQ(0, received);
  17633. }
  17634. namespace no_proxy_test {
  17635. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17636. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17637. // calling listen().
  17638. class ScopedServer {
  17639. public:
  17640. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17641. ~ScopedServer() {
  17642. svr_.stop();
  17643. if (th_.joinable()) { th_.join(); }
  17644. }
  17645. Server &svr() { return svr_; }
  17646. int port() const { return port_; }
  17647. void listen() {
  17648. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17649. svr_.wait_until_ready();
  17650. }
  17651. private:
  17652. Server svr_;
  17653. std::thread th_;
  17654. int port_ = 0;
  17655. };
  17656. class ProxyAndTargetServers {
  17657. public:
  17658. ProxyAndTargetServers() {
  17659. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17660. proxy_hits_++;
  17661. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17662. res.set_content("via-proxy", "text/plain");
  17663. });
  17664. target_.Get(".*", [this](const Request &req, Response &res) {
  17665. target_hits_++;
  17666. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17667. res.set_content("direct", "text/plain");
  17668. });
  17669. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17670. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17671. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17672. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17673. proxy_mock_.wait_until_ready();
  17674. target_.wait_until_ready();
  17675. }
  17676. ~ProxyAndTargetServers() {
  17677. proxy_mock_.stop();
  17678. target_.stop();
  17679. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17680. if (target_thread_.joinable()) { target_thread_.join(); }
  17681. }
  17682. Server &proxy_mock() { return proxy_mock_; }
  17683. Server &target() { return target_; }
  17684. int proxy_port() const { return proxy_port_; }
  17685. int target_port() const { return target_port_; }
  17686. int proxy_hits() const { return proxy_hits_.load(); }
  17687. int target_hits() const { return target_hits_.load(); }
  17688. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17689. void reset_counters() {
  17690. proxy_hits_ = 0;
  17691. target_hits_ = 0;
  17692. last_had_proxy_authz_ = false;
  17693. }
  17694. private:
  17695. Server proxy_mock_;
  17696. Server target_;
  17697. std::thread proxy_thread_;
  17698. std::thread target_thread_;
  17699. int proxy_port_ = 0;
  17700. int target_port_ = 0;
  17701. std::atomic<int> proxy_hits_{0};
  17702. std::atomic<int> target_hits_{0};
  17703. std::atomic<bool> last_had_proxy_authz_{false};
  17704. };
  17705. inline std::unique_ptr<Client> make_client(const std::string &host,
  17706. ProxyAndTargetServers &s) {
  17707. auto cli = detail::make_unique<Client>(host, s.target_port());
  17708. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17709. cli->set_proxy("127.0.0.1", s.proxy_port());
  17710. return cli;
  17711. }
  17712. } // namespace no_proxy_test
  17713. using no_proxy_test::make_client;
  17714. using no_proxy_test::ProxyAndTargetServers;
  17715. TEST(NoProxyTest, ExactHostnameBypasses) {
  17716. ProxyAndTargetServers s;
  17717. auto cli = make_client("example.com", s);
  17718. cli->set_no_proxy({"example.com"});
  17719. auto res = cli->Get("/");
  17720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17721. EXPECT_EQ(0, s.proxy_hits());
  17722. EXPECT_EQ(1, s.target_hits());
  17723. }
  17724. TEST(NoProxyTest, SubdomainBypasses) {
  17725. ProxyAndTargetServers s;
  17726. auto cli = make_client("foo.example.com", s);
  17727. cli->set_no_proxy({"example.com"});
  17728. auto res = cli->Get("/");
  17729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17730. EXPECT_EQ(0, s.proxy_hits());
  17731. EXPECT_EQ(1, s.target_hits());
  17732. }
  17733. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17734. // Regression guard: "evilexample.com" must not be considered a subdomain
  17735. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17736. // check would let traffic bypass the proxy and leak credentials direct
  17737. // to the attacker host.
  17738. ProxyAndTargetServers s;
  17739. auto cli = make_client("evilexample.com", s);
  17740. cli->set_no_proxy({"example.com"});
  17741. auto res = cli->Get("/");
  17742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17743. EXPECT_GE(s.proxy_hits(), 1);
  17744. EXPECT_EQ(0, s.target_hits());
  17745. }
  17746. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17747. ProxyAndTargetServers s;
  17748. auto cli = make_client("example.com.evil.com", s);
  17749. cli->set_no_proxy({"example.com"});
  17750. auto res = cli->Get("/");
  17751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17752. EXPECT_GE(s.proxy_hits(), 1);
  17753. EXPECT_EQ(0, s.target_hits());
  17754. }
  17755. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17756. ProxyAndTargetServers s;
  17757. auto cli = make_client("example.com", s);
  17758. cli->set_no_proxy({".example.com"});
  17759. auto res = cli->Get("/");
  17760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17761. EXPECT_EQ(0, s.proxy_hits());
  17762. EXPECT_EQ(1, s.target_hits());
  17763. }
  17764. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17765. ProxyAndTargetServers s;
  17766. auto cli = make_client("Example.COM", s);
  17767. cli->set_no_proxy({"EXAMPLE.com"});
  17768. auto res = cli->Get("/");
  17769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17770. EXPECT_EQ(0, s.proxy_hits());
  17771. EXPECT_EQ(1, s.target_hits());
  17772. }
  17773. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17774. ProxyAndTargetServers s;
  17775. auto cli = make_client("example.com.", s);
  17776. cli->set_no_proxy({"example.com"});
  17777. auto res = cli->Get("/");
  17778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17779. EXPECT_EQ(0, s.proxy_hits());
  17780. EXPECT_EQ(1, s.target_hits());
  17781. }
  17782. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17783. // Trailing dots must be normalized on BOTH sides — host and entry.
  17784. // An implementation that only strips the host-side trailing dot would
  17785. // fail to match host "example.com" against entry "example.com." because
  17786. // a literal substring search would compare 11 chars against 12.
  17787. ProxyAndTargetServers s;
  17788. auto cli = make_client("example.com", s);
  17789. cli->set_no_proxy({"example.com."});
  17790. auto res = cli->Get("/");
  17791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17792. EXPECT_EQ(0, s.proxy_hits());
  17793. EXPECT_EQ(1, s.target_hits());
  17794. }
  17795. TEST(NoProxyTest, WildcardBypassesEverything) {
  17796. ProxyAndTargetServers s;
  17797. auto cli = make_client("anything.invalid.test", s);
  17798. cli->set_no_proxy({"*"});
  17799. auto res = cli->Get("/");
  17800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17801. EXPECT_EQ(0, s.proxy_hits());
  17802. EXPECT_EQ(1, s.target_hits());
  17803. }
  17804. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17805. ProxyAndTargetServers s;
  17806. Client cli("127.0.0.1", s.target_port());
  17807. cli.set_proxy("127.0.0.1", s.proxy_port());
  17808. cli.set_no_proxy({"127.0.0.1"});
  17809. auto res = cli.Get("/");
  17810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17811. EXPECT_EQ(0, s.proxy_hits());
  17812. EXPECT_EQ(1, s.target_hits());
  17813. }
  17814. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17815. ProxyAndTargetServers s;
  17816. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17817. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17818. cli.set_proxy("127.0.0.1", s.proxy_port());
  17819. cli.set_no_proxy({"::1"});
  17820. auto res = cli.Get("/");
  17821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17822. EXPECT_EQ(0, s.proxy_hits());
  17823. EXPECT_EQ(1, s.target_hits());
  17824. }
  17825. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17826. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17827. // must still be recognized as IPv6 for CIDR matching. Implementations
  17828. // that detect IPv6 only when the host begins with '[' would parse the
  17829. // host as a hostname and miss the match.
  17830. ProxyAndTargetServers s;
  17831. Client cli("fe80::1", s.target_port());
  17832. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17833. cli.set_proxy("127.0.0.1", s.proxy_port());
  17834. cli.set_no_proxy({"fe80::/10"});
  17835. auto res = cli.Get("/");
  17836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17837. EXPECT_EQ(0, s.proxy_hits());
  17838. EXPECT_EQ(1, s.target_hits());
  17839. }
  17840. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17841. ProxyAndTargetServers s;
  17842. Client cli("::1", s.target_port());
  17843. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17844. cli.set_proxy("127.0.0.1", s.proxy_port());
  17845. cli.set_no_proxy({"[::1]"});
  17846. auto res = cli.Get("/");
  17847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17848. EXPECT_EQ(0, s.proxy_hits());
  17849. EXPECT_EQ(1, s.target_hits());
  17850. }
  17851. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17852. ProxyAndTargetServers s;
  17853. Client cli("fe80::1", s.target_port());
  17854. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17855. cli.set_proxy("127.0.0.1", s.proxy_port());
  17856. cli.set_no_proxy({"[fe80::]/10"});
  17857. auto res = cli.Get("/");
  17858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17859. EXPECT_EQ(0, s.proxy_hits());
  17860. EXPECT_EQ(1, s.target_hits());
  17861. }
  17862. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17863. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17864. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17865. // tricks via address-family conversion.
  17866. ProxyAndTargetServers s;
  17867. Client cli("::ffff:127.0.0.1", s.target_port());
  17868. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17869. cli.set_proxy("127.0.0.1", s.proxy_port());
  17870. cli.set_no_proxy({"127.0.0.1"});
  17871. auto res = cli.Get("/");
  17872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17873. EXPECT_GE(s.proxy_hits(), 1);
  17874. EXPECT_EQ(0, s.target_hits());
  17875. }
  17876. TEST(NoProxyTest, IPv4CidrMatch) {
  17877. ProxyAndTargetServers s;
  17878. Client cli("127.0.0.1", s.target_port());
  17879. cli.set_proxy("127.0.0.1", s.proxy_port());
  17880. cli.set_no_proxy({"127.0.0.0/8"});
  17881. auto res = cli.Get("/");
  17882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17883. EXPECT_EQ(0, s.proxy_hits());
  17884. EXPECT_EQ(1, s.target_hits());
  17885. }
  17886. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17887. ProxyAndTargetServers s;
  17888. Client cli("127.0.0.1", s.target_port());
  17889. cli.set_proxy("127.0.0.1", s.proxy_port());
  17890. cli.set_no_proxy({"10.0.0.0/8"});
  17891. auto res = cli.Get("/");
  17892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17893. EXPECT_GE(s.proxy_hits(), 1);
  17894. EXPECT_EQ(0, s.target_hits());
  17895. }
  17896. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17897. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17898. // IPv4 target matches.
  17899. ProxyAndTargetServers s;
  17900. Client cli("127.0.0.1", s.target_port());
  17901. cli.set_proxy("127.0.0.1", s.proxy_port());
  17902. cli.set_no_proxy({"0.0.0.0/0"});
  17903. auto res = cli.Get("/");
  17904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17905. EXPECT_EQ(0, s.proxy_hits());
  17906. EXPECT_EQ(1, s.target_hits());
  17907. }
  17908. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17909. ProxyAndTargetServers s;
  17910. Client cli("127.0.0.1", s.target_port());
  17911. cli.set_proxy("127.0.0.1", s.proxy_port());
  17912. cli.set_no_proxy({"127.0.0.1"});
  17913. auto res = cli.Get("/");
  17914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17915. EXPECT_EQ(0, s.proxy_hits());
  17916. EXPECT_EQ(1, s.target_hits());
  17917. }
  17918. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17919. ProxyAndTargetServers s;
  17920. Client cli("127.0.0.1", s.target_port());
  17921. cli.set_proxy("127.0.0.1", s.proxy_port());
  17922. cli.set_no_proxy({"127.0.0.0/33"});
  17923. auto res = cli.Get("/");
  17924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17925. EXPECT_GE(s.proxy_hits(), 1);
  17926. EXPECT_EQ(0, s.target_hits());
  17927. }
  17928. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17929. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17930. ProxyAndTargetServers s;
  17931. Client cli("127.0.0.1", s.target_port());
  17932. cli.set_proxy("127.0.0.1", s.proxy_port());
  17933. cli.set_no_proxy({"127.0.0.1/"});
  17934. auto res = cli.Get("/");
  17935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17936. EXPECT_GE(s.proxy_hits(), 1);
  17937. EXPECT_EQ(0, s.target_hits());
  17938. }
  17939. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17940. ProxyAndTargetServers s;
  17941. auto cli = make_client("internal.corp", s);
  17942. cli->set_proxy_basic_auth("u", "p");
  17943. cli->set_no_proxy({"internal.corp"});
  17944. auto res = cli->Get("/");
  17945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17946. EXPECT_EQ(1, s.target_hits());
  17947. EXPECT_EQ(0, s.proxy_hits());
  17948. EXPECT_FALSE(s.last_had_proxy_authz())
  17949. << "Proxy-Authorization must not be sent direct to the target";
  17950. }
  17951. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17952. ProxyAndTargetServers s;
  17953. auto cli = make_client("public.example", s);
  17954. cli->set_proxy_basic_auth("u", "p");
  17955. cli->set_no_proxy({"internal.corp"}); // does not match
  17956. auto res = cli->Get("/");
  17957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17958. EXPECT_GE(s.proxy_hits(), 1);
  17959. EXPECT_TRUE(s.last_had_proxy_authz());
  17960. }
  17961. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17962. ProxyAndTargetServers s;
  17963. auto cli = make_client("anything.test", s);
  17964. auto res = cli->Get("/");
  17965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17966. EXPECT_GE(s.proxy_hits(), 1);
  17967. EXPECT_EQ(0, s.target_hits());
  17968. }
  17969. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17970. ProxyAndTargetServers s;
  17971. auto cli = make_client("example.com", s);
  17972. cli->set_no_proxy({"example.com:8080"});
  17973. auto res = cli->Get("/");
  17974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17975. EXPECT_GE(s.proxy_hits(), 1);
  17976. EXPECT_EQ(0, s.target_hits());
  17977. }
  17978. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17979. ProxyAndTargetServers s;
  17980. auto cli = make_client("anything.test", s);
  17981. cli->set_no_proxy({"", " ", "\t"});
  17982. auto res = cli->Get("/");
  17983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17984. EXPECT_GE(s.proxy_hits(), 1);
  17985. EXPECT_EQ(0, s.target_hits());
  17986. }
  17987. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17988. // An entry with leading/trailing whitespace must still match — env-style
  17989. // values are commonly pasted with stray spaces and an implementation
  17990. // that feeds the raw token directly to inet_pton would fail to match
  17991. // valid CIDRs because of the spaces.
  17992. ProxyAndTargetServers s;
  17993. Client cli("127.0.0.1", s.target_port());
  17994. cli.set_proxy("127.0.0.1", s.proxy_port());
  17995. cli.set_no_proxy({" 127.0.0.0/8 "});
  17996. auto res = cli.Get("/");
  17997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17998. EXPECT_EQ(0, s.proxy_hits());
  17999. EXPECT_EQ(1, s.target_hits());
  18000. }
  18001. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  18002. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  18003. // go direct and must NOT carry Proxy-Authorization.
  18004. std::atomic<int> proxy_hits{0};
  18005. std::atomic<int> target_hits{0};
  18006. std::atomic<bool> target_saw_authz{false};
  18007. no_proxy_test::ScopedServer proxy_mock, target;
  18008. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18009. proxy_hits++;
  18010. res.status = 302;
  18011. res.set_header("Location", "http://127.0.0.1:" +
  18012. std::to_string(target.port()) + "/landed");
  18013. });
  18014. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18015. target_hits++;
  18016. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  18017. res.set_content("direct", "text/plain");
  18018. });
  18019. proxy_mock.listen();
  18020. target.listen();
  18021. Client cli("public.example", target.port());
  18022. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18023. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18024. cli.set_proxy_basic_auth("u", "p");
  18025. cli.set_no_proxy({"127.0.0.1"});
  18026. cli.set_follow_location(true);
  18027. auto res = cli.Get("/redir");
  18028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18029. EXPECT_GE(proxy_hits.load(), 1);
  18030. EXPECT_GE(target_hits.load(), 1);
  18031. EXPECT_FALSE(target_saw_authz.load());
  18032. }
  18033. #ifdef CPPHTTPLIB_SSL_ENABLED
  18034. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  18035. // Direct origin replying 407 must not trigger the digest retry; otherwise
  18036. // proxy creds would be sent to the (possibly hostile) origin.
  18037. std::atomic<int> target_hits{0};
  18038. std::atomic<bool> target_saw_proxy_authz{false};
  18039. no_proxy_test::ScopedServer target;
  18040. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18041. target_hits++;
  18042. if (req.has_header("Proxy-Authorization")) {
  18043. target_saw_proxy_authz = true;
  18044. }
  18045. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18046. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  18047. "nonce=\"abc\", algorithm=MD5");
  18048. });
  18049. target.listen();
  18050. // The proxy address is set to the target's port: the bypass MUST kick in;
  18051. // if it doesn't, the test still routes "via proxy" to the same server and
  18052. // the Proxy-Authorization assertion below catches the leak.
  18053. Client cli("evil.example", target.port());
  18054. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  18055. cli.set_proxy("127.0.0.1", target.port());
  18056. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18057. cli.set_no_proxy({"evil.example"});
  18058. auto res = cli.Get("/x");
  18059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18060. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18061. EXPECT_EQ(1, target_hits.load());
  18062. EXPECT_FALSE(target_saw_proxy_authz.load());
  18063. }
  18064. #endif
  18065. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  18066. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  18067. std::atomic<int> proxy_hits{0};
  18068. std::atomic<int> bypass_hits{0};
  18069. std::atomic<bool> proxy_saw_c_url{false};
  18070. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  18071. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  18072. proxy_hits++;
  18073. if (req.path.find("/start") != std::string::npos) {
  18074. res.status = 302;
  18075. res.set_header("Location", "http://127.0.0.1:" +
  18076. std::to_string(bypass_server.port()) +
  18077. "/middle");
  18078. return;
  18079. }
  18080. if (req.path.find("/end") != std::string::npos) {
  18081. proxy_saw_c_url = true;
  18082. res.set_content("c-via-proxy", "text/plain");
  18083. return;
  18084. }
  18085. res.set_content("unexpected", "text/plain");
  18086. });
  18087. // public.example's "advertised" port is arbitrary (the request never lands
  18088. // there — it goes through the proxy), but use a dynamic value to stay
  18089. // friendly with sharded parallel runs.
  18090. int public_port = bypass_server.port();
  18091. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  18092. bypass_hits++;
  18093. res.status = 302;
  18094. res.set_header("Location", "http://public.example:" +
  18095. std::to_string(public_port) + "/end");
  18096. });
  18097. proxy_mock.listen();
  18098. bypass_server.listen();
  18099. Client cli("public.example", public_port);
  18100. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18101. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18102. cli.set_no_proxy({"127.0.0.1"});
  18103. cli.set_follow_location(true);
  18104. auto res = cli.Get("/start");
  18105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18106. EXPECT_EQ(StatusCode::OK_200, res->status);
  18107. EXPECT_EQ("c-via-proxy", res->body);
  18108. EXPECT_GE(proxy_hits.load(), 2);
  18109. EXPECT_GE(bypass_hits.load(), 1);
  18110. EXPECT_TRUE(proxy_saw_c_url.load());
  18111. }
  18112. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  18113. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  18114. // request reconnects to the correct endpoint.
  18115. std::atomic<int> proxy_hits{0};
  18116. std::atomic<int> target_hits{0};
  18117. no_proxy_test::ScopedServer proxy_mock, target;
  18118. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18119. proxy_hits++;
  18120. res.set_content("via-proxy", "text/plain");
  18121. });
  18122. target.svr().Get(".*", [&](const Request &, Response &res) {
  18123. target_hits++;
  18124. res.set_content("direct", "text/plain");
  18125. });
  18126. proxy_mock.listen();
  18127. target.listen();
  18128. Client cli("public.example", target.port());
  18129. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18130. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18131. cli.set_keep_alive(true);
  18132. auto res1 = cli.Get("/a");
  18133. ASSERT_TRUE(res1);
  18134. EXPECT_EQ("via-proxy", res1->body);
  18135. EXPECT_EQ(1, proxy_hits.load());
  18136. EXPECT_EQ(0, target_hits.load());
  18137. cli.set_no_proxy({"public.example"});
  18138. auto res2 = cli.Get("/b");
  18139. ASSERT_TRUE(res2);
  18140. EXPECT_EQ("direct", res2->body);
  18141. EXPECT_EQ(1, proxy_hits.load());
  18142. EXPECT_EQ(1, target_hits.load());
  18143. }
  18144. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  18145. namespace proxy_tunnel_test {
  18146. // SSLServer counterpart to no_proxy_test::ScopedServer.
  18147. class ScopedSSLServer {
  18148. public:
  18149. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  18150. port_ = svr_.bind_to_any_port("127.0.0.1");
  18151. }
  18152. ~ScopedSSLServer() {
  18153. svr_.stop();
  18154. if (th_.joinable()) { th_.join(); }
  18155. }
  18156. SSLServer &svr() { return svr_; }
  18157. int port() const { return port_; }
  18158. void listen() {
  18159. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18160. svr_.wait_until_ready();
  18161. }
  18162. private:
  18163. SSLServer svr_;
  18164. std::thread th_;
  18165. int port_ = 0;
  18166. };
  18167. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  18168. class ScopedConnectProxy {
  18169. public:
  18170. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  18171. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  18172. if (listen_fd_ < 0) { return; }
  18173. int yes = 1;
  18174. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  18175. sockaddr_in a{};
  18176. a.sin_family = AF_INET;
  18177. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18178. a.sin_port = 0;
  18179. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  18180. return;
  18181. }
  18182. socklen_t alen = sizeof(a);
  18183. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  18184. 0) {
  18185. return;
  18186. }
  18187. port_ = ntohs(a.sin_port);
  18188. if (::listen(listen_fd_, 1) != 0) { return; }
  18189. th_ = std::thread([this] { run(); });
  18190. }
  18191. ~ScopedConnectProxy() {
  18192. stop_ = true;
  18193. if (listen_fd_ >= 0) {
  18194. ::shutdown(listen_fd_, SHUT_RDWR);
  18195. ::close(listen_fd_);
  18196. }
  18197. if (th_.joinable()) { th_.join(); }
  18198. }
  18199. int port() const { return port_; }
  18200. int connect_hits() const { return connect_hits_.load(); }
  18201. private:
  18202. void run() {
  18203. while (!stop_.load()) {
  18204. fd_set rfds;
  18205. FD_ZERO(&rfds);
  18206. FD_SET(listen_fd_, &rfds);
  18207. timeval tv{0, 100 * 1000};
  18208. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18209. if (sel <= 0) { continue; }
  18210. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18211. if (client_fd < 0) { continue; }
  18212. std::string req;
  18213. char buf[2048];
  18214. while (req.find("\r\n\r\n") == std::string::npos) {
  18215. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18216. if (n <= 0) { break; }
  18217. req.append(buf, static_cast<size_t>(n));
  18218. }
  18219. if (req.compare(0, 7, "CONNECT") != 0) {
  18220. ::close(client_fd);
  18221. continue;
  18222. }
  18223. connect_hits_++;
  18224. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18225. ::send(client_fd, ok, std::strlen(ok), 0);
  18226. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18227. sockaddr_in o{};
  18228. o.sin_family = AF_INET;
  18229. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18230. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18231. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18232. 0) {
  18233. ::close(client_fd);
  18234. ::close(origin_fd);
  18235. continue;
  18236. }
  18237. auto forward = [](int from, int to) {
  18238. char b[8192];
  18239. for (;;) {
  18240. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18241. if (n <= 0) { break; }
  18242. ssize_t off = 0;
  18243. while (off < n) {
  18244. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18245. if (s <= 0) {
  18246. off = n;
  18247. break;
  18248. }
  18249. off += s;
  18250. }
  18251. }
  18252. ::shutdown(to, SHUT_WR);
  18253. };
  18254. std::thread t1([&] { forward(client_fd, origin_fd); });
  18255. std::thread t2([&] { forward(origin_fd, client_fd); });
  18256. t1.join();
  18257. t2.join();
  18258. ::close(client_fd);
  18259. ::close(origin_fd);
  18260. }
  18261. }
  18262. int forward_port_ = -1;
  18263. int listen_fd_ = -1;
  18264. int port_ = 0;
  18265. std::thread th_;
  18266. std::atomic<bool> stop_{false};
  18267. std::atomic<int> connect_hits_{0};
  18268. };
  18269. } // namespace proxy_tunnel_test
  18270. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18271. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18272. // retry; otherwise proxy creds would be sent to the origin.
  18273. std::atomic<int> origin_hits{0};
  18274. std::atomic<bool> origin_saw_proxy_authz{false};
  18275. proxy_tunnel_test::ScopedSSLServer origin;
  18276. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18277. origin_hits++;
  18278. if (req.has_header("Proxy-Authorization")) {
  18279. origin_saw_proxy_authz = true;
  18280. }
  18281. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18282. res.set_header("Proxy-Authenticate",
  18283. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18284. "algorithm=MD5");
  18285. });
  18286. origin.listen();
  18287. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18288. ASSERT_NE(0, proxy.port());
  18289. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18290. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18291. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18292. // and answer with its own status, making this test flaky.
  18293. SSLClient cli("127.0.0.1", origin.port());
  18294. cli.enable_server_certificate_verification(false);
  18295. cli.set_proxy("127.0.0.1", proxy.port());
  18296. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18297. auto res = cli.Get("/x");
  18298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18299. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18300. EXPECT_EQ(1, origin_hits.load());
  18301. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18302. EXPECT_EQ(1, proxy.connect_hits());
  18303. }
  18304. #endif