test.cc 853 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423
  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. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // A valid numeric prefix does not make the entire quality value valid.
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=0.5junk,application/json", result));
  894. // Empty quality value
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("text/html;q=,application/json", result));
  897. // Invalid media type format (no slash and not wildcard)
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("invalidtype,application/json", result));
  900. // Valid cases should still work
  901. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*/*");
  904. EXPECT_TRUE(detail::parse_accept_header("*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*");
  907. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "text/*");
  910. }
  911. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  912. // elements, so a leading, trailing or doubled comma is a legal Accept value
  913. // and must not be answered with 400 Bad Request.
  914. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  915. struct {
  916. const char *value;
  917. std::vector<std::string> expected;
  918. } cases[] = {
  919. {",application/json", {"application/json"}},
  920. {"text/html,", {"text/html"}},
  921. {"text/html,,*/*", {"text/html", "*/*"}},
  922. // An empty element may be spelled with whitespace in it
  923. {"text/html, , application/json", {"text/html", "application/json"}},
  924. // Nothing but empty elements is an empty list, which means the same
  925. // thing as no Accept header at all
  926. {",,,", {}},
  927. // Quality values still apply across ignored empty elements
  928. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  929. };
  930. for (const auto &c : cases) {
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  933. << "value: " << c.value;
  934. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  935. }
  936. // An invalid entry is still rejected when empty elements surround it
  937. std::vector<std::string> result;
  938. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  939. }
  940. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  941. Server svr;
  942. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  943. EXPECT_EQ(req.accept_content_types.size(), 3U);
  944. EXPECT_EQ(req.accept_content_types[0], "application/json");
  945. EXPECT_EQ(req.accept_content_types[1], "text/html");
  946. EXPECT_EQ(req.accept_content_types[2], "*/*");
  947. res.set_content("ok", "text/plain");
  948. });
  949. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  950. EXPECT_TRUE(false);
  951. res.set_content("bad request", "text/plain");
  952. });
  953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  954. auto se = detail::scope_exit([&] {
  955. svr.stop();
  956. listen_thread.join();
  957. ASSERT_FALSE(svr.is_running());
  958. });
  959. svr.wait_until_ready();
  960. Client cli("localhost", PORT);
  961. {
  962. auto res = cli.Get(
  963. "/accept_ok",
  964. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  966. EXPECT_EQ(StatusCode::OK_200, res->status);
  967. }
  968. {
  969. auto res = cli.Get("/accept_bad_request",
  970. Headers{{"Accept", "text/html;q=abc,application/json"}});
  971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  972. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  973. }
  974. }
  975. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  976. Server svr;
  977. svr.Get("/", [](const Request & /*req*/, Response &res) {
  978. res.set_content("ok", "text/plain");
  979. });
  980. std::atomic<int> start_count{0};
  981. std::atomic<bool> running_when_called{false};
  982. svr.set_start_handler([&]() {
  983. running_when_called = svr.is_running();
  984. start_count++;
  985. });
  986. auto port = svr.bind_to_any_port(HOST);
  987. std::thread t([&]() { svr.listen_after_bind(); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. t.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. // A successful request proves the accept loop is running, which the start
  995. // handler precedes; so by now the handler must have run exactly once.
  996. Client cli(HOST, port);
  997. cli.set_connection_timeout(std::chrono::seconds(5));
  998. auto res = cli.Get("/");
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. EXPECT_EQ(1, start_count.load());
  1002. EXPECT_TRUE(running_when_called.load());
  1003. }
  1004. TEST(DivideTest, DivideStringTests) {
  1005. auto divide = [](const std::string &str, char d) {
  1006. std::string lhs;
  1007. std::string rhs;
  1008. detail::divide(str, d,
  1009. [&](const char *lhs_data, std::size_t lhs_size,
  1010. const char *rhs_data, std::size_t rhs_size) {
  1011. lhs.assign(lhs_data, lhs_size);
  1012. rhs.assign(rhs_data, rhs_size);
  1013. });
  1014. return std::make_pair(std::move(lhs), std::move(rhs));
  1015. };
  1016. {
  1017. const auto res = divide("", '=');
  1018. EXPECT_EQ(res.first, "");
  1019. EXPECT_EQ(res.second, "");
  1020. }
  1021. {
  1022. const auto res = divide("=", '=');
  1023. EXPECT_EQ(res.first, "");
  1024. EXPECT_EQ(res.second, "");
  1025. }
  1026. {
  1027. const auto res = divide(" ", '=');
  1028. EXPECT_EQ(res.first, " ");
  1029. EXPECT_EQ(res.second, "");
  1030. }
  1031. {
  1032. const auto res = divide("a", '=');
  1033. EXPECT_EQ(res.first, "a");
  1034. EXPECT_EQ(res.second, "");
  1035. }
  1036. {
  1037. const auto res = divide("a=", '=');
  1038. EXPECT_EQ(res.first, "a");
  1039. EXPECT_EQ(res.second, "");
  1040. }
  1041. {
  1042. const auto res = divide("=b", '=');
  1043. EXPECT_EQ(res.first, "");
  1044. EXPECT_EQ(res.second, "b");
  1045. }
  1046. {
  1047. const auto res = divide("a=b", '=');
  1048. EXPECT_EQ(res.first, "a");
  1049. EXPECT_EQ(res.second, "b");
  1050. }
  1051. {
  1052. const auto res = divide("a=b=", '=');
  1053. EXPECT_EQ(res.first, "a");
  1054. EXPECT_EQ(res.second, "b=");
  1055. }
  1056. {
  1057. const auto res = divide("a=b=c", '=');
  1058. EXPECT_EQ(res.first, "a");
  1059. EXPECT_EQ(res.second, "b=c");
  1060. }
  1061. }
  1062. TEST(SplitTest, ParseQueryString) {
  1063. string s = "key1=val1&key2=val2&key3=val3";
  1064. Params dic;
  1065. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1066. [&](const char *b, const char *e) {
  1067. string key, val;
  1068. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1069. if (key.empty()) {
  1070. key.assign(b2, e2);
  1071. } else {
  1072. val.assign(b2, e2);
  1073. }
  1074. });
  1075. dic.emplace(key, val);
  1076. });
  1077. EXPECT_EQ("val1", dic.find("key1")->second);
  1078. EXPECT_EQ("val2", dic.find("key2")->second);
  1079. EXPECT_EQ("val3", dic.find("key3")->second);
  1080. }
  1081. TEST(SplitTest, ParseInvalidQueryTests) {
  1082. {
  1083. string s = " ";
  1084. Params dict;
  1085. detail::parse_query_text(s, dict);
  1086. EXPECT_TRUE(dict.empty());
  1087. }
  1088. {
  1089. string s = " = =";
  1090. Params dict;
  1091. detail::parse_query_text(s, dict);
  1092. EXPECT_TRUE(dict.empty());
  1093. }
  1094. }
  1095. TEST(ParseQueryTest, ParseQueryString) {
  1096. {
  1097. std::string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::parse_query_text(s, dic);
  1100. EXPECT_EQ("val1", dic.find("key1")->second);
  1101. EXPECT_EQ("val2", dic.find("key2")->second);
  1102. EXPECT_EQ("val3", dic.find("key3")->second);
  1103. }
  1104. {
  1105. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1106. Params dic;
  1107. detail::parse_query_text(s, dic);
  1108. EXPECT_EQ("", dic.find("key1")->second);
  1109. EXPECT_EQ("val1", dic.find("key2")->second);
  1110. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1111. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1112. }
  1113. }
  1114. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1115. Params dic;
  1116. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1117. dic.emplace("key1", "val1");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1119. dic.emplace("key2", "val2");
  1120. dic.emplace("key3", "val3");
  1121. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1122. }
  1123. // Joins every entry of a Headers or Params into "key=value " so a whole
  1124. // traversal can be compared in one assertion. Both are instantiations of the
  1125. // same insertion-ordered container, so one helper serves both.
  1126. template <typename Map> static std::string entries_to_string(const Map &m) {
  1127. std::string s;
  1128. for (const auto &entry : m) {
  1129. s += entry.first + "=" + entry.second + " ";
  1130. }
  1131. return s;
  1132. }
  1133. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1134. // Params used to be a std::multimap, which sorted by name and handed the
  1135. // caller's query back alphabetised. A client signing its query string could
  1136. // not reproduce the order it asked for.
  1137. Params dic;
  1138. dic.emplace("zulu", "1");
  1139. dic.emplace("alpha", "2");
  1140. dic.emplace("mike", "3");
  1141. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1142. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1143. }
  1144. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1145. Params dic;
  1146. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1147. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1148. }
  1149. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1150. Request req;
  1151. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1152. req.params);
  1153. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1154. EXPECT_EQ("first", req.get_param_value("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1156. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1157. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1158. EXPECT_EQ("", req.get_param_value("tag", 3));
  1159. }
  1160. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1161. // Params shares its container with Headers, which matches field names
  1162. // case-insensitively. Parameter names must not pick that up.
  1163. Params dic;
  1164. dic.emplace("Key", "upper");
  1165. dic.emplace("key", "lower");
  1166. EXPECT_EQ(2U, dic.size());
  1167. EXPECT_EQ(1U, dic.count("Key"));
  1168. EXPECT_EQ(1U, dic.count("key"));
  1169. EXPECT_EQ("upper", dic.find("Key")->second);
  1170. EXPECT_EQ("lower", dic.find("key")->second);
  1171. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1172. }
  1173. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1174. Server svr;
  1175. std::string order;
  1176. svr.Get("/order", [&](const Request &req, Response &res) {
  1177. order = entries_to_string(req.params);
  1178. res.set_content("ok", "text/plain");
  1179. });
  1180. auto port = svr.bind_to_any_port(HOST);
  1181. thread t = thread([&] { svr.listen_after_bind(); });
  1182. auto se = detail::scope_exit([&] {
  1183. svr.stop();
  1184. t.join();
  1185. ASSERT_FALSE(svr.is_running());
  1186. });
  1187. svr.wait_until_ready();
  1188. Client cli(HOST, port);
  1189. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1190. ASSERT_TRUE(res);
  1191. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1192. }
  1193. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1194. Server svr;
  1195. std::string field_order, file_order;
  1196. svr.Post("/order", [&](const Request &req, Response &res) {
  1197. for (const auto &field : req.form.fields) {
  1198. field_order += field.first + "=" + field.second.content + " ";
  1199. }
  1200. for (const auto &file : req.form.files) {
  1201. file_order += file.first + "=" + file.second.filename + " ";
  1202. }
  1203. res.set_content("ok", "text/plain");
  1204. });
  1205. auto port = svr.bind_to_any_port(HOST);
  1206. thread t = thread([&] { svr.listen_after_bind(); });
  1207. auto se = detail::scope_exit([&] {
  1208. svr.stop();
  1209. t.join();
  1210. ASSERT_FALSE(svr.is_running());
  1211. });
  1212. svr.wait_until_ready();
  1213. UploadFormDataItems items = {
  1214. {"zulu", "1", "", ""},
  1215. {"alpha", "2", "", ""},
  1216. {"mike", "3", "", ""},
  1217. {"zebra", "z", "z.txt", "text/plain"},
  1218. {"apple", "a", "a.txt", "text/plain"},
  1219. };
  1220. Client cli(HOST, port);
  1221. auto res = cli.Post("/order", items);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1224. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1225. }
  1226. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1227. Server svr;
  1228. std::vector<std::string> values;
  1229. std::string first, second, out_of_range, order;
  1230. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1231. values = req.form.get_fields("tag");
  1232. first = req.form.get_field("tag", 0);
  1233. second = req.form.get_field("tag", 1);
  1234. out_of_range = req.form.get_field("tag", 2);
  1235. for (const auto &field : req.form.fields) {
  1236. order += field.first + "=" + field.second.content + " ";
  1237. }
  1238. res.set_content("ok", "text/plain");
  1239. });
  1240. auto port = svr.bind_to_any_port(HOST);
  1241. thread t = thread([&] { svr.listen_after_bind(); });
  1242. auto se = detail::scope_exit([&] {
  1243. svr.stop();
  1244. t.join();
  1245. ASSERT_FALSE(svr.is_running());
  1246. });
  1247. svr.wait_until_ready();
  1248. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1249. // not adjacent in the container.
  1250. UploadFormDataItems items = {
  1251. {"tag", "first", "", ""},
  1252. {"other", "x", "", ""},
  1253. {"tag", "second", "", ""},
  1254. };
  1255. Client cli(HOST, port);
  1256. auto res = cli.Post("/repeated", items);
  1257. ASSERT_TRUE(res);
  1258. ASSERT_EQ(2U, values.size());
  1259. EXPECT_EQ("first", values[0]);
  1260. EXPECT_EQ("second", values[1]);
  1261. EXPECT_EQ("first", first);
  1262. EXPECT_EQ("second", second);
  1263. // std::multimap already kept entries sharing a name in insertion order, so
  1264. // everything above passes without this change too. The whole traversal is
  1265. // what tells the two apart: sorting by name would hoist "other" to the front
  1266. // and the two "tag" parts would end up adjacent.
  1267. EXPECT_EQ("tag=first other=x tag=second ", order);
  1268. // Advancing past the last entry of a name used to run off the container;
  1269. // the container's saturating increment makes it return the default instead.
  1270. EXPECT_EQ("", out_of_range);
  1271. }
  1272. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1273. // Server::read_content() keeps a FormFields::iterator alive across the
  1274. // content callbacks that fill the part it points at. The container is
  1275. // vector-backed, so a later emplace can reallocate and invalidate an older
  1276. // iterator; 64 parts grow the vector through seven reallocations, which
  1277. // checks that every part's content still lands in its own entry.
  1278. const size_t part_count = 64;
  1279. // One formula for both the parts sent and the values expected back, so the
  1280. // two cannot drift apart.
  1281. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1282. auto content_of = [](size_t i) {
  1283. return std::string(64, static_cast<char>('a' + (i % 26)));
  1284. };
  1285. Server svr;
  1286. std::vector<std::pair<std::string, std::string>> received;
  1287. svr.Post("/many", [&](const Request &req, Response &res) {
  1288. for (const auto &field : req.form.fields) {
  1289. received.emplace_back(field.first, field.second.content);
  1290. }
  1291. res.set_content("ok", "text/plain");
  1292. });
  1293. auto port = svr.bind_to_any_port(HOST);
  1294. thread t = thread([&] { svr.listen_after_bind(); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. t.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. UploadFormDataItems items;
  1302. for (size_t i = 0; i < part_count; i++) {
  1303. items.push_back({name_of(i), content_of(i), "", ""});
  1304. }
  1305. Client cli(HOST, port);
  1306. auto res = cli.Post("/many", items);
  1307. ASSERT_TRUE(res);
  1308. ASSERT_EQ(part_count, received.size());
  1309. for (size_t i = 0; i < part_count; i++) {
  1310. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1311. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1312. }
  1313. }
  1314. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1315. string content_type = "multipart/form-data; boundary=something";
  1316. string boundary;
  1317. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1318. EXPECT_TRUE(ret);
  1319. EXPECT_EQ(boundary, "something");
  1320. }
  1321. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1322. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1323. string boundary;
  1324. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1325. EXPECT_TRUE(ret);
  1326. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1327. }
  1328. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1329. string content_type =
  1330. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1331. string boundary;
  1332. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1333. EXPECT_TRUE(ret);
  1334. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1335. }
  1336. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1337. string content_type =
  1338. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1339. string boundary;
  1340. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1341. EXPECT_TRUE(ret);
  1342. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1343. }
  1344. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1345. const string boundary(70, 'a');
  1346. string content_type = "multipart/form-data; boundary=" + boundary;
  1347. string parsed;
  1348. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1349. EXPECT_TRUE(ret);
  1350. EXPECT_EQ(parsed, boundary);
  1351. }
  1352. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1353. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1354. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1355. string parsed;
  1356. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1357. EXPECT_FALSE(ret);
  1358. }
  1359. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1360. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1361. // is 72 characters on the wire and still valid.
  1362. const string boundary(70, 'a');
  1363. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1364. string parsed;
  1365. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1366. EXPECT_EQ(parsed, boundary);
  1367. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1368. parsed.clear();
  1369. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1370. }
  1371. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1372. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1373. // The parameter parser must not treat that '=' as the key/value separator.
  1374. string content_type =
  1375. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1376. "charset=UTF-8";
  1377. string parsed;
  1378. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1379. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1380. }
  1381. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1382. // A ';' inside the quoted-string is part of the value, not a parameter
  1383. // separator, so it must not truncate the boundary.
  1384. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1385. string parsed;
  1386. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1387. EXPECT_EQ(parsed, "a;b");
  1388. }
  1389. TEST(ParseDispositionParamsTest, QuotedValues) {
  1390. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1391. // ';' and '=' are ordinary characters inside one.
  1392. struct {
  1393. const char *value;
  1394. std::vector<std::pair<const char *, const char *>> expected;
  1395. } cases[] = {
  1396. {"name=\"file1\"; filename=\"a.txt\"",
  1397. {{"name", "file1"}, {"filename", "a.txt"}}},
  1398. // Whitespace around '=' and ';' is still trimmed
  1399. {"name=\"file2\" ;filename = \"a.html\"",
  1400. {{"name", "file2"}, {"filename", "a.html"}}},
  1401. // '=' inside the value used to leave only the text after the last one
  1402. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1403. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1404. {"name=\"x=y\"", {{"name", "x=y"}}},
  1405. // ';' inside the value used to truncate the pair and leave a bogus one
  1406. {"name=\"file3\"; filename=\"a;b.txt\"",
  1407. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1408. // An unquoted value keeps working, and so does filename*
  1409. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1410. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1411. // A parameter with no key is dropped rather than turned into one whose
  1412. // key is the value
  1413. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1414. };
  1415. for (const auto &c : cases) {
  1416. Params params;
  1417. detail::parse_disposition_params(c.value, params);
  1418. for (const auto &kv : c.expected) {
  1419. auto it = params.find(kv.first);
  1420. ASSERT_NE(it, params.end())
  1421. << "value: " << c.value << ", key: " << kv.first;
  1422. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1423. }
  1424. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1425. }
  1426. }
  1427. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1428. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1429. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1430. Server svr;
  1431. std::string field_value, file_name, file_filename;
  1432. bool has_field = false, has_file = false;
  1433. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1434. has_field = req.form.has_field("x=y");
  1435. field_value = req.form.get_field("x=y");
  1436. has_file = req.form.has_file("file1");
  1437. const auto &file = req.form.get_file("file1");
  1438. file_name = file.name;
  1439. file_filename = file.filename;
  1440. res.set_content("ok", "text/plain");
  1441. });
  1442. auto port = svr.bind_to_any_port(HOST);
  1443. thread t = thread([&] { svr.listen_after_bind(); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. t.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. UploadFormDataItems items = {
  1451. {"x=y", "field-value", "", ""},
  1452. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1453. };
  1454. Client cli(HOST, port);
  1455. auto res = cli.Post("/quoted", items);
  1456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1457. ASSERT_EQ(StatusCode::OK_200, res->status);
  1458. EXPECT_TRUE(has_field);
  1459. EXPECT_EQ("field-value", field_value);
  1460. EXPECT_TRUE(has_file);
  1461. EXPECT_EQ("file1", file_name);
  1462. EXPECT_EQ("a;b=report.pdf", file_filename);
  1463. }
  1464. TEST(GetHeaderValueTest, DefaultValue) {
  1465. Headers headers = {{"Dummy", "Dummy"}};
  1466. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1467. EXPECT_STREQ("text/plain", val);
  1468. }
  1469. TEST(GetHeaderValueTest, DefaultValueInt) {
  1470. Headers headers = {{"Dummy", "Dummy"}};
  1471. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1472. EXPECT_EQ(100ull, val);
  1473. }
  1474. TEST(GetHeaderValueTest, RegularValue) {
  1475. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1476. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1477. EXPECT_STREQ("text/html", val);
  1478. }
  1479. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1480. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1481. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1482. EXPECT_STREQ("text/html", val);
  1483. }
  1484. TEST(GetHeaderValueTest, SetContent) {
  1485. Response res;
  1486. res.set_content("html", "text/html");
  1487. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1488. res.set_content("text", "text/plain");
  1489. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1490. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1491. }
  1492. TEST(GetHeaderValueTest, RegularValueInt) {
  1493. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1494. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1495. EXPECT_EQ(100ull, val);
  1496. }
  1497. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1498. Headers headers = {{"Content-Length", "x"}};
  1499. auto is_invalid_value = false;
  1500. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1501. is_invalid_value);
  1502. EXPECT_EQ(0ull, val);
  1503. EXPECT_TRUE(is_invalid_value);
  1504. }
  1505. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1506. // An all-digit value that overflows size_t must be reported as invalid, not
  1507. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1508. // a large length to a small one on 32-bit builds, leaving the framing length
  1509. // wrong while is_invalid_value stayed false.
  1510. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1511. auto is_invalid_value = false;
  1512. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1513. is_invalid_value);
  1514. EXPECT_TRUE(is_invalid_value);
  1515. // A well-formed length is unaffected.
  1516. Headers ok = {{"Content-Length", "1234"}};
  1517. is_invalid_value = false;
  1518. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1519. is_invalid_value);
  1520. EXPECT_EQ(1234ull, val);
  1521. EXPECT_FALSE(is_invalid_value);
  1522. }
  1523. TEST(GetHeaderValueTest, Range) {
  1524. {
  1525. Headers headers = {make_range_header({{1, -1}})};
  1526. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1527. EXPECT_STREQ("bytes=1-", val);
  1528. }
  1529. {
  1530. Headers headers = {make_range_header({{-1, 1}})};
  1531. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1532. EXPECT_STREQ("bytes=-1", val);
  1533. }
  1534. {
  1535. Headers headers = {make_range_header({{1, 10}})};
  1536. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1537. EXPECT_STREQ("bytes=1-10", val);
  1538. }
  1539. {
  1540. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1541. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1542. EXPECT_STREQ("bytes=1-10, 100-", val);
  1543. }
  1544. {
  1545. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1546. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1547. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1548. }
  1549. {
  1550. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1551. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1552. EXPECT_STREQ("bytes=0-0, -1", val);
  1553. }
  1554. }
  1555. TEST(BearerTokenAuthTest, SchemeValidation) {
  1556. // A value shorter than "Bearer " must not throw from the fixed-length
  1557. // substr, and a non-Bearer scheme must not be reported as a token.
  1558. struct {
  1559. const char *value;
  1560. const char *expected;
  1561. } cases[] = {
  1562. {"x", ""},
  1563. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1564. {"Bearer abc123", "abc123"},
  1565. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1566. };
  1567. for (const auto &c : cases) {
  1568. Request req;
  1569. req.set_header("Authorization", c.value);
  1570. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1571. }
  1572. }
  1573. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1574. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1575. // to depend on the standard library (libstdc++ handed back duplicates in
  1576. // reverse insertion order, libc++ in insertion order).
  1577. Request req;
  1578. req.set_header("Accept-Encoding", "gzip");
  1579. req.set_header("Accept-Encoding", "deflate");
  1580. req.set_header("Accept-Encoding", "br");
  1581. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1582. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1584. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1585. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1586. }
  1587. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1588. Request req;
  1589. req.set_header("X-Test", "only");
  1590. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1591. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1593. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1594. }
  1595. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1596. Headers headers;
  1597. headers.emplace("Host", "example.com");
  1598. headers.emplace("Accept-Encoding", "gzip");
  1599. headers.emplace("User-Agent", "test");
  1600. headers.emplace("Accept-Encoding", "deflate");
  1601. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1602. "Accept-Encoding=deflate ",
  1603. entries_to_string(headers));
  1604. }
  1605. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1606. Headers headers = {{"Content-Type", "text/html"},
  1607. {"CONTENT-TYPE", "text/xml"}};
  1608. EXPECT_EQ(2U, headers.count("content-type"));
  1609. auto it = headers.find("content-type");
  1610. ASSERT_TRUE(it != headers.end());
  1611. EXPECT_EQ("text/html", it->second);
  1612. }
  1613. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1614. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1615. // drop only those fields and leave everything positioned between them.
  1616. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1617. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1618. auto rng = headers.equal_range("a");
  1619. headers.erase(rng.first, rng.second);
  1620. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1621. }
  1622. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1623. Headers headers = {
  1624. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1625. EXPECT_EQ(3U, headers.erase("A"));
  1626. EXPECT_EQ(0U, headers.count("A"));
  1627. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1628. }
  1629. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1630. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1631. headers.emplace_front("Host", "example.com");
  1632. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1633. entries_to_string(headers));
  1634. }
  1635. TEST(ParseHeaderValueTest, Range) {
  1636. {
  1637. Ranges ranges;
  1638. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1639. EXPECT_TRUE(ret);
  1640. EXPECT_EQ(1u, ranges.size());
  1641. EXPECT_EQ(1u, ranges[0].first);
  1642. EXPECT_EQ(-1, ranges[0].second);
  1643. }
  1644. {
  1645. Ranges ranges;
  1646. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1647. EXPECT_TRUE(ret);
  1648. EXPECT_EQ(1u, ranges.size());
  1649. EXPECT_EQ(-1, ranges[0].first);
  1650. EXPECT_EQ(1u, ranges[0].second);
  1651. }
  1652. {
  1653. Ranges ranges;
  1654. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(1u, ranges.size());
  1657. EXPECT_EQ(1u, ranges[0].first);
  1658. EXPECT_EQ(10u, ranges[0].second);
  1659. }
  1660. {
  1661. Ranges ranges;
  1662. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1663. EXPECT_FALSE(ret);
  1664. }
  1665. {
  1666. Ranges ranges;
  1667. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1668. EXPECT_TRUE(ret);
  1669. EXPECT_EQ(2u, ranges.size());
  1670. EXPECT_EQ(1u, ranges[0].first);
  1671. EXPECT_EQ(10u, ranges[0].second);
  1672. EXPECT_EQ(100u, ranges[1].first);
  1673. EXPECT_EQ(-1, ranges[1].second);
  1674. }
  1675. {
  1676. Ranges ranges;
  1677. auto ret =
  1678. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1679. EXPECT_TRUE(ret);
  1680. EXPECT_EQ(3u, ranges.size());
  1681. EXPECT_EQ(1u, ranges[0].first);
  1682. EXPECT_EQ(10u, ranges[0].second);
  1683. EXPECT_EQ(100u, ranges[1].first);
  1684. EXPECT_EQ(200u, ranges[1].second);
  1685. EXPECT_EQ(300u, ranges[2].first);
  1686. EXPECT_EQ(400u, ranges[2].second);
  1687. }
  1688. {
  1689. Ranges ranges;
  1690. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1703. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1704. EXPECT_FALSE(
  1705. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1706. EXPECT_TRUE(ranges.empty());
  1707. }
  1708. {
  1709. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1710. // remainder of the representation, so it stays accepted.
  1711. Ranges ranges;
  1712. auto ret =
  1713. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1714. EXPECT_TRUE(ret);
  1715. ASSERT_EQ(1u, ranges.size());
  1716. EXPECT_EQ(0, ranges[0].first);
  1717. EXPECT_EQ(-1, ranges[0].second);
  1718. }
  1719. }
  1720. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1721. Request req;
  1722. req.set_header("Accept-Encoding", "gzip");
  1723. Response res;
  1724. res.set_header("Content-Type", "text/plain");
  1725. auto ret = detail::encoding_type(req, res);
  1726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1727. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1728. #else
  1729. EXPECT_TRUE(ret == detail::EncodingType::None);
  1730. #endif
  1731. }
  1732. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1733. Request req;
  1734. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1749. Request req;
  1750. req.set_header("Accept-Encoding",
  1751. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1756. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1757. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1758. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1759. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1760. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1761. #else
  1762. EXPECT_TRUE(ret == detail::EncodingType::None);
  1763. #endif
  1764. }
  1765. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1766. // All supported encodings rejected with q=0 should return None
  1767. Request req;
  1768. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1769. Response res;
  1770. res.set_header("Content-Type", "text/plain");
  1771. auto ret = detail::encoding_type(req, res);
  1772. EXPECT_TRUE(ret == detail::EncodingType::None);
  1773. }
  1774. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1775. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1776. Request req;
  1777. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1778. Response res;
  1779. res.set_header("Content-Type", "text/plain");
  1780. auto ret = detail::encoding_type(req, res);
  1781. EXPECT_TRUE(ret == detail::EncodingType::None);
  1782. }
  1783. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1784. Request req;
  1785. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1786. Response res;
  1787. res.set_header("Content-Type", "text/plain");
  1788. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1789. }
  1790. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1791. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. EXPECT_TRUE(ret == detail::EncodingType::None);
  1798. }
  1799. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1800. // RFC 7231: Accept-Encoding values are case-insensitive
  1801. Request req;
  1802. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1803. Response res;
  1804. res.set_header("Content-Type", "text/plain");
  1805. auto ret = detail::encoding_type(req, res);
  1806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1807. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1808. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1809. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1810. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1811. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1812. #else
  1813. EXPECT_TRUE(ret == detail::EncodingType::None);
  1814. #endif
  1815. }
  1816. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1817. // q value should determine priority, not hardcoded order
  1818. Request req;
  1819. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1820. Response res;
  1821. res.set_header("Content-Type", "text/plain");
  1822. auto ret = detail::encoding_type(req, res);
  1823. // gzip has highest q=1.0, so it should be selected even though
  1824. // br and zstd are also supported
  1825. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1826. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1827. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1828. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1829. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1830. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1831. #else
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. #endif
  1834. }
  1835. TEST(BufferStreamTest, read) {
  1836. detail::BufferStream strm1;
  1837. Stream &strm = strm1;
  1838. EXPECT_EQ(5, strm.write("hello"));
  1839. char buf[512];
  1840. EXPECT_EQ(2, strm.read(buf, 2));
  1841. EXPECT_EQ('h', buf[0]);
  1842. EXPECT_EQ('e', buf[1]);
  1843. EXPECT_EQ(2, strm.read(buf, 2));
  1844. EXPECT_EQ('l', buf[0]);
  1845. EXPECT_EQ('l', buf[1]);
  1846. EXPECT_EQ(1, strm.read(buf, 1));
  1847. EXPECT_EQ('o', buf[0]);
  1848. EXPECT_EQ(0, strm.read(buf, 1));
  1849. }
  1850. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1851. auto host = "www.httpwatch.com";
  1852. auto ip = hosted_at(host);
  1853. EXPECT_EQ("23.96.13.243", ip);
  1854. std::vector<std::string> addrs;
  1855. hosted_at(host, addrs);
  1856. EXPECT_EQ(1u, addrs.size());
  1857. }
  1858. #if 0 // It depends on each test environment...
  1859. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1860. auto host = "www.youtube.com";
  1861. std::vector<std::string> addrs;
  1862. hosted_at(host, addrs);
  1863. EXPECT_EQ(20u, addrs.size());
  1864. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1865. EXPECT_TRUE(it != addrs.end());
  1866. }
  1867. #endif
  1868. class ChunkedEncodingTest : public ::testing::Test {
  1869. protected:
  1870. ChunkedEncodingTest()
  1871. : cli_(HOST, PORT)
  1872. #ifdef CPPHTTPLIB_SSL_ENABLED
  1873. ,
  1874. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1875. #endif
  1876. {
  1877. cli_.set_connection_timeout(2);
  1878. #ifdef CPPHTTPLIB_SSL_ENABLED
  1879. cli_.enable_server_certificate_verification(false);
  1880. #endif
  1881. }
  1882. virtual void SetUp() {
  1883. read_file("./image.jpg", image_data_);
  1884. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1885. res.set_content("Hello World!", "text/plain");
  1886. });
  1887. svr_.Get(
  1888. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1889. res.set_chunked_content_provider(
  1890. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1891. size_t remaining = image_data_.size() - offset;
  1892. if (remaining == 0) {
  1893. sink.done();
  1894. } else {
  1895. constexpr size_t CHUNK_SIZE = 1024;
  1896. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1897. sink.write(&image_data_[offset], send_size);
  1898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1899. }
  1900. return true;
  1901. });
  1902. });
  1903. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1904. svr_.wait_until_ready();
  1905. }
  1906. virtual void TearDown() {
  1907. svr_.stop();
  1908. if (!request_threads_.empty()) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(1));
  1910. for (auto &t : request_threads_) {
  1911. t.join();
  1912. }
  1913. }
  1914. t_.join();
  1915. }
  1916. #ifdef CPPHTTPLIB_SSL_ENABLED
  1917. SSLClient cli_;
  1918. SSLServer svr_;
  1919. #else
  1920. Client cli_;
  1921. Server svr_;
  1922. #endif
  1923. thread t_;
  1924. std::vector<thread> request_threads_;
  1925. std::string image_data_;
  1926. };
  1927. TEST_F(ChunkedEncodingTest, NormalGet) {
  1928. auto res = cli_.Get("/chunked");
  1929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1930. std::string out;
  1931. read_file("./image.jpg", out);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. EXPECT_EQ(out, res->body);
  1934. }
  1935. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1936. std::string body;
  1937. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1942. std::string out;
  1943. read_file("./image.jpg", out);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. EXPECT_EQ(out, body);
  1946. }
  1947. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1948. std::string body;
  1949. auto res = cli_.Get(
  1950. "/chunked",
  1951. [&](const Response &response) {
  1952. EXPECT_EQ(StatusCode::OK_200, response.status);
  1953. return true;
  1954. },
  1955. [&](const char *data, size_t data_length) {
  1956. body.append(data, data_length);
  1957. return true;
  1958. });
  1959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1960. std::string out;
  1961. read_file("./image.jpg", out);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ(out, body);
  1964. }
  1965. TEST(RangeTest, FromHTTPBin_Online) {
  1966. auto host = "httpbingo.org";
  1967. auto path = std::string{"/range/32"};
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. auto port = 443;
  1970. SSLClient cli(host, port);
  1971. #else
  1972. auto port = 80;
  1973. Client cli(host, port);
  1974. #endif
  1975. cli.set_connection_timeout(5);
  1976. {
  1977. auto res = cli.Get(path);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_EQ(StatusCode::OK_200, res->status);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, -1}})};
  1984. auto res = cli.Get(path, headers);
  1985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1986. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1988. }
  1989. {
  1990. Headers headers = {make_range_header({{1, 10}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("bcdefghijk", res->body);
  1994. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1995. }
  1996. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1997. // entire resource, while the original httpbin returned 200. Both are
  1998. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1999. {
  2000. Headers headers = {make_range_header({{0, 31}})};
  2001. auto res = cli.Get(path, headers);
  2002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2003. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2004. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2005. res->status == StatusCode::PartialContent_206);
  2006. }
  2007. {
  2008. Headers headers = {make_range_header({{0, -1}})};
  2009. auto res = cli.Get(path, headers);
  2010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2011. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2012. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2013. res->status == StatusCode::PartialContent_206);
  2014. }
  2015. // go-httpbin returns 206 with clamped range for over-range requests,
  2016. // while the original httpbin returned 416. Both behaviors are observed
  2017. // in real servers, so we only verify the request succeeds.
  2018. {
  2019. Headers headers = {make_range_header({{0, 32}})};
  2020. auto res = cli.Get(path, headers);
  2021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2022. }
  2023. }
  2024. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2025. auto host = "unresolvableaddress.local";
  2026. auto path = std::string{"/"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(1);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_FALSE(res);
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(8));
  2040. }
  2041. #if defined(__linux__) && defined(__GLIBC__) && \
  2042. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2043. // Forward declaration: in split builds split.py strips `inline` and moves the
  2044. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2045. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2046. // against the symbol in both header-only and split builds.
  2047. namespace httplib {
  2048. namespace detail {
  2049. int getaddrinfo_with_timeout(const char *node, const char *service,
  2050. const struct addrinfo *hints,
  2051. struct addrinfo **res, time_t timeout_sec);
  2052. } // namespace detail
  2053. } // namespace httplib
  2054. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2055. //
  2056. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2057. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2058. // gai_suspend() call hits the connection timeout the function calls
  2059. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2060. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2061. // still alive and still references the now-destroyed stack frame.
  2062. //
  2063. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2064. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2065. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2066. // and runs them in a container.
  2067. namespace {
  2068. bool should_run_issue_2431_tests() {
  2069. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2070. return v && *v && std::string(v) != "0";
  2071. }
  2072. std::string unique_unresolvable_host(int n) {
  2073. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2074. // glibc still asks the configured nameserver — which is exactly the path
  2075. // we want to exercise. A unique label per call avoids the resolver cache.
  2076. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2077. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2078. std::to_string(n) + ".invalid";
  2079. }
  2080. } // namespace
  2081. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2082. if (!should_run_issue_2431_tests()) {
  2083. GTEST_SKIP()
  2084. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2085. }
  2086. for (int i = 0; i < 8; ++i) {
  2087. struct addrinfo hints;
  2088. memset(&hints, 0, sizeof(hints));
  2089. hints.ai_family = AF_UNSPEC;
  2090. hints.ai_socktype = SOCK_STREAM;
  2091. auto host = unique_unresolvable_host(i);
  2092. struct addrinfo *result = nullptr;
  2093. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2094. &result, /*timeout_sec=*/1);
  2095. if (rc == 0 && result) { freeaddrinfo(result); }
  2096. }
  2097. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2098. // stack region they still believe holds their gaicb.
  2099. std::this_thread::sleep_for(std::chrono::seconds(3));
  2100. }
  2101. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2102. if (!should_run_issue_2431_tests()) {
  2103. GTEST_SKIP()
  2104. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2105. }
  2106. std::atomic<bool> stop{false};
  2107. std::vector<std::thread> threads;
  2108. for (int t = 0; t < 8; ++t) {
  2109. threads.emplace_back([t, &stop] {
  2110. int i = 0;
  2111. while (!stop.load(std::memory_order_relaxed)) {
  2112. struct addrinfo hints;
  2113. memset(&hints, 0, sizeof(hints));
  2114. hints.ai_family = AF_UNSPEC;
  2115. hints.ai_socktype = SOCK_STREAM;
  2116. auto host = unique_unresolvable_host(t * 100000 + i++);
  2117. struct addrinfo *result = nullptr;
  2118. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2119. &result, /*timeout_sec=*/1);
  2120. if (rc == 0 && result) { freeaddrinfo(result); }
  2121. }
  2122. });
  2123. }
  2124. std::this_thread::sleep_for(std::chrono::seconds(8));
  2125. stop.store(true, std::memory_order_relaxed);
  2126. for (auto &th : threads) {
  2127. th.join();
  2128. }
  2129. std::this_thread::sleep_for(std::chrono::seconds(3));
  2130. }
  2131. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2132. if (!should_run_issue_2431_tests()) {
  2133. GTEST_SKIP()
  2134. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2135. }
  2136. std::atomic<bool> stop{false};
  2137. std::vector<std::thread> threads;
  2138. for (int t = 0; t < 8; ++t) {
  2139. threads.emplace_back([t, &stop] {
  2140. int i = 0;
  2141. while (!stop.load(std::memory_order_relaxed)) {
  2142. auto host = unique_unresolvable_host(t * 100000 + i++);
  2143. Client cli(host, 80);
  2144. cli.set_connection_timeout(1, 0);
  2145. cli.set_read_timeout(1, 0);
  2146. cli.set_write_timeout(1, 0);
  2147. (void)cli.Get("/");
  2148. }
  2149. });
  2150. }
  2151. std::this_thread::sleep_for(std::chrono::seconds(8));
  2152. stop.store(true, std::memory_order_relaxed);
  2153. for (auto &th : threads) {
  2154. th.join();
  2155. }
  2156. std::this_thread::sleep_for(std::chrono::seconds(3));
  2157. }
  2158. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2159. TEST(ConnectionErrorTest, InvalidHost) {
  2160. auto host = "-abcde.com";
  2161. #ifdef CPPHTTPLIB_SSL_ENABLED
  2162. auto port = 443;
  2163. SSLClient cli(host, port);
  2164. #else
  2165. auto port = 80;
  2166. Client cli(host, port);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. EXPECT_EQ(Error::Connection, res.error());
  2172. }
  2173. TEST(ConnectionErrorTest, InvalidHost2) {
  2174. auto host = "httpcan.org/";
  2175. #ifdef CPPHTTPLIB_SSL_ENABLED
  2176. SSLClient cli(host);
  2177. #else
  2178. Client cli(host);
  2179. #endif
  2180. cli.set_connection_timeout(std::chrono::seconds(2));
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(!res);
  2183. EXPECT_EQ(Error::Connection, res.error());
  2184. }
  2185. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2186. auto host = "httpcan.org/";
  2187. #ifdef CPPHTTPLIB_SSL_ENABLED
  2188. SSLClient cli(host);
  2189. #else
  2190. Client cli(host);
  2191. #endif
  2192. cli.set_connection_timeout(std::chrono::seconds(2));
  2193. auto res = cli.Get("/");
  2194. ASSERT_TRUE(!res);
  2195. stringstream s;
  2196. s << "error code: " << res.error();
  2197. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2198. }
  2199. TEST(ConnectionErrorTest, InvalidPort) {
  2200. auto host = "localhost";
  2201. auto port = 44380;
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. SSLClient cli(host, port);
  2204. #else
  2205. Client cli(host, port);
  2206. #endif
  2207. cli.set_connection_timeout(std::chrono::seconds(2));
  2208. auto res = cli.Get("/");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_TRUE(Error::Connection == res.error() ||
  2211. Error::ConnectionTimeout == res.error());
  2212. }
  2213. TEST(ConnectionErrorTest, Timeout_Online) {
  2214. auto host = "google.com";
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 44380;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 8080;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(std::chrono::seconds(2));
  2223. // only probe one address type so that the error reason
  2224. // correlates to the timed-out IPv4, not the unsupported
  2225. // IPv6 connection attempt
  2226. cli.set_address_family(AF_INET);
  2227. auto res = cli.Get("/");
  2228. ASSERT_TRUE(!res);
  2229. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2230. }
  2231. TEST(CancelTest, NoCancel_Online) {
  2232. auto host = "httpbingo.org";
  2233. auto path = std::string{"/range/32"};
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. auto port = 443;
  2236. SSLClient cli(host, port);
  2237. #else
  2238. auto port = 80;
  2239. Client cli(host, port);
  2240. #endif
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2248. // Use /bytes with a large payload so that the DownloadProgress callback
  2249. // (which only fires for Content-Length responses) is invoked before the
  2250. // entire body is received, giving cancellation a chance to fire.
  2251. auto host = "httpbingo.org";
  2252. auto path = std::string{"/bytes/524288"};
  2253. #ifdef CPPHTTPLIB_SSL_ENABLED
  2254. auto port = 443;
  2255. SSLClient cli(host, port);
  2256. #else
  2257. auto port = 80;
  2258. Client cli(host, port);
  2259. #endif
  2260. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. ASSERT_TRUE(!res);
  2263. EXPECT_EQ(Error::Canceled, res.error());
  2264. }
  2265. TEST(CancelTest, WithCancelLargePayload_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/bytes/524288"};
  2268. #ifdef CPPHTTPLIB_SSL_ENABLED
  2269. auto port = 443;
  2270. SSLClient cli(host, port);
  2271. #else
  2272. auto port = 80;
  2273. Client cli(host, port);
  2274. #endif
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. uint32_t count = 0;
  2277. auto res =
  2278. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. TEST(CancelTest, NoCancelPost) {
  2283. Server svr;
  2284. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. Client cli(HOST, PORT);
  2295. cli.set_connection_timeout(std::chrono::seconds(5));
  2296. auto res =
  2297. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2298. "application/json", [](uint64_t, uint64_t) { return true; });
  2299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2300. EXPECT_EQ("Hello World!", res->body);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. }
  2303. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2304. Server svr;
  2305. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2306. res.set_content("Hello World!", "text/plain");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. Client cli(HOST, PORT);
  2316. cli.set_connection_timeout(std::chrono::seconds(5));
  2317. auto res =
  2318. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2319. "application/json", [](uint64_t, uint64_t) { return false; });
  2320. ASSERT_TRUE(!res);
  2321. EXPECT_EQ(Error::Canceled, res.error());
  2322. }
  2323. TEST(CancelTest, WithCancelLargePayloadPost) {
  2324. Server svr;
  2325. svr.set_payload_max_length(200 * 1024 * 1024);
  2326. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2327. res.set_content(LARGE_DATA, "text/plain");
  2328. });
  2329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. Client cli(HOST, PORT);
  2337. cli.set_payload_max_length(200 * 1024 * 1024);
  2338. cli.set_connection_timeout(std::chrono::seconds(5));
  2339. auto res =
  2340. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2341. "application/json", [](uint64_t, uint64_t) { return false; });
  2342. ASSERT_TRUE(!res);
  2343. EXPECT_EQ(Error::Canceled, res.error());
  2344. }
  2345. TEST(CancelTest, NoCancelPut) {
  2346. Server svr;
  2347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2348. res.set_content("Hello World!", "text/plain");
  2349. });
  2350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2351. auto se = detail::scope_exit([&] {
  2352. svr.stop();
  2353. thread.join();
  2354. ASSERT_FALSE(svr.is_running());
  2355. });
  2356. svr.wait_until_ready();
  2357. Client cli(HOST, PORT);
  2358. cli.set_connection_timeout(std::chrono::seconds(5));
  2359. auto res =
  2360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2361. "application/json", [](uint64_t, uint64_t) { return true; });
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ("Hello World!", res->body);
  2364. EXPECT_EQ(StatusCode::OK_200, res->status);
  2365. }
  2366. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2367. Server svr;
  2368. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2369. res.set_content("Hello World!", "text/plain");
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. Client cli(HOST, PORT);
  2379. cli.set_connection_timeout(std::chrono::seconds(5));
  2380. auto res =
  2381. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2382. "application/json", [](uint64_t, uint64_t) { return false; });
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Canceled, res.error());
  2385. }
  2386. TEST(CancelTest, WithCancelLargePayloadPut) {
  2387. Server svr;
  2388. svr.set_payload_max_length(200 * 1024 * 1024);
  2389. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2390. res.set_content(LARGE_DATA, "text/plain");
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. Client cli(HOST, PORT);
  2400. cli.set_payload_max_length(200 * 1024 * 1024);
  2401. cli.set_connection_timeout(std::chrono::seconds(5));
  2402. auto res =
  2403. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2404. "application/json", [](uint64_t, uint64_t) { return false; });
  2405. ASSERT_TRUE(!res);
  2406. EXPECT_EQ(Error::Canceled, res.error());
  2407. }
  2408. TEST(CancelTest, NoCancelPatch) {
  2409. Server svr;
  2410. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. Client cli(HOST, PORT);
  2421. cli.set_connection_timeout(std::chrono::seconds(5));
  2422. auto res =
  2423. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2424. "application/json", [](uint64_t, uint64_t) { return true; });
  2425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2426. EXPECT_EQ("Hello World!", res->body);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. }
  2429. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2430. Server svr;
  2431. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2432. res.set_content("Hello World!", "text/plain");
  2433. });
  2434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2435. auto se = detail::scope_exit([&] {
  2436. svr.stop();
  2437. thread.join();
  2438. ASSERT_FALSE(svr.is_running());
  2439. });
  2440. svr.wait_until_ready();
  2441. Client cli(HOST, PORT);
  2442. cli.set_connection_timeout(std::chrono::seconds(5));
  2443. auto res =
  2444. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2445. "application/json", [](uint64_t, uint64_t) { return false; });
  2446. ASSERT_TRUE(!res);
  2447. EXPECT_EQ(Error::Canceled, res.error());
  2448. }
  2449. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2450. Server svr;
  2451. svr.set_payload_max_length(200 * 1024 * 1024);
  2452. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2453. res.set_content(LARGE_DATA, "text/plain");
  2454. });
  2455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2456. auto se = detail::scope_exit([&] {
  2457. svr.stop();
  2458. thread.join();
  2459. ASSERT_FALSE(svr.is_running());
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, PORT);
  2463. cli.set_payload_max_length(200 * 1024 * 1024);
  2464. cli.set_connection_timeout(std::chrono::seconds(5));
  2465. auto res =
  2466. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2467. "application/json", [](uint64_t, uint64_t) { return false; });
  2468. ASSERT_TRUE(!res);
  2469. EXPECT_EQ(Error::Canceled, res.error());
  2470. }
  2471. TEST(CancelTest, NoCancelDelete) {
  2472. Server svr;
  2473. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!", "text/plain");
  2475. });
  2476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. thread.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, PORT);
  2484. cli.set_connection_timeout(std::chrono::seconds(5));
  2485. auto res =
  2486. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2487. "application/json", [](uint64_t, uint64_t) { return true; });
  2488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2489. EXPECT_EQ("Hello World!", res->body);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. }
  2492. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2493. Server svr;
  2494. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2495. res.set_content("Hello World!", "text/plain");
  2496. });
  2497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2498. auto se = detail::scope_exit([&] {
  2499. svr.stop();
  2500. thread.join();
  2501. ASSERT_FALSE(svr.is_running());
  2502. });
  2503. svr.wait_until_ready();
  2504. Client cli(HOST, PORT);
  2505. cli.set_connection_timeout(std::chrono::seconds(5));
  2506. auto res =
  2507. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2508. "application/json", [](uint64_t, uint64_t) { return false; });
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::Canceled, res.error());
  2511. }
  2512. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2513. Server svr;
  2514. svr.set_payload_max_length(200 * 1024 * 1024);
  2515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2516. res.set_content(LARGE_DATA, "text/plain");
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. Client cli(HOST, PORT);
  2526. cli.set_payload_max_length(200 * 1024 * 1024);
  2527. cli.set_connection_timeout(std::chrono::seconds(5));
  2528. auto res =
  2529. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2530. "application/json", [](uint64_t, uint64_t) { return false; });
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. static std::string remove_whitespace(const std::string &input) {
  2535. std::string output;
  2536. output.reserve(input.size());
  2537. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2538. [](unsigned char c) { return !std::isspace(c); });
  2539. return output;
  2540. }
  2541. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2542. auto host = "httpbingo.org";
  2543. auto path = std::string{"/basic-auth/hello/world"};
  2544. #ifdef CPPHTTPLIB_SSL_ENABLED
  2545. auto port = 443;
  2546. SSLClient cli(host, port);
  2547. #else
  2548. auto port = 80;
  2549. Client cli(host, port);
  2550. #endif
  2551. {
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. auto res = cli.Get(
  2558. path, Headers{make_basic_authentication_header("hello", "world")});
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. auto body = remove_whitespace(res->body);
  2561. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2562. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2563. EXPECT_EQ(StatusCode::OK_200, res->status);
  2564. }
  2565. {
  2566. cli.set_basic_auth("hello", "world");
  2567. auto res = cli.Get(path);
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. auto body = remove_whitespace(res->body);
  2570. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2571. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2572. EXPECT_EQ(StatusCode::OK_200, res->status);
  2573. }
  2574. {
  2575. cli.set_basic_auth("hello", "bad");
  2576. auto res = cli.Get(path);
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2579. }
  2580. {
  2581. cli.set_basic_auth("bad", "world");
  2582. auto res = cli.Get(path);
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2585. }
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2589. auto host = "httpbingo.org";
  2590. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2591. auto paths = std::vector<std::string>{
  2592. "/digest-auth/auth/hello/world/MD5",
  2593. "/digest-auth/auth/hello/world/SHA-256",
  2594. };
  2595. auto port = 443;
  2596. SSLClient cli(host, port);
  2597. {
  2598. auto res = cli.Get(unauth_path);
  2599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2600. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2601. }
  2602. {
  2603. cli.set_digest_auth("hello", "world");
  2604. for (const auto &path : paths) {
  2605. auto res = cli.Get(path.c_str());
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. auto body = remove_whitespace(res->body);
  2608. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2609. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. cli.set_digest_auth("hello", "bad");
  2613. for (const auto &path : paths) {
  2614. auto res = cli.Get(path.c_str());
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2617. }
  2618. }
  2619. }
  2620. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2621. // comma-separated list of challenges, and each challenge may itself carry a
  2622. // comma-separated auth-param list, so a server can legally offer Basic
  2623. // before Digest, either as two field lines or packed into one. Runs one 401
  2624. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2625. // value() joins them in receipt order) and checks that the retry carries a
  2626. // well-formed Digest Authorization header naming expected_realm.
  2627. static void
  2628. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2629. const std::string &expected_realm) {
  2630. std::atomic<int> hits{0};
  2631. Server svr;
  2632. svr.Get("/x", [&](const Request &req, Response &res) {
  2633. if (++hits == 1) {
  2634. res.status = StatusCode::Unauthorized_401;
  2635. for (const auto &challenge : challenges) {
  2636. res.set_header("WWW-Authenticate", challenge);
  2637. }
  2638. } else {
  2639. auto authorization = req.get_header_value("Authorization");
  2640. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2641. EXPECT_NE(std::string::npos,
  2642. authorization.find("realm=\"" + expected_realm + "\""));
  2643. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2644. res.set_content("ok", "text/plain");
  2645. }
  2646. });
  2647. auto port = svr.bind_to_any_port(HOST);
  2648. std::thread t([&]() { svr.listen_after_bind(); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. t.join();
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, port);
  2655. cli.set_digest_auth("hello", "world");
  2656. auto res = cli.Get("/x");
  2657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2658. EXPECT_EQ(2, hits.load());
  2659. }
  2660. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2661. static const char *kDigestChallenge =
  2662. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2663. "algorithm=MD5";
  2664. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2665. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2666. "testrealm");
  2667. }
  2668. // Same challenge list with the schemes in the opposite order, to make sure
  2669. // the fix above didn't just special-case "Basic first".
  2670. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2671. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2672. "testrealm");
  2673. }
  2674. // A comma inside a quoted auth-param value must not be mistaken for the
  2675. // separator between two challenges (or two auth-params).
  2676. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2677. run_digest_challenge_list_test(
  2678. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2679. "algorithm=MD5"},
  2680. "test,realm");
  2681. }
  2682. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2683. // make_digest_authentication_header() dereferences both unconditionally, so
  2684. // a server sending a challenge missing either one must not be treated as
  2685. // usable -- doing so used to crash the client with std::out_of_range.
  2686. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2687. Server svr;
  2688. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2689. res.status = StatusCode::Unauthorized_401;
  2690. res.set_header("WWW-Authenticate", challenge);
  2691. });
  2692. auto port = svr.bind_to_any_port(HOST);
  2693. std::thread t([&]() { svr.listen_after_bind(); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. t.join();
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, port);
  2700. cli.set_digest_auth("hello", "world");
  2701. auto res = cli.Get("/x");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2704. }
  2705. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2706. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2707. }
  2708. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2709. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2710. }
  2711. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2712. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2713. }
  2714. #endif
  2715. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2716. auto host = "google.com";
  2717. auto another_host = "example.com";
  2718. auto wrong_ip = "0.0.0.0";
  2719. #ifdef CPPHTTPLIB_SSL_ENABLED
  2720. SSLClient cli(host);
  2721. #else
  2722. Client cli(host);
  2723. #endif
  2724. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2725. auto res = cli.Get("/");
  2726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2727. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2728. }
  2729. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2730. auto host = "google.com";
  2731. auto wrong_ip = "0.0.0.0";
  2732. #ifdef CPPHTTPLIB_SSL_ENABLED
  2733. SSLClient cli(host);
  2734. #else
  2735. Client cli(host);
  2736. #endif
  2737. cli.set_hostname_addr_map({{host, wrong_ip}});
  2738. auto res = cli.Get("/");
  2739. ASSERT_TRUE(!res);
  2740. EXPECT_EQ(Error::Connection, res.error());
  2741. }
  2742. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2743. // A mapped value that is not an IP literal must be resolved. "localhost"
  2744. // resolves from the hosts file, so this test needs no external DNS.
  2745. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2746. auto host = "target.invalid";
  2747. Server svr;
  2748. std::string received_host;
  2749. svr.Get("/hi", [&](const Request &req, Response &res) {
  2750. received_host = req.get_header_value("Host");
  2751. res.set_content("Hello World!", "text/plain");
  2752. });
  2753. auto port = svr.bind_to_any_port(HOST);
  2754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2755. auto se = detail::scope_exit([&] {
  2756. svr.stop();
  2757. thread.join();
  2758. ASSERT_FALSE(svr.is_running());
  2759. });
  2760. svr.wait_until_ready();
  2761. Client cli(host, port);
  2762. cli.set_hostname_addr_map({{host, HOST}});
  2763. auto res = cli.Get("/hi");
  2764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2765. EXPECT_EQ(StatusCode::OK_200, res->status);
  2766. // The mapping only redirects the connection; the identity stays host_.
  2767. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2768. }
  2769. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2770. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2771. auto host = "target.invalid";
  2772. Server svr;
  2773. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2774. res.set_content("Hello World!", "text/plain");
  2775. });
  2776. auto port = svr.bind_to_any_port("127.0.0.1");
  2777. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2778. auto se = detail::scope_exit([&] {
  2779. svr.stop();
  2780. thread.join();
  2781. ASSERT_FALSE(svr.is_running());
  2782. });
  2783. svr.wait_until_ready();
  2784. Client cli(host, port);
  2785. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2786. auto res = cli.Get("/hi");
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::OK_200, res->status);
  2789. }
  2790. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2791. // An empty mapped value must leave host_ as the connection target. Without
  2792. // that guard the empty value would become the host argument, getaddrinfo
  2793. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2794. // loopback - silently connecting somewhere the caller never asked for.
  2795. // The server listens on loopback, so such a fallback would succeed and is
  2796. // therefore observable as a failure of this test.
  2797. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2798. Server svr;
  2799. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. });
  2802. auto port = svr.bind_to_any_port(HOST);
  2803. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2804. auto se = detail::scope_exit([&] {
  2805. svr.stop();
  2806. thread.join();
  2807. ASSERT_FALSE(svr.is_running());
  2808. });
  2809. svr.wait_until_ready();
  2810. Client cli(blackhole, port);
  2811. cli.set_hostname_addr_map({{blackhole, ""}});
  2812. cli.set_connection_timeout(1);
  2813. auto res = cli.Get("/hi");
  2814. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2815. }
  2816. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2817. auto host = "httpbingo.org";
  2818. auto path = std::string{"/absolute-redirect/3"};
  2819. #ifdef CPPHTTPLIB_SSL_ENABLED
  2820. SSLClient cli(host);
  2821. #else
  2822. Client cli(host);
  2823. #endif
  2824. cli.set_follow_location(true);
  2825. auto res = cli.Get(path);
  2826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2827. EXPECT_EQ(StatusCode::OK_200, res->status);
  2828. }
  2829. TEST(RedirectTest, Redirect_Online) {
  2830. auto host = "httpbingo.org";
  2831. auto path = std::string{"/redirect/3"};
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. SSLClient cli(host);
  2834. #else
  2835. Client cli(host);
  2836. #endif
  2837. cli.set_follow_location(true);
  2838. auto res = cli.Get(path);
  2839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2840. EXPECT_EQ(StatusCode::OK_200, res->status);
  2841. }
  2842. TEST(RelativeRedirectTest, Redirect_Online) {
  2843. auto host = "httpbingo.org";
  2844. auto path = std::string{"/relative-redirect/3"};
  2845. #ifdef CPPHTTPLIB_SSL_ENABLED
  2846. SSLClient cli(host);
  2847. #else
  2848. Client cli(host);
  2849. #endif
  2850. cli.set_follow_location(true);
  2851. auto res = cli.Get(path);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. }
  2855. TEST(TooManyRedirectTest, Redirect_Online) {
  2856. auto host = "httpbingo.org";
  2857. auto path = std::string{"/redirect/21"};
  2858. #ifdef CPPHTTPLIB_SSL_ENABLED
  2859. SSLClient cli(host);
  2860. #else
  2861. Client cli(host);
  2862. #endif
  2863. cli.set_follow_location(true);
  2864. auto res = cli.Get(path);
  2865. ASSERT_TRUE(!res);
  2866. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2867. }
  2868. #ifdef CPPHTTPLIB_SSL_ENABLED
  2869. TEST(YahooRedirectTest, Redirect_Online) {
  2870. Client cli("yahoo.com");
  2871. auto res = cli.Get("/");
  2872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2873. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2874. cli.set_follow_location(true);
  2875. res = cli.Get("/");
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2879. }
  2880. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2881. #define REDIR_HOST "httpbingo.org"
  2882. #define REDIR_PATH "/redirect-to"
  2883. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2884. SSLClient cli(REDIR_HOST);
  2885. cli.set_follow_location(true);
  2886. auto res =
  2887. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. }
  2891. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2892. SSLClient cli(REDIR_HOST);
  2893. cli.set_follow_location(true);
  2894. Params params;
  2895. params.emplace("url", "http://example.com");
  2896. params.emplace("status_code", "302");
  2897. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::OK_200, res->status);
  2900. }
  2901. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2902. SSLClient cli(REDIR_HOST);
  2903. cli.set_follow_location(true);
  2904. Params params;
  2905. params.emplace("url", "http://example.com");
  2906. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::OK_200, res->status);
  2909. }
  2910. TEST(UrlWithSpace, Redirect_Online) {
  2911. SSLClient cli("edge.forgecdn.net");
  2912. cli.set_follow_location(true);
  2913. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2917. }
  2918. #endif
  2919. #if !defined(_WIN32) && !defined(_WIN64)
  2920. TEST(ReceiveSignals, Signal) {
  2921. auto setupSignalHandlers = []() {
  2922. struct sigaction act;
  2923. sigemptyset(&act.sa_mask);
  2924. act.sa_flags = SA_SIGINFO;
  2925. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2926. switch (sig) {
  2927. case SIGINT:
  2928. default: break;
  2929. }
  2930. };
  2931. ::sigaction(SIGINT, &act, nullptr);
  2932. };
  2933. Server svr;
  2934. int port = 0;
  2935. auto thread = std::thread([&]() {
  2936. setupSignalHandlers();
  2937. port = svr.bind_to_any_port(HOST);
  2938. svr.listen_after_bind();
  2939. });
  2940. auto se = detail::scope_exit([&] {
  2941. svr.stop();
  2942. thread.join();
  2943. ASSERT_FALSE(svr.is_running());
  2944. });
  2945. svr.wait_until_ready();
  2946. ASSERT_TRUE(svr.is_running());
  2947. pthread_kill(thread.native_handle(), SIGINT);
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2949. ASSERT_TRUE(svr.is_running());
  2950. }
  2951. #endif
  2952. TEST(RedirectToDifferentPort, Redirect) {
  2953. Server svr1;
  2954. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2955. res.set_content("Hello World!", "text/plain");
  2956. });
  2957. int svr1_port = 0;
  2958. auto thread1 = std::thread([&]() {
  2959. svr1_port = svr1.bind_to_any_port(HOST);
  2960. svr1.listen_after_bind();
  2961. });
  2962. Server svr2;
  2963. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2964. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2965. });
  2966. int svr2_port = 0;
  2967. auto thread2 = std::thread([&]() {
  2968. svr2_port = svr2.bind_to_any_port(HOST);
  2969. svr2.listen_after_bind();
  2970. });
  2971. auto se = detail::scope_exit([&] {
  2972. svr2.stop();
  2973. thread2.join();
  2974. svr1.stop();
  2975. thread1.join();
  2976. ASSERT_FALSE(svr2.is_running());
  2977. ASSERT_FALSE(svr1.is_running());
  2978. });
  2979. svr1.wait_until_ready();
  2980. svr2.wait_until_ready();
  2981. Client cli("localhost", svr2_port);
  2982. cli.set_follow_location(true);
  2983. auto res = cli.Get("/2");
  2984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2985. EXPECT_EQ(StatusCode::OK_200, res->status);
  2986. EXPECT_EQ("Hello World!", res->body);
  2987. }
  2988. static void
  2989. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2990. Server svr1;
  2991. std::string captured_authorization;
  2992. svr1.Get("/target", [&](const Request &req, Response &res) {
  2993. captured_authorization = req.get_header_value("Authorization");
  2994. res.set_content("OK", "text/plain");
  2995. });
  2996. int svr1_port = 0;
  2997. auto thread1 = std::thread([&]() {
  2998. svr1_port = svr1.bind_to_any_port(HOST);
  2999. svr1.listen_after_bind();
  3000. });
  3001. Server svr2;
  3002. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3003. res.set_redirect(
  3004. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3005. });
  3006. int svr2_port = 0;
  3007. auto thread2 = std::thread([&]() {
  3008. svr2_port = svr2.bind_to_any_port(HOST);
  3009. svr2.listen_after_bind();
  3010. });
  3011. auto se = detail::scope_exit([&] {
  3012. svr2.stop();
  3013. thread2.join();
  3014. svr1.stop();
  3015. thread1.join();
  3016. ASSERT_FALSE(svr2.is_running());
  3017. ASSERT_FALSE(svr1.is_running());
  3018. });
  3019. svr1.wait_until_ready();
  3020. svr2.wait_until_ready();
  3021. Client cli("localhost", svr2_port);
  3022. cli.set_follow_location(true);
  3023. set_auth(cli);
  3024. auto res = cli.Get("/redir");
  3025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3026. EXPECT_EQ(StatusCode::OK_200, res->status);
  3027. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3028. EXPECT_TRUE(captured_authorization.empty());
  3029. }
  3030. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3031. TestDoNotForwardCredentialsOnRedirect(
  3032. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3033. }
  3034. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3035. TestDoNotForwardCredentialsOnRedirect(
  3036. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3037. }
  3038. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3039. Server svr1;
  3040. std::string captured_cookie;
  3041. bool target_hit = false;
  3042. svr1.Get("/target", [&](const Request &req, Response &res) {
  3043. captured_cookie = req.get_header_value("Cookie");
  3044. target_hit = true;
  3045. res.set_content("OK", "text/plain");
  3046. });
  3047. int svr1_port = 0;
  3048. auto thread1 = std::thread([&]() {
  3049. svr1_port = svr1.bind_to_any_port(HOST);
  3050. svr1.listen_after_bind();
  3051. });
  3052. Server svr2;
  3053. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3054. res.set_redirect(
  3055. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3056. });
  3057. int svr2_port = 0;
  3058. auto thread2 = std::thread([&]() {
  3059. svr2_port = svr2.bind_to_any_port(HOST);
  3060. svr2.listen_after_bind();
  3061. });
  3062. auto se = detail::scope_exit([&] {
  3063. svr2.stop();
  3064. thread2.join();
  3065. svr1.stop();
  3066. thread1.join();
  3067. ASSERT_FALSE(svr2.is_running());
  3068. ASSERT_FALSE(svr1.is_running());
  3069. });
  3070. svr1.wait_until_ready();
  3071. svr2.wait_until_ready();
  3072. Client cli("localhost", svr2_port);
  3073. cli.set_follow_location(true);
  3074. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3075. auto res = cli.Get("/redir", headers);
  3076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3077. EXPECT_EQ(StatusCode::OK_200, res->status);
  3078. EXPECT_TRUE(target_hit);
  3079. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3080. EXPECT_TRUE(captured_cookie.empty());
  3081. }
  3082. TEST(RedirectToSamePort, ForwardCookie) {
  3083. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3084. // header so that ordinary session flows keep working.
  3085. Server svr;
  3086. std::string captured_cookie;
  3087. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3088. res.set_redirect("/target", 302);
  3089. });
  3090. svr.Get("/target", [&](const Request &req, Response &res) {
  3091. captured_cookie = req.get_header_value("Cookie");
  3092. res.set_content("OK", "text/plain");
  3093. });
  3094. auto port = svr.bind_to_any_port(HOST);
  3095. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3096. auto se = detail::scope_exit([&] {
  3097. svr.stop();
  3098. thread.join();
  3099. ASSERT_FALSE(svr.is_running());
  3100. });
  3101. svr.wait_until_ready();
  3102. Client cli(HOST, port);
  3103. cli.set_follow_location(true);
  3104. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3105. auto res = cli.Get("/redir", headers);
  3106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3107. EXPECT_EQ(StatusCode::OK_200, res->status);
  3108. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3109. }
  3110. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3111. Server svr;
  3112. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3113. // Port number that overflows int — should not crash
  3114. res.set_redirect("http://localhost:99999999999999999999/target");
  3115. });
  3116. auto port = svr.bind_to_any_port(HOST);
  3117. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3118. auto se = detail::scope_exit([&] {
  3119. svr.stop();
  3120. thread.join();
  3121. ASSERT_FALSE(svr.is_running());
  3122. });
  3123. svr.wait_until_ready();
  3124. Client cli(HOST, port);
  3125. cli.set_follow_location(true);
  3126. auto res = cli.Get("/redir");
  3127. // Should fail gracefully, not crash (no valid response due to bad port)
  3128. EXPECT_FALSE(res);
  3129. }
  3130. TEST(RedirectFromPageWithContent, Redirect) {
  3131. Server svr;
  3132. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3133. res.set_content("___", "text/plain");
  3134. res.set_redirect("/2");
  3135. });
  3136. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3137. res.set_content("Hello World!", "text/plain");
  3138. });
  3139. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3140. auto se = detail::scope_exit([&] {
  3141. svr.stop();
  3142. th.join();
  3143. ASSERT_FALSE(svr.is_running());
  3144. });
  3145. svr.wait_until_ready();
  3146. {
  3147. Client cli("localhost", PORT);
  3148. cli.set_follow_location(true);
  3149. std::string body;
  3150. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3151. body.append(data, data_length);
  3152. return true;
  3153. });
  3154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3155. EXPECT_EQ(StatusCode::OK_200, res->status);
  3156. EXPECT_EQ("Hello World!", body);
  3157. }
  3158. {
  3159. Client cli("localhost", PORT);
  3160. std::string body;
  3161. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3162. body.append(data, data_length);
  3163. return true;
  3164. });
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::Found_302, res->status);
  3167. EXPECT_EQ("___", body);
  3168. }
  3169. }
  3170. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3171. Server svr;
  3172. auto port_str = std::to_string(PORT);
  3173. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3174. auto expected_host = "[::1]:" + port_str;
  3175. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3176. res.set_content("___", "text/plain");
  3177. // res.set_redirect("/2");
  3178. res.set_redirect(redirect_url);
  3179. });
  3180. svr.Get("/2", [&](const Request &req, Response &res) {
  3181. auto host_header = req.headers.find("Host");
  3182. ASSERT_TRUE(host_header != req.headers.end());
  3183. EXPECT_EQ(expected_host, host_header->second);
  3184. res.set_content("Hello World!", "text/plain");
  3185. });
  3186. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3187. auto se = detail::scope_exit([&] {
  3188. svr.stop();
  3189. th.join();
  3190. ASSERT_FALSE(svr.is_running());
  3191. });
  3192. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3193. // actually starts anything, so the condition !svr.is_running() will
  3194. // always remain true, and the loop never stops.
  3195. // This basically counts how many milliseconds have passed since the
  3196. // call to svr.listen(), and if after 5 seconds nothing started yet
  3197. // aborts the test.
  3198. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3199. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3200. ASSERT_LT(milliseconds, 5000U);
  3201. }
  3202. {
  3203. Client cli("::1", PORT);
  3204. cli.set_follow_location(true);
  3205. std::string body;
  3206. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3207. body.append(data, data_length);
  3208. return true;
  3209. });
  3210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3211. EXPECT_EQ(StatusCode::OK_200, res->status);
  3212. EXPECT_EQ("Hello World!", body);
  3213. }
  3214. {
  3215. Client cli("::1", PORT);
  3216. std::string body;
  3217. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3218. body.append(data, data_length);
  3219. return true;
  3220. });
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::Found_302, res->status);
  3223. EXPECT_EQ("___", body);
  3224. }
  3225. }
  3226. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3227. Server svr;
  3228. svr.Get("/foo", [](const Request &req, Response &res) {
  3229. auto a = req.params.find("a");
  3230. if (a != req.params.end()) {
  3231. res.set_content((*a).second, "text/plain");
  3232. res.status = StatusCode::OK_200;
  3233. } else {
  3234. res.status = StatusCode::BadRequest_400;
  3235. }
  3236. });
  3237. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3238. auto se = detail::scope_exit([&] {
  3239. svr.stop();
  3240. thread.join();
  3241. ASSERT_FALSE(svr.is_running());
  3242. });
  3243. svr.wait_until_ready();
  3244. {
  3245. Client cli(HOST, PORT);
  3246. cli.set_path_encode(false);
  3247. auto res = cli.Get("/foo?a=explicitly+encoded");
  3248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3249. EXPECT_EQ(StatusCode::OK_200, res->status);
  3250. // This expects it back with a space, as the `+` won't have been
  3251. // url-encoded, and server-side the params get decoded turning `+`
  3252. // into spaces.
  3253. EXPECT_EQ("explicitly encoded", res->body);
  3254. }
  3255. }
  3256. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3257. // When path encoding is disabled the client must transmit the supplied
  3258. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3259. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3260. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3261. // than a space (0x20). Assert on the raw wire target to catch this.
  3262. Server svr;
  3263. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3264. svr.Get("/foo", [&](const Request &req, Response &res) {
  3265. EXPECT_EQ(expected_target, req.target);
  3266. res.status = StatusCode::OK_200;
  3267. });
  3268. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3269. auto se = detail::scope_exit([&] {
  3270. svr.stop();
  3271. thread.join();
  3272. ASSERT_FALSE(svr.is_running());
  3273. });
  3274. svr.wait_until_ready();
  3275. {
  3276. Client cli(HOST, PORT);
  3277. cli.set_path_encode(false);
  3278. auto res = cli.Get(expected_target.c_str());
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. }
  3283. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3284. // `open_stream()` used to skip the path encoding that the buffered send
  3285. // path applies, so the same `path` produced different bytes in the request
  3286. // line depending on which API was used. Assert the two agree.
  3287. Server svr;
  3288. std::string target;
  3289. svr.Get(".*", [&](const Request &req, Response &res) {
  3290. target = req.target;
  3291. res.status = StatusCode::OK_200;
  3292. });
  3293. auto port = svr.bind_to_any_port(HOST);
  3294. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3295. auto se = detail::scope_exit([&] {
  3296. svr.stop();
  3297. thread.join();
  3298. ASSERT_FALSE(svr.is_running());
  3299. });
  3300. svr.wait_until_ready();
  3301. struct {
  3302. const char *path;
  3303. const char *expected;
  3304. } cases[] = {
  3305. {"/a b?x=1", "/a%20b?x=1"},
  3306. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3307. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3308. };
  3309. for (const auto &c : cases) {
  3310. Client cli(HOST, port);
  3311. target.clear();
  3312. auto res = cli.Get(c.path);
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3315. auto buffered_target = target;
  3316. target.clear();
  3317. auto handle = cli.open_stream("GET", c.path);
  3318. EXPECT_TRUE(handle.is_valid())
  3319. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3320. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3321. }
  3322. }
  3323. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3324. // The `set_path_encode(false)` contract — transmit the supplied target
  3325. // verbatim — must hold for the streaming API too.
  3326. Server svr;
  3327. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3328. std::string target;
  3329. svr.Get("/foo", [&](const Request &req, Response &res) {
  3330. target = req.target;
  3331. res.status = StatusCode::OK_200;
  3332. });
  3333. auto port = svr.bind_to_any_port(HOST);
  3334. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3335. auto se = detail::scope_exit([&] {
  3336. svr.stop();
  3337. thread.join();
  3338. ASSERT_FALSE(svr.is_running());
  3339. });
  3340. svr.wait_until_ready();
  3341. {
  3342. Client cli(HOST, port);
  3343. cli.set_path_encode(false);
  3344. auto handle = cli.open_stream("GET", expected_target);
  3345. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3346. EXPECT_EQ(expected_target, target);
  3347. }
  3348. }
  3349. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3350. // With path encoding enabled a CR/LF in the target is percent-encoded
  3351. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3352. // write_request_line still backstops `set_path_encode(false)`, which is
  3353. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3354. Server svr;
  3355. // Captured before routing: the decoded path contains a newline, which a
  3356. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3357. std::string target;
  3358. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3359. target = req.target;
  3360. res.status = StatusCode::OK_200;
  3361. return Server::HandlerResponse::Handled;
  3362. });
  3363. auto port = svr.bind_to_any_port(HOST);
  3364. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3365. auto se = detail::scope_exit([&] {
  3366. svr.stop();
  3367. thread.join();
  3368. ASSERT_FALSE(svr.is_running());
  3369. });
  3370. svr.wait_until_ready();
  3371. {
  3372. Client cli(HOST, port);
  3373. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3374. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3375. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3376. }
  3377. }
  3378. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3379. // Every control character is percent-encoded, not just CR/LF, so the target
  3380. // passes the request-target check in write_request_line.
  3381. Server svr;
  3382. std::string target;
  3383. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3384. target = req.target;
  3385. res.status = StatusCode::OK_200;
  3386. return Server::HandlerResponse::Handled;
  3387. });
  3388. auto port = svr.bind_to_any_port(HOST);
  3389. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3390. auto se = detail::scope_exit([&] {
  3391. svr.stop();
  3392. thread.join();
  3393. ASSERT_FALSE(svr.is_running());
  3394. });
  3395. svr.wait_until_ready();
  3396. {
  3397. Client cli(HOST, port);
  3398. auto res = cli.Get("/a\tb\x1b\x7f");
  3399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3400. EXPECT_EQ("/a%09b%1B%7F", target);
  3401. }
  3402. }
  3403. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3404. // Nothing may reach the wire: a raw CR/LF target would split the request
  3405. // line and inject headers.
  3406. Server svr;
  3407. // Pre-routing so that "not called" means nothing reached the server at all,
  3408. // rather than merely failing to match a handler pattern.
  3409. auto handler_called = false;
  3410. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3411. handler_called = true;
  3412. res.status = StatusCode::OK_200;
  3413. return Server::HandlerResponse::Handled;
  3414. });
  3415. auto port = svr.bind_to_any_port(HOST);
  3416. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3417. auto se = detail::scope_exit([&] {
  3418. svr.stop();
  3419. thread.join();
  3420. ASSERT_FALSE(svr.is_running());
  3421. });
  3422. svr.wait_until_ready();
  3423. {
  3424. Client cli(HOST, port);
  3425. cli.set_path_encode(false);
  3426. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3427. EXPECT_FALSE(handle.is_valid());
  3428. EXPECT_EQ(Error::Write, handle.error);
  3429. EXPECT_FALSE(handler_called);
  3430. }
  3431. }
  3432. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3433. // Which of the two branches runs is decided by whether the query component
  3434. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3435. // an empty query and must still fall back to building one from
  3436. // `req.params`, while a non-empty query must win over `req.params`.
  3437. Server svr;
  3438. std::string target;
  3439. svr.Get("/foo", [&](const Request &req, Response &res) {
  3440. target = req.target;
  3441. res.status = StatusCode::OK_200;
  3442. });
  3443. auto port = svr.bind_to_any_port(HOST);
  3444. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3445. auto se = detail::scope_exit([&] {
  3446. svr.stop();
  3447. thread.join();
  3448. ASSERT_FALSE(svr.is_running());
  3449. });
  3450. svr.wait_until_ready();
  3451. {
  3452. // Trailing `?` -> empty query component -> `req.params` is used.
  3453. Client cli(HOST, port);
  3454. Request req;
  3455. req.method = "GET";
  3456. req.path = "/foo?";
  3457. req.params.emplace("a", "1");
  3458. target.clear();
  3459. auto res = cli.send(req);
  3460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3461. EXPECT_EQ("/foo?a=1", target);
  3462. }
  3463. {
  3464. // Non-empty query in `req.path` -> `req.params` is not appended.
  3465. Client cli(HOST, port);
  3466. Request req;
  3467. req.method = "GET";
  3468. req.path = "/foo?b=2";
  3469. req.params.emplace("a", "1");
  3470. target.clear();
  3471. auto res = cli.send(req);
  3472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3473. EXPECT_EQ("/foo?b=2", target);
  3474. }
  3475. }
  3476. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3477. Server svr;
  3478. svr.Get("/", [](const Request &req, Response &) {
  3479. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3480. });
  3481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3482. auto se = detail::scope_exit([&] {
  3483. svr.stop();
  3484. thread.join();
  3485. ASSERT_FALSE(svr.is_running());
  3486. });
  3487. svr.wait_until_ready();
  3488. {
  3489. Client cli(HOST, PORT);
  3490. cli.set_path_encode(false);
  3491. auto res = cli.Get("/?something=%0A");
  3492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3493. EXPECT_EQ(StatusCode::OK_200, res->status);
  3494. }
  3495. }
  3496. TEST(BindServerTest, BindDualStack) {
  3497. Server svr;
  3498. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3499. res.set_content("Hello World!", "text/plain");
  3500. });
  3501. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3502. auto se = detail::scope_exit([&] {
  3503. svr.stop();
  3504. thread.join();
  3505. ASSERT_FALSE(svr.is_running());
  3506. });
  3507. svr.wait_until_ready();
  3508. {
  3509. Client cli("127.0.0.1", PORT);
  3510. auto res = cli.Get("/1");
  3511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3512. EXPECT_EQ(StatusCode::OK_200, res->status);
  3513. EXPECT_EQ("Hello World!", res->body);
  3514. }
  3515. {
  3516. Client cli("::1", PORT);
  3517. auto res = cli.Get("/1");
  3518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3519. EXPECT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ("Hello World!", res->body);
  3521. }
  3522. }
  3523. TEST(BindServerTest, BindAndListenSeparately) {
  3524. Server svr;
  3525. int port = svr.bind_to_any_port("0.0.0.0");
  3526. ASSERT_TRUE(svr.is_valid());
  3527. ASSERT_TRUE(port > 0);
  3528. svr.stop();
  3529. }
  3530. // Reports whether anything is still listening on a loopback port. A plain
  3531. // connect() is used instead of a Client request because a socket left bound by
  3532. // mistake accepts the connection into its backlog and never answers, which
  3533. // would hang the test instead of failing it.
  3534. static bool is_loopback_port_accepting(int port) {
  3535. sockaddr_in addr{};
  3536. addr.sin_family = AF_INET;
  3537. addr.sin_port = htons(static_cast<uint16_t>(port));
  3538. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3539. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3540. EXPECT_NE(sock, INVALID_SOCKET);
  3541. if (sock == INVALID_SOCKET) { return false; }
  3542. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3543. static_cast<socklen_t>(sizeof(addr)));
  3544. detail::close_socket(sock);
  3545. return ret == 0;
  3546. }
  3547. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3548. Server svr;
  3549. auto port = svr.bind_to_any_port("127.0.0.1");
  3550. ASSERT_TRUE(port > 0);
  3551. svr.stop();
  3552. // bind_to_any_port() already called listen(2), so until stop() closed the
  3553. // descriptor the port kept accepting connections into the backlog. ASSERT
  3554. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3555. // below blocks forever in the accept loop.
  3556. ASSERT_FALSE(is_loopback_port_accepting(port));
  3557. // Nothing is left to accept on, so listen_after_bind() must report failure
  3558. // instead of returning success without ever serving.
  3559. EXPECT_FALSE(svr.listen_after_bind());
  3560. // The failed listen marks the server decommissioned, so a waiter returns
  3561. // instead of spinning forever.
  3562. svr.wait_until_ready();
  3563. }
  3564. #ifdef CPPHTTPLIB_SSL_ENABLED
  3565. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3567. CLIENT_CA_CERT_DIR);
  3568. int port = svr.bind_to_any_port("0.0.0.0");
  3569. ASSERT_TRUE(svr.is_valid());
  3570. ASSERT_TRUE(port > 0);
  3571. svr.stop();
  3572. }
  3573. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3574. // or a rejected CustomRoute() registration would not stop the server binding.
  3575. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3577. CLIENT_CA_CERT_DIR);
  3578. ASSERT_TRUE(svr.is_valid());
  3579. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3580. EXPECT_FALSE(svr.is_valid());
  3581. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3582. }
  3583. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3584. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3585. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3586. int port = svr.bind_to_any_port("0.0.0.0");
  3587. ASSERT_TRUE(svr.is_valid());
  3588. ASSERT_TRUE(port > 0);
  3589. svr.stop();
  3590. }
  3591. TEST(BindServerTest, UpdateCertsPem) {
  3592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3593. int port = svr.bind_to_any_port("0.0.0.0");
  3594. ASSERT_TRUE(svr.is_valid());
  3595. ASSERT_TRUE(port > 0);
  3596. // Read PEM files
  3597. std::string cert_pem, key_pem, ca_pem;
  3598. read_file(SERVER_CERT_FILE, cert_pem);
  3599. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3600. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3601. // Update server certificates using PEM API
  3602. ASSERT_TRUE(
  3603. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3604. ASSERT_TRUE(svr.is_valid());
  3605. svr.stop();
  3606. }
  3607. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3608. // Start server with client CA (enables client auth)
  3609. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3610. ASSERT_TRUE(svr.is_valid());
  3611. bool handler_called = false;
  3612. svr.Get("/test", [&](const Request &req, Response &res) {
  3613. handler_called = true;
  3614. // Verify client certificate is present
  3615. auto cert = req.peer_cert();
  3616. EXPECT_TRUE(static_cast<bool>(cert));
  3617. res.set_content("ok", "text/plain");
  3618. });
  3619. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3620. auto se = detail::scope_exit([&] {
  3621. svr.stop();
  3622. t.join();
  3623. ASSERT_FALSE(svr.is_running());
  3624. });
  3625. svr.wait_until_ready();
  3626. // Read PEM files
  3627. std::string cert_pem, key_pem, ca_pem;
  3628. read_file(SERVER_CERT_FILE, cert_pem);
  3629. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3630. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3631. // Update server certificates and client CA using PEM API while server running
  3632. ASSERT_TRUE(
  3633. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3634. // Connect with client certificate
  3635. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3636. cli.enable_server_certificate_verification(false);
  3637. cli.set_connection_timeout(30);
  3638. auto res = cli.Get("/test");
  3639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3640. ASSERT_EQ(StatusCode::OK_200, res->status);
  3641. ASSERT_TRUE(handler_called);
  3642. EXPECT_EQ("ok", res->body);
  3643. }
  3644. #endif
  3645. TEST(ErrorHandlerTest, ContentLength) {
  3646. Server svr;
  3647. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3648. res.status = StatusCode::OK_200;
  3649. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3650. "text/html"); // <= Content-Length still 13
  3651. });
  3652. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3653. res.set_content("Hello World!\n", "text/plain");
  3654. res.status = 524;
  3655. });
  3656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3657. auto se = detail::scope_exit([&] {
  3658. svr.stop();
  3659. thread.join();
  3660. ASSERT_FALSE(svr.is_running());
  3661. });
  3662. svr.wait_until_ready();
  3663. {
  3664. Client cli(HOST, PORT);
  3665. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3667. EXPECT_EQ(StatusCode::OK_200, res->status);
  3668. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3669. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3670. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3671. }
  3672. }
  3673. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3674. TEST(ExceptionTest, WithoutExceptionHandler) {
  3675. Server svr;
  3676. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3677. throw std::runtime_error("exception...");
  3678. });
  3679. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3680. throw std::runtime_error("exception\r\n...");
  3681. });
  3682. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3683. auto se = detail::scope_exit([&] {
  3684. svr.stop();
  3685. listen_thread.join();
  3686. ASSERT_FALSE(svr.is_running());
  3687. });
  3688. svr.wait_until_ready();
  3689. Client cli("localhost", PORT);
  3690. {
  3691. auto res = cli.Get("/exception");
  3692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3693. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3694. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3695. }
  3696. {
  3697. auto res = cli.Get("/unknown");
  3698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3699. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3700. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3701. }
  3702. }
  3703. TEST(ExceptionTest, WithExceptionHandler) {
  3704. Server svr;
  3705. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3706. std::exception_ptr ep) {
  3707. EXPECT_FALSE(ep == nullptr);
  3708. try {
  3709. std::rethrow_exception(ep);
  3710. } catch (std::exception &e) {
  3711. EXPECT_EQ("abc", std::string(e.what()));
  3712. } catch (...) {}
  3713. res.status = StatusCode::InternalServerError_500;
  3714. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3715. "text/html"); // <= Content-Length still 13 at this point
  3716. });
  3717. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3718. res.set_content("Hello World!\n", "text/plain");
  3719. throw std::runtime_error("abc");
  3720. });
  3721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3722. auto se = detail::scope_exit([&] {
  3723. svr.stop();
  3724. thread.join();
  3725. ASSERT_FALSE(svr.is_running());
  3726. });
  3727. svr.wait_until_ready();
  3728. for (size_t i = 0; i < 10; i++) {
  3729. Client cli(HOST, PORT);
  3730. for (size_t j = 0; j < 100; j++) {
  3731. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3734. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3735. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3736. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3737. }
  3738. cli.set_keep_alive(true);
  3739. for (size_t j = 0; j < 100; j++) {
  3740. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3742. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3743. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3744. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3745. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3746. }
  3747. }
  3748. }
  3749. TEST(ExceptionTest, AndErrorHandler) {
  3750. Server svr;
  3751. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3752. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3753. });
  3754. svr.set_exception_handler(
  3755. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3756. EXPECT_FALSE(ep == nullptr);
  3757. try {
  3758. std::rethrow_exception(ep);
  3759. } catch (std::exception &e) {
  3760. res.set_content(e.what(), "text/html");
  3761. } catch (...) {}
  3762. res.status = StatusCode::InternalServerError_500;
  3763. });
  3764. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3765. throw std::runtime_error("EXCEPTION");
  3766. });
  3767. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3768. res.set_content("ERROR", "text/html");
  3769. res.status = StatusCode::InternalServerError_500;
  3770. });
  3771. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3772. auto se = detail::scope_exit([&] {
  3773. svr.stop();
  3774. thread.join();
  3775. ASSERT_FALSE(svr.is_running());
  3776. });
  3777. svr.wait_until_ready();
  3778. Client cli(HOST, PORT);
  3779. {
  3780. auto res = cli.Get("/exception");
  3781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3782. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3783. EXPECT_EQ("EXCEPTION", res->body);
  3784. }
  3785. {
  3786. auto res = cli.Get("/error");
  3787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3788. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3789. EXPECT_EQ("ERROR", res->body);
  3790. }
  3791. {
  3792. auto res = cli.Get("/invalid");
  3793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3795. EXPECT_EQ("NOT_FOUND", res->body);
  3796. }
  3797. }
  3798. #endif
  3799. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3800. // process_request() wraps only routing() in a try/catch, so an exception from
  3801. // any other user callback used to unwind into the task queue - which does not
  3802. // catch - and terminate the process. Each test below runs the server on a
  3803. // single worker thread: a guard that catches the exception but still loses the
  3804. // thread would otherwise be hidden by a spare worker serving the follow-up
  3805. // request. Note that a regression here aborts the whole test binary rather
  3806. // than failing one test.
  3807. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3808. Server svr;
  3809. svr.new_task_queue = [] { return new ThreadPool(1); };
  3810. std::atomic<int> reported{0};
  3811. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3812. if (err == Error::UserCallbackException) { reported++; }
  3813. });
  3814. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3815. res.set_content_provider(
  3816. 1024, "text/plain",
  3817. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3818. sink.write("hello", 5);
  3819. throw std::runtime_error("from the content provider");
  3820. });
  3821. });
  3822. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3823. res.set_content("ok", "text/plain");
  3824. });
  3825. auto port = svr.bind_to_any_port(HOST);
  3826. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3827. auto se = detail::scope_exit([&] {
  3828. svr.stop();
  3829. listen_thread.join();
  3830. ASSERT_FALSE(svr.is_running());
  3831. });
  3832. svr.wait_until_ready();
  3833. {
  3834. Client cli(HOST, port);
  3835. cli.set_read_timeout(5, 0);
  3836. EXPECT_FALSE(cli.Get("/throw"));
  3837. }
  3838. EXPECT_TRUE(svr.is_running());
  3839. EXPECT_EQ(1, reported.load());
  3840. // A request on a fresh connection is still served.
  3841. {
  3842. Client cli(HOST, port);
  3843. auto res = cli.Get("/ok");
  3844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3845. EXPECT_EQ(StatusCode::OK_200, res->status);
  3846. EXPECT_EQ("ok", res->body);
  3847. }
  3848. }
  3849. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3850. Server svr;
  3851. svr.new_task_queue = [] { return new ThreadPool(1); };
  3852. std::atomic<bool> should_throw{true};
  3853. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3854. res.set_content("hi", "text/plain");
  3855. });
  3856. svr.set_post_routing_handler(
  3857. [&](const Request & /*req*/, Response & /*res*/) {
  3858. if (should_throw) {
  3859. throw std::runtime_error("from the post-routing handler");
  3860. }
  3861. });
  3862. auto port = svr.bind_to_any_port(HOST);
  3863. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3864. auto se = detail::scope_exit([&] {
  3865. svr.stop();
  3866. listen_thread.join();
  3867. ASSERT_FALSE(svr.is_running());
  3868. });
  3869. svr.wait_until_ready();
  3870. {
  3871. Client cli(HOST, port);
  3872. cli.set_read_timeout(5, 0);
  3873. EXPECT_FALSE(cli.Get("/hi"));
  3874. }
  3875. EXPECT_TRUE(svr.is_running());
  3876. should_throw = false;
  3877. {
  3878. Client cli(HOST, port);
  3879. auto res = cli.Get("/hi");
  3880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3881. EXPECT_EQ(StatusCode::OK_200, res->status);
  3882. EXPECT_EQ("hi", res->body);
  3883. }
  3884. }
  3885. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3886. // The guard reports the caught exception through the error logger, which is
  3887. // a user callback too. A logger that throws has to be contained as well, or
  3888. // the process would terminate from inside the catch.
  3889. Server svr;
  3890. svr.new_task_queue = [] { return new ThreadPool(1); };
  3891. std::atomic<int> reported{0};
  3892. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3893. if (err == Error::UserCallbackException) {
  3894. reported++;
  3895. throw std::runtime_error("from the error logger");
  3896. }
  3897. });
  3898. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3899. res.set_content_provider(
  3900. 1024, "text/plain",
  3901. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3902. sink.write("hello", 5);
  3903. throw std::runtime_error("from the content provider");
  3904. });
  3905. });
  3906. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3907. res.set_content("ok", "text/plain");
  3908. });
  3909. auto port = svr.bind_to_any_port(HOST);
  3910. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3911. auto se = detail::scope_exit([&] {
  3912. svr.stop();
  3913. listen_thread.join();
  3914. ASSERT_FALSE(svr.is_running());
  3915. });
  3916. svr.wait_until_ready();
  3917. {
  3918. Client cli(HOST, port);
  3919. cli.set_read_timeout(5, 0);
  3920. EXPECT_FALSE(cli.Get("/throw"));
  3921. }
  3922. EXPECT_TRUE(svr.is_running());
  3923. EXPECT_EQ(1, reported.load());
  3924. {
  3925. Client cli(HOST, port);
  3926. auto res = cli.Get("/ok");
  3927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3928. EXPECT_EQ(StatusCode::OK_200, res->status);
  3929. EXPECT_EQ("ok", res->body);
  3930. }
  3931. }
  3932. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3933. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3934. // so the exception unwinds through the ws::WebSocket object on its way to
  3935. // the guard. None of the HTTP cases above cross that.
  3936. Server svr;
  3937. svr.new_task_queue = [] { return new ThreadPool(1); };
  3938. std::atomic<int> reported{0};
  3939. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3940. if (err == Error::UserCallbackException) { reported++; }
  3941. });
  3942. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3943. throw std::runtime_error("from the WebSocket handler");
  3944. });
  3945. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3946. res.set_content("ok", "text/plain");
  3947. });
  3948. auto port = svr.bind_to_any_port(HOST);
  3949. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3950. auto se = detail::scope_exit([&] {
  3951. svr.stop();
  3952. listen_thread.join();
  3953. ASSERT_FALSE(svr.is_running());
  3954. });
  3955. svr.wait_until_ready();
  3956. {
  3957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3958. "/ws");
  3959. auto res = client.connect();
  3960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3961. // The server dropped the connection instead of dying.
  3962. std::string msg;
  3963. EXPECT_FALSE(client.read(msg));
  3964. client.close();
  3965. }
  3966. EXPECT_TRUE(svr.is_running());
  3967. EXPECT_EQ(1, reported.load());
  3968. {
  3969. Client cli(HOST, port);
  3970. auto res = cli.Get("/ok");
  3971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3972. EXPECT_EQ(StatusCode::OK_200, res->status);
  3973. EXPECT_EQ("ok", res->body);
  3974. }
  3975. }
  3976. #ifdef CPPHTTPLIB_SSL_ENABLED
  3977. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3978. // SSLServer::process_and_close_socket() is a separate overload with its own
  3979. // guard, so it is exercised on its own.
  3980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3981. ASSERT_TRUE(svr.is_valid());
  3982. svr.new_task_queue = [] { return new ThreadPool(1); };
  3983. std::atomic<int> reported{0};
  3984. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3985. if (err == Error::UserCallbackException) { reported++; }
  3986. });
  3987. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3988. res.set_content_provider(
  3989. 1024, "text/plain",
  3990. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3991. sink.write("hello", 5);
  3992. throw std::runtime_error("from the content provider");
  3993. });
  3994. });
  3995. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3996. res.set_content("ok", "text/plain");
  3997. });
  3998. auto port = svr.bind_to_any_port(HOST);
  3999. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4000. auto se = detail::scope_exit([&] {
  4001. svr.stop();
  4002. listen_thread.join();
  4003. ASSERT_FALSE(svr.is_running());
  4004. });
  4005. svr.wait_until_ready();
  4006. {
  4007. SSLClient cli(HOST, port);
  4008. cli.enable_server_certificate_verification(false);
  4009. cli.set_read_timeout(5, 0);
  4010. EXPECT_FALSE(cli.Get("/throw"));
  4011. }
  4012. EXPECT_TRUE(svr.is_running());
  4013. EXPECT_EQ(1, reported.load());
  4014. {
  4015. SSLClient cli(HOST, port);
  4016. cli.enable_server_certificate_verification(false);
  4017. auto res = cli.Get("/ok");
  4018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4019. EXPECT_EQ(StatusCode::OK_200, res->status);
  4020. EXPECT_EQ("ok", res->body);
  4021. }
  4022. }
  4023. #endif
  4024. #endif
  4025. TEST(NoContentTest, ContentLength) {
  4026. Server svr;
  4027. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4028. res.status = StatusCode::NoContent_204;
  4029. });
  4030. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4031. auto se = detail::scope_exit([&] {
  4032. svr.stop();
  4033. thread.join();
  4034. ASSERT_FALSE(svr.is_running());
  4035. });
  4036. svr.wait_until_ready();
  4037. {
  4038. Client cli(HOST, PORT);
  4039. auto res = cli.Get("/hi");
  4040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4041. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4042. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4043. }
  4044. }
  4045. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4046. #ifdef CPPHTTPLIB_SSL_ENABLED
  4047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4048. ASSERT_TRUE(svr.is_valid());
  4049. #else
  4050. Server svr;
  4051. #endif
  4052. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4053. if (req.path == "/routing_handler") {
  4054. res.set_header("PRE_ROUTING", "on");
  4055. res.set_content("Routing Handler", "text/plain");
  4056. return httplib::Server::HandlerResponse::Handled;
  4057. }
  4058. return httplib::Server::HandlerResponse::Unhandled;
  4059. });
  4060. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4061. res.set_content("Error", "text/html");
  4062. });
  4063. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4064. if (req.path == "/routing_handler") {
  4065. res.set_header("POST_ROUTING", "on");
  4066. }
  4067. });
  4068. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4069. res.set_content("Hello World!\n", "text/plain");
  4070. });
  4071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4072. auto se = detail::scope_exit([&] {
  4073. svr.stop();
  4074. thread.join();
  4075. ASSERT_FALSE(svr.is_running());
  4076. });
  4077. svr.wait_until_ready();
  4078. {
  4079. #ifdef CPPHTTPLIB_SSL_ENABLED
  4080. SSLClient cli(HOST, PORT);
  4081. cli.enable_server_certificate_verification(false);
  4082. #else
  4083. Client cli(HOST, PORT);
  4084. #endif
  4085. auto res = cli.Get("/routing_handler");
  4086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4087. EXPECT_EQ(StatusCode::OK_200, res->status);
  4088. EXPECT_EQ("Routing Handler", res->body);
  4089. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4090. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4091. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4092. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4093. }
  4094. {
  4095. #ifdef CPPHTTPLIB_SSL_ENABLED
  4096. SSLClient cli(HOST, PORT);
  4097. cli.enable_server_certificate_verification(false);
  4098. #else
  4099. Client cli(HOST, PORT);
  4100. #endif
  4101. auto res = cli.Get("/hi");
  4102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4103. EXPECT_EQ(StatusCode::OK_200, res->status);
  4104. EXPECT_EQ("Hello World!\n", res->body);
  4105. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4106. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4107. }
  4108. {
  4109. #ifdef CPPHTTPLIB_SSL_ENABLED
  4110. SSLClient cli(HOST, PORT);
  4111. cli.enable_server_certificate_verification(false);
  4112. #else
  4113. Client cli(HOST, PORT);
  4114. #endif
  4115. auto res = cli.Get("/aaa");
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4118. EXPECT_EQ("Error", res->body);
  4119. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4120. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4121. }
  4122. }
  4123. TEST(RequestHandlerTest, PreRequestHandler) {
  4124. auto route_path = "/user/:user";
  4125. Server svr;
  4126. svr.Get("/hi", [](const Request &, Response &res) {
  4127. res.set_content("hi", "text/plain");
  4128. });
  4129. svr.Get(route_path, [](const Request &req, Response &res) {
  4130. res.set_content(req.path_params.at("user"), "text/plain");
  4131. });
  4132. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4133. if (req.matched_route == route_path) {
  4134. auto user = req.path_params.at("user");
  4135. if (user != "john") {
  4136. res.status = StatusCode::Forbidden_403;
  4137. res.set_content("error", "text/html");
  4138. return Server::HandlerResponse::Handled;
  4139. }
  4140. }
  4141. return Server::HandlerResponse::Unhandled;
  4142. });
  4143. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4144. auto se = detail::scope_exit([&] {
  4145. svr.stop();
  4146. thread.join();
  4147. ASSERT_FALSE(svr.is_running());
  4148. });
  4149. svr.wait_until_ready();
  4150. Client cli(HOST, PORT);
  4151. {
  4152. auto res = cli.Get("/hi");
  4153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4154. EXPECT_EQ(StatusCode::OK_200, res->status);
  4155. EXPECT_EQ("hi", res->body);
  4156. }
  4157. {
  4158. auto res = cli.Get("/user/john");
  4159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4160. EXPECT_EQ(StatusCode::OK_200, res->status);
  4161. EXPECT_EQ("john", res->body);
  4162. }
  4163. {
  4164. auto res = cli.Get("/user/invalid-user");
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4167. EXPECT_EQ("error", res->body);
  4168. }
  4169. }
  4170. // The pre-request handler must run before the request body is read, so a
  4171. // rejected request never forces the server to buffer a (potentially large)
  4172. // body. Here the posted body is larger than the payload limit: if the body
  4173. // were read first the server would answer 413, but because the pre-request
  4174. // handler runs first it answers 403 and the body is never read.
  4175. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4176. Server svr;
  4177. svr.set_payload_max_length(8);
  4178. auto handler_ran = false;
  4179. svr.Post("/reject", [&](const Request &req, Response &res) {
  4180. handler_ran = true;
  4181. res.set_content(req.body, "text/plain");
  4182. });
  4183. svr.Post("/accept", [](const Request &req, Response &res) {
  4184. res.set_content(req.body, "text/plain");
  4185. });
  4186. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4187. if (req.matched_route == "/reject") {
  4188. res.status = StatusCode::Forbidden_403;
  4189. res.set_content("denied", "text/plain");
  4190. return Server::HandlerResponse::Handled;
  4191. }
  4192. return Server::HandlerResponse::Unhandled;
  4193. });
  4194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4195. auto se = detail::scope_exit([&] {
  4196. svr.stop();
  4197. thread.join();
  4198. ASSERT_FALSE(svr.is_running());
  4199. });
  4200. svr.wait_until_ready();
  4201. Client cli(HOST, PORT);
  4202. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4203. // rejects with 403 before the body is read, so 413 is never reached.
  4204. {
  4205. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4207. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4208. EXPECT_EQ("denied", res->body);
  4209. EXPECT_FALSE(handler_ran);
  4210. }
  4211. // An approved route still reads the body and enforces the payload limit.
  4212. {
  4213. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4215. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4216. }
  4217. }
  4218. TEST(UserDataTest, BasicOperations) {
  4219. httplib::UserData ud;
  4220. // Initially empty
  4221. EXPECT_FALSE(ud.has("key"));
  4222. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4223. // set and get
  4224. ud.set("key", 42);
  4225. EXPECT_TRUE(ud.has("key"));
  4226. auto *p = ud.get<int>("key");
  4227. ASSERT_NE(nullptr, p);
  4228. EXPECT_EQ(42, *p);
  4229. // Type mismatch → nullptr
  4230. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4231. // Overwrite with different type
  4232. ud.set("key", std::string("hello"));
  4233. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4234. auto *s = ud.get<std::string>("key");
  4235. ASSERT_NE(nullptr, s);
  4236. EXPECT_EQ("hello", *s);
  4237. // erase
  4238. ud.erase("key");
  4239. EXPECT_FALSE(ud.has("key"));
  4240. // clear
  4241. ud.set("a", 1);
  4242. ud.set("b", 2);
  4243. ud.clear();
  4244. EXPECT_FALSE(ud.has("a"));
  4245. EXPECT_FALSE(ud.has("b"));
  4246. }
  4247. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4248. struct AuthCtx {
  4249. std::string user_id;
  4250. };
  4251. Server svr;
  4252. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4253. res.user_data.set("auth", AuthCtx{"alice"});
  4254. return Server::HandlerResponse::Unhandled;
  4255. });
  4256. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4257. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4258. ASSERT_NE(nullptr, ctx);
  4259. res.set_content("Hello " + ctx->user_id, "text/plain");
  4260. });
  4261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4262. auto se = detail::scope_exit([&] {
  4263. svr.stop();
  4264. thread.join();
  4265. ASSERT_FALSE(svr.is_running());
  4266. });
  4267. svr.wait_until_ready();
  4268. Client cli(HOST, PORT);
  4269. auto res = cli.Get("/me");
  4270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4271. EXPECT_EQ(StatusCode::OK_200, res->status);
  4272. EXPECT_EQ("Hello alice", res->body);
  4273. }
  4274. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4275. struct RoleCtx {
  4276. std::string role;
  4277. };
  4278. Server svr;
  4279. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4280. res.user_data.set("role", RoleCtx{"admin"});
  4281. return Server::HandlerResponse::Unhandled;
  4282. });
  4283. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4284. auto *ctx = res.user_data.get<RoleCtx>("role");
  4285. ASSERT_NE(nullptr, ctx);
  4286. res.set_content(ctx->role, "text/plain");
  4287. });
  4288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4289. auto se = detail::scope_exit([&] {
  4290. svr.stop();
  4291. thread.join();
  4292. ASSERT_FALSE(svr.is_running());
  4293. });
  4294. svr.wait_until_ready();
  4295. Client cli(HOST, PORT);
  4296. auto res = cli.Get("/role");
  4297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4298. EXPECT_EQ(StatusCode::OK_200, res->status);
  4299. EXPECT_EQ("admin", res->body);
  4300. }
  4301. TEST(InvalidFormatTest, StatusCode) {
  4302. Server svr;
  4303. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4304. res.set_content("Hello World!\n", "text/plain");
  4305. res.status = 9999; // Status should be a three-digit code...
  4306. });
  4307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4308. auto se = detail::scope_exit([&] {
  4309. svr.stop();
  4310. thread.join();
  4311. ASSERT_FALSE(svr.is_running());
  4312. });
  4313. svr.wait_until_ready();
  4314. {
  4315. Client cli(HOST, PORT);
  4316. auto res = cli.Get("/hi");
  4317. ASSERT_FALSE(res);
  4318. }
  4319. }
  4320. TEST(URLFragmentTest, WithFragment) {
  4321. Server svr;
  4322. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4323. EXPECT_TRUE(req.target == "/hi");
  4324. });
  4325. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4326. auto se = detail::scope_exit([&] {
  4327. svr.stop();
  4328. thread.join();
  4329. ASSERT_FALSE(svr.is_running());
  4330. });
  4331. svr.wait_until_ready();
  4332. {
  4333. Client cli(HOST, PORT);
  4334. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4335. EXPECT_TRUE(res);
  4336. EXPECT_EQ(StatusCode::OK_200, res->status);
  4337. res = cli.Get("/hi%23key1=val1=key2=val2");
  4338. EXPECT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4340. }
  4341. }
  4342. TEST(HeaderWriter, SetHeaderWriter) {
  4343. Server svr;
  4344. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4345. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4346. return detail::write_headers(strm, hdrs);
  4347. });
  4348. svr.Get("/hi", [](const Request &req, Response &res) {
  4349. auto it = req.headers.find("CustomClientHeader");
  4350. EXPECT_TRUE(it != req.headers.end());
  4351. EXPECT_EQ(it->second, "CustomClientValue");
  4352. res.set_content("Hello World!\n", "text/plain");
  4353. });
  4354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4355. auto se = detail::scope_exit([&] {
  4356. svr.stop();
  4357. thread.join();
  4358. ASSERT_FALSE(svr.is_running());
  4359. });
  4360. svr.wait_until_ready();
  4361. {
  4362. Client cli(HOST, PORT);
  4363. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4364. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4365. return detail::write_headers(strm, hdrs);
  4366. });
  4367. auto res = cli.Get("/hi");
  4368. EXPECT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. auto it = res->headers.find("CustomServerHeader");
  4371. EXPECT_TRUE(it != res->headers.end());
  4372. EXPECT_EQ(it->second, "CustomServerValue");
  4373. }
  4374. }
  4375. class ServerTest : public ::testing::Test {
  4376. protected:
  4377. ServerTest()
  4378. : cli_(HOST, PORT)
  4379. #ifdef CPPHTTPLIB_SSL_ENABLED
  4380. ,
  4381. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4382. #endif
  4383. {
  4384. #ifdef CPPHTTPLIB_SSL_ENABLED
  4385. cli_.enable_server_certificate_verification(false);
  4386. #endif
  4387. // Allow LARGE_DATA (100MB) responses
  4388. cli_.set_payload_max_length(200 * 1024 * 1024);
  4389. }
  4390. virtual void SetUp() {
  4391. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4392. svr_.set_payload_max_length(200 * 1024 * 1024);
  4393. svr_.set_mount_point("/", "./www");
  4394. svr_.set_mount_point("/mount", "./www2");
  4395. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4396. svr_.Get("/hi",
  4397. [&](const Request & /*req*/, Response &res) {
  4398. res.set_content("Hello World!", "text/plain");
  4399. })
  4400. .Get("/file_content",
  4401. [&](const Request & /*req*/, Response &res) {
  4402. res.set_file_content("./www/dir/test.html");
  4403. })
  4404. .Get("/file_content_with_content_type",
  4405. [&](const Request & /*req*/, Response &res) {
  4406. res.set_file_content("./www/file", "text/plain");
  4407. })
  4408. .Get("/invalid_file_content",
  4409. [&](const Request & /*req*/, Response &res) {
  4410. res.set_file_content("./www/dir/invalid_file_path");
  4411. })
  4412. .Get("/http_response_splitting",
  4413. [&](const Request & /*req*/, Response &res) {
  4414. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4415. EXPECT_EQ(0U, res.headers.size());
  4416. EXPECT_FALSE(res.has_header("a"));
  4417. res.set_header("a", "1\nSet-Cookie: a=1");
  4418. EXPECT_EQ(0U, res.headers.size());
  4419. EXPECT_FALSE(res.has_header("a"));
  4420. res.set_header("a", "1\rSet-Cookie: a=1");
  4421. EXPECT_EQ(0U, res.headers.size());
  4422. EXPECT_FALSE(res.has_header("a"));
  4423. res.set_header("a\r\nb", "0");
  4424. EXPECT_EQ(0U, res.headers.size());
  4425. EXPECT_FALSE(res.has_header("a"));
  4426. res.set_header("a\rb", "0");
  4427. EXPECT_EQ(0U, res.headers.size());
  4428. EXPECT_FALSE(res.has_header("a"));
  4429. res.set_header("a\nb", "0");
  4430. EXPECT_EQ(0U, res.headers.size());
  4431. EXPECT_FALSE(res.has_header("a"));
  4432. res.set_redirect("1\r\nSet-Cookie: a=1");
  4433. EXPECT_EQ(0U, res.headers.size());
  4434. EXPECT_FALSE(res.has_header("Location"));
  4435. })
  4436. .Get("/slow",
  4437. [&](const Request & /*req*/, Response &res) {
  4438. std::this_thread::sleep_for(std::chrono::seconds(4));
  4439. res.set_content("slow", "text/plain");
  4440. })
  4441. #if 0
  4442. .Post("/slowpost",
  4443. [&](const Request & /*req*/, Response &res) {
  4444. std::this_thread::sleep_for(std::chrono::seconds(2));
  4445. res.set_content("slow", "text/plain");
  4446. })
  4447. #endif
  4448. .Get("/remote_addr",
  4449. [&](const Request &req, Response &res) {
  4450. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4451. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4452. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4453. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4454. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4455. #endif
  4456. res.set_content(req.remote_addr, "text/plain");
  4457. })
  4458. .Get("/local_addr",
  4459. [&](const Request &req, Response &res) {
  4460. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4461. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4462. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4463. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4464. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4465. #endif
  4466. auto local_addr = req.local_addr;
  4467. auto local_port = std::to_string(req.local_port);
  4468. res.set_content(local_addr.append(":").append(local_port),
  4469. "text/plain");
  4470. })
  4471. .Get("/endwith%",
  4472. [&](const Request & /*req*/, Response &res) {
  4473. res.set_content("Hello World!", "text/plain");
  4474. })
  4475. .Get("/a\\+\\+b",
  4476. [&](const Request &req, Response &res) {
  4477. ASSERT_TRUE(req.has_param("a +b"));
  4478. auto val = req.get_param_value("a +b");
  4479. res.set_content(val, "text/plain");
  4480. })
  4481. .Get("/", [&](const Request & /*req*/,
  4482. Response &res) { res.set_redirect("/hi"); })
  4483. .Post("/1",
  4484. [](const Request & /*req*/, Response &res) {
  4485. res.set_redirect("/2", StatusCode::SeeOther_303);
  4486. })
  4487. .Get("/2",
  4488. [](const Request & /*req*/, Response &res) {
  4489. res.set_content("redirected.", "text/plain");
  4490. res.status = StatusCode::OK_200;
  4491. })
  4492. .Post("/person",
  4493. [&](const Request &req, Response &res) {
  4494. if (req.has_param("name") && req.has_param("note")) {
  4495. persons_[req.get_param_value("name")] =
  4496. req.get_param_value("note");
  4497. } else {
  4498. res.status = StatusCode::BadRequest_400;
  4499. }
  4500. })
  4501. .Put("/person",
  4502. [&](const Request &req, Response &res) {
  4503. if (req.has_param("name") && req.has_param("note")) {
  4504. persons_[req.get_param_value("name")] =
  4505. req.get_param_value("note");
  4506. } else {
  4507. res.status = StatusCode::BadRequest_400;
  4508. }
  4509. })
  4510. .Get("/person/(.*)",
  4511. [&](const Request &req, Response &res) {
  4512. string name = req.matches[1];
  4513. if (persons_.find(name) != persons_.end()) {
  4514. auto note = persons_[name];
  4515. res.set_content(note, "text/plain");
  4516. } else {
  4517. res.status = StatusCode::NotFound_404;
  4518. }
  4519. })
  4520. .Delete("/person",
  4521. [&](const Request &req, Response &res) {
  4522. if (req.has_param("name")) {
  4523. string name = req.get_param_value("name");
  4524. if (persons_.find(name) != persons_.end()) {
  4525. persons_.erase(name);
  4526. res.set_content("DELETED", "text/plain");
  4527. } else {
  4528. res.status = StatusCode::NotFound_404;
  4529. }
  4530. } else {
  4531. res.status = StatusCode::BadRequest_400;
  4532. }
  4533. })
  4534. .Post("/x-www-form-urlencoded-json",
  4535. [&](const Request &req, Response &res) {
  4536. auto json = req.get_param_value("json");
  4537. ASSERT_EQ(JSON_DATA, json);
  4538. res.set_content(json, "appliation/json");
  4539. res.status = StatusCode::OK_200;
  4540. })
  4541. .Get("/streamed-chunked",
  4542. [&](const Request & /*req*/, Response &res) {
  4543. res.set_chunked_content_provider(
  4544. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4545. sink.os << "123";
  4546. sink.os << "456";
  4547. sink.os << "789";
  4548. sink.done();
  4549. return true;
  4550. });
  4551. })
  4552. .Get("/streamed-chunked-with-prohibited-trailer",
  4553. [&](const Request & /*req*/, Response &res) {
  4554. auto i = new int(0);
  4555. // Declare both a prohibited trailer (Content-Length) and an
  4556. // allowed one
  4557. res.set_header("Trailer", "Content-Length, X-Allowed");
  4558. res.set_chunked_content_provider(
  4559. "text/plain",
  4560. [i](size_t /*offset*/, DataSink &sink) {
  4561. switch (*i) {
  4562. case 0: sink.os << "123"; break;
  4563. case 1: sink.os << "456"; break;
  4564. case 2: sink.os << "789"; break;
  4565. case 3: {
  4566. sink.done_with_trailer(
  4567. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4568. } break;
  4569. }
  4570. (*i)++;
  4571. return true;
  4572. },
  4573. [i](bool success) {
  4574. EXPECT_TRUE(success);
  4575. delete i;
  4576. });
  4577. })
  4578. .Get("/streamed-chunked2",
  4579. [&](const Request & /*req*/, Response &res) {
  4580. auto i = new int(0);
  4581. res.set_chunked_content_provider(
  4582. "text/plain",
  4583. [i](size_t /*offset*/, DataSink &sink) {
  4584. switch (*i) {
  4585. case 0: sink.os << "123"; break;
  4586. case 1: sink.os << "456"; break;
  4587. case 2: sink.os << "789"; break;
  4588. case 3: sink.done(); break;
  4589. }
  4590. (*i)++;
  4591. return true;
  4592. },
  4593. [i](bool success) {
  4594. EXPECT_TRUE(success);
  4595. delete i;
  4596. });
  4597. })
  4598. .Get("/streamed-chunked-with-trailer",
  4599. [&](const Request & /*req*/, Response &res) {
  4600. auto i = new int(0);
  4601. res.set_header("Trailer", "Dummy1, Dummy2");
  4602. res.set_chunked_content_provider(
  4603. "text/plain",
  4604. [i](size_t /*offset*/, DataSink &sink) {
  4605. switch (*i) {
  4606. case 0: sink.os << "123"; break;
  4607. case 1: sink.os << "456"; break;
  4608. case 2: sink.os << "789"; break;
  4609. case 3: {
  4610. sink.done_with_trailer(
  4611. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4612. } break;
  4613. }
  4614. (*i)++;
  4615. return true;
  4616. },
  4617. [i](bool success) {
  4618. EXPECT_TRUE(success);
  4619. delete i;
  4620. });
  4621. })
  4622. .Get("/streamed",
  4623. [&](const Request & /*req*/, Response &res) {
  4624. res.set_content_provider(
  4625. 6, "text/plain",
  4626. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4627. sink.os << (offset < 3 ? "a" : "b");
  4628. return true;
  4629. });
  4630. })
  4631. .Get("/streamed-without-length",
  4632. [&](const Request & /*req*/, Response &res) {
  4633. auto data = new std::string("abcdefg");
  4634. res.set_content_provider(
  4635. "text/plain",
  4636. [data](size_t offset, DataSink &sink) {
  4637. if (offset < data->size()) {
  4638. sink.os << data->substr(offset);
  4639. }
  4640. sink.done();
  4641. return true;
  4642. },
  4643. [data](bool success) {
  4644. EXPECT_TRUE(success);
  4645. delete data;
  4646. });
  4647. })
  4648. .Get("/streamed-with-range",
  4649. [&](const Request &req, Response &res) {
  4650. auto data = new std::string("abcdefg");
  4651. // An explicit status keeps the server from picking the 206 it
  4652. // would otherwise choose for a ranged request, so the response
  4653. // is not a partial representation.
  4654. auto status = req.get_param_value("status");
  4655. if (status == "200") {
  4656. res.status = StatusCode::OK_200;
  4657. } else if (status == "403") {
  4658. res.status = StatusCode::Forbidden_403;
  4659. }
  4660. res.set_content_provider(
  4661. data->size(), "text/plain",
  4662. [data](size_t offset, size_t length, DataSink &sink) {
  4663. size_t DATA_CHUNK_SIZE = 4;
  4664. const auto &d = *data;
  4665. auto out_len =
  4666. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4667. auto ret =
  4668. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4669. EXPECT_TRUE(ret);
  4670. return true;
  4671. },
  4672. [data, &req](bool success) {
  4673. EXPECT_EQ(success, !req.has_param("error"));
  4674. delete data;
  4675. });
  4676. })
  4677. .Get("/streamed-cancel",
  4678. [&](const Request & /*req*/, Response &res) {
  4679. res.set_content_provider(
  4680. size_t(-1), "text/plain",
  4681. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4682. sink.os << "data_chunk";
  4683. return true;
  4684. });
  4685. })
  4686. .Get("/regex-with-delimiter",
  4687. [&](const Request &req, Response & /*res*/) {
  4688. ASSERT_TRUE(req.has_param("key"));
  4689. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4690. })
  4691. .Get("/with-range",
  4692. [&](const Request & /*req*/, Response &res) {
  4693. res.set_content("abcdefg", "text/plain");
  4694. })
  4695. .Get("/test-start-time",
  4696. [&](const Request &req, Response & /*res*/) {
  4697. EXPECT_NE(req.start_time_,
  4698. std::chrono::steady_clock::time_point::min());
  4699. })
  4700. .Get("/with-range-customized-response",
  4701. [&](const Request & /*req*/, Response &res) {
  4702. res.status = StatusCode::BadRequest_400;
  4703. res.set_content(JSON_DATA, "application/json");
  4704. })
  4705. .Post("/chunked",
  4706. [&](const Request &req, Response & /*res*/) {
  4707. EXPECT_EQ(req.body, "dechunked post body");
  4708. })
  4709. .Post("/large-chunked",
  4710. [&](const Request &req, Response & /*res*/) {
  4711. std::string expected(6 * 30 * 1024u, 'a');
  4712. EXPECT_EQ(req.body, expected);
  4713. })
  4714. .Post("/multipart",
  4715. [&](const Request &req, Response & /*res*/) {
  4716. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4717. req.form.get_field_count("text2") +
  4718. req.form.get_field_count("file3") +
  4719. req.form.get_field_count("file4"));
  4720. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4721. req.form.get_file_count("file2"));
  4722. ASSERT_TRUE(!req.form.has_file("???"));
  4723. ASSERT_TRUE(!req.form.has_field("???"));
  4724. ASSERT_TRUE(req.body.empty());
  4725. {
  4726. const auto &text = req.form.get_field("text1");
  4727. EXPECT_EQ("text default", text);
  4728. }
  4729. {
  4730. const auto &text = req.form.get_field("text2");
  4731. EXPECT_EQ("aωb", text);
  4732. }
  4733. {
  4734. const auto &file = req.form.get_file("file1");
  4735. EXPECT_EQ("hello.txt", file.filename);
  4736. EXPECT_EQ("text/plain", file.content_type);
  4737. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4738. }
  4739. {
  4740. const auto &file = req.form.get_file("file2");
  4741. EXPECT_EQ("world.json", file.filename);
  4742. EXPECT_EQ("application/json", file.content_type);
  4743. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4744. }
  4745. {
  4746. const auto &text = req.form.get_field("file3");
  4747. EXPECT_EQ(0u, text.size());
  4748. }
  4749. {
  4750. const auto &text = req.form.get_field("file4");
  4751. EXPECT_EQ(0u, text.size());
  4752. }
  4753. })
  4754. .Post("/multipart/multi_file_values",
  4755. [&](const Request &req, Response & /*res*/) {
  4756. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4757. req.form.get_field_count("multi_text1"));
  4758. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4759. ASSERT_TRUE(!req.form.has_file("???"));
  4760. ASSERT_TRUE(!req.form.has_field("???"));
  4761. ASSERT_TRUE(req.body.empty());
  4762. {
  4763. const auto &text = req.form.get_field("text");
  4764. EXPECT_EQ("default text", text);
  4765. }
  4766. {
  4767. const auto &text1_values = req.form.get_fields("multi_text1");
  4768. EXPECT_EQ(2u, text1_values.size());
  4769. EXPECT_EQ("aaaaa", text1_values[0]);
  4770. EXPECT_EQ("bbbbb", text1_values[1]);
  4771. }
  4772. {
  4773. const auto &file1_values = req.form.get_files("multi_file1");
  4774. EXPECT_EQ(2u, file1_values.size());
  4775. auto file1 = file1_values[0];
  4776. EXPECT_EQ(file1.filename, "hello.txt");
  4777. EXPECT_EQ(file1.content_type, "text/plain");
  4778. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4779. auto file2 = file1_values[1];
  4780. EXPECT_EQ(file2.filename, "world.json");
  4781. EXPECT_EQ(file2.content_type, "application/json");
  4782. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4783. }
  4784. })
  4785. .Post("/empty",
  4786. [&](const Request &req, Response &res) {
  4787. EXPECT_EQ(req.body, "");
  4788. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4789. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4790. res.set_content("empty", "text/plain");
  4791. })
  4792. .Post("/empty-no-content-type",
  4793. [&](const Request &req, Response &res) {
  4794. EXPECT_EQ(req.body, "");
  4795. EXPECT_FALSE(req.has_header("Content-Type"));
  4796. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4797. res.set_content("empty-no-content-type", "text/plain");
  4798. })
  4799. .Post("/path-only",
  4800. [&](const Request &req, Response &res) {
  4801. EXPECT_EQ(req.body, "");
  4802. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4803. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4804. res.set_content("path-only", "text/plain");
  4805. })
  4806. .Post("/path-headers-only",
  4807. [&](const Request &req, Response &res) {
  4808. EXPECT_EQ(req.body, "");
  4809. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4810. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4811. EXPECT_EQ("world", req.get_header_value("hello"));
  4812. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4813. res.set_content("path-headers-only", "text/plain");
  4814. })
  4815. .Post("/post-large",
  4816. [&](const Request &req, Response &res) {
  4817. EXPECT_EQ(req.body, LARGE_DATA);
  4818. res.set_content(req.body, "text/plain");
  4819. })
  4820. .Post("/post-loopback",
  4821. [&](const Request &, Response &res,
  4822. ContentReader const &content_reader) {
  4823. std::string body;
  4824. content_reader([&](const char *data, size_t data_length) {
  4825. body.append(data, data_length);
  4826. return true;
  4827. });
  4828. res.set_content(body, "text/plain");
  4829. })
  4830. .Put("/put-loopback",
  4831. [&](const Request &, Response &res,
  4832. ContentReader const &content_reader) {
  4833. std::string body;
  4834. content_reader([&](const char *data, size_t data_length) {
  4835. body.append(data, data_length);
  4836. return true;
  4837. });
  4838. res.set_content(body, "text/plain");
  4839. })
  4840. .Patch("/patch-loopback",
  4841. [&](const Request &, Response &res,
  4842. ContentReader const &content_reader) {
  4843. std::string body;
  4844. content_reader([&](const char *data, size_t data_length) {
  4845. body.append(data, data_length);
  4846. return true;
  4847. });
  4848. res.set_content(body, "text/plain");
  4849. })
  4850. .Put("/empty-no-content-type",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_EQ(req.body, "");
  4853. EXPECT_FALSE(req.has_header("Content-Type"));
  4854. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4855. res.set_content("empty-no-content-type", "text/plain");
  4856. })
  4857. .Put("/put",
  4858. [&](const Request &req, Response &res) {
  4859. EXPECT_EQ(req.body, "PUT");
  4860. res.set_content(req.body, "text/plain");
  4861. })
  4862. .Put("/put-large",
  4863. [&](const Request &req, Response &res) {
  4864. EXPECT_EQ(req.body, LARGE_DATA);
  4865. res.set_content(req.body, "text/plain");
  4866. })
  4867. .Patch("/patch",
  4868. [&](const Request &req, Response &res) {
  4869. EXPECT_EQ(req.body, "PATCH");
  4870. res.set_content(req.body, "text/plain");
  4871. })
  4872. .Delete("/delete",
  4873. [&](const Request & /*req*/, Response &res) {
  4874. res.set_content("DELETE", "text/plain");
  4875. })
  4876. .Delete("/delete-body",
  4877. [&](const Request &req, Response &res) {
  4878. EXPECT_EQ(req.body, "content");
  4879. res.set_content(req.body, "text/plain");
  4880. })
  4881. .Options(R"(\*)",
  4882. [&](const Request & /*req*/, Response &res) {
  4883. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4884. })
  4885. .CustomRoute("PROPFIND", "/dav/:id",
  4886. [&](const Request &req, Response &res) {
  4887. res.set_header("x-body-size",
  4888. std::to_string(req.body.size()));
  4889. res.set_header("x-matched-route", req.matched_route);
  4890. res.set_header("x-dav-id", req.path_params.at("id"));
  4891. res.status = StatusCode::MultiStatus_207;
  4892. res.set_content(req.body, "application/xml");
  4893. })
  4894. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4895. [&](const Request &req, Response &res) {
  4896. res.set_header("x-dav-match", req.matches[1]);
  4897. res.status = StatusCode::MultiStatus_207;
  4898. })
  4899. .CustomRoute("MKCOL", "/dav-mkcol",
  4900. [&](const Request &req, Response &res) {
  4901. EXPECT_TRUE(req.body.empty());
  4902. res.status = StatusCode::Created_201;
  4903. })
  4904. .CustomRoute(
  4905. "REPORT", "/dav-report",
  4906. [&](const Request & /*req*/, Response &res,
  4907. const ContentReader &content_reader) {
  4908. std::string body;
  4909. content_reader([&](const char *data, size_t data_length) {
  4910. body.append(data, data_length);
  4911. return true;
  4912. });
  4913. res.set_header("x-body-size", std::to_string(body.size()));
  4914. res.status = StatusCode::MultiStatus_207;
  4915. res.set_content(body, "application/xml");
  4916. })
  4917. .Get("/request-target",
  4918. [&](const Request &req, Response & /*res*/) {
  4919. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4920. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4921. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4922. })
  4923. .Get("/long-query-value",
  4924. [&](const Request &req, Response & /*res*/) {
  4925. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4926. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4927. })
  4928. .Get("/too-long-query-value",
  4929. [&](const Request &req, Response & /*res*/) {
  4930. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4931. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4932. })
  4933. .Get("/array-param",
  4934. [&](const Request &req, Response & /*res*/) {
  4935. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4936. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4937. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4938. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4939. })
  4940. .Get("/array-param-values",
  4941. [&](const Request &req, Response & /*res*/) {
  4942. auto values = req.get_param_values("array");
  4943. EXPECT_EQ(3u, values.size());
  4944. EXPECT_EQ("value1", values[0]);
  4945. EXPECT_EQ("value2", values[1]);
  4946. EXPECT_EQ("value3", values[2]);
  4947. auto empty = req.get_param_values("nonexistent");
  4948. EXPECT_TRUE(empty.empty());
  4949. })
  4950. .Post("/validate-no-multiple-headers",
  4951. [&](const Request &req, Response & /*res*/) {
  4952. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4953. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4954. })
  4955. .Post("/content_receiver",
  4956. [&](const Request &req, Response &res,
  4957. const ContentReader &content_reader) {
  4958. if (req.is_multipart_form_data()) {
  4959. std::vector<FormData> items;
  4960. content_reader(
  4961. [&](const FormData &file) {
  4962. items.push_back(file);
  4963. return true;
  4964. },
  4965. [&](const char *data, size_t data_length) {
  4966. items.back().content.append(data, data_length);
  4967. return true;
  4968. });
  4969. EXPECT_EQ(5u, items.size());
  4970. {
  4971. const auto &file = get_file_value(items, "text1");
  4972. EXPECT_TRUE(file.filename.empty());
  4973. EXPECT_EQ("text default", file.content);
  4974. }
  4975. {
  4976. const auto &file = get_file_value(items, "text2");
  4977. EXPECT_TRUE(file.filename.empty());
  4978. EXPECT_EQ("aωb", file.content);
  4979. }
  4980. {
  4981. const auto &file = get_file_value(items, "file1");
  4982. EXPECT_EQ("hello.txt", file.filename);
  4983. EXPECT_EQ("text/plain", file.content_type);
  4984. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4985. }
  4986. {
  4987. const auto &file = get_file_value(items, "file2");
  4988. EXPECT_EQ("world.json", file.filename);
  4989. EXPECT_EQ("application/json", file.content_type);
  4990. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4991. }
  4992. {
  4993. const auto &file = get_file_value(items, "file3");
  4994. EXPECT_TRUE(file.filename.empty());
  4995. EXPECT_EQ("application/octet-stream", file.content_type);
  4996. EXPECT_EQ(0u, file.content.size());
  4997. }
  4998. } else {
  4999. std::string body;
  5000. content_reader([&](const char *data, size_t data_length) {
  5001. EXPECT_EQ(7U, data_length);
  5002. body.append(data, data_length);
  5003. return true;
  5004. });
  5005. EXPECT_EQ(body, "content");
  5006. res.set_content(body, "text/plain");
  5007. }
  5008. })
  5009. .Put("/content_receiver",
  5010. [&](const Request & /*req*/, Response &res,
  5011. const ContentReader &content_reader) {
  5012. std::string body;
  5013. content_reader([&](const char *data, size_t data_length) {
  5014. body.append(data, data_length);
  5015. return true;
  5016. });
  5017. EXPECT_EQ(body, "content");
  5018. res.set_content(body, "text/plain");
  5019. })
  5020. .Patch("/content_receiver",
  5021. [&](const Request & /*req*/, Response &res,
  5022. const ContentReader &content_reader) {
  5023. std::string body;
  5024. content_reader([&](const char *data, size_t data_length) {
  5025. body.append(data, data_length);
  5026. return true;
  5027. });
  5028. EXPECT_EQ(body, "content");
  5029. res.set_content(body, "text/plain");
  5030. })
  5031. .Post("/query-string-and-body",
  5032. [&](const Request &req, Response & /*res*/) {
  5033. ASSERT_TRUE(req.has_param("key"));
  5034. EXPECT_EQ(req.get_param_value("key"), "value");
  5035. EXPECT_EQ(req.body, "content");
  5036. })
  5037. .Get("/last-request",
  5038. [&](const Request &req, Response & /*res*/) {
  5039. EXPECT_EQ("close", req.get_header_value("Connection"));
  5040. })
  5041. .Get(R"(/redirect/(\d+))",
  5042. [&](const Request &req, Response &res) {
  5043. auto num = std::stoi(req.matches[1]) + 1;
  5044. std::string url = "/redirect/" + std::to_string(num);
  5045. res.set_redirect(url);
  5046. })
  5047. .Post("/binary",
  5048. [&](const Request &req, Response &res) {
  5049. EXPECT_EQ(4U, req.body.size());
  5050. EXPECT_EQ("application/octet-stream",
  5051. req.get_header_value("Content-Type"));
  5052. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5053. res.set_content(req.body, "application/octet-stream");
  5054. })
  5055. .Put("/binary",
  5056. [&](const Request &req, Response &res) {
  5057. EXPECT_EQ(4U, req.body.size());
  5058. EXPECT_EQ("application/octet-stream",
  5059. req.get_header_value("Content-Type"));
  5060. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5061. res.set_content(req.body, "application/octet-stream");
  5062. })
  5063. .Patch("/binary",
  5064. [&](const Request &req, Response &res) {
  5065. EXPECT_EQ(4U, req.body.size());
  5066. EXPECT_EQ("application/octet-stream",
  5067. req.get_header_value("Content-Type"));
  5068. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5069. res.set_content(req.body, "application/octet-stream");
  5070. })
  5071. .Delete("/binary",
  5072. [&](const Request &req, Response &res) {
  5073. EXPECT_EQ(4U, req.body.size());
  5074. EXPECT_EQ("application/octet-stream",
  5075. req.get_header_value("Content-Type"));
  5076. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5077. res.set_content(req.body, "application/octet-stream");
  5078. })
  5079. .Get("/issue1772",
  5080. [&](const Request & /*req*/, Response &res) {
  5081. res.status = 401;
  5082. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5083. })
  5084. .Delete("/issue609",
  5085. [](const httplib::Request &, httplib::Response &res,
  5086. const httplib::ContentReader &) {
  5087. res.set_content("ok", "text/plain");
  5088. })
  5089. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5090. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5091. .Get("/compress",
  5092. [&](const Request & /*req*/, Response &res) {
  5093. res.set_content(
  5094. "12345678901234567890123456789012345678901234567890123456789"
  5095. "01234567890123456789012345678901234567890",
  5096. "text/plain");
  5097. })
  5098. .Get("/compress-with-charset",
  5099. [&](const Request & /*req*/, Response &res) {
  5100. res.set_content(
  5101. "12345678901234567890123456789012345678901234567890123456789"
  5102. "01234567890123456789012345678901234567890",
  5103. "application/json; charset=utf-8");
  5104. })
  5105. .Get("/nocompress",
  5106. [&](const Request & /*req*/, Response &res) {
  5107. res.set_content(
  5108. "12345678901234567890123456789012345678901234567890123456789"
  5109. "01234567890123456789012345678901234567890",
  5110. "application/octet-stream");
  5111. })
  5112. .Post("/compress-multipart",
  5113. [&](const Request &req, Response & /*res*/) {
  5114. EXPECT_EQ(2u, req.form.fields.size());
  5115. ASSERT_TRUE(!req.form.has_field("???"));
  5116. {
  5117. const auto &text = req.form.get_field("key1");
  5118. EXPECT_EQ("test", text);
  5119. }
  5120. {
  5121. const auto &text = req.form.get_field("key2");
  5122. EXPECT_EQ("--abcdefg123", text);
  5123. }
  5124. })
  5125. #endif
  5126. ;
  5127. persons_["john"] = "programmer";
  5128. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5129. svr_.wait_until_ready();
  5130. }
  5131. virtual void TearDown() {
  5132. svr_.stop();
  5133. if (!request_threads_.empty()) {
  5134. std::this_thread::sleep_for(std::chrono::seconds(1));
  5135. for (auto &t : request_threads_) {
  5136. t.join();
  5137. }
  5138. }
  5139. t_.join();
  5140. }
  5141. map<string, string> persons_;
  5142. #ifdef CPPHTTPLIB_SSL_ENABLED
  5143. SSLClient cli_;
  5144. SSLServer svr_;
  5145. #else
  5146. Client cli_;
  5147. Server svr_;
  5148. #endif
  5149. thread t_;
  5150. std::vector<thread> request_threads_;
  5151. };
  5152. TEST_F(ServerTest, GetMethod200) {
  5153. auto res = cli_.Get("/hi");
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. EXPECT_EQ("HTTP/1.1", res->version);
  5156. EXPECT_EQ(StatusCode::OK_200, res->status);
  5157. EXPECT_EQ("OK", res->reason);
  5158. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5159. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5160. EXPECT_EQ("Hello World!", res->body);
  5161. }
  5162. TEST_F(ServerTest, GetEmptyFile) {
  5163. auto res = cli_.Get("/empty_file");
  5164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5165. EXPECT_EQ(StatusCode::OK_200, res->status);
  5166. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5168. EXPECT_EQ("", res->body);
  5169. }
  5170. TEST_F(ServerTest, GetFileContent) {
  5171. auto res = cli_.Get("/file_content");
  5172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5175. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5176. EXPECT_EQ("test.html", res->body);
  5177. }
  5178. TEST_F(ServerTest, GetFileContentWithRange) {
  5179. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5181. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5182. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5183. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5184. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5185. EXPECT_EQ("est", res->body);
  5186. }
  5187. TEST_F(ServerTest, GetFileContentWithContentType) {
  5188. auto res = cli_.Get("/file_content_with_content_type");
  5189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5190. EXPECT_EQ(StatusCode::OK_200, res->status);
  5191. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5192. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5193. EXPECT_EQ("file\n", res->body);
  5194. }
  5195. TEST_F(ServerTest, GetInvalidFileContent) {
  5196. auto res = cli_.Get("/invalid_file_content");
  5197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5198. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5199. }
  5200. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5201. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ("HTTP/1.1", res->version);
  5204. EXPECT_EQ(StatusCode::OK_200, res->status);
  5205. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5206. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5207. EXPECT_EQ("Hello World!", res->body);
  5208. }
  5209. TEST_F(ServerTest, GetMethod302) {
  5210. auto res = cli_.Get("/");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::Found_302, res->status);
  5213. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5214. }
  5215. TEST_F(ServerTest, GetMethod302Redirect) {
  5216. cli_.set_follow_location(true);
  5217. auto res = cli_.Get("/");
  5218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5219. EXPECT_EQ(StatusCode::OK_200, res->status);
  5220. EXPECT_EQ("Hello World!", res->body);
  5221. EXPECT_EQ("/hi", res->location);
  5222. }
  5223. TEST_F(ServerTest, GetMethod404) {
  5224. auto res = cli_.Get("/invalid");
  5225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5227. }
  5228. TEST_F(ServerTest, HeadMethod200) {
  5229. auto res = cli_.Head("/hi");
  5230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5231. EXPECT_EQ(StatusCode::OK_200, res->status);
  5232. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5233. EXPECT_TRUE(res->body.empty());
  5234. }
  5235. TEST_F(ServerTest, HeadMethod200Static) {
  5236. auto res = cli_.Head("/mount/dir/index.html");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. EXPECT_EQ(StatusCode::OK_200, res->status);
  5239. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5240. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5241. EXPECT_TRUE(res->body.empty());
  5242. }
  5243. TEST_F(ServerTest, HeadMethod404) {
  5244. auto res = cli_.Head("/invalid");
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5247. EXPECT_TRUE(res->body.empty());
  5248. }
  5249. TEST_F(ServerTest, GetMethodPersonJohn) {
  5250. auto res = cli_.Get("/person/john");
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5254. EXPECT_EQ("programmer", res->body);
  5255. }
  5256. TEST_F(ServerTest, PostMethod1) {
  5257. auto res = cli_.Get("/person/john1");
  5258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5259. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5260. res = cli_.Post("/person", "name=john1&note=coder",
  5261. "application/x-www-form-urlencoded");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. ASSERT_EQ(StatusCode::OK_200, res->status);
  5264. res = cli_.Get("/person/john1");
  5265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5266. ASSERT_EQ(StatusCode::OK_200, res->status);
  5267. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5268. ASSERT_EQ("coder", res->body);
  5269. }
  5270. TEST_F(ServerTest, PostMethod2) {
  5271. auto res = cli_.Get("/person/john2");
  5272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5273. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5274. Params params;
  5275. params.emplace("name", "john2");
  5276. params.emplace("note", "coder");
  5277. res = cli_.Post("/person", params);
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. ASSERT_EQ(StatusCode::OK_200, res->status);
  5280. res = cli_.Get("/person/john2");
  5281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5282. ASSERT_EQ(StatusCode::OK_200, res->status);
  5283. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5284. ASSERT_EQ("coder", res->body);
  5285. }
  5286. TEST_F(ServerTest, PutMethod3) {
  5287. auto res = cli_.Get("/person/john3");
  5288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5289. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5290. Params params;
  5291. params.emplace("name", "john3");
  5292. params.emplace("note", "coder");
  5293. res = cli_.Put("/person", params);
  5294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5295. ASSERT_EQ(StatusCode::OK_200, res->status);
  5296. res = cli_.Get("/person/john3");
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. ASSERT_EQ(StatusCode::OK_200, res->status);
  5299. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5300. ASSERT_EQ("coder", res->body);
  5301. }
  5302. TEST_F(ServerTest, DeleteMethod1) {
  5303. auto res = cli_.Get("/person/john4");
  5304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5305. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5306. Params params;
  5307. params.emplace("name", "john4");
  5308. params.emplace("note", "coder");
  5309. res = cli_.Post("/person", params);
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. ASSERT_EQ(StatusCode::OK_200, res->status);
  5312. res = cli_.Get("/person/john4");
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. ASSERT_EQ(StatusCode::OK_200, res->status);
  5315. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5316. ASSERT_EQ("coder", res->body);
  5317. Params delete_params;
  5318. delete_params.emplace("name", "john4");
  5319. res = cli_.Delete("/person", delete_params);
  5320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5321. ASSERT_EQ(StatusCode::OK_200, res->status);
  5322. ASSERT_EQ("DELETED", res->body);
  5323. res = cli_.Get("/person/john4");
  5324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5325. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5326. }
  5327. TEST_F(ServerTest, DeleteMethod2) {
  5328. auto res = cli_.Get("/person/john5");
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5331. Params params;
  5332. params.emplace("name", "john5");
  5333. params.emplace("note", "developer");
  5334. res = cli_.Post("/person", params);
  5335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5336. ASSERT_EQ(StatusCode::OK_200, res->status);
  5337. res = cli_.Get("/person/john5");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. ASSERT_EQ(StatusCode::OK_200, res->status);
  5340. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5341. ASSERT_EQ("developer", res->body);
  5342. Params delete_params;
  5343. delete_params.emplace("name", "john5");
  5344. Headers headers;
  5345. headers.emplace("Custom-Header", "test-value");
  5346. res = cli_.Delete("/person", headers, delete_params);
  5347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5348. ASSERT_EQ(StatusCode::OK_200, res->status);
  5349. ASSERT_EQ("DELETED", res->body);
  5350. res = cli_.Get("/person/john5");
  5351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5352. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5353. }
  5354. TEST_F(ServerTest, DeleteMethod3) {
  5355. auto res = cli_.Get("/person/john6");
  5356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5357. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5358. Params params;
  5359. params.emplace("name", "john6");
  5360. params.emplace("note", "tester");
  5361. res = cli_.Post("/person", params);
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::OK_200, res->status);
  5364. res = cli_.Get("/person/john6");
  5365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5366. ASSERT_EQ(StatusCode::OK_200, res->status);
  5367. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5368. ASSERT_EQ("tester", res->body);
  5369. Params delete_params;
  5370. delete_params.emplace("name", "john6");
  5371. Headers headers;
  5372. headers.emplace("Custom-Header", "test-value");
  5373. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5375. ASSERT_EQ(StatusCode::OK_200, res->status);
  5376. ASSERT_EQ("DELETED", res->body);
  5377. res = cli_.Get("/person/john6");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5380. }
  5381. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5382. Params params;
  5383. params.emplace("json", JSON_DATA);
  5384. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. ASSERT_EQ(JSON_DATA, res->body);
  5388. }
  5389. TEST_F(ServerTest, PostEmptyContent) {
  5390. auto res = cli_.Post("/empty", "", "text/plain");
  5391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5392. ASSERT_EQ(StatusCode::OK_200, res->status);
  5393. ASSERT_EQ("empty", res->body);
  5394. }
  5395. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5396. auto res = cli_.Post("/empty-no-content-type");
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. ASSERT_EQ(StatusCode::OK_200, res->status);
  5399. ASSERT_EQ("empty-no-content-type", res->body);
  5400. }
  5401. TEST_F(ServerTest, PostPathOnly) {
  5402. auto res = cli_.Post("/path-only");
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. ASSERT_EQ(StatusCode::OK_200, res->status);
  5405. ASSERT_EQ("path-only", res->body);
  5406. }
  5407. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5408. auto res = cli_.Post("/path-headers-only",
  5409. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5411. ASSERT_EQ(StatusCode::OK_200, res->status);
  5412. ASSERT_EQ("path-headers-only", res->body);
  5413. }
  5414. TEST_F(ServerTest, PostLarge) {
  5415. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. ASSERT_EQ(StatusCode::OK_200, res->status);
  5418. EXPECT_EQ(LARGE_DATA, res->body);
  5419. }
  5420. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5421. auto res = cli_.Put("/empty-no-content-type");
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. ASSERT_EQ(StatusCode::OK_200, res->status);
  5424. ASSERT_EQ("empty-no-content-type", res->body);
  5425. }
  5426. TEST_F(ServerTest, GetMethodDir) {
  5427. auto res = cli_.Get("/dir/");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5431. auto body = R"(<html>
  5432. <head>
  5433. </head>
  5434. <body>
  5435. <a href="/dir/test.html">Test</a>
  5436. <a href="/hi">hi</a>
  5437. </body>
  5438. </html>
  5439. )";
  5440. EXPECT_EQ(body, res->body);
  5441. }
  5442. TEST_F(ServerTest, GetMethodDirTest) {
  5443. auto res = cli_.Get("/dir/test.html");
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. EXPECT_EQ(StatusCode::OK_200, res->status);
  5446. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5447. EXPECT_EQ("test.html", res->body);
  5448. }
  5449. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5450. auto res = cli_.Get("/dir/../dir/test.html");
  5451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5452. EXPECT_EQ(StatusCode::OK_200, res->status);
  5453. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5454. EXPECT_EQ("test.html", res->body);
  5455. }
  5456. TEST_F(ServerTest, GetMethodInvalidPath) {
  5457. auto res = cli_.Get("/dir/../test.html");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5460. }
  5461. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5462. auto res = cli_.Get("/../www/dir/test.html");
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5465. }
  5466. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5467. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5470. }
  5471. TEST_F(ServerTest, GetMethodDirMountTest) {
  5472. auto res = cli_.Get("/mount/dir/test.html");
  5473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5474. EXPECT_EQ(StatusCode::OK_200, res->status);
  5475. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5476. EXPECT_EQ("test.html", res->body);
  5477. }
  5478. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5479. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5483. EXPECT_EQ("test.html", res->body);
  5484. }
  5485. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5486. auto res = cli_.Get("/mount/dir/../test.html");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5489. }
  5490. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5491. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5493. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5494. }
  5495. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5496. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5499. }
  5500. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5501. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5504. }
  5505. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5506. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5508. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5509. }
  5510. TEST_F(ServerTest, PostMethod303) {
  5511. auto res = cli_.Post("/1", "body", "text/plain");
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5514. EXPECT_EQ("/2", res->get_header_value("Location"));
  5515. }
  5516. TEST_F(ServerTest, PostMethod303Redirect) {
  5517. cli_.set_follow_location(true);
  5518. auto res = cli_.Post("/1", "body", "text/plain");
  5519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5520. EXPECT_EQ(StatusCode::OK_200, res->status);
  5521. EXPECT_EQ("redirected.", res->body);
  5522. EXPECT_EQ("/2", res->location);
  5523. }
  5524. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5525. auto res = cli_.Get("/dir/test.abcde");
  5526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5527. EXPECT_EQ(StatusCode::OK_200, res->status);
  5528. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5529. EXPECT_EQ("abcde", res->body);
  5530. }
  5531. TEST_F(ServerTest, StaticFileRange) {
  5532. auto res =
  5533. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5536. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5537. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5538. EXPECT_EQ(true, res->has_header("Content-Range"));
  5539. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5540. EXPECT_EQ(std::string("cd"), res->body);
  5541. }
  5542. TEST_F(ServerTest, StaticFileRanges) {
  5543. auto res = cli_.Get("/dir/test.abcde",
  5544. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5547. EXPECT_TRUE(
  5548. res->get_header_value("Content-Type")
  5549. .find(
  5550. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5551. 0);
  5552. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5553. }
  5554. TEST_F(ServerTest, StaticFileRangeHead) {
  5555. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5557. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5558. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5559. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5560. EXPECT_EQ(true, res->has_header("Content-Range"));
  5561. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5562. }
  5563. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5564. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5566. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5568. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5569. EXPECT_EQ(true, res->has_header("Content-Range"));
  5570. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5571. res->get_header_value("Content-Range"));
  5572. EXPECT_EQ("LAST\n", res->body);
  5573. }
  5574. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5575. auto res =
  5576. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5578. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5579. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5580. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5581. EXPECT_EQ(true, res->has_header("Content-Range"));
  5582. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5583. }
  5584. TEST_F(ServerTest, StaticFileBigFile) {
  5585. auto res = cli_.Get("/dir/1MB.txt");
  5586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5587. EXPECT_EQ(StatusCode::OK_200, res->status);
  5588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5589. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5590. }
  5591. TEST_F(ServerTest, InvalidBaseDirMount) {
  5592. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5593. }
  5594. TEST_F(ServerTest, Binary) {
  5595. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5596. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5597. "application/octet-stream");
  5598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5599. ASSERT_EQ(StatusCode::OK_200, res->status);
  5600. ASSERT_EQ(4U, res->body.size());
  5601. res = cli_.Put("/binary", binary.data(), binary.size(),
  5602. "application/octet-stream");
  5603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5604. ASSERT_EQ(StatusCode::OK_200, res->status);
  5605. ASSERT_EQ(4U, res->body.size());
  5606. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5607. "application/octet-stream");
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. ASSERT_EQ(StatusCode::OK_200, res->status);
  5610. ASSERT_EQ(4U, res->body.size());
  5611. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5612. "application/octet-stream");
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. ASSERT_EQ(StatusCode::OK_200, res->status);
  5615. ASSERT_EQ(4U, res->body.size());
  5616. }
  5617. TEST_F(ServerTest, BinaryString) {
  5618. auto binary = std::string("\x00\x01\x02\x03", 4);
  5619. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. ASSERT_EQ(StatusCode::OK_200, res->status);
  5622. ASSERT_EQ(4U, res->body.size());
  5623. res = cli_.Put("/binary", binary, "application/octet-stream");
  5624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5625. ASSERT_EQ(StatusCode::OK_200, res->status);
  5626. ASSERT_EQ(4U, res->body.size());
  5627. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5629. ASSERT_EQ(StatusCode::OK_200, res->status);
  5630. ASSERT_EQ(4U, res->body.size());
  5631. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. ASSERT_EQ(StatusCode::OK_200, res->status);
  5634. ASSERT_EQ(4U, res->body.size());
  5635. }
  5636. TEST_F(ServerTest, EmptyRequest) {
  5637. auto res = cli_.Get("");
  5638. ASSERT_TRUE(!res);
  5639. EXPECT_EQ(Error::Connection, res.error());
  5640. }
  5641. TEST_F(ServerTest, LongRequest) {
  5642. std::string request;
  5643. for (size_t i = 0; i < 545; i++) {
  5644. request += "/TooLongRequest";
  5645. }
  5646. request += "OK";
  5647. auto res = cli_.Get(request.c_str());
  5648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5649. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5650. }
  5651. TEST_F(ServerTest, TooLongRequest) {
  5652. std::string request;
  5653. for (size_t i = 0; i < 546; i++) {
  5654. request += "/TooLongRequest";
  5655. }
  5656. request += "_NG";
  5657. auto start = std::chrono::high_resolution_clock::now();
  5658. cli_.set_keep_alive(true);
  5659. auto res = cli_.Get(request.c_str());
  5660. auto end = std::chrono::high_resolution_clock::now();
  5661. auto elapsed =
  5662. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5663. .count();
  5664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5665. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5666. EXPECT_LE(elapsed, 1000);
  5667. EXPECT_EQ("close", res->get_header_value("Connection"));
  5668. EXPECT_FALSE(cli_.is_socket_open());
  5669. }
  5670. TEST_F(ServerTest, AlmostTooLongRequest) {
  5671. // test for #2046 - URI length check shouldn't include other content on req
  5672. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5673. // leading /, space, HTTP/1.1)
  5674. std::string request =
  5675. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5676. auto res = cli_.Get(request.c_str());
  5677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5678. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5679. }
  5680. TEST_F(ServerTest, LongHeader) {
  5681. Request req;
  5682. req.method = "GET";
  5683. req.path = "/hi";
  5684. std::string host_and_port;
  5685. host_and_port += HOST;
  5686. host_and_port += ":";
  5687. host_and_port += std::to_string(PORT);
  5688. req.headers.emplace("Host", host_and_port.c_str());
  5689. req.headers.emplace("Accept", "*/*");
  5690. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5691. req.headers.emplace(
  5692. "Header-Name",
  5693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5721. "@@@@@@@@@@@@@@@@");
  5722. auto res = std::make_shared<Response>();
  5723. auto error = Error::Success;
  5724. auto ret = cli_.send(req, *res, error);
  5725. ASSERT_TRUE(ret);
  5726. EXPECT_EQ(StatusCode::OK_200, res->status);
  5727. }
  5728. TEST_F(ServerTest, LongQueryValue) {
  5729. auto start = std::chrono::high_resolution_clock::now();
  5730. cli_.set_keep_alive(true);
  5731. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5732. auto end = std::chrono::high_resolution_clock::now();
  5733. auto elapsed =
  5734. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5735. .count();
  5736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5737. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5738. EXPECT_LE(elapsed, 1000);
  5739. EXPECT_EQ("close", res->get_header_value("Connection"));
  5740. EXPECT_FALSE(cli_.is_socket_open());
  5741. }
  5742. TEST_F(ServerTest, TooLongQueryValue) {
  5743. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5744. ASSERT_FALSE(res);
  5745. EXPECT_EQ(Error::Read, res.error());
  5746. }
  5747. TEST_F(ServerTest, TooLongHeader) {
  5748. Request req;
  5749. req.method = "GET";
  5750. req.path = "/hi";
  5751. std::string host_and_port;
  5752. host_and_port += HOST;
  5753. host_and_port += ":";
  5754. host_and_port += std::to_string(PORT);
  5755. req.headers.emplace("Host", host_and_port.c_str());
  5756. req.headers.emplace("Accept", "*/*");
  5757. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5758. req.headers.emplace(
  5759. "Header-Name",
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5788. "@@@@@@@@@@@@@@@@@");
  5789. auto res = std::make_shared<Response>();
  5790. auto error = Error::Success;
  5791. auto ret = cli_.send(req, *res, error);
  5792. ASSERT_TRUE(ret);
  5793. EXPECT_EQ(StatusCode::OK_200, res->status);
  5794. }
  5795. TEST_F(ServerTest, HeaderCountAtLimit) {
  5796. // Test with headers just under the 100 limit
  5797. httplib::Headers headers;
  5798. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5799. // This should keep us just under the 100 header limit
  5800. for (int i = 0; i < 95; i++) {
  5801. std::string name = "X-Test-Header-" + std::to_string(i);
  5802. std::string value = "value" + std::to_string(i);
  5803. headers.emplace(name, value);
  5804. }
  5805. // This should work fine as we're under the limit
  5806. auto res = cli_.Get("/hi", headers);
  5807. EXPECT_TRUE(res);
  5808. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5809. }
  5810. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5811. // Test with many headers to exceed the 100 limit
  5812. httplib::Headers headers;
  5813. // Add 150 headers to definitely exceed the 100 limit
  5814. for (int i = 0; i < 150; i++) {
  5815. std::string name = "X-Test-Header-" + std::to_string(i);
  5816. std::string value = "value" + std::to_string(i);
  5817. headers.emplace(name, value);
  5818. }
  5819. // This should fail due to exceeding header count limit
  5820. cli_.set_keep_alive(true);
  5821. auto res = cli_.Get("/hi", headers);
  5822. // The server should respond with 400 Bad Request
  5823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5824. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5825. EXPECT_EQ("close", res->get_header_value("Connection"));
  5826. EXPECT_FALSE(cli_.is_socket_open());
  5827. }
  5828. TEST_F(ServerTest, PercentEncoding) {
  5829. auto res = cli_.Get("/e%6edwith%");
  5830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5831. EXPECT_EQ(StatusCode::OK_200, res->status);
  5832. }
  5833. TEST_F(ServerTest, PercentEncodingUnicode) {
  5834. auto res = cli_.Get("/e%u006edwith%");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. }
  5838. TEST_F(ServerTest, InvalidPercentEncoding) {
  5839. auto res = cli_.Get("/%endwith%");
  5840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5841. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5842. }
  5843. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5844. auto res = cli_.Get("/%uendwith%");
  5845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5846. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5847. }
  5848. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5849. auto res = cli_.Get("/hello?aaa=bbb%");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5852. }
  5853. TEST_F(ServerTest, PlusSignEncoding) {
  5854. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. EXPECT_EQ(StatusCode::OK_200, res->status);
  5857. EXPECT_EQ("a +b", res->body);
  5858. }
  5859. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5860. // This test simulates a potential DoS attack using many headers
  5861. // to verify our security fix prevents memory exhaustion
  5862. httplib::Headers attack_headers;
  5863. // Attempt to add many headers like an attacker would (200 headers to far
  5864. // exceed limit)
  5865. for (int i = 0; i < 200; i++) {
  5866. std::string name = "X-Attack-Header-" + std::to_string(i);
  5867. std::string value = "attack_payload_" + std::to_string(i);
  5868. attack_headers.emplace(name, value);
  5869. }
  5870. // Try to POST with excessive headers
  5871. cli_.set_keep_alive(true);
  5872. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5873. // Should either fail or return 400 Bad Request due to security limit
  5874. if (res) {
  5875. // If we get a response, it should be 400 Bad Request
  5876. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5877. EXPECT_EQ("close", res->get_header_value("Connection"));
  5878. }
  5879. EXPECT_FALSE(cli_.is_socket_open());
  5880. }
  5881. TEST_F(ServerTest, MultipartFormData) {
  5882. UploadFormDataItems items = {
  5883. {"text1", "text default", "", ""},
  5884. {"text2", "aωb", "", ""},
  5885. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5886. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5887. {"file3", "", "", "application/octet-stream"},
  5888. {"file4", "", "", " application/json tmp-string "}};
  5889. auto res = cli_.Post("/multipart", items);
  5890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5891. EXPECT_EQ(StatusCode::OK_200, res->status);
  5892. }
  5893. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5894. UploadFormDataItems items = {
  5895. {"text", "default text", "", ""},
  5896. {"multi_text1", "aaaaa", "", ""},
  5897. {"multi_text1", "bbbbb", "", ""},
  5898. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5899. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5900. "application/json"},
  5901. };
  5902. auto res = cli_.Post("/multipart/multi_file_values", items);
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. EXPECT_EQ(StatusCode::OK_200, res->status);
  5905. }
  5906. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5907. auto res = cli_.Get("/hi");
  5908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5909. EXPECT_EQ(StatusCode::OK_200, res->status);
  5910. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5911. EXPECT_EQ("Hello World!", res->body);
  5912. }
  5913. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5914. Request req;
  5915. req.method = "POST";
  5916. req.path = "/chunked";
  5917. std::string host_and_port;
  5918. host_and_port += HOST;
  5919. host_and_port += ":";
  5920. host_and_port += std::to_string(PORT);
  5921. req.headers.emplace("Host", host_and_port.c_str());
  5922. req.headers.emplace("Accept", "*/*");
  5923. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5924. req.headers.emplace("Content-Type", "text/plain");
  5925. req.headers.emplace("Content-Length", "0");
  5926. req.headers.emplace(
  5927. "Transfer-Encoding",
  5928. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5929. // Client does not chunk, so make a chunked body manually.
  5930. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5931. auto res = std::make_shared<Response>();
  5932. auto error = Error::Success;
  5933. auto ret = cli_.send(req, *res, error);
  5934. ASSERT_TRUE(ret);
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. }
  5937. template <typename ClientT>
  5938. static void expect_chunked_body_status(ClientT &cli, const char *body,
  5939. int expected_status) {
  5940. Request req;
  5941. req.method = "POST";
  5942. req.path = "/chunked";
  5943. std::string host_and_port;
  5944. host_and_port += HOST;
  5945. host_and_port += ":";
  5946. host_and_port += std::to_string(PORT);
  5947. req.headers.emplace("Host", host_and_port.c_str());
  5948. req.headers.emplace("Content-Length", "0");
  5949. req.headers.emplace("Transfer-Encoding", "chunked");
  5950. req.body = body;
  5951. auto res = std::make_shared<Response>();
  5952. auto error = Error::Success;
  5953. ASSERT_TRUE(cli.send(req, *res, error));
  5954. EXPECT_EQ(expected_status, res->status);
  5955. }
  5956. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5957. // rather than treat them as valid lengths.
  5958. template <typename ClientT>
  5959. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5960. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  5961. }
  5962. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5963. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5964. }
  5965. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5966. expect_chunked_body_rejected(
  5967. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5968. }
  5969. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  5970. // chunk-size line carries no CR, LF or other control character ahead of its
  5971. // terminator. Such a line must be refused rather than read as extension text.
  5972. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  5973. expect_chunked_body_rejected(
  5974. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5975. }
  5976. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  5977. expect_chunked_body_rejected(
  5978. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5979. }
  5980. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  5981. expect_chunked_body_rejected(
  5982. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5983. }
  5984. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  5985. // The literal stays split: a hex escape consumes every hex digit that
  5986. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  5987. expect_chunked_body_rejected(
  5988. cli_, "4;a\x01"
  5989. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5990. }
  5991. TEST_F(ServerTest, AcceptsChunkExtension) {
  5992. expect_chunked_body_status(cli_,
  5993. "4;name=value\r\ndech\r\n"
  5994. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  5995. "0;last\r\n\r\n",
  5996. StatusCode::OK_200);
  5997. }
  5998. TEST_F(ServerTest, GetStreamed2) {
  5999. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6002. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6003. EXPECT_EQ(true, res->has_header("Content-Range"));
  6004. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6005. EXPECT_EQ(std::string("ab"), res->body);
  6006. }
  6007. TEST_F(ServerTest, GetStreamed) {
  6008. auto res = cli_.Get("/streamed");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::OK_200, res->status);
  6011. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6012. EXPECT_EQ(std::string("aaabbb"), res->body);
  6013. }
  6014. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6015. auto res = cli_.Get("/streamed-without-length",
  6016. Headers{make_range_header({{0, -1}})});
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ(false, res->has_header("Content-Length"));
  6020. EXPECT_EQ(false, res->has_header("Content-Range"));
  6021. EXPECT_EQ(std::string("abcdefg"), res->body);
  6022. }
  6023. TEST_F(ServerTest, GetStreamedWithRange1) {
  6024. auto res =
  6025. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6028. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6029. EXPECT_EQ(true, res->has_header("Content-Range"));
  6030. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6031. EXPECT_EQ(std::string("def"), res->body);
  6032. }
  6033. TEST_F(ServerTest, GetStreamedWithRange2) {
  6034. auto res =
  6035. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6037. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6038. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6039. EXPECT_EQ(true, res->has_header("Content-Range"));
  6040. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6041. EXPECT_EQ(std::string("bcdefg"), res->body);
  6042. }
  6043. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6044. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6047. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6048. EXPECT_EQ(true, res->has_header("Content-Range"));
  6049. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6050. EXPECT_EQ(std::string("efg"), res->body);
  6051. }
  6052. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6053. auto res =
  6054. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6056. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6057. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6058. EXPECT_EQ(false, res->has_header("Content-Range"));
  6059. EXPECT_EQ(0U, res->body.size());
  6060. }
  6061. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6062. // Only a 206 is served as a partial representation. Under any other status
  6063. // `apply_ranges()` reported the full content length, so the body must match
  6064. // that header, and the content provider must never be asked for an offset
  6065. // outside the representation.
  6066. auto check = [&](int status, const char *range) {
  6067. auto path =
  6068. std::string("/streamed-with-range?status=") + std::to_string(status);
  6069. auto ctx = path + " Range: " + range;
  6070. auto res = cli_.Get(path, Headers{{"Range", range}});
  6071. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6072. EXPECT_EQ(status, res->status) << ctx;
  6073. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6074. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6075. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6076. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6077. };
  6078. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6079. check(403, "bytes=3-5");
  6080. // The offset is far past the representation.
  6081. check(403, "bytes=100000-100200");
  6082. // `first_pos` is still -1 here, and the bounds asserts in
  6083. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6084. check(403, "bytes=-3");
  6085. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6086. // multipart branch would have written one that is empty.
  6087. check(403, "bytes=1-2, 4-5");
  6088. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6089. // covers the whole representation.
  6090. check(200, "bytes=3-5");
  6091. check(200, "bytes=1-2, 4-5");
  6092. }
  6093. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6094. auto res =
  6095. cli_.Get("/streamed-with-range",
  6096. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6097. "92233720368547758079223372036854775807"}});
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6100. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6101. EXPECT_EQ(false, res->has_header("Content-Range"));
  6102. EXPECT_EQ(0U, res->body.size());
  6103. }
  6104. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6105. auto res = cli_.Get(
  6106. "/with-range",
  6107. Headers{{"Range",
  6108. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6109. {"Accept-Encoding", ""}});
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6112. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6113. EXPECT_EQ(true, res->has_header("Content-Range"));
  6114. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6115. EXPECT_EQ(std::string("abcdefg"), res->body);
  6116. }
  6117. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6118. auto res = cli_.Get("/with-range", Headers{
  6119. {"Range", "bytes=0-"},
  6120. {"Accept-Encoding", ""},
  6121. });
  6122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6123. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6124. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6125. EXPECT_EQ(true, res->has_header("Content-Range"));
  6126. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6127. EXPECT_EQ(std::string("abcdefg"), res->body);
  6128. }
  6129. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6130. auto res = cli_.Get("/streamed-with-range",
  6131. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6134. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6135. EXPECT_EQ(false, res->has_header("Content-Range"));
  6136. EXPECT_EQ(267U, res->body.size());
  6137. // Check that both range contents are present
  6138. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6139. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6140. // Check that Content-Range headers are present for both ranges
  6141. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6142. std::string::npos);
  6143. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6144. std::string::npos);
  6145. }
  6146. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6147. Ranges ranges;
  6148. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6149. ranges.emplace_back(0, -1);
  6150. }
  6151. auto res = cli_.Get("/streamed-with-range?error",
  6152. Headers{{make_range_header(ranges)}});
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6155. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6156. EXPECT_EQ(false, res->has_header("Content-Range"));
  6157. EXPECT_EQ(0U, res->body.size());
  6158. }
  6159. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6160. auto res = cli_.Get("/streamed-with-range",
  6161. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6164. EXPECT_EQ(5U, res->body.size());
  6165. // Check that overlapping ranges are coalesced into a single range
  6166. EXPECT_EQ("bcdef", res->body);
  6167. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6168. // Should be single range, not multipart
  6169. EXPECT_TRUE(res->has_header("Content-Range"));
  6170. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6171. }
  6172. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6173. auto res = cli_.Get("/streamed-with-range",
  6174. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6177. EXPECT_EQ(268U, res->body.size());
  6178. // Check that both range contents are present
  6179. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6180. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6181. // Check that Content-Range headers are present for both ranges
  6182. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6183. std::string::npos);
  6184. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6185. std::string::npos);
  6186. }
  6187. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6188. auto res = cli_.Get("/streamed-with-range",
  6189. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6192. EXPECT_EQ(269U, res->body.size());
  6193. // Check that both duplicate range contents are present
  6194. size_t first_abc = res->body.find("abc\r\n");
  6195. EXPECT_TRUE(first_abc != std::string::npos);
  6196. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6197. EXPECT_TRUE(second_abc != std::string::npos);
  6198. // Check that Content-Range headers are present for both ranges
  6199. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6200. EXPECT_TRUE(first_range != std::string::npos);
  6201. size_t second_range =
  6202. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6203. EXPECT_TRUE(second_range != std::string::npos);
  6204. }
  6205. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6206. auto res =
  6207. cli_.Get("/streamed-with-range?error",
  6208. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6210. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6211. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6212. EXPECT_EQ(false, res->has_header("Content-Range"));
  6213. EXPECT_EQ(0U, res->body.size());
  6214. }
  6215. TEST_F(ServerTest, GetStreamedEndless) {
  6216. uint64_t offset = 0;
  6217. auto res = cli_.Get("/streamed-cancel",
  6218. [&](const char * /*data*/, uint64_t data_length) {
  6219. if (offset < 100) {
  6220. offset += data_length;
  6221. return true;
  6222. }
  6223. return false;
  6224. });
  6225. ASSERT_TRUE(!res);
  6226. EXPECT_EQ(Error::Canceled, res.error());
  6227. }
  6228. TEST_F(ServerTest, ClientStop) {
  6229. std::atomic_size_t count{4};
  6230. std::vector<std::thread> threads;
  6231. for (auto i = count.load(); i != 0; --i) {
  6232. threads.emplace_back([&]() {
  6233. auto res = cli_.Get("/streamed-cancel",
  6234. [&](const char *, uint64_t) { return true; });
  6235. --count;
  6236. ASSERT_TRUE(!res);
  6237. EXPECT_TRUE(res.error() == Error::Canceled ||
  6238. res.error() == Error::Read || res.error() == Error::Write);
  6239. });
  6240. }
  6241. std::this_thread::sleep_for(std::chrono::seconds(2));
  6242. while (count != 0) {
  6243. cli_.stop();
  6244. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6245. }
  6246. for (auto &t : threads) {
  6247. t.join();
  6248. }
  6249. }
  6250. TEST_F(ServerTest, GetWithRange1) {
  6251. auto res = cli_.Get("/with-range", Headers{
  6252. make_range_header({{3, 5}}),
  6253. {"Accept-Encoding", ""},
  6254. });
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6257. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6258. EXPECT_EQ(true, res->has_header("Content-Range"));
  6259. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6260. EXPECT_EQ(std::string("def"), res->body);
  6261. }
  6262. TEST_F(ServerTest, GetWithRange2) {
  6263. auto res = cli_.Get("/with-range", Headers{
  6264. make_range_header({{1, -1}}),
  6265. {"Accept-Encoding", ""},
  6266. });
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6269. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6270. EXPECT_EQ(true, res->has_header("Content-Range"));
  6271. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6272. EXPECT_EQ(std::string("bcdefg"), res->body);
  6273. }
  6274. TEST_F(ServerTest, GetWithRange3) {
  6275. auto res = cli_.Get("/with-range", Headers{
  6276. make_range_header({{0, 0}}),
  6277. {"Accept-Encoding", ""},
  6278. });
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6281. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6282. EXPECT_EQ(true, res->has_header("Content-Range"));
  6283. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6284. EXPECT_EQ(std::string("a"), res->body);
  6285. }
  6286. TEST_F(ServerTest, GetWithRange4) {
  6287. auto res = cli_.Get("/with-range", Headers{
  6288. make_range_header({{-1, 2}}),
  6289. {"Accept-Encoding", ""},
  6290. });
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6293. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6294. EXPECT_EQ(true, res->has_header("Content-Range"));
  6295. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6296. EXPECT_EQ(std::string("fg"), res->body);
  6297. }
  6298. TEST_F(ServerTest, GetWithRange5) {
  6299. auto res = cli_.Get("/with-range", Headers{
  6300. make_range_header({{0, 5}}),
  6301. {"Accept-Encoding", ""},
  6302. });
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6305. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6306. EXPECT_EQ(true, res->has_header("Content-Range"));
  6307. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6308. EXPECT_EQ(std::string("abcdef"), res->body);
  6309. }
  6310. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6311. auto res =
  6312. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6315. }
  6316. TEST_F(ServerTest, GetWithRangeMultipart) {
  6317. auto res =
  6318. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6321. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6322. EXPECT_EQ(false, res->has_header("Content-Range"));
  6323. EXPECT_EQ(267U, res->body.size());
  6324. }
  6325. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6326. auto res = cli_.Get("/with-range",
  6327. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6329. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6330. }
  6331. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6332. auto res = cli_.Get("/with-range-customized-response",
  6333. Headers{{make_range_header({{1, 2}})}});
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6336. EXPECT_EQ(true, res->has_header("Content-Length"));
  6337. EXPECT_EQ(false, res->has_header("Content-Range"));
  6338. EXPECT_EQ(JSON_DATA, res->body);
  6339. }
  6340. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6341. auto res = cli_.Get("/with-range-customized-response",
  6342. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6345. EXPECT_EQ(true, res->has_header("Content-Length"));
  6346. EXPECT_EQ(false, res->has_header("Content-Range"));
  6347. EXPECT_EQ(JSON_DATA, res->body);
  6348. }
  6349. TEST_F(ServerTest, Issue1772) {
  6350. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6352. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6353. }
  6354. TEST_F(ServerTest, Issue609) {
  6355. auto res = cli_.Delete("/issue609");
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::OK_200, res->status);
  6358. EXPECT_EQ(std::string("ok"), res->body);
  6359. }
  6360. TEST_F(ServerTest, GetStreamedChunked) {
  6361. auto res = cli_.Get("/streamed-chunked");
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::OK_200, res->status);
  6364. EXPECT_EQ(std::string("123456789"), res->body);
  6365. }
  6366. TEST_F(ServerTest, GetStreamedChunked2) {
  6367. auto res = cli_.Get("/streamed-chunked2");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::OK_200, res->status);
  6370. EXPECT_EQ(std::string("123456789"), res->body);
  6371. }
  6372. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6373. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. EXPECT_EQ(StatusCode::OK_200, res->status);
  6376. EXPECT_EQ(std::string("123456789"), res->body);
  6377. EXPECT_TRUE(res->has_header("Trailer"));
  6378. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6379. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6380. // Trailers are now stored separately from headers (security fix)
  6381. EXPECT_EQ(2U, res->trailers.size());
  6382. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6383. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6384. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6385. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6386. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6387. // Verify trailers are NOT in headers (security verification)
  6388. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6389. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6390. }
  6391. TEST_F(ServerTest, LargeChunkedPost) {
  6392. Request req;
  6393. req.method = "POST";
  6394. req.path = "/large-chunked";
  6395. std::string host_and_port;
  6396. host_and_port += HOST;
  6397. host_and_port += ":";
  6398. host_and_port += std::to_string(PORT);
  6399. req.headers.emplace("Host", host_and_port.c_str());
  6400. req.headers.emplace("Accept", "*/*");
  6401. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6402. req.headers.emplace("Content-Type", "text/plain");
  6403. req.headers.emplace("Content-Length", "0");
  6404. req.headers.emplace("Transfer-Encoding", "chunked");
  6405. std::string long_string(30 * 1024u, 'a');
  6406. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6407. // Attempt to make a large enough post to exceed OS buffers, to test that
  6408. // the server handles short reads if the full chunk data isn't available.
  6409. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6410. auto res = std::make_shared<Response>();
  6411. auto error = Error::Success;
  6412. auto ret = cli_.send(req, *res, error);
  6413. ASSERT_TRUE(ret);
  6414. EXPECT_EQ(StatusCode::OK_200, res->status);
  6415. }
  6416. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6417. auto res = cli_.Get("/remote_addr");
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. EXPECT_EQ(StatusCode::OK_200, res->status);
  6420. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6421. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6422. }
  6423. TEST_F(ServerTest, GetMethodLocalAddr) {
  6424. auto res = cli_.Get("/local_addr");
  6425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6428. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6429. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6430. }
  6431. TEST_F(ServerTest, HTTPResponseSplitting) {
  6432. auto res = cli_.Get("/http_response_splitting");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. }
  6436. TEST_F(ServerTest, SlowRequest) {
  6437. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6438. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6439. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6440. }
  6441. #if 0
  6442. TEST_F(ServerTest, SlowPost) {
  6443. char buffer[64 * 1024];
  6444. memset(buffer, 0x42, sizeof(buffer));
  6445. auto res = cli_.Post(
  6446. "/slowpost", 64 * 1024 * 1024,
  6447. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6448. auto ret = sink.write(buffer, sizeof(buffer));
  6449. EXPECT_TRUE(ret);
  6450. return true;
  6451. },
  6452. "text/plain");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. }
  6456. TEST_F(ServerTest, SlowPostFail) {
  6457. char buffer[64 * 1024];
  6458. memset(buffer, 0x42, sizeof(buffer));
  6459. cli_.set_write_timeout(std::chrono::seconds(0));
  6460. auto res = cli_.Post(
  6461. "/slowpost", 64 * 1024 * 1024,
  6462. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6463. sink.write(buffer, sizeof(buffer));
  6464. return true;
  6465. },
  6466. "text/plain");
  6467. ASSERT_TRUE(!res);
  6468. EXPECT_EQ(Error::Write, res.error());
  6469. }
  6470. #endif
  6471. TEST_F(ServerTest, Put) {
  6472. auto res = cli_.Put("/put", "PUT", "text/plain");
  6473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6474. EXPECT_EQ(StatusCode::OK_200, res->status);
  6475. EXPECT_EQ("PUT", res->body);
  6476. }
  6477. TEST_F(ServerTest, PutWithContentProvider) {
  6478. auto res = cli_.Put(
  6479. "/put", 3,
  6480. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6481. sink.os << "PUT";
  6482. return true;
  6483. },
  6484. "text/plain");
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. EXPECT_EQ(StatusCode::OK_200, res->status);
  6487. EXPECT_EQ("PUT", res->body);
  6488. }
  6489. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6490. auto res = cli_.Post(
  6491. "/post", 42,
  6492. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6493. return false;
  6494. },
  6495. "text/plain");
  6496. ASSERT_TRUE(!res);
  6497. EXPECT_EQ(Error::Canceled, res.error());
  6498. }
  6499. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6500. auto res = cli_.Put(
  6501. "/put",
  6502. [](size_t /*offset*/, DataSink &sink) {
  6503. sink.os << "PUT";
  6504. sink.done();
  6505. return true;
  6506. },
  6507. "text/plain");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. EXPECT_EQ(StatusCode::OK_200, res->status);
  6510. EXPECT_EQ("PUT", res->body);
  6511. }
  6512. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6513. auto res = cli_.Post(
  6514. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6515. "text/plain");
  6516. ASSERT_TRUE(!res);
  6517. EXPECT_EQ(Error::Canceled, res.error());
  6518. }
  6519. TEST_F(ServerTest, PostLoopBack) {
  6520. std::string body;
  6521. auto res = cli_.Post(
  6522. "/post-loopback", 9,
  6523. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6524. EXPECT_EQ(9u, length);
  6525. sink.write("123", 3);
  6526. sink.write("456", 3);
  6527. sink.write("789", 3);
  6528. return true;
  6529. },
  6530. "text/plain",
  6531. [&body](const char *data, size_t data_length) {
  6532. body.append(data, data_length);
  6533. return true;
  6534. });
  6535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6536. EXPECT_EQ(StatusCode::OK_200, res->status);
  6537. EXPECT_EQ("123456789", body);
  6538. }
  6539. TEST_F(ServerTest, PutLoopBack) {
  6540. std::string body;
  6541. auto res = cli_.Put(
  6542. "/put-loopback", 9,
  6543. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6544. EXPECT_EQ(9u, length);
  6545. sink.write("123", 3);
  6546. sink.write("456", 3);
  6547. sink.write("789", 3);
  6548. return true;
  6549. },
  6550. "text/plain",
  6551. [&body](const char *data, size_t data_length) {
  6552. body.append(data, data_length);
  6553. return true;
  6554. });
  6555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6556. EXPECT_EQ(StatusCode::OK_200, res->status);
  6557. EXPECT_EQ("123456789", body);
  6558. }
  6559. TEST_F(ServerTest, PatchLoopBack) {
  6560. std::string body;
  6561. auto res = cli_.Patch(
  6562. "/patch-loopback", 9,
  6563. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6564. EXPECT_EQ(9u, length);
  6565. sink.write("123", 3);
  6566. sink.write("456", 3);
  6567. sink.write("789", 3);
  6568. return true;
  6569. },
  6570. "text/plain",
  6571. [&body](const char *data, size_t data_length) {
  6572. body.append(data, data_length);
  6573. return true;
  6574. });
  6575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6576. EXPECT_EQ(StatusCode::OK_200, res->status);
  6577. EXPECT_EQ("123456789", body);
  6578. }
  6579. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6580. std::string body;
  6581. auto res = cli_.Post(
  6582. "/post-loopback",
  6583. [](size_t /*offset*/, DataSink &sink) {
  6584. sink.write("123", 3);
  6585. sink.write("456", 3);
  6586. sink.write("789", 3);
  6587. sink.done();
  6588. return true;
  6589. },
  6590. "text/plain",
  6591. [&body](const char *data, size_t data_length) {
  6592. body.append(data, data_length);
  6593. return true;
  6594. });
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. EXPECT_EQ("123456789", body);
  6598. }
  6599. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6600. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6601. cli_.set_compress(true);
  6602. auto res = cli_.Put(
  6603. "/put", 3,
  6604. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6605. sink.os << "PUT";
  6606. return true;
  6607. },
  6608. "text/plain");
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::OK_200, res->status);
  6611. EXPECT_EQ("PUT", res->body);
  6612. }
  6613. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6614. cli_.set_compress(true);
  6615. auto res = cli_.Post(
  6616. "/post", 42,
  6617. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6618. return false;
  6619. },
  6620. "text/plain");
  6621. ASSERT_TRUE(!res);
  6622. EXPECT_EQ(Error::Canceled, res.error());
  6623. }
  6624. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6625. cli_.set_compress(true);
  6626. auto res = cli_.Put(
  6627. "/put",
  6628. [](size_t /*offset*/, DataSink &sink) {
  6629. sink.os << "PUT";
  6630. sink.done();
  6631. return true;
  6632. },
  6633. "text/plain");
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. EXPECT_EQ("PUT", res->body);
  6637. }
  6638. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6639. cli_.set_compress(true);
  6640. auto res = cli_.Post(
  6641. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6642. "text/plain");
  6643. ASSERT_TRUE(!res);
  6644. EXPECT_EQ(Error::Canceled, res.error());
  6645. }
  6646. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6647. cli_.set_compress(true);
  6648. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. EXPECT_EQ(LARGE_DATA, res->body);
  6652. }
  6653. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6654. #ifdef CPPHTTPLIB_SSL_ENABLED
  6655. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6656. Client cli(s.c_str());
  6657. cli.enable_server_certificate_verification(false);
  6658. #else
  6659. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6660. Client cli(s.c_str());
  6661. #endif
  6662. cli.set_compress(true);
  6663. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6665. EXPECT_EQ(StatusCode::OK_200, res->status);
  6666. EXPECT_EQ(LARGE_DATA, res->body);
  6667. // The compressed size should be less than a 10th of the original. May vary
  6668. // depending on the zlib library.
  6669. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6670. static_cast<uint64_t>(10 * 1024 * 1024));
  6671. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6672. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6673. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6674. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6675. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6676. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6677. #endif
  6678. }
  6679. TEST_F(ServerTest, PutContentWithDeflate) {
  6680. cli_.set_compress(false);
  6681. Headers headers;
  6682. headers.emplace("Content-Encoding", "deflate");
  6683. // PUT in deflate format:
  6684. auto res = cli_.Put("/put", headers,
  6685. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ(StatusCode::OK_200, res->status);
  6688. EXPECT_EQ("PUT", res->body);
  6689. }
  6690. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6691. Headers headers;
  6692. headers.emplace("Accept-Encoding", "gzip, deflate");
  6693. auto res = cli_.Get("/streamed-chunked", headers);
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::OK_200, res->status);
  6696. EXPECT_EQ(std::string("123456789"), res->body);
  6697. }
  6698. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6699. Headers headers;
  6700. headers.emplace("Accept-Encoding", "gzip, deflate");
  6701. auto res = cli_.Get("/streamed-chunked2", headers);
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_EQ(StatusCode::OK_200, res->status);
  6704. EXPECT_EQ(std::string("123456789"), res->body);
  6705. }
  6706. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6707. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. }
  6711. TEST(GzipDecompressor, ChunkedDecompression) {
  6712. std::string data;
  6713. for (size_t i = 0; i < 32 * 1024; ++i) {
  6714. data.push_back(static_cast<char>('a' + i % 26));
  6715. }
  6716. std::string compressed_data;
  6717. {
  6718. httplib::detail::gzip_compressor compressor;
  6719. bool result = compressor.compress(
  6720. data.data(), data.size(),
  6721. /*last=*/true,
  6722. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6723. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6724. compressed_data_size);
  6725. return true;
  6726. });
  6727. ASSERT_TRUE(result);
  6728. }
  6729. std::string decompressed_data;
  6730. {
  6731. httplib::detail::gzip_decompressor decompressor;
  6732. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6733. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6734. size_t chunk_size = 130;
  6735. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6736. chunk_begin += chunk_size) {
  6737. size_t current_chunk_size =
  6738. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6739. bool result = decompressor.decompress(
  6740. compressed_data.data() + chunk_begin, current_chunk_size,
  6741. [&](const char *decompressed_data_chunk,
  6742. size_t decompressed_data_chunk_size) {
  6743. decompressed_data.insert(decompressed_data.size(),
  6744. decompressed_data_chunk,
  6745. decompressed_data_chunk_size);
  6746. return true;
  6747. });
  6748. ASSERT_TRUE(result);
  6749. }
  6750. }
  6751. ASSERT_EQ(data, decompressed_data);
  6752. }
  6753. TEST(GzipDecompressor, DeflateDecompression) {
  6754. std::string original_text = "Raw deflate without gzip";
  6755. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6756. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6757. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6758. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6759. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6760. std::string decompressed_data;
  6761. {
  6762. httplib::detail::gzip_decompressor decompressor;
  6763. bool result = decompressor.decompress(
  6764. compressed_data.data(), compressed_data.size(),
  6765. [&](const char *decompressed_data_chunk,
  6766. size_t decompressed_data_chunk_size) {
  6767. decompressed_data.insert(decompressed_data.size(),
  6768. decompressed_data_chunk,
  6769. decompressed_data_chunk_size);
  6770. return true;
  6771. });
  6772. ASSERT_TRUE(result);
  6773. }
  6774. ASSERT_EQ(original_text, decompressed_data);
  6775. }
  6776. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6777. std::string original_text = "Raw deflate without gzip";
  6778. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6779. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6780. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6781. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6782. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6783. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6784. std::string decompressed_data;
  6785. {
  6786. httplib::detail::gzip_decompressor decompressor;
  6787. bool result = decompressor.decompress(
  6788. compressed_data.data(), compressed_data.size(),
  6789. [&](const char *decompressed_data_chunk,
  6790. size_t decompressed_data_chunk_size) {
  6791. decompressed_data.insert(decompressed_data.size(),
  6792. decompressed_data_chunk,
  6793. decompressed_data_chunk_size);
  6794. return true;
  6795. });
  6796. ASSERT_TRUE(result);
  6797. }
  6798. ASSERT_EQ(original_text, decompressed_data);
  6799. }
  6800. #endif
  6801. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6802. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6803. Headers headers;
  6804. headers.emplace("Accept-Encoding", "br");
  6805. auto res = cli_.Get("/streamed-chunked", headers);
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. EXPECT_EQ(std::string("123456789"), res->body);
  6809. }
  6810. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6811. Headers headers;
  6812. headers.emplace("Accept-Encoding", "br");
  6813. auto res = cli_.Get("/streamed-chunked2", headers);
  6814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6815. EXPECT_EQ(StatusCode::OK_200, res->status);
  6816. EXPECT_EQ(std::string("123456789"), res->body);
  6817. }
  6818. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6819. cli_.set_compress(true);
  6820. auto res = cli_.Put(
  6821. "/put", 3,
  6822. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6823. sink.os << "PUT";
  6824. return true;
  6825. },
  6826. "text/plain");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. EXPECT_EQ(StatusCode::OK_200, res->status);
  6829. EXPECT_EQ("PUT", res->body);
  6830. }
  6831. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6832. cli_.set_compress(true);
  6833. auto res = cli_.Put(
  6834. "/put",
  6835. [](size_t /*offset*/, DataSink &sink) {
  6836. sink.os << "PUT";
  6837. sink.done();
  6838. return true;
  6839. },
  6840. "text/plain");
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. EXPECT_EQ(StatusCode::OK_200, res->status);
  6843. EXPECT_EQ("PUT", res->body);
  6844. }
  6845. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6846. cli_.set_compress(true);
  6847. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. EXPECT_EQ(LARGE_DATA, res->body);
  6851. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6852. }
  6853. #endif
  6854. TEST_F(ServerTest, Patch) {
  6855. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. EXPECT_EQ("PATCH", res->body);
  6859. }
  6860. TEST_F(ServerTest, Delete) {
  6861. auto res = cli_.Delete("/delete");
  6862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6863. EXPECT_EQ(StatusCode::OK_200, res->status);
  6864. EXPECT_EQ("DELETE", res->body);
  6865. }
  6866. TEST_F(ServerTest, DeleteContentReceiver) {
  6867. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. EXPECT_EQ("content", res->body);
  6871. }
  6872. TEST_F(ServerTest, Options) {
  6873. auto res = cli_.Options("*");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6877. EXPECT_TRUE(res->body.empty());
  6878. }
  6879. TEST_F(ServerTest, URL) {
  6880. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. }
  6884. TEST_F(ServerTest, ArrayParam) {
  6885. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6887. EXPECT_EQ(StatusCode::OK_200, res->status);
  6888. }
  6889. TEST_F(ServerTest, ArrayParamValues) {
  6890. auto res =
  6891. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. }
  6895. TEST_F(ServerTest, NoMultipleHeaders) {
  6896. Headers headers = {{"Content-Length", "5"}};
  6897. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6898. "text/plain");
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. }
  6902. TEST_F(ServerTest, PostContentReceiver) {
  6903. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6905. ASSERT_EQ(StatusCode::OK_200, res->status);
  6906. ASSERT_EQ("content", res->body);
  6907. }
  6908. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6909. UploadFormDataItems items = {
  6910. {"text1", "text default", "", ""},
  6911. {"text2", "aωb", "", ""},
  6912. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6913. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6914. {"file3", "", "", "application/octet-stream"},
  6915. };
  6916. auto res = cli_.Post("/content_receiver", items);
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::OK_200, res->status);
  6919. }
  6920. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6921. UploadFormDataItems items = {
  6922. {"text1", "text default", "", ""},
  6923. {"text2", "aωb", "", ""},
  6924. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6925. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6926. {"file3", "", "", "application/octet-stream"},
  6927. };
  6928. auto boundary = std::string("+++++");
  6929. std::string body;
  6930. for (const auto &item : items) {
  6931. body += "--" + boundary + "\r\n";
  6932. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6933. if (!item.filename.empty()) {
  6934. body += "; filename=\"" + item.filename + "\"";
  6935. }
  6936. body += "\r\n";
  6937. if (!item.content_type.empty()) {
  6938. body += "Content-Type: " + item.content_type + "\r\n";
  6939. }
  6940. body += "\r\n";
  6941. body += item.content + "\r\n";
  6942. }
  6943. body += "--" + boundary + "--\r\n";
  6944. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6945. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. }
  6949. TEST(MultipartFormDataTest, FieldEscaping) {
  6950. Server svr;
  6951. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6952. const ContentReader &content_reader) {
  6953. ASSERT_TRUE(req.is_multipart_form_data());
  6954. std::vector<FormData> received;
  6955. content_reader(
  6956. [&](const FormData &file) {
  6957. received.push_back(file);
  6958. return true;
  6959. },
  6960. [&](const char *data, size_t data_length) {
  6961. received.back().content.append(data, data_length);
  6962. return true;
  6963. });
  6964. // '"', CR and LF in names and filenames are escaped following the
  6965. // WHATWG HTML standard, so each part still parses as a single part
  6966. // with no injected headers. Content types get CR/LF escaped too,
  6967. // while '"' (legal there, e.g. quoted charset) is preserved.
  6968. ASSERT_EQ(4U, received.size());
  6969. EXPECT_EQ("na%22me", received[0].name);
  6970. EXPECT_EQ("quoted name", received[0].content);
  6971. EXPECT_EQ("file", received[1].name);
  6972. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6973. received[1].filename);
  6974. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6975. EXPECT_EQ("injected", received[1].content);
  6976. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6977. EXPECT_EQ("my%22file.txt", received[2].filename);
  6978. EXPECT_EQ("cr lf name", received[2].content);
  6979. EXPECT_EQ("typed", received[3].name);
  6980. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6981. received[3].content_type);
  6982. EXPECT_EQ("typed content", received[3].content);
  6983. });
  6984. auto port = svr.bind_to_any_port("localhost");
  6985. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6986. auto se = detail::scope_exit([&] {
  6987. svr.stop();
  6988. t.join();
  6989. ASSERT_FALSE(svr.is_running());
  6990. });
  6991. svr.wait_until_ready();
  6992. Client cli("localhost", port);
  6993. UploadFormDataItems items = {
  6994. {"na\"me", "quoted name", "", ""},
  6995. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6996. "application/octet-stream"},
  6997. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6998. {"typed", "typed content", "",
  6999. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7000. };
  7001. auto res = cli.Post("/post", items);
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::OK_200, res->status);
  7004. }
  7005. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7006. const UploadFormDataItems items = {
  7007. {"name1", "Content 1", "", ""},
  7008. {"name2", "Content 2", "file2.txt", "text/plain"},
  7009. };
  7010. Server svr;
  7011. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7012. const ContentReader &content_reader) {
  7013. ASSERT_TRUE(req.is_multipart_form_data());
  7014. std::vector<FormData> received;
  7015. content_reader(
  7016. [&](const FormData &file) {
  7017. received.push_back(file);
  7018. return true;
  7019. },
  7020. [&](const char *data, size_t data_length) {
  7021. received.back().content.append(data, data_length);
  7022. return true;
  7023. });
  7024. ASSERT_EQ(2U, received.size());
  7025. EXPECT_EQ("name1", received[0].name);
  7026. EXPECT_EQ("Content 1", received[0].content);
  7027. EXPECT_EQ("name2", received[1].name);
  7028. EXPECT_EQ("Content 2", received[1].content);
  7029. EXPECT_EQ("file2.txt", received[1].filename);
  7030. EXPECT_EQ("text/plain", received[1].content_type);
  7031. });
  7032. auto port = svr.bind_to_any_port("localhost");
  7033. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7034. auto se = detail::scope_exit([&] {
  7035. svr.stop();
  7036. t.join();
  7037. ASSERT_FALSE(svr.is_running());
  7038. });
  7039. svr.wait_until_ready();
  7040. Client cli("localhost", port);
  7041. // Whole-body serialization with a generated boundary
  7042. {
  7043. MultipartFormDataWriter writer;
  7044. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7045. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7046. writer.content_type());
  7047. auto body = writer.serialize(items);
  7048. EXPECT_EQ(body.size(), writer.content_length(items));
  7049. auto res = cli.Post("/post", body, writer.content_type());
  7050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7051. EXPECT_EQ(StatusCode::OK_200, res->status);
  7052. }
  7053. // Per-part framing with a custom boundary via a content provider
  7054. {
  7055. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7056. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7057. MultipartFormDataWriter writer("custom-boundary_123");
  7058. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7059. std::string body;
  7060. for (const auto &item : items) {
  7061. body += writer.item_begin(item);
  7062. body += item.content;
  7063. body += MultipartFormDataWriter::item_end();
  7064. }
  7065. body += writer.finish();
  7066. EXPECT_EQ(body.size(), writer.content_length(items));
  7067. auto res = cli.Post(
  7068. "/post", body.size(),
  7069. [&](size_t offset, size_t length, DataSink &sink) {
  7070. sink.write(body.data() + offset, length);
  7071. return true;
  7072. },
  7073. writer.content_type());
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::OK_200, res->status);
  7076. }
  7077. }
  7078. TEST_F(ServerTest, PostContentReceiverGzip) {
  7079. cli_.set_compress(true);
  7080. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. ASSERT_EQ(StatusCode::OK_200, res->status);
  7083. ASSERT_EQ("content", res->body);
  7084. }
  7085. TEST_F(ServerTest, PutContentReceiver) {
  7086. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. ASSERT_EQ(StatusCode::OK_200, res->status);
  7089. ASSERT_EQ("content", res->body);
  7090. }
  7091. TEST_F(ServerTest, PatchContentReceiver) {
  7092. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7094. ASSERT_EQ(StatusCode::OK_200, res->status);
  7095. ASSERT_EQ("content", res->body);
  7096. }
  7097. template <typename ClientType>
  7098. void TestWithHeadersAndContentReceiver(
  7099. ClientType &cli,
  7100. std::function<Result(ClientType &, const std::string &, const Headers &,
  7101. const std::string &, const std::string &,
  7102. ContentReceiver, DownloadProgress)>
  7103. request_func) {
  7104. Headers headers;
  7105. headers.emplace("X-Custom-Header", "test-value");
  7106. std::string received_body;
  7107. auto res = request_func(
  7108. cli, "/content_receiver", headers, "content", "application/json",
  7109. [&](const char *data, size_t data_length) {
  7110. received_body.append(data, data_length);
  7111. return true;
  7112. },
  7113. nullptr);
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::OK_200, res->status);
  7116. EXPECT_EQ("content", received_body);
  7117. }
  7118. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7119. #ifdef CPPHTTPLIB_SSL_ENABLED
  7120. using ClientT = SSLClient;
  7121. #else
  7122. using ClientT = Client;
  7123. #endif
  7124. TestWithHeadersAndContentReceiver<ClientT>(
  7125. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7126. const std::string &body, const std::string &content_type,
  7127. ContentReceiver receiver, DownloadProgress progress) {
  7128. return cli.Post(path, headers, body, content_type, receiver, progress);
  7129. });
  7130. }
  7131. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7132. #ifdef CPPHTTPLIB_SSL_ENABLED
  7133. using ClientT = SSLClient;
  7134. #else
  7135. using ClientT = Client;
  7136. #endif
  7137. TestWithHeadersAndContentReceiver<ClientT>(
  7138. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7139. const std::string &body, const std::string &content_type,
  7140. ContentReceiver receiver, DownloadProgress progress) {
  7141. return cli.Put(path, headers, body, content_type, receiver, progress);
  7142. });
  7143. }
  7144. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7145. #ifdef CPPHTTPLIB_SSL_ENABLED
  7146. using ClientT = SSLClient;
  7147. #else
  7148. using ClientT = Client;
  7149. #endif
  7150. TestWithHeadersAndContentReceiver<ClientT>(
  7151. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7152. const std::string &body, const std::string &content_type,
  7153. ContentReceiver receiver, DownloadProgress progress) {
  7154. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7155. });
  7156. }
  7157. template <typename ClientType>
  7158. void TestWithHeadersAndContentReceiverWithProgress(
  7159. ClientType &cli,
  7160. std::function<Result(ClientType &, const std::string &, const Headers &,
  7161. const std::string &, const std::string &,
  7162. ContentReceiver, DownloadProgress)>
  7163. request_func) {
  7164. Headers headers;
  7165. headers.emplace("X-Test-Header", "progress-test");
  7166. std::string received_body;
  7167. auto progress_called = false;
  7168. auto res = request_func(
  7169. cli, "/content_receiver", headers, "content", "text/plain",
  7170. [&](const char *data, size_t data_length) {
  7171. received_body.append(data, data_length);
  7172. return true;
  7173. },
  7174. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7175. progress_called = true;
  7176. return true;
  7177. });
  7178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7179. EXPECT_EQ(StatusCode::OK_200, res->status);
  7180. EXPECT_EQ("content", received_body);
  7181. EXPECT_TRUE(progress_called);
  7182. }
  7183. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7184. #ifdef CPPHTTPLIB_SSL_ENABLED
  7185. using ClientT = SSLClient;
  7186. #else
  7187. using ClientT = Client;
  7188. #endif
  7189. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7191. const std::string &body, const std::string &content_type,
  7192. ContentReceiver receiver, DownloadProgress progress) {
  7193. return cli.Post(path, headers, body, content_type, receiver, progress);
  7194. });
  7195. }
  7196. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7197. #ifdef CPPHTTPLIB_SSL_ENABLED
  7198. using ClientT = SSLClient;
  7199. #else
  7200. using ClientT = Client;
  7201. #endif
  7202. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7203. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7204. const std::string &body, const std::string &content_type,
  7205. ContentReceiver receiver, DownloadProgress progress) {
  7206. return cli.Put(path, headers, body, content_type, receiver, progress);
  7207. });
  7208. }
  7209. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7210. #ifdef CPPHTTPLIB_SSL_ENABLED
  7211. using ClientT = SSLClient;
  7212. #else
  7213. using ClientT = Client;
  7214. #endif
  7215. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7216. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7217. const std::string &body, const std::string &content_type,
  7218. ContentReceiver receiver, DownloadProgress progress) {
  7219. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7220. });
  7221. }
  7222. template <typename ClientType>
  7223. void TestWithHeadersAndContentReceiverError(
  7224. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7225. const Headers &, const std::string &,
  7226. const std::string &, ContentReceiver)>
  7227. request_func) {
  7228. Headers headers;
  7229. headers.emplace("X-Error-Test", "true");
  7230. std::string received_body;
  7231. auto receiver_failed = false;
  7232. auto res =
  7233. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7234. [&](const char *data, size_t data_length) {
  7235. received_body.append(data, data_length);
  7236. receiver_failed = true;
  7237. return false;
  7238. });
  7239. ASSERT_FALSE(res);
  7240. EXPECT_TRUE(receiver_failed);
  7241. }
  7242. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7243. #ifdef CPPHTTPLIB_SSL_ENABLED
  7244. using ClientT = SSLClient;
  7245. #else
  7246. using ClientT = Client;
  7247. #endif
  7248. TestWithHeadersAndContentReceiverError<ClientT>(
  7249. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7250. const std::string &body, const std::string &content_type,
  7251. ContentReceiver receiver) {
  7252. return cli.Post(path, headers, body, content_type, receiver);
  7253. });
  7254. }
  7255. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7256. #ifdef CPPHTTPLIB_SSL_ENABLED
  7257. using ClientT = SSLClient;
  7258. #else
  7259. using ClientT = Client;
  7260. #endif
  7261. TestWithHeadersAndContentReceiverError<ClientT>(
  7262. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7263. const std::string &body, const std::string &content_type,
  7264. ContentReceiver receiver) {
  7265. return cli.Put(path, headers, body, content_type, receiver);
  7266. });
  7267. }
  7268. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7269. #ifdef CPPHTTPLIB_SSL_ENABLED
  7270. using ClientT = SSLClient;
  7271. #else
  7272. using ClientT = Client;
  7273. #endif
  7274. TestWithHeadersAndContentReceiverError<ClientT>(
  7275. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7276. const std::string &body, const std::string &content_type,
  7277. ContentReceiver receiver) {
  7278. return cli.Patch(path, headers, body, content_type, receiver);
  7279. });
  7280. }
  7281. TEST_F(ServerTest, PostQueryStringAndBody) {
  7282. auto res =
  7283. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7285. ASSERT_EQ(StatusCode::OK_200, res->status);
  7286. }
  7287. TEST_F(ServerTest, HTTP2Magic) {
  7288. Request req;
  7289. req.method = "PRI";
  7290. req.path = "*";
  7291. req.body = "SM";
  7292. auto res = std::make_shared<Response>();
  7293. auto error = Error::Success;
  7294. auto ret = cli_.send(req, *res, error);
  7295. ASSERT_TRUE(ret);
  7296. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7297. }
  7298. TEST_F(ServerTest, KeepAlive) {
  7299. auto res = cli_.Get("/hi");
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7303. EXPECT_EQ("Hello World!", res->body);
  7304. res = cli_.Get("/hi");
  7305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7306. EXPECT_EQ(StatusCode::OK_200, res->status);
  7307. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7308. EXPECT_EQ("Hello World!", res->body);
  7309. res = cli_.Get("/hi");
  7310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7311. EXPECT_EQ(StatusCode::OK_200, res->status);
  7312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7313. EXPECT_EQ("Hello World!", res->body);
  7314. res = cli_.Get("/not-exist");
  7315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7316. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7317. res = cli_.Post("/empty", "", "text/plain");
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::OK_200, res->status);
  7320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7321. EXPECT_EQ("empty", res->body);
  7322. EXPECT_EQ("close", res->get_header_value("Connection"));
  7323. res = cli_.Post(
  7324. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7325. "text/plain");
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::OK_200, res->status);
  7328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7329. EXPECT_EQ("empty", res->body);
  7330. cli_.set_keep_alive(false);
  7331. res = cli_.Get("/last-request");
  7332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7333. EXPECT_EQ(StatusCode::OK_200, res->status);
  7334. EXPECT_EQ("close", res->get_header_value("Connection"));
  7335. }
  7336. TEST_F(ServerTest, TooManyRedirect) {
  7337. cli_.set_follow_location(true);
  7338. auto res = cli_.Get("/redirect/0");
  7339. ASSERT_TRUE(!res);
  7340. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7341. }
  7342. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7343. Request req;
  7344. req.method = "FOOBAR";
  7345. req.path = "/hi";
  7346. cli_.set_keep_alive(true);
  7347. auto res = cli_.send(req);
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7350. EXPECT_EQ("close", res->get_header_value("Connection"));
  7351. EXPECT_FALSE(cli_.is_socket_open());
  7352. }
  7353. TEST_F(ServerTest, CustomRouteReadsBody) {
  7354. const std::string xml =
  7355. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7356. Request req;
  7357. req.method = "PROPFIND";
  7358. req.path = "/dav/dir";
  7359. req.set_header("Depth", "1");
  7360. req.body = xml;
  7361. auto res = cli_.send(req);
  7362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7363. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7364. EXPECT_EQ(xml, res->body);
  7365. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7366. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7367. }
  7368. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7369. Request req;
  7370. req.method = "PROPFIND";
  7371. req.path = "/dav/42";
  7372. auto res = cli_.send(req);
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7375. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7376. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7377. }
  7378. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7379. Request req;
  7380. req.method = "PROPFIND";
  7381. req.path = "/dav-re/123";
  7382. auto res = cli_.send(req);
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7385. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7386. }
  7387. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7388. Request req;
  7389. req.method = "MKCOL";
  7390. req.path = "/dav-mkcol";
  7391. auto res = cli_.send(req);
  7392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7393. EXPECT_EQ(StatusCode::Created_201, res->status);
  7394. }
  7395. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7396. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7397. Request req;
  7398. req.method = "REPORT";
  7399. req.path = "/dav-report";
  7400. req.body = xml;
  7401. auto res = cli_.send(req);
  7402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7403. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7404. EXPECT_EQ(xml, res->body);
  7405. }
  7406. // A content reader route must fire even when the request carries no body,
  7407. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7408. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7409. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7410. Request req;
  7411. req.method = "REPORT";
  7412. req.path = "/dav-report";
  7413. auto res = cli_.send(req);
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7416. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7417. }
  7418. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7419. Request req;
  7420. req.method = "PROPFIND";
  7421. req.path = "/not-dav";
  7422. auto res = cli_.send(req);
  7423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7425. }
  7426. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7427. Request req;
  7428. req.method = "UNLOCK";
  7429. req.path = "/dav/dir";
  7430. cli_.set_keep_alive(true);
  7431. auto res = cli_.send(req);
  7432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7433. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7434. EXPECT_EQ("close", res->get_header_value("Connection"));
  7435. EXPECT_FALSE(cli_.is_socket_open());
  7436. }
  7437. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7438. // The mount point serves this path, but only for GET and HEAD.
  7439. auto get_res = cli_.Get("/dir/index.html");
  7440. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7441. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7442. Request req;
  7443. req.method = "PROPFIND";
  7444. req.path = "/dir/index.html";
  7445. auto res = cli_.send(req);
  7446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7448. }
  7449. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7450. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7451. cli_.set_keep_alive(true);
  7452. for (auto i = 0; i < 2; i++) {
  7453. Request req;
  7454. req.method = "PROPFIND";
  7455. req.path = "/dav/dir";
  7456. req.body = xml;
  7457. auto res = cli_.send(req);
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7460. EXPECT_EQ(xml, res->body);
  7461. EXPECT_TRUE(cli_.is_socket_open());
  7462. }
  7463. // A built-in method must still be served on the same connection.
  7464. cli_.set_keep_alive(false);
  7465. auto res = cli_.Get("/hi");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. EXPECT_EQ("close", res->get_header_value("Connection"));
  7469. }
  7470. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7471. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7472. Request req;
  7473. req.method = "PROPFIND";
  7474. req.path = "/dav/dir";
  7475. req.set_header("Expect", "100-continue");
  7476. req.body = xml;
  7477. auto res = cli_.send(req);
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7480. EXPECT_EQ(xml, res->body);
  7481. }
  7482. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7483. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7484. TEST_F(ServerTest, Gzip) {
  7485. Headers headers;
  7486. headers.emplace("Accept-Encoding", "gzip, deflate");
  7487. auto res = cli_.Get("/compress", headers);
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7490. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7491. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7492. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7493. "7890123456789012345678901234567890",
  7494. res->body);
  7495. EXPECT_EQ(StatusCode::OK_200, res->status);
  7496. }
  7497. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7498. Headers headers;
  7499. headers.emplace("Accept-Encoding", "gzip, deflate");
  7500. auto res = cli_.Get("/compress-with-charset", headers);
  7501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7502. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7503. EXPECT_EQ("application/json; charset=utf-8",
  7504. res->get_header_value("Content-Type"));
  7505. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7506. "7890123456789012345678901234567890",
  7507. res->body);
  7508. EXPECT_EQ(StatusCode::OK_200, res->status);
  7509. }
  7510. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7511. Headers headers;
  7512. headers.emplace("Accept-Encoding", "");
  7513. auto res = cli_.Get("/compress", headers);
  7514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7515. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7516. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7517. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7518. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7519. "7890123456789012345678901234567890",
  7520. res->body);
  7521. EXPECT_EQ(StatusCode::OK_200, res->status);
  7522. }
  7523. TEST_F(ServerTest, GzipWithContentReceiver) {
  7524. Headers headers;
  7525. headers.emplace("Accept-Encoding", "gzip, deflate");
  7526. std::string body;
  7527. auto res = cli_.Get("/compress", headers,
  7528. [&](const char *data, uint64_t data_length) {
  7529. EXPECT_EQ(100U, data_length);
  7530. body.append(data, data_length);
  7531. return true;
  7532. });
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7535. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7536. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7537. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7538. "7890123456789012345678901234567890",
  7539. body);
  7540. EXPECT_EQ(StatusCode::OK_200, res->status);
  7541. }
  7542. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7543. Headers headers;
  7544. headers.emplace("Accept-Encoding", "gzip, deflate");
  7545. cli_.set_decompress(false);
  7546. auto res = cli_.Get("/compress", headers);
  7547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7548. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7550. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7551. EXPECT_EQ(33U, res->body.size());
  7552. EXPECT_EQ(StatusCode::OK_200, res->status);
  7553. }
  7554. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7555. Headers headers;
  7556. headers.emplace("Accept-Encoding", "");
  7557. std::string body;
  7558. auto res = cli_.Get("/compress", headers,
  7559. [&](const char *data, uint64_t data_length) {
  7560. EXPECT_EQ(100U, data_length);
  7561. body.append(data, data_length);
  7562. return true;
  7563. });
  7564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7565. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7567. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7568. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7569. "7890123456789012345678901234567890",
  7570. body);
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. }
  7573. TEST_F(ServerTest, NoGzip) {
  7574. Headers headers;
  7575. headers.emplace("Accept-Encoding", "gzip, deflate");
  7576. auto res = cli_.Get("/nocompress", headers);
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7579. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7580. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7581. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7582. "7890123456789012345678901234567890",
  7583. res->body);
  7584. EXPECT_EQ(StatusCode::OK_200, res->status);
  7585. }
  7586. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7587. Headers headers;
  7588. headers.emplace("Accept-Encoding", "gzip, deflate");
  7589. std::string body;
  7590. auto res = cli_.Get("/nocompress", headers,
  7591. [&](const char *data, uint64_t data_length) {
  7592. EXPECT_EQ(100U, data_length);
  7593. body.append(data, data_length);
  7594. return true;
  7595. });
  7596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7597. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7598. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7599. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7600. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7601. "7890123456789012345678901234567890",
  7602. body);
  7603. EXPECT_EQ(StatusCode::OK_200, res->status);
  7604. }
  7605. TEST_F(ServerTest, MultipartFormDataGzip) {
  7606. UploadFormDataItems items = {
  7607. {"key1", "test", "", ""},
  7608. {"key2", "--abcdefg123", "", ""},
  7609. };
  7610. cli_.set_compress(true);
  7611. auto res = cli_.Post("/compress-multipart", items);
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ(StatusCode::OK_200, res->status);
  7614. }
  7615. #endif
  7616. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7617. // Static file compression is opt-in, so these run their own server rather than
  7618. // flipping it on for the shared ServerTest fixture, which would silently
  7619. // rewrite what every other static file test is asserting.
  7620. class StaticFileCompressionTest : public ::testing::Test {
  7621. protected:
  7622. void TearDown() override {
  7623. if (t_.joinable()) {
  7624. svr_.stop();
  7625. t_.join();
  7626. }
  7627. }
  7628. int start(const std::function<void(Server &)> &configure = nullptr) {
  7629. // Serves the same tree as a directory of build-time compressed assets
  7630. // would be served: the mount point names the coding the files are already
  7631. // stored in. Registered before "/" so it is the one that matches.
  7632. svr_.set_mount_point("/pre-encoded", "./www",
  7633. {{"Content-Encoding", "gzip"}});
  7634. svr_.set_mount_point("/", "./www");
  7635. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7636. res.set_file_content("./www/dir/index.html", "text/html");
  7637. });
  7638. svr_.Get("/pre-encoded-file-content",
  7639. [](const Request & /*req*/, Response &res) {
  7640. res.set_header("Content-Encoding", "gzip");
  7641. res.set_file_content("./www/dir/index.html", "text/html");
  7642. });
  7643. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7644. res.set_content_provider(
  7645. 6, "text/plain",
  7646. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7647. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7648. return true;
  7649. });
  7650. });
  7651. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7652. res.set_content_provider(
  7653. 1000, "text/plain",
  7654. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7655. if (offset < 100) {
  7656. std::string data(100, 'A');
  7657. sink.write(data.data(), data.size());
  7658. return true;
  7659. }
  7660. std::this_thread::sleep_for(std::chrono::seconds(2));
  7661. std::string data(900, 'B');
  7662. sink.write(data.data(), data.size());
  7663. return true;
  7664. });
  7665. });
  7666. if (configure) { configure(svr_); }
  7667. auto port = svr_.bind_to_any_port(HOST);
  7668. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7669. svr_.wait_until_ready();
  7670. return port;
  7671. }
  7672. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7673. // Every file under ./www except 1MB.txt is smaller than the default
  7674. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7675. // it out of the way.
  7676. static void enable_without_floor(Server &svr) {
  7677. svr.set_static_file_compression(true);
  7678. svr.set_static_file_compression_min_length(0);
  7679. }
  7680. Server svr_;
  7681. std::thread t_;
  7682. };
  7683. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7684. auto port = start();
  7685. Client cli(HOST, port);
  7686. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7688. EXPECT_EQ(StatusCode::OK_200, res->status);
  7689. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7690. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7691. EXPECT_EQ(1048576U, res->body.size());
  7692. }
  7693. TEST_F(StaticFileCompressionTest, MountPoint) {
  7694. auto port = start(enable);
  7695. Client cli(HOST, port);
  7696. cli.set_decompress(false);
  7697. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7702. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7703. // The response stays self-delimiting: a length, not a chunked body.
  7704. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7705. EXPECT_EQ(std::to_string(res->body.size()),
  7706. res->get_header_value("Content-Length"));
  7707. EXPECT_LT(res->body.size(), 1048576U);
  7708. EXPECT_FALSE(res->body.empty());
  7709. }
  7710. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7711. auto port = start(enable);
  7712. Client cli(HOST, port);
  7713. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7715. EXPECT_EQ(StatusCode::OK_200, res->status);
  7716. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7717. EXPECT_EQ(1048576U, res->body.size());
  7718. }
  7719. TEST_F(StaticFileCompressionTest, FileContent) {
  7720. auto port = start(enable_without_floor);
  7721. Client cli(HOST, port);
  7722. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7726. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7727. EXPECT_EQ(104U, res->body.size());
  7728. }
  7729. // A handler that serves an already-encoded file names the coding itself. The
  7730. // file-backed path decided its coding from Accept-Encoding and the content
  7731. // type alone, so it compressed the stored bytes a second time and appended a
  7732. // second Content-Encoding field line.
  7733. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7734. auto port = start(enable_without_floor);
  7735. Client cli(HOST, port);
  7736. cli.set_decompress(false);
  7737. auto res = cli.Get("/pre-encoded-file-content",
  7738. Headers{{"Accept-Encoding", "gzip"}});
  7739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7740. EXPECT_EQ(StatusCode::OK_200, res->status);
  7741. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7742. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7743. // Vary belongs to a coding the server chose, and it chose none here.
  7744. EXPECT_FALSE(res->has_header("Vary"));
  7745. // The file travels exactly as it is stored on disk.
  7746. EXPECT_EQ(104U, res->body.size());
  7747. }
  7748. // The 1MB file clears the default floor, so this one runs the configuration a
  7749. // deployment would actually have.
  7750. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7751. auto port = start(enable);
  7752. Client cli(HOST, port);
  7753. cli.set_decompress(false);
  7754. auto res =
  7755. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7759. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7760. EXPECT_FALSE(res->has_header("Vary"));
  7761. EXPECT_EQ(1048576U, res->body.size());
  7762. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7763. }
  7764. TEST_F(StaticFileCompressionTest, Head) {
  7765. auto port = start(enable);
  7766. Client cli(HOST, port);
  7767. cli.set_decompress(false);
  7768. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7769. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7770. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7774. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7775. // HEAD still reports the size a GET would return.
  7776. EXPECT_EQ(get->get_header_value("Content-Length"),
  7777. res->get_header_value("Content-Length"));
  7778. EXPECT_TRUE(res->body.empty());
  7779. }
  7780. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7781. auto port = start(enable);
  7782. Client cli(HOST, port);
  7783. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7784. {"Accept-Encoding", "gzip"}});
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7787. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7788. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7789. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7790. EXPECT_EQ("cd", res->body);
  7791. }
  7792. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7793. auto port = start(enable);
  7794. Client cli(HOST, port);
  7795. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7797. EXPECT_EQ(StatusCode::OK_200, res->status);
  7798. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7799. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7800. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7801. }
  7802. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7803. auto port = start(enable);
  7804. Client cli(HOST, port);
  7805. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7807. EXPECT_EQ(StatusCode::OK_200, res->status);
  7808. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7809. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7810. EXPECT_TRUE(res->body.empty());
  7811. }
  7812. TEST_F(StaticFileCompressionTest, MinLength) {
  7813. auto port = start(enable);
  7814. Client cli(HOST, port);
  7815. // 104 bytes, well under the default floor. Compressing it would add the
  7816. // gzip header and trailer to a body that already fits in one packet.
  7817. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ(StatusCode::OK_200, res->status);
  7820. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7821. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7822. }
  7823. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7824. auto port = start([](Server &svr) {
  7825. svr.set_static_file_compression(true);
  7826. svr.set_static_file_compression_min_length(1);
  7827. });
  7828. Client cli(HOST, port);
  7829. cli.set_decompress(false);
  7830. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7832. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7833. // A 9-byte file comes back larger than it went in, because gzip's header and
  7834. // trailer outweigh anything deflate can save. That is the end of the range
  7835. // the floor exists to keep out.
  7836. EXPECT_GT(res->body.size(), 9U);
  7837. }
  7838. TEST_F(StaticFileCompressionTest, MaxLength) {
  7839. auto port = start([](Server &svr) {
  7840. svr.set_static_file_compression(true);
  7841. svr.set_static_file_compression_min_length(0);
  7842. svr.set_static_file_compression_max_length(1024);
  7843. });
  7844. Client cli(HOST, port);
  7845. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7846. // defines `small` as a macro on Windows.
  7847. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7848. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7849. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7850. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7851. // Under it: compressed.
  7852. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7853. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7854. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7855. }
  7856. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7857. auto port = start(enable_without_floor);
  7858. Client cli(HOST, port);
  7859. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7860. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7861. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7862. auto identity_etag = identity->get_header_value("ETag");
  7863. ASSERT_FALSE(identity_etag.empty());
  7864. auto gzipped =
  7865. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7866. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7867. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7868. auto gzip_etag = gzipped->get_header_value("ETag");
  7869. ASSERT_FALSE(gzip_etag.empty());
  7870. // Two representations, two validators.
  7871. EXPECT_NE(identity_etag, gzip_etag);
  7872. // Each one revalidates against the request that would produce it...
  7873. auto fresh =
  7874. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7875. {"If-None-Match", gzip_etag}});
  7876. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7877. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7878. auto fresh_identity =
  7879. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7880. {"If-None-Match", identity_etag}});
  7881. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7882. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7883. // ...and not against the other representation.
  7884. auto crossed =
  7885. cli.Get("/dir/index.html",
  7886. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7887. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7888. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7889. }
  7890. // The opt-in covers responses the server reads off disk itself. A caller's own
  7891. // known-length provider keeps its Content-Length and, more importantly, keeps
  7892. // delivering incrementally: routing it through a compressor would hold every
  7893. // write back until zlib's window filled.
  7894. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7895. auto port = start(enable);
  7896. Client cli(HOST, port);
  7897. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7901. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7902. EXPECT_EQ("aaabbb", res->body);
  7903. }
  7904. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7905. auto port = start(enable);
  7906. Client cli(HOST, port);
  7907. cli.set_read_timeout(1, 0);
  7908. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7909. Headers{{"Accept-Encoding", "gzip"}});
  7910. ASSERT_TRUE(handle.is_valid());
  7911. // The provider writes 100 bytes and then stalls for longer than the read
  7912. // timeout. Those first bytes have to arrive anyway: run the response through
  7913. // a compressor and zlib holds them until its window fills, so the read would
  7914. // come back empty instead.
  7915. char buf[256];
  7916. auto n = handle.read(buf, sizeof(buf));
  7917. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7918. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7919. }
  7920. #endif
  7921. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7922. TEST_F(ServerTest, Brotli) {
  7923. Headers headers;
  7924. headers.emplace("Accept-Encoding", "br");
  7925. auto res = cli_.Get("/compress", headers);
  7926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7927. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7929. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7930. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7931. "7890123456789012345678901234567890",
  7932. res->body);
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. #endif
  7936. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7937. TEST_F(ServerTest, Zstd) {
  7938. Headers headers;
  7939. headers.emplace("Accept-Encoding", "zstd");
  7940. auto res = cli_.Get("/compress", headers);
  7941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7942. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7944. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7945. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7946. "7890123456789012345678901234567890",
  7947. res->body);
  7948. EXPECT_EQ(StatusCode::OK_200, res->status);
  7949. }
  7950. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7951. Headers headers;
  7952. headers.emplace("Accept-Encoding", "");
  7953. auto res = cli_.Get("/compress", headers);
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7956. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7957. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7958. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7959. "7890123456789012345678901234567890",
  7960. res->body);
  7961. EXPECT_EQ(StatusCode::OK_200, res->status);
  7962. }
  7963. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7964. Headers headers;
  7965. headers.emplace("Accept-Encoding", "zstd");
  7966. std::string body;
  7967. auto res = cli_.Get("/compress", headers,
  7968. [&](const char *data, uint64_t data_length) {
  7969. EXPECT_EQ(100U, data_length);
  7970. body.append(data, data_length);
  7971. return true;
  7972. });
  7973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7974. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7975. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7976. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7977. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7978. "7890123456789012345678901234567890",
  7979. body);
  7980. EXPECT_EQ(StatusCode::OK_200, res->status);
  7981. }
  7982. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7983. Headers headers;
  7984. headers.emplace("Accept-Encoding", "zstd");
  7985. cli_.set_decompress(false);
  7986. auto res = cli_.Get("/compress", headers);
  7987. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7988. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7989. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7990. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7994. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. ASSERT_EQ(26U, res->body.size());
  7997. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7998. 0);
  7999. }
  8000. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8001. Headers headers;
  8002. headers.emplace("Accept-Encoding", "");
  8003. std::string body;
  8004. auto res = cli_.Get("/compress", headers,
  8005. [&](const char *data, uint64_t data_length) {
  8006. EXPECT_EQ(100U, data_length);
  8007. body.append(data, data_length);
  8008. return true;
  8009. });
  8010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8011. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8012. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8013. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8014. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8015. "7890123456789012345678901234567890",
  8016. body);
  8017. EXPECT_EQ(StatusCode::OK_200, res->status);
  8018. }
  8019. TEST_F(ServerTest, NoZstd) {
  8020. Headers headers;
  8021. headers.emplace("Accept-Encoding", "zstd");
  8022. auto res = cli_.Get("/nocompress", headers);
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8025. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8026. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8027. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8028. "7890123456789012345678901234567890",
  8029. res->body);
  8030. EXPECT_EQ(StatusCode::OK_200, res->status);
  8031. }
  8032. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8033. Headers headers;
  8034. headers.emplace("Accept-Encoding", "zstd");
  8035. std::string body;
  8036. auto res = cli_.Get("/nocompress", headers,
  8037. [&](const char *data, uint64_t data_length) {
  8038. EXPECT_EQ(100U, data_length);
  8039. body.append(data, data_length);
  8040. return true;
  8041. });
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8044. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8045. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8046. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8047. "7890123456789012345678901234567890",
  8048. body);
  8049. EXPECT_EQ(StatusCode::OK_200, res->status);
  8050. }
  8051. // TODO: How to enable zstd ??
  8052. TEST_F(ServerTest, MultipartFormDataZstd) {
  8053. UploadFormDataItems items = {
  8054. {"key1", "test", "", ""},
  8055. {"key2", "--abcdefg123", "", ""},
  8056. };
  8057. Headers headers;
  8058. headers.emplace("Accept-Encoding", "zstd");
  8059. cli_.set_compress(true);
  8060. auto res = cli_.Post("/compress-multipart", headers, items);
  8061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8062. EXPECT_EQ(StatusCode::OK_200, res->status);
  8063. }
  8064. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8065. Headers headers;
  8066. headers.emplace("Accept-Encoding", "zstd");
  8067. cli_.set_compress(true);
  8068. auto res = cli_.Put(
  8069. "/put", headers, 3,
  8070. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8071. sink.os << "PUT";
  8072. return true;
  8073. },
  8074. "text/plain");
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_EQ(StatusCode::OK_200, res->status);
  8077. EXPECT_EQ("PUT", res->body);
  8078. }
  8079. // Pre-compression logging tests
  8080. TEST_F(ServerTest, PreCompressionLogging) {
  8081. // Test data for compression (matches the actual /compress endpoint content)
  8082. const std::string test_content =
  8083. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8084. "3456789012345678901234567890";
  8085. // Variables to capture logging data
  8086. std::string pre_compression_body;
  8087. std::string pre_compression_content_type;
  8088. std::string pre_compression_content_encoding;
  8089. std::string post_compression_body;
  8090. std::string post_compression_content_type;
  8091. std::string post_compression_content_encoding;
  8092. // Set up pre-compression logger
  8093. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8094. const Response &res) {
  8095. pre_compression_body = res.body;
  8096. pre_compression_content_type = res.get_header_value("Content-Type");
  8097. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8098. });
  8099. // Set up post-compression logger
  8100. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8101. post_compression_body = res.body;
  8102. post_compression_content_type = res.get_header_value("Content-Type");
  8103. post_compression_content_encoding =
  8104. res.get_header_value("Content-Encoding");
  8105. });
  8106. // Test with gzip compression
  8107. Headers headers;
  8108. headers.emplace("Accept-Encoding", "gzip");
  8109. auto res = cli_.Get("/compress", headers);
  8110. // Verify response was compressed
  8111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8112. EXPECT_EQ(StatusCode::OK_200, res->status);
  8113. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8114. // Verify pre-compression logger captured uncompressed content
  8115. EXPECT_EQ(test_content, pre_compression_body);
  8116. EXPECT_EQ("text/plain", pre_compression_content_type);
  8117. EXPECT_TRUE(pre_compression_content_encoding
  8118. .empty()); // No encoding header before compression
  8119. // Verify post-compression logger captured compressed content
  8120. EXPECT_NE(test_content,
  8121. post_compression_body); // Should be different after compression
  8122. EXPECT_EQ("text/plain", post_compression_content_type);
  8123. EXPECT_EQ("gzip", post_compression_content_encoding);
  8124. // Verify compressed content is smaller
  8125. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8126. }
  8127. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8128. const std::string test_content =
  8129. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8130. "3456789012345678901234567890";
  8131. std::string pre_compression_body;
  8132. std::string post_compression_body;
  8133. svr_.set_pre_compression_logger(
  8134. [&](const Request & /*req*/, const Response &res) {
  8135. pre_compression_body = res.body;
  8136. });
  8137. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8138. post_compression_body = res.body;
  8139. });
  8140. Headers headers;
  8141. headers.emplace("Accept-Encoding", "br");
  8142. auto res = cli_.Get("/compress", headers);
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8146. // Verify pre-compression content is uncompressed
  8147. EXPECT_EQ(test_content, pre_compression_body);
  8148. // Verify post-compression content is compressed
  8149. EXPECT_NE(test_content, post_compression_body);
  8150. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8151. }
  8152. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8153. const std::string test_content =
  8154. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8155. "3456789012345678901234567890";
  8156. std::string pre_compression_body;
  8157. std::string post_compression_body;
  8158. svr_.set_pre_compression_logger(
  8159. [&](const Request & /*req*/, const Response &res) {
  8160. pre_compression_body = res.body;
  8161. });
  8162. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8163. post_compression_body = res.body;
  8164. });
  8165. // Request without compression (use /nocompress endpoint)
  8166. Headers headers;
  8167. auto res = cli_.Get("/nocompress", headers);
  8168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8169. EXPECT_EQ(StatusCode::OK_200, res->status);
  8170. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8171. // Pre-compression logger should not be called when no compression is applied
  8172. EXPECT_TRUE(
  8173. pre_compression_body.empty()); // Pre-compression logger not called
  8174. EXPECT_EQ(
  8175. test_content,
  8176. post_compression_body); // Post-compression logger captures final content
  8177. }
  8178. TEST_F(ServerTest, LoggerSeesContentLength) {
  8179. size_t logged_content_length = 0;
  8180. std::string logged_content_length_header;
  8181. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8182. logged_content_length = res.content_length_;
  8183. logged_content_length_header = res.get_header_value("Content-Length");
  8184. });
  8185. auto res = cli_.Get("/nocompress");
  8186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8187. EXPECT_EQ(StatusCode::OK_200, res->status);
  8188. EXPECT_EQ(res->body.size(), logged_content_length);
  8189. EXPECT_EQ(std::to_string(logged_content_length),
  8190. logged_content_length_header);
  8191. }
  8192. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8193. const std::string test_content =
  8194. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8195. "3456789012345678901234567890";
  8196. std::string pre_compression_body;
  8197. bool pre_logger_called = false;
  8198. // Set only pre-compression logger
  8199. svr_.set_pre_compression_logger(
  8200. [&](const Request & /*req*/, const Response &res) {
  8201. pre_compression_body = res.body;
  8202. pre_logger_called = true;
  8203. });
  8204. Headers headers;
  8205. headers.emplace("Accept-Encoding", "gzip");
  8206. auto res = cli_.Get("/compress", headers);
  8207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8208. EXPECT_EQ(StatusCode::OK_200, res->status);
  8209. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8210. // Verify pre-compression logger was called
  8211. EXPECT_TRUE(pre_logger_called);
  8212. EXPECT_EQ(test_content, pre_compression_body);
  8213. }
  8214. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8215. {
  8216. // Test with Expect: 100-continue header - success case
  8217. // Server returns 100 Continue, client sends body, server returns 200 OK
  8218. Request req;
  8219. req.method = "POST";
  8220. req.path = "/post-large";
  8221. req.set_header("Expect", "100-continue");
  8222. req.body = LARGE_DATA;
  8223. Response res;
  8224. auto error = Error::Success;
  8225. cli_.set_keep_alive(true);
  8226. auto ret = cli_.send(req, res, error);
  8227. EXPECT_TRUE(ret);
  8228. EXPECT_EQ(StatusCode::OK_200, res.status);
  8229. EXPECT_EQ(LARGE_DATA, res.body);
  8230. }
  8231. {
  8232. // Test with Expect: 100-continue header - error case
  8233. // Client should not send the body when server returns an error
  8234. Request req;
  8235. req.method = "POST";
  8236. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8237. req.set_header("Expect", "100-continue");
  8238. req.body = LARGE_DATA;
  8239. Response res;
  8240. auto error = Error::Success;
  8241. auto start = std::chrono::high_resolution_clock::now();
  8242. cli_.set_keep_alive(true);
  8243. auto ret = cli_.send(req, res, error);
  8244. auto end = std::chrono::high_resolution_clock::now();
  8245. auto elapsed =
  8246. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8247. .count();
  8248. // With Expect: 100-continue, request completes successfully but with error
  8249. EXPECT_TRUE(ret);
  8250. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8251. EXPECT_EQ("close", res.get_header_value("Connection"));
  8252. EXPECT_FALSE(cli_.is_socket_open());
  8253. EXPECT_LE(elapsed, 2000);
  8254. }
  8255. {
  8256. // Send an extra GET request to ensure error recovery without hanging
  8257. Request req;
  8258. req.method = "GET";
  8259. req.path = "/hi";
  8260. auto start = std::chrono::high_resolution_clock::now();
  8261. auto res = cli_.send(req);
  8262. auto end = std::chrono::high_resolution_clock::now();
  8263. auto elapsed =
  8264. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8265. .count();
  8266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8267. EXPECT_EQ(StatusCode::OK_200, res->status);
  8268. EXPECT_EQ("Hello World!", res->body);
  8269. EXPECT_LE(elapsed, 500);
  8270. }
  8271. }
  8272. TEST(ZstdDecompressor, ChunkedDecompression) {
  8273. std::string data;
  8274. for (size_t i = 0; i < 32 * 1024; ++i) {
  8275. data.push_back(static_cast<char>('a' + i % 26));
  8276. }
  8277. std::string compressed_data;
  8278. {
  8279. httplib::detail::zstd_compressor compressor;
  8280. bool result = compressor.compress(
  8281. data.data(), data.size(),
  8282. /*last=*/true,
  8283. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8284. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8285. compressed_data_size);
  8286. return true;
  8287. });
  8288. ASSERT_TRUE(result);
  8289. }
  8290. std::string decompressed_data;
  8291. {
  8292. httplib::detail::zstd_decompressor decompressor;
  8293. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8294. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8295. size_t chunk_size = 130;
  8296. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8297. chunk_begin += chunk_size) {
  8298. size_t current_chunk_size =
  8299. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8300. bool result = decompressor.decompress(
  8301. compressed_data.data() + chunk_begin, current_chunk_size,
  8302. [&](const char *decompressed_data_chunk,
  8303. size_t decompressed_data_chunk_size) {
  8304. decompressed_data.insert(decompressed_data.size(),
  8305. decompressed_data_chunk,
  8306. decompressed_data_chunk_size);
  8307. return true;
  8308. });
  8309. ASSERT_TRUE(result);
  8310. }
  8311. }
  8312. ASSERT_EQ(data, decompressed_data);
  8313. }
  8314. TEST(ZstdDecompressor, Decompress) {
  8315. std::string original_text = "Compressed with ZSTD";
  8316. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8317. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8318. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8319. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8320. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8321. std::string decompressed_data;
  8322. {
  8323. httplib::detail::zstd_decompressor decompressor;
  8324. bool result = decompressor.decompress(
  8325. compressed_data.data(), compressed_data.size(),
  8326. [&](const char *decompressed_data_chunk,
  8327. size_t decompressed_data_chunk_size) {
  8328. decompressed_data.insert(decompressed_data.size(),
  8329. decompressed_data_chunk,
  8330. decompressed_data_chunk_size);
  8331. return true;
  8332. });
  8333. ASSERT_TRUE(result);
  8334. }
  8335. ASSERT_EQ(original_text, decompressed_data);
  8336. }
  8337. #endif
  8338. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8339. // separate chunks so that the server sees each part in its own read(). Used to
  8340. // place a read boundary at a specific offset of a request body.
  8341. static bool send_request_in_parts(time_t read_timeout_sec,
  8342. const std::vector<std::string> &parts,
  8343. std::string *resp = nullptr,
  8344. int port = PORT) {
  8345. auto error = Error::Success;
  8346. auto client_sock = detail::create_client_socket(
  8347. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8348. /*connection_timeout_sec=*/5, 0,
  8349. /*read_timeout_sec=*/5, 0,
  8350. /*write_timeout_sec=*/5, 0, std::string(), error);
  8351. if (client_sock == INVALID_SOCKET) { return false; }
  8352. auto ret = detail::process_client_socket(
  8353. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8354. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8355. for (size_t i = 0; i < parts.size(); i++) {
  8356. const auto &part = parts[i];
  8357. if (part.size() !=
  8358. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8359. return false;
  8360. }
  8361. if (i + 1 < parts.size()) {
  8362. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8363. }
  8364. }
  8365. char buf[512];
  8366. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8367. while (line_reader.getline()) {
  8368. if (resp) { *resp += line_reader.ptr(); }
  8369. }
  8370. return true;
  8371. });
  8372. detail::close_socket(client_sock);
  8373. return ret;
  8374. }
  8375. // Sends a raw request to a server listening at HOST:PORT.
  8376. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8377. std::string *resp = nullptr, int port = PORT) {
  8378. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8379. }
  8380. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8381. Server svr;
  8382. std::string header_value;
  8383. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8384. header_value = req.get_header_value("foo");
  8385. res.set_content("ok", "text/plain");
  8386. });
  8387. thread t = thread([&] { svr.listen(HOST, PORT); });
  8388. auto se = detail::scope_exit([&] {
  8389. svr.stop();
  8390. t.join();
  8391. ASSERT_FALSE(svr.is_running());
  8392. });
  8393. svr.wait_until_ready();
  8394. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8395. // like characters are not treated the same - use vertical tab and escape.
  8396. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8397. "foo: \t \v bar \x1B\t \r\n"
  8398. "Connection: close\r\n"
  8399. "\r\n";
  8400. std::string res;
  8401. ASSERT_TRUE(send_request(5, req, &res));
  8402. EXPECT_EQ(header_value, "");
  8403. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8404. }
  8405. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8406. Server svr;
  8407. std::string received;
  8408. svr.Get("/order", [&](const Request &req, Response &res) {
  8409. received = entries_to_string(req.headers);
  8410. res.set_content("ok", "text/plain");
  8411. });
  8412. auto port = svr.bind_to_any_port(HOST);
  8413. thread t = thread([&] { svr.listen_after_bind(); });
  8414. auto se = detail::scope_exit([&] {
  8415. svr.stop();
  8416. t.join();
  8417. ASSERT_FALSE(svr.is_running());
  8418. });
  8419. svr.wait_until_ready();
  8420. const std::string req = "GET /order HTTP/1.1\r\n"
  8421. "X-First: 1\r\n"
  8422. "X-Dup: a\r\n"
  8423. "X-Second: 2\r\n"
  8424. "X-Dup: b\r\n"
  8425. "Connection: close\r\n"
  8426. "\r\n";
  8427. std::string res;
  8428. ASSERT_TRUE(send_request(5, req, &res, port));
  8429. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8430. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8431. }
  8432. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8433. Server svr;
  8434. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8435. res.set_header("Set-Cookie", "first=1");
  8436. res.set_header("X-Between", "y");
  8437. res.set_header("Set-Cookie", "second=2");
  8438. res.set_content("ok", "text/plain");
  8439. });
  8440. auto port = svr.bind_to_any_port(HOST);
  8441. thread t = thread([&] { svr.listen_after_bind(); });
  8442. auto se = detail::scope_exit([&] {
  8443. svr.stop();
  8444. t.join();
  8445. ASSERT_FALSE(svr.is_running());
  8446. });
  8447. svr.wait_until_ready();
  8448. Client cli(HOST, port);
  8449. auto res = cli.Get("/cookies");
  8450. ASSERT_TRUE(res);
  8451. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8452. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8453. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8454. }
  8455. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8456. Server svr;
  8457. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8458. auto i = new int(0);
  8459. res.set_header("Trailer", "X-Safe, X-Reflected");
  8460. res.set_chunked_content_provider(
  8461. "text/plain",
  8462. [i](size_t /*offset*/, DataSink &sink) {
  8463. if (*i == 0) {
  8464. sink.os << "body";
  8465. } else {
  8466. Headers trailer;
  8467. // A valid trailer that must survive.
  8468. trailer.emplace("X-Safe", "safe");
  8469. // Attacker-controlled value carrying CR/LF (response splitting).
  8470. trailer.emplace("X-Reflected",
  8471. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8472. // Attacker-controlled name carrying CR/LF.
  8473. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8474. sink.done_with_trailer(trailer);
  8475. }
  8476. (*i)++;
  8477. return true;
  8478. },
  8479. [i](bool /*success*/) { delete i; });
  8480. });
  8481. thread t = thread([&] { svr.listen(HOST, PORT); });
  8482. auto se = detail::scope_exit([&] {
  8483. svr.stop();
  8484. t.join();
  8485. ASSERT_FALSE(svr.is_running());
  8486. });
  8487. svr.wait_until_ready();
  8488. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8489. "Host: " + HOST +
  8490. "\r\n"
  8491. "Connection: close\r\n"
  8492. "\r\n";
  8493. std::string res;
  8494. ASSERT_TRUE(send_request(5, req, &res));
  8495. // The injected fields must not appear anywhere in the raw response.
  8496. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8497. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8498. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8499. // Invalid trailers are dropped entirely, matching set_header().
  8500. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8501. // The valid trailer still passes through.
  8502. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8503. }
  8504. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8505. Server svr;
  8506. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8507. // res.headers is a public field an application can populate directly,
  8508. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8509. // A valid header that must survive.
  8510. res.headers.emplace("X-Safe", "safe");
  8511. // Attacker-controlled value carrying CR/LF (response splitting).
  8512. res.headers.emplace("X-Reflected",
  8513. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8514. // Attacker-controlled name carrying CR/LF.
  8515. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8516. res.set_content("body", "text/plain");
  8517. });
  8518. thread t = thread([&] { svr.listen(HOST, PORT); });
  8519. auto se = detail::scope_exit([&] {
  8520. svr.stop();
  8521. t.join();
  8522. ASSERT_FALSE(svr.is_running());
  8523. });
  8524. svr.wait_until_ready();
  8525. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8526. "Host: " + HOST +
  8527. "\r\n"
  8528. "Connection: close\r\n"
  8529. "\r\n";
  8530. std::string res;
  8531. ASSERT_TRUE(send_request(5, req, &res));
  8532. // The injected fields must not appear anywhere in the raw response.
  8533. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8534. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8535. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8536. // Invalid headers are dropped entirely, matching set_header().
  8537. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8538. // The valid header still passes through.
  8539. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8540. }
  8541. // Forward declaration: in split builds split.py strips `inline` and moves the
  8542. // definition into httplib.cc, so detail::write_request_line is not visible from
  8543. // the public httplib.h. Re-declaring it here lets the tests link against the
  8544. // symbol in both header-only and split builds.
  8545. namespace httplib {
  8546. namespace detail {
  8547. ssize_t write_request_line(Stream &strm, const std::string &method,
  8548. const std::string &path);
  8549. } // namespace detail
  8550. } // namespace httplib
  8551. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8552. // A well-formed target is written verbatim.
  8553. {
  8554. detail::BufferStream strm;
  8555. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8556. EXPECT_GT(n, 0);
  8557. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8558. }
  8559. // A target carrying CR/LF, SP or other control octets must be rejected
  8560. // before anything reaches the wire, otherwise it splits the request line and
  8561. // injects a header or a whole request. This is what a decoded redirect
  8562. // Location ("%0D%0A") turns into when path encoding is disabled.
  8563. const std::string evil_targets[] = {
  8564. "/a\r\nInjected: pwned",
  8565. "/a\rInjected",
  8566. "/a\nInjected",
  8567. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8568. "/a b",
  8569. "/a\tb",
  8570. "/a\x7f",
  8571. };
  8572. for (const auto &evil : evil_targets) {
  8573. detail::BufferStream strm;
  8574. auto n = detail::write_request_line(strm, "GET", evil);
  8575. EXPECT_LT(n, 0);
  8576. EXPECT_TRUE(strm.get_buffer().empty());
  8577. }
  8578. }
  8579. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8580. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8581. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8582. // target -- what a redirect Location "%0D%0A" decodes to -- reaches
  8583. // write_request. The client must fail cleanly with Error::Write instead of
  8584. // putting a request-line-less, header-injecting request on the wire.
  8585. Server svr;
  8586. svr.Get("/a", [](const Request &, Response &res) {
  8587. res.set_content("ok", "text/plain");
  8588. });
  8589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8590. auto se = detail::scope_exit([&] {
  8591. svr.stop();
  8592. thread.join();
  8593. ASSERT_FALSE(svr.is_running());
  8594. });
  8595. svr.wait_until_ready();
  8596. {
  8597. Client cli(HOST, PORT);
  8598. cli.set_path_encode(false);
  8599. // The request is rejected before anything is written, so the connection
  8600. // stays silent and the subsequent response read would otherwise block for
  8601. // the full default read timeout. Shorten it -- the assertion is on the
  8602. // error, not the timeout.
  8603. cli.set_read_timeout(1, 0);
  8604. auto res = cli.Get("/a\r\nInjected: pwned");
  8605. EXPECT_FALSE(res);
  8606. EXPECT_EQ(Error::Write, res.error());
  8607. }
  8608. }
  8609. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8610. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8611. // including extension methods.
  8612. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8613. for (const auto &method : good_methods) {
  8614. detail::BufferStream strm;
  8615. auto n = detail::write_request_line(strm, method, "/");
  8616. EXPECT_GT(n, 0);
  8617. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8618. }
  8619. // A method carrying CR/LF would split the request line and smuggle a whole
  8620. // request ahead of the real one. A space or an empty method corrupts the
  8621. // request line. All must be rejected before anything reaches the wire.
  8622. const std::string evil_methods[] = {
  8623. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8624. "GET\r\nInjected: pwned",
  8625. "GET\r",
  8626. "GET\n",
  8627. "GE T",
  8628. "",
  8629. };
  8630. for (const auto &evil : evil_methods) {
  8631. detail::BufferStream strm;
  8632. auto n = detail::write_request_line(strm, evil, "/");
  8633. EXPECT_LT(n, 0);
  8634. EXPECT_TRUE(strm.get_buffer().empty());
  8635. }
  8636. }
  8637. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8638. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8639. // through Client::send must fail with Error::Write and no request, neither
  8640. // the smuggled one nor the real one, may reach the server.
  8641. Server svr;
  8642. std::atomic<int> request_count(0);
  8643. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8644. request_count++;
  8645. res.status = StatusCode::OK_200;
  8646. return Server::HandlerResponse::Handled;
  8647. });
  8648. auto port = svr.bind_to_any_port(HOST);
  8649. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8650. auto se = detail::scope_exit([&] {
  8651. svr.stop();
  8652. thread.join();
  8653. ASSERT_FALSE(svr.is_running());
  8654. });
  8655. svr.wait_until_ready();
  8656. {
  8657. Client cli(HOST, port);
  8658. const std::string evil_methods[] = {
  8659. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8660. "GE T",
  8661. "",
  8662. };
  8663. for (const auto &evil : evil_methods) {
  8664. Request req;
  8665. req.method = evil;
  8666. req.path = "/";
  8667. auto res = cli.send(req);
  8668. EXPECT_FALSE(res);
  8669. EXPECT_EQ(Error::Write, res.error());
  8670. }
  8671. auto handle =
  8672. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8673. EXPECT_FALSE(handle.is_valid());
  8674. EXPECT_EQ(Error::Write, handle.error);
  8675. // A valid request on the same client still goes through.
  8676. auto res = cli.Get("/");
  8677. ASSERT_TRUE(res);
  8678. EXPECT_EQ(StatusCode::OK_200, res->status);
  8679. }
  8680. EXPECT_EQ(1, request_count.load());
  8681. }
  8682. // Sends a raw request and verifies that there isn't a crash or exception.
  8683. static void test_raw_request(const std::string &req,
  8684. std::string *out = nullptr) {
  8685. Server svr;
  8686. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8687. res.set_content("ok", "text/plain");
  8688. });
  8689. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8690. res.set_content("ok", "text/plain");
  8691. });
  8692. svr.Get("/header_field_value_check",
  8693. [&](const Request & /*req*/, Response &res) {
  8694. res.set_content("ok", "text/plain");
  8695. });
  8696. svr.CustomRoute("PROPFIND", "/dav",
  8697. [&](const Request & /*req*/, Response &res) {
  8698. res.status = StatusCode::MultiStatus_207;
  8699. });
  8700. // Server read timeout must be longer than the client read timeout for the
  8701. // bug to reproduce, probably to force the server to process a request
  8702. // without a trailing blank line.
  8703. const time_t client_read_timeout_sec = 1;
  8704. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8705. bool listen_thread_ok = false;
  8706. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8707. auto se = detail::scope_exit([&] {
  8708. svr.stop();
  8709. t.join();
  8710. ASSERT_FALSE(svr.is_running());
  8711. EXPECT_TRUE(listen_thread_ok);
  8712. });
  8713. svr.wait_until_ready();
  8714. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8715. }
  8716. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8717. // A certain header line causes an exception if the header property is parsed
  8718. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8719. test_raw_request(
  8720. "GET /hi HTTP/1.1\r\n"
  8721. " : "
  8722. " "
  8723. " ");
  8724. }
  8725. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8726. // A certain header line causes an exception if the header property *name* is
  8727. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8728. // greedy matcher and requires backtracking when there are a lot of ":"
  8729. // characters.
  8730. // This occurs with libc++ but not libstdc++.
  8731. test_raw_request(
  8732. "GET /hi HTTP/1.1\r\n"
  8733. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8734. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8735. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8736. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8737. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8738. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8739. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8740. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8741. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8742. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8743. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8744. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8745. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8746. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8747. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8748. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8749. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8750. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8751. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8752. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8753. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8754. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8755. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8756. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8757. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8758. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8759. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8760. "&&&%%%");
  8761. }
  8762. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8763. // Make sure this doesn't crash the server.
  8764. // In a previous version of the header line regex, the "\r" rendered the line
  8765. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8766. // a new position where the leading white space ended and the field value
  8767. // began.
  8768. // The crash occurs with libc++ but not libstdc++.
  8769. test_raw_request("GET /hi HTTP/1.1\r\n"
  8770. "a:" +
  8771. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8772. "\r\n"
  8773. "\r\n");
  8774. }
  8775. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8776. std::string out;
  8777. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8778. "Content-Type: text/plain\r\n"
  8779. "Transfer-Encoding: chunked\r\n"
  8780. "\r\n"
  8781. "nothex\r\n",
  8782. &out);
  8783. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8784. }
  8785. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8786. std::string out;
  8787. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8788. "Content-Type: text/plain\r\n"
  8789. "Transfer-Encoding: chunked\r\n"
  8790. "\r\n"
  8791. "3\r\n"
  8792. "xyz\r\n"
  8793. "NaN\r\n",
  8794. &out);
  8795. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8796. }
  8797. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8798. std::string out;
  8799. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8800. "Content-Type: text/plain\r\n"
  8801. "Transfer-Encoding: chunked\r\n"
  8802. "\r\n"
  8803. // Length is too large for 64 bits.
  8804. "1ffffffffffffffff\r\n"
  8805. "xyz\r\n",
  8806. &out);
  8807. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8808. }
  8809. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8810. test_raw_request("GET /hi HTTP/1.1\r\n"
  8811. "Content-Type: text/plain\r\n\r");
  8812. }
  8813. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8814. std::string out;
  8815. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8816. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8817. }
  8818. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8819. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8820. std::string out;
  8821. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8822. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8823. }
  8824. }
  8825. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8826. std::string out;
  8827. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8828. "Connection: close\r\n\r\n",
  8829. &out);
  8830. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8831. }
  8832. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8833. Server svr;
  8834. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8835. EXPECT_TRUE(!req.remote_addr.empty());
  8836. });
  8837. thread t = thread([&] { svr.listen(HOST, PORT); });
  8838. auto se = detail::scope_exit([&] {
  8839. svr.stop();
  8840. t.join();
  8841. ASSERT_FALSE(svr.is_running());
  8842. });
  8843. svr.wait_until_ready();
  8844. // Send an invalid request line to trigger Bad Request
  8845. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8846. std::string out;
  8847. ASSERT_TRUE(send_request(5, bad_req, &out));
  8848. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8849. }
  8850. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8851. // answered right away rather than blocking on a read that waits for EOF.
  8852. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8853. std::string out;
  8854. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8855. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8856. }
  8857. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8858. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8859. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8860. for (const auto *method : methods) {
  8861. Server svr;
  8862. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8863. EXPECT_FALSE(svr.is_valid()) << method;
  8864. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8865. }
  8866. }
  8867. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8868. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8869. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8870. for (const auto *method : methods) {
  8871. Server svr;
  8872. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8873. EXPECT_FALSE(svr.is_valid()) << method;
  8874. }
  8875. }
  8876. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8877. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8878. "COPY", "MOVE", "LOCK",
  8879. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8880. Server svr;
  8881. for (const auto *method : methods) {
  8882. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8883. }
  8884. EXPECT_TRUE(svr.is_valid());
  8885. }
  8886. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8887. Server svr;
  8888. svr.CustomRoute("POST", "/x",
  8889. [](const Request &, Response &, const ContentReader &) {});
  8890. EXPECT_FALSE(svr.is_valid());
  8891. }
  8892. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8893. Server svr;
  8894. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8895. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8896. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8897. EXPECT_FALSE(svr.is_valid());
  8898. }
  8899. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8900. Server svr;
  8901. auto captured = Error::Success;
  8902. svr.set_error_logger(
  8903. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8904. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8905. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8906. }
  8907. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8908. std::string out;
  8909. std::string request(
  8910. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8911. test_raw_request(request, &out);
  8912. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8913. }
  8914. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8915. std::string out;
  8916. std::string request(
  8917. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8918. test_raw_request(request, &out);
  8919. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8920. }
  8921. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8922. std::string out;
  8923. std::string request(
  8924. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8925. test_raw_request(request, &out);
  8926. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8927. }
  8928. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8929. std::string out;
  8930. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8931. "Test: \r\n\r\n",
  8932. &out);
  8933. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8934. }
  8935. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8936. Server svr;
  8937. std::string x_custom;
  8938. std::string cookie;
  8939. std::string xff;
  8940. std::string x_unicode;
  8941. std::string x_iis;
  8942. svr.Get("/check", [&](const Request &req, Response &res) {
  8943. x_custom = req.get_header_value("X-Custom");
  8944. cookie = req.get_header_value("Cookie");
  8945. xff = req.get_header_value("X-Forwarded-For");
  8946. x_unicode = req.get_header_value("X-Unicode");
  8947. x_iis = req.get_header_value("X-IIS");
  8948. res.set_content("ok", "text/plain");
  8949. });
  8950. thread t = thread([&] { svr.listen(HOST, PORT); });
  8951. auto se = detail::scope_exit([&] {
  8952. svr.stop();
  8953. t.join();
  8954. ASSERT_FALSE(svr.is_running());
  8955. });
  8956. svr.wait_until_ready();
  8957. const std::string req = "GET /check HTTP/1.1\r\n"
  8958. "Host: localhost\r\n"
  8959. "X-Custom: a%0D%0AInjected: b\r\n"
  8960. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8961. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8962. "X-Unicode: %E3%81%82\r\n"
  8963. "X-IIS: %u00E9\r\n"
  8964. "Connection: close\r\n"
  8965. "\r\n";
  8966. std::string res;
  8967. ASSERT_TRUE(send_request(5, req, &res));
  8968. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8969. // Every value must be returned verbatim (wire form), with no decoding.
  8970. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8971. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8972. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8973. EXPECT_EQ("%E3%81%82", x_unicode);
  8974. EXPECT_EQ("%u00E9", x_iis);
  8975. }
  8976. // Applications that previously relied on automatic percent-decoding can
  8977. // reproduce the old behavior by explicitly calling decode_path_component()
  8978. // or, for RFC 3986 conformance, decode_uri_component().
  8979. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8980. Server svr;
  8981. std::string decoded;
  8982. svr.Get("/check", [&](const Request &req, Response &res) {
  8983. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8984. res.set_content("ok", "text/plain");
  8985. });
  8986. thread t = thread([&] { svr.listen(HOST, PORT); });
  8987. auto se = detail::scope_exit([&] {
  8988. svr.stop();
  8989. t.join();
  8990. ASSERT_FALSE(svr.is_running());
  8991. });
  8992. svr.wait_until_ready();
  8993. const std::string req = "GET /check HTTP/1.1\r\n"
  8994. "Host: localhost\r\n"
  8995. "X-Custom: hello%20world\r\n"
  8996. "Connection: close\r\n"
  8997. "\r\n";
  8998. std::string res;
  8999. ASSERT_TRUE(send_request(5, req, &res));
  9000. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9001. EXPECT_EQ("hello world", decoded);
  9002. }
  9003. // Regression test for #2033. Browsers send Referer values that include
  9004. // percent-encoded characters such as %0A inside the URL. Decoding the
  9005. // header value would either trip the post-decode CR/LF/NUL guard (the
  9006. // original bug, returning 400) or, after that guard was relaxed, silently
  9007. // store a literal LF — both unacceptable. The wire form must round-trip.
  9008. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9009. Server svr;
  9010. std::string referer;
  9011. svr.Get("/check", [&](const Request &req, Response &res) {
  9012. referer = req.get_header_value("Referer");
  9013. res.set_content("ok", "text/plain");
  9014. });
  9015. thread t = thread([&] { svr.listen(HOST, PORT); });
  9016. auto se = detail::scope_exit([&] {
  9017. svr.stop();
  9018. t.join();
  9019. ASSERT_FALSE(svr.is_running());
  9020. });
  9021. svr.wait_until_ready();
  9022. const std::string req = "GET /check HTTP/1.1\r\n"
  9023. "Host: localhost\r\n"
  9024. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9025. "Connection: close\r\n"
  9026. "\r\n";
  9027. std::string res;
  9028. ASSERT_TRUE(send_request(5, req, &res));
  9029. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9030. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9031. }
  9032. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9033. Server svr;
  9034. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9035. res.set_header("Cache-Control", "no-cache");
  9036. res.set_chunked_content_provider(
  9037. "text/event-stream", [](size_t offset, DataSink &sink) {
  9038. std::string s = "data:";
  9039. s += std::to_string(offset);
  9040. s += "\n\n";
  9041. auto ret = sink.write(s.data(), s.size());
  9042. EXPECT_TRUE(ret);
  9043. std::this_thread::sleep_for(std::chrono::seconds(1));
  9044. return true;
  9045. });
  9046. });
  9047. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9048. svr.wait_until_ready();
  9049. Client client(HOST, PORT);
  9050. const Headers headers = {{"Accept", "text/event-stream"}};
  9051. auto get_thread = std::thread([&client, &headers]() {
  9052. auto res = client.Get(
  9053. "/events", headers,
  9054. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9055. });
  9056. auto se = detail::scope_exit([&] {
  9057. svr.stop();
  9058. get_thread.join();
  9059. listen_thread.join();
  9060. ASSERT_FALSE(svr.is_running());
  9061. });
  9062. // Give GET time to get a few messages.
  9063. std::this_thread::sleep_for(std::chrono::seconds(2));
  9064. }
  9065. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9066. httplib::Server svr;
  9067. svr.Post("/hi",
  9068. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9069. res.status = StatusCode::OK_200;
  9070. });
  9071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9072. svr.wait_until_ready();
  9073. Client cli(HOST, PORT);
  9074. auto res = cli.Post("/hi", "data", "text/plain");
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_EQ(StatusCode::OK_200, res->status);
  9077. svr.stop();
  9078. thread.join();
  9079. ASSERT_FALSE(svr.is_running());
  9080. res = cli.Post("/hi", "data", "text/plain");
  9081. ASSERT_FALSE(res);
  9082. }
  9083. TEST(ServerStopTest, ListenFailure) {
  9084. Server svr;
  9085. auto t = thread([&]() {
  9086. auto ret = svr.listen("????", PORT);
  9087. EXPECT_FALSE(ret);
  9088. });
  9089. svr.wait_until_ready();
  9090. svr.stop();
  9091. t.join();
  9092. }
  9093. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9094. TEST(ServerStopTest, Decommision) {
  9095. Server svr;
  9096. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9097. for (int i = 0; i < 4; i++) {
  9098. auto is_even = !(i % 2);
  9099. std::thread t{[&] {
  9100. try {
  9101. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9102. if (is_even) {
  9103. throw std::runtime_error("Some thing that happens to go wrong.");
  9104. }
  9105. svr.listen(HOST, PORT);
  9106. } catch (...) { svr.decommission(); }
  9107. }};
  9108. svr.wait_until_ready();
  9109. // Server is up
  9110. {
  9111. Client cli(HOST, PORT);
  9112. auto res = cli.Get("/hi");
  9113. if (is_even) {
  9114. EXPECT_FALSE(res);
  9115. } else {
  9116. EXPECT_TRUE(res);
  9117. EXPECT_EQ("hi...", res->body);
  9118. }
  9119. }
  9120. svr.stop();
  9121. t.join();
  9122. // Server is down...
  9123. {
  9124. Client cli(HOST, PORT);
  9125. auto res = cli.Get("/hi");
  9126. EXPECT_FALSE(res);
  9127. }
  9128. }
  9129. }
  9130. #endif
  9131. // Helper function for string body upload progress tests
  9132. template <typename SetupHandler, typename ClientCall>
  9133. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9134. ClientCall &&client_call,
  9135. const string &body) {
  9136. Server svr;
  9137. setup_handler(svr);
  9138. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9139. auto se = detail::scope_exit([&] {
  9140. svr.stop();
  9141. t.join();
  9142. });
  9143. svr.wait_until_ready();
  9144. Client cli(HOST, PORT);
  9145. vector<uint64_t> progress_values;
  9146. bool progress_called = false;
  9147. auto res =
  9148. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9149. progress_values.push_back(current);
  9150. progress_called = true;
  9151. return true;
  9152. });
  9153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9154. EXPECT_EQ(200, res->status);
  9155. EXPECT_TRUE(progress_called);
  9156. }
  9157. TEST(UploadProgressTest, PostStringBodyBasic) {
  9158. TestStringBodyUploadProgress(
  9159. [](Server &svr) {
  9160. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9161. res.set_content("received", "text/plain");
  9162. });
  9163. },
  9164. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9165. return cli.Post("/test", body, "text/plain", progress_callback);
  9166. },
  9167. "test data for upload progress");
  9168. }
  9169. TEST(UploadProgressTest, PutStringBodyBasic) {
  9170. TestStringBodyUploadProgress(
  9171. [](Server &svr) {
  9172. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9173. res.set_content("put received", "text/plain");
  9174. });
  9175. },
  9176. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9177. return cli.Put("/test", body, "text/plain", progress_callback);
  9178. },
  9179. "put test data for upload progress");
  9180. }
  9181. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9182. TestStringBodyUploadProgress(
  9183. [](Server &svr) {
  9184. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9185. res.set_content("patch received", "text/plain");
  9186. });
  9187. },
  9188. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9189. return cli.Patch("/test", body, "text/plain", progress_callback);
  9190. },
  9191. "patch test data for upload progress");
  9192. }
  9193. // Helper function for content provider upload progress tests
  9194. template <typename SetupHandler, typename ClientCall>
  9195. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9196. ClientCall &&client_call) {
  9197. Server svr;
  9198. setup_handler(svr);
  9199. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9200. auto se = detail::scope_exit([&] {
  9201. svr.stop();
  9202. t.join();
  9203. });
  9204. svr.wait_until_ready();
  9205. Client cli(HOST, PORT);
  9206. vector<uint64_t> progress_values;
  9207. auto res =
  9208. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9209. progress_values.push_back(current);
  9210. return true;
  9211. });
  9212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9213. EXPECT_EQ(200, res->status);
  9214. EXPECT_FALSE(progress_values.empty());
  9215. }
  9216. TEST(UploadProgressTest, PostContentProviderProgress) {
  9217. TestContentProviderUploadProgress(
  9218. [](Server &svr) {
  9219. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9220. res.set_content("provider received", "text/plain");
  9221. });
  9222. },
  9223. [](Client &cli, UploadProgress progress_callback) {
  9224. return cli.Post(
  9225. "/test", 10,
  9226. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9227. sink.os << "test data";
  9228. return true;
  9229. },
  9230. "text/plain", progress_callback);
  9231. });
  9232. }
  9233. // Helper function for multipart upload progress tests
  9234. template <typename SetupHandler, typename ClientCall>
  9235. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9236. ClientCall &&client_call,
  9237. const string &endpoint) {
  9238. Server svr;
  9239. setup_handler(svr);
  9240. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9241. auto se = detail::scope_exit([&] {
  9242. svr.stop();
  9243. t.join();
  9244. });
  9245. svr.wait_until_ready();
  9246. Client cli(HOST, PORT);
  9247. vector<uint64_t> progress_values;
  9248. UploadFormDataItems items = {
  9249. {"field1", "value1", "", ""},
  9250. {"field2", "longer value for progress tracking test", "", ""},
  9251. {"file1", "file content data for upload progress", "test.txt",
  9252. "text/plain"}};
  9253. auto res = client_call(cli, endpoint, items,
  9254. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9255. progress_values.push_back(current);
  9256. return true;
  9257. });
  9258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9259. EXPECT_EQ(200, res->status);
  9260. EXPECT_FALSE(progress_values.empty());
  9261. }
  9262. TEST(UploadProgressTest, PostMultipartProgress) {
  9263. TestMultipartUploadProgress(
  9264. [](Server &svr) {
  9265. svr.Post("/multipart", [](const Request &req, Response &res) {
  9266. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9267. res.set_content("multipart received", "text/plain");
  9268. });
  9269. },
  9270. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9271. UploadProgress progress_callback) {
  9272. return cli.Post(endpoint, items, progress_callback);
  9273. },
  9274. "/multipart");
  9275. }
  9276. // Helper function for basic download progress tests
  9277. template <typename SetupHandler, typename ClientCall>
  9278. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9279. ClientCall &&client_call, const string &endpoint,
  9280. size_t expected_content_size) {
  9281. Server svr;
  9282. setup_handler(svr);
  9283. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9284. auto se = detail::scope_exit([&] {
  9285. svr.stop();
  9286. t.join();
  9287. });
  9288. svr.wait_until_ready();
  9289. Client cli(HOST, PORT);
  9290. vector<uint64_t> progress_values;
  9291. auto res = client_call(cli, endpoint,
  9292. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9293. progress_values.push_back(current);
  9294. return true;
  9295. });
  9296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9297. EXPECT_EQ(200, res->status);
  9298. EXPECT_FALSE(progress_values.empty());
  9299. EXPECT_EQ(expected_content_size, res->body.size());
  9300. }
  9301. TEST(DownloadProgressTest, GetBasic) {
  9302. TestBasicDownloadProgress(
  9303. [](Server &svr) {
  9304. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9305. string content(1000, 'D');
  9306. res.set_content(content, "text/plain");
  9307. });
  9308. },
  9309. [](Client &cli, const string &endpoint,
  9310. DownloadProgress progress_callback) {
  9311. return cli.Get(endpoint, progress_callback);
  9312. },
  9313. "/download", 1000u);
  9314. }
  9315. // Helper function for content receiver download progress tests
  9316. template <typename SetupHandler, typename ClientCall>
  9317. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9318. ClientCall &&client_call,
  9319. const string &endpoint,
  9320. size_t expected_content_size) {
  9321. Server svr;
  9322. setup_handler(svr);
  9323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9324. auto se = detail::scope_exit([&] {
  9325. svr.stop();
  9326. t.join();
  9327. });
  9328. svr.wait_until_ready();
  9329. Client cli(HOST, PORT);
  9330. vector<uint64_t> progress_values;
  9331. string received_body;
  9332. auto res = client_call(
  9333. cli, endpoint,
  9334. [&](const char *data, size_t data_length) -> bool {
  9335. received_body.append(data, data_length);
  9336. return true;
  9337. },
  9338. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9339. progress_values.push_back(current);
  9340. return true;
  9341. });
  9342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9343. EXPECT_EQ(200, res->status);
  9344. EXPECT_FALSE(progress_values.empty());
  9345. EXPECT_EQ(expected_content_size, received_body.size());
  9346. EXPECT_TRUE(res->body.empty());
  9347. }
  9348. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9349. TestContentReceiverDownloadProgress(
  9350. [](Server &svr) {
  9351. svr.Get("/download-receiver",
  9352. [](const Request & /*req*/, Response &res) {
  9353. string content(2000, 'R');
  9354. res.set_content(content, "text/plain");
  9355. });
  9356. },
  9357. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9358. DownloadProgress progress_callback) {
  9359. return cli.Get(endpoint, content_receiver, progress_callback);
  9360. },
  9361. "/download-receiver", 2000u);
  9362. }
  9363. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9364. // A provider reaching a pass with nothing to hand over - an empty buffer
  9365. // popped off a queue, say - must not be taken to mean the body is finished.
  9366. // It used to end the loop with the terminating chunk unwritten while the
  9367. // server still considered the response complete, so the peer waited for an
  9368. // end that never arrived.
  9369. Server svr;
  9370. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9371. auto step = std::make_shared<int>(0);
  9372. res.set_chunked_content_provider("text/plain",
  9373. [step](size_t /*offset*/, DataSink &sink) {
  9374. switch ((*step)++) {
  9375. case 0: sink.write("", 0); break;
  9376. case 1: sink.write("hello", 5); break;
  9377. default: sink.done(); break;
  9378. }
  9379. return true;
  9380. });
  9381. });
  9382. auto port = svr.bind_to_any_port(HOST);
  9383. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9384. auto listen_se = detail::scope_exit([&] {
  9385. svr.stop();
  9386. listen_thread.join();
  9387. ASSERT_FALSE(svr.is_running());
  9388. });
  9389. svr.wait_until_ready();
  9390. Client cli(HOST, port);
  9391. // Without the fix the body is never terminated, so bound the wait rather
  9392. // than letting the test hang on the default read timeout.
  9393. cli.set_read_timeout(5, 0);
  9394. auto res = cli.Get("/stream");
  9395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9396. EXPECT_EQ(StatusCode::OK_200, res->status);
  9397. EXPECT_EQ("hello", res->body);
  9398. }
  9399. TEST(StreamingTest, NoContentLengthStreaming) {
  9400. Server svr;
  9401. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9402. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9403. if (offset < 6) {
  9404. sink.os << (offset < 3 ? "a" : "b");
  9405. } else {
  9406. sink.done();
  9407. }
  9408. return true;
  9409. });
  9410. });
  9411. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9412. auto listen_se = detail::scope_exit([&] {
  9413. svr.stop();
  9414. listen_thread.join();
  9415. ASSERT_FALSE(svr.is_running());
  9416. });
  9417. svr.wait_until_ready();
  9418. Client client(HOST, PORT);
  9419. auto get_thread = std::thread([&client]() {
  9420. std::string s;
  9421. auto res =
  9422. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9423. s += std::string(data, len);
  9424. return true;
  9425. });
  9426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9427. EXPECT_EQ(StatusCode::OK_200, res->status);
  9428. EXPECT_EQ("aaabbb", s);
  9429. });
  9430. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9431. // Give GET time to get a few messages.
  9432. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9433. }
  9434. TEST(MountTest, Unmount) {
  9435. Server svr;
  9436. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9437. auto se = detail::scope_exit([&] {
  9438. svr.stop();
  9439. listen_thread.join();
  9440. ASSERT_FALSE(svr.is_running());
  9441. });
  9442. svr.wait_until_ready();
  9443. Client cli("localhost", PORT);
  9444. svr.set_mount_point("/mount2", "./www2");
  9445. auto res = cli.Get("/");
  9446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9448. res = cli.Get("/mount2/dir/test.html");
  9449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9450. EXPECT_EQ(StatusCode::OK_200, res->status);
  9451. svr.set_mount_point("/", "./www");
  9452. res = cli.Get("/dir/");
  9453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9454. EXPECT_EQ(StatusCode::OK_200, res->status);
  9455. svr.remove_mount_point("/");
  9456. res = cli.Get("/dir/");
  9457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9459. svr.remove_mount_point("/mount2");
  9460. res = cli.Get("/mount2/dir/test.html");
  9461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9462. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9463. }
  9464. TEST(MountTest, PathSegmentBoundary) {
  9465. Server svr;
  9466. svr.set_mount_point("/mount2", "./www2");
  9467. svr.set_mount_point("/", "./www");
  9468. auto port = svr.bind_to_any_port(HOST);
  9469. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9470. auto se = detail::scope_exit([&] {
  9471. svr.stop();
  9472. listen_thread.join();
  9473. ASSERT_FALSE(svr.is_running());
  9474. });
  9475. svr.wait_until_ready();
  9476. Client cli(HOST, port);
  9477. auto res = cli.Get("/mount2/dir/test.html");
  9478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9479. EXPECT_EQ(StatusCode::OK_200, res->status);
  9480. // "/mount2" must not match part-way through a path segment.
  9481. res = cli.Get("/mount2dir/test.html");
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9484. // A mount point ending in '/' keeps matching every path below it.
  9485. res = cli.Get("/dir/test.html");
  9486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9487. EXPECT_EQ(StatusCode::OK_200, res->status);
  9488. }
  9489. TEST(MountTest, Redicect) {
  9490. Server svr;
  9491. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9492. auto se = detail::scope_exit([&] {
  9493. svr.stop();
  9494. listen_thread.join();
  9495. ASSERT_FALSE(svr.is_running());
  9496. });
  9497. svr.set_mount_point("/", "./www");
  9498. svr.wait_until_ready();
  9499. Client cli("localhost", PORT);
  9500. auto res = cli.Get("/dir/");
  9501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9502. EXPECT_EQ(StatusCode::OK_200, res->status);
  9503. res = cli.Get("/dir");
  9504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9505. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9506. res = cli.Get("/file");
  9507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9508. EXPECT_EQ(StatusCode::OK_200, res->status);
  9509. res = cli.Get("/file/");
  9510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9511. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9512. cli.set_follow_location(true);
  9513. res = cli.Get("/dir");
  9514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9515. EXPECT_EQ(StatusCode::OK_200, res->status);
  9516. }
  9517. TEST(MountTest, MultibytesPathName) {
  9518. Server svr;
  9519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9520. auto se = detail::scope_exit([&] {
  9521. svr.stop();
  9522. listen_thread.join();
  9523. ASSERT_FALSE(svr.is_running());
  9524. });
  9525. svr.set_mount_point("/", "./www");
  9526. svr.wait_until_ready();
  9527. Client cli("localhost", PORT);
  9528. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9530. EXPECT_EQ(StatusCode::OK_200, res->status);
  9531. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9532. }
  9533. #ifdef _WIN32
  9534. // Issue #2435: mmap::open() must succeed even when another handle holds
  9535. // the file open for writing (e.g. an active log file).
  9536. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9537. const char *path = "mmap_concurrent_writer_test.txt";
  9538. const char *content = "hello";
  9539. {
  9540. std::ofstream f(path, std::ios::binary);
  9541. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9542. }
  9543. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9544. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9545. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9546. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9547. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9548. detail::mmap m(path);
  9549. ASSERT_TRUE(m.is_open());
  9550. EXPECT_EQ(strlen(content), m.size());
  9551. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9552. }
  9553. #endif
  9554. #ifndef _WIN32
  9555. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9556. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9557. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9558. TEST(MmapTest, FailedMappingIsNotOpen) {
  9559. const char *path = "./mmap_failed_mapping_test_dir";
  9560. ASSERT_EQ(0, ::mkdir(path, 0755));
  9561. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9562. detail::mmap m(path);
  9563. EXPECT_FALSE(m.is_open());
  9564. EXPECT_EQ(0U, m.size());
  9565. EXPECT_NE(static_cast<const void *>(m.data()),
  9566. static_cast<const void *>(MAP_FAILED));
  9567. }
  9568. #endif
  9569. TEST(KeepAliveTest, ReadTimeout) {
  9570. Server svr;
  9571. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9572. std::this_thread::sleep_for(std::chrono::seconds(2));
  9573. res.set_content("a", "text/plain");
  9574. });
  9575. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9576. res.set_content("b", "text/plain");
  9577. });
  9578. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9579. auto se = detail::scope_exit([&] {
  9580. svr.stop();
  9581. listen_thread.join();
  9582. ASSERT_FALSE(svr.is_running());
  9583. });
  9584. svr.wait_until_ready();
  9585. Client cli("localhost", PORT);
  9586. cli.set_keep_alive(true);
  9587. cli.set_read_timeout(std::chrono::seconds(1));
  9588. auto resa = cli.Get("/a");
  9589. ASSERT_FALSE(resa);
  9590. EXPECT_EQ(Error::Read, resa.error());
  9591. auto resb = cli.Get("/b");
  9592. ASSERT_TRUE(resb);
  9593. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9594. EXPECT_EQ("b", resb->body);
  9595. }
  9596. TEST(KeepAliveTest, MaxCount) {
  9597. size_t keep_alive_max_count = 3;
  9598. Server svr;
  9599. svr.set_keep_alive_max_count(keep_alive_max_count);
  9600. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9601. res.set_content("Hello World!", "text/plain");
  9602. });
  9603. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9604. auto se = detail::scope_exit([&] {
  9605. svr.stop();
  9606. listen_thread.join();
  9607. ASSERT_FALSE(svr.is_running());
  9608. });
  9609. svr.wait_until_ready();
  9610. Client cli(HOST, PORT);
  9611. cli.set_keep_alive(true);
  9612. for (size_t i = 0; i < 5; i++) {
  9613. auto result = cli.Get("/hi");
  9614. ASSERT_TRUE(result);
  9615. EXPECT_EQ(StatusCode::OK_200, result->status);
  9616. if (i == keep_alive_max_count - 1) {
  9617. EXPECT_EQ("close", result->get_header_value("Connection"));
  9618. } else {
  9619. EXPECT_FALSE(result->has_header("Connection"));
  9620. }
  9621. }
  9622. }
  9623. TEST(KeepAliveTest, Issue1041) {
  9624. Server svr;
  9625. svr.set_keep_alive_timeout(3);
  9626. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9627. res.set_content("Hello World!", "text/plain");
  9628. });
  9629. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9630. auto se = detail::scope_exit([&] {
  9631. svr.stop();
  9632. listen_thread.join();
  9633. ASSERT_FALSE(svr.is_running());
  9634. });
  9635. svr.wait_until_ready();
  9636. Client cli(HOST, PORT);
  9637. cli.set_keep_alive(true);
  9638. auto result = cli.Get("/hi");
  9639. ASSERT_TRUE(result);
  9640. EXPECT_EQ(StatusCode::OK_200, result->status);
  9641. std::this_thread::sleep_for(std::chrono::seconds(5));
  9642. result = cli.Get("/hi");
  9643. ASSERT_TRUE(result);
  9644. EXPECT_EQ(StatusCode::OK_200, result->status);
  9645. }
  9646. TEST(KeepAliveTest, Issue1959) {
  9647. Server svr;
  9648. svr.set_keep_alive_timeout(5);
  9649. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9650. res.set_content("a", "text/plain");
  9651. });
  9652. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9653. auto se = detail::scope_exit([&] {
  9654. if (!svr.is_running()) return;
  9655. svr.stop();
  9656. listen_thread.join();
  9657. ASSERT_FALSE(svr.is_running());
  9658. });
  9659. svr.wait_until_ready();
  9660. Client cli("localhost", PORT);
  9661. cli.set_keep_alive(true);
  9662. using namespace std::chrono;
  9663. auto start = steady_clock::now();
  9664. cli.Get("/a");
  9665. svr.stop();
  9666. listen_thread.join();
  9667. auto end = steady_clock::now();
  9668. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9669. EXPECT_LT(elapsed, 5000);
  9670. }
  9671. #ifdef CPPHTTPLIB_SSL_ENABLED
  9672. TEST(KeepAliveTest, SSLClientReconnection) {
  9673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9674. ASSERT_TRUE(svr.is_valid());
  9675. svr.set_keep_alive_timeout(1);
  9676. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9677. res.set_content("Hello World!", "text/plain");
  9678. });
  9679. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9680. auto se = detail::scope_exit([&] {
  9681. svr.stop();
  9682. listen_thread.join();
  9683. ASSERT_FALSE(svr.is_running());
  9684. });
  9685. svr.wait_until_ready();
  9686. SSLClient cli(HOST, PORT);
  9687. cli.enable_server_certificate_verification(false);
  9688. cli.set_keep_alive(true);
  9689. auto result = cli.Get("/hi");
  9690. ASSERT_TRUE(result);
  9691. EXPECT_EQ(StatusCode::OK_200, result->status);
  9692. result = cli.Get("/hi");
  9693. ASSERT_TRUE(result);
  9694. EXPECT_EQ(StatusCode::OK_200, result->status);
  9695. std::this_thread::sleep_for(std::chrono::seconds(2));
  9696. // Recoonect
  9697. result = cli.Get("/hi");
  9698. ASSERT_TRUE(result);
  9699. EXPECT_EQ(StatusCode::OK_200, result->status);
  9700. result = cli.Get("/hi");
  9701. ASSERT_TRUE(result);
  9702. EXPECT_EQ(StatusCode::OK_200, result->status);
  9703. }
  9704. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9706. ASSERT_TRUE(svr.is_valid());
  9707. svr.set_keep_alive_timeout(1);
  9708. std::string content = "reconnect";
  9709. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9710. res.set_content("Hello World!", "text/plain");
  9711. });
  9712. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9713. auto se = detail::scope_exit([&] {
  9714. svr.stop();
  9715. listen_thread.join();
  9716. ASSERT_FALSE(svr.is_running());
  9717. });
  9718. svr.wait_until_ready();
  9719. SSLClient cli(HOST, PORT);
  9720. cli.enable_server_certificate_verification(false);
  9721. cli.set_keep_alive(true);
  9722. auto result = cli.Post(
  9723. "/hi", content.size(),
  9724. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9725. sink.write(content.c_str(), content.size());
  9726. return true;
  9727. },
  9728. "text/plain");
  9729. ASSERT_TRUE(result);
  9730. EXPECT_EQ(200, result->status);
  9731. std::this_thread::sleep_for(std::chrono::seconds(2));
  9732. // Recoonect
  9733. result = cli.Post(
  9734. "/hi", content.size(),
  9735. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9736. sink.write(content.c_str(), content.size());
  9737. return true;
  9738. },
  9739. "text/plain");
  9740. ASSERT_TRUE(result);
  9741. EXPECT_EQ(200, result->status);
  9742. result = cli.Post(
  9743. "/hi", content.size(),
  9744. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9745. sink.write(content.c_str(), content.size());
  9746. return true;
  9747. },
  9748. "text/plain");
  9749. ASSERT_TRUE(result);
  9750. EXPECT_EQ(200, result->status);
  9751. }
  9752. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9753. using namespace httplib::tls;
  9754. {
  9755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9756. ASSERT_TRUE(svr.is_valid());
  9757. svr.Get("/sni", [&](const Request &req, Response &res) {
  9758. std::string expected = req.sni();
  9759. EXPECT_EQ(expected, req.get_param_value("expected"));
  9760. res.set_content("ok", "text/plain");
  9761. });
  9762. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9763. auto se = detail::scope_exit([&] {
  9764. svr.stop();
  9765. listen_thread.join();
  9766. ASSERT_FALSE(svr.is_running());
  9767. });
  9768. svr.wait_until_ready();
  9769. {
  9770. SSLClient cli("localhost", PORT);
  9771. cli.enable_server_certificate_verification(false);
  9772. auto res = cli.Get("/sni?expected=localhost");
  9773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9774. }
  9775. {
  9776. SSLClient cli("::1", PORT);
  9777. cli.enable_server_certificate_verification(false);
  9778. auto res = cli.Get("/sni?expected=");
  9779. // NOTE: This may fail if the server is listening on IPv4 only
  9780. // (e.g., when localhost resolves to 127.0.0.1 only)
  9781. if (res) {
  9782. EXPECT_EQ(StatusCode::OK_200, res->status);
  9783. } else {
  9784. EXPECT_EQ(Error::Connection, res.error());
  9785. }
  9786. }
  9787. }
  9788. }
  9789. #endif
  9790. TEST(ClientProblemDetectionTest, ContentProvider) {
  9791. Server svr;
  9792. size_t content_length = 1024 * 1024;
  9793. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9794. res.set_content_provider(
  9795. content_length, "text/plain",
  9796. [&](size_t offset, size_t length, DataSink &sink) {
  9797. auto out_len = std::min(length, static_cast<size_t>(1024));
  9798. std::string out(out_len, '@');
  9799. sink.write(out.data(), out_len);
  9800. return offset < 4096;
  9801. },
  9802. [](bool success) { ASSERT_FALSE(success); });
  9803. });
  9804. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9805. res.set_content_provider(
  9806. 0, "text/plain",
  9807. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9808. EXPECT_TRUE(false);
  9809. return true;
  9810. },
  9811. [](bool success) { ASSERT_FALSE(success); });
  9812. });
  9813. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9814. auto se = detail::scope_exit([&] {
  9815. svr.stop();
  9816. listen_thread.join();
  9817. ASSERT_FALSE(svr.is_running());
  9818. });
  9819. svr.wait_until_ready();
  9820. Client cli("localhost", PORT);
  9821. {
  9822. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9823. size_t /*data_length*/) { return false; });
  9824. ASSERT_FALSE(res);
  9825. }
  9826. {
  9827. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9828. size_t /*data_length*/) { return false; });
  9829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9830. }
  9831. }
  9832. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9833. // A provider that reports success without writing anything and without
  9834. // calling done() used to be handed the same offset and length again on every
  9835. // pass, so it spun for as long as the peer stayed connected.
  9836. Server svr;
  9837. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9838. res.set_content("ok", "text/plain");
  9839. });
  9840. auto port = svr.bind_to_any_port(HOST);
  9841. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9842. auto se = detail::scope_exit([&] {
  9843. svr.stop();
  9844. listen_thread.join();
  9845. ASSERT_FALSE(svr.is_running());
  9846. });
  9847. svr.wait_until_ready();
  9848. std::atomic<int> call_count{0};
  9849. Client cli(HOST, port);
  9850. auto res = cli.Post(
  9851. "/", 1024,
  9852. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9853. // Give up after enough passes to show the spin, so that losing the
  9854. // check below fails this test instead of hanging it.
  9855. return ++call_count < 100;
  9856. },
  9857. "text/plain");
  9858. ASSERT_FALSE(res);
  9859. EXPECT_EQ(Error::Write, res.error());
  9860. EXPECT_EQ(1, call_count.load());
  9861. }
  9862. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9863. // A writer only has to assign `write`. The other three used to be left as
  9864. // empty std::functions, so a provider calling one threw
  9865. // std::bad_function_call out of the thread running it and took the whole
  9866. // process down.
  9867. DataSink sink;
  9868. std::string written;
  9869. sink.write = [&](const char *data, size_t data_len) {
  9870. written.append(data, data_len);
  9871. return true;
  9872. };
  9873. EXPECT_TRUE(sink.is_writable());
  9874. sink.done();
  9875. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9876. EXPECT_TRUE(written.empty());
  9877. }
  9878. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9879. // A sink that cannot carry trailers still has to finish.
  9880. DataSink sink;
  9881. auto done_count = 0;
  9882. sink.done = [&]() { done_count++; };
  9883. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9884. EXPECT_EQ(1, done_count);
  9885. }
  9886. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9887. Server svr;
  9888. const std::string body(4096, 'x');
  9889. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9890. res.set_content_provider(body.size(), "text/plain",
  9891. [&](size_t offset, size_t length, DataSink &sink) {
  9892. sink.write(body.data() + offset, length);
  9893. sink.done();
  9894. return true;
  9895. });
  9896. });
  9897. auto port = svr.bind_to_any_port(HOST);
  9898. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9899. auto se = detail::scope_exit([&] {
  9900. svr.stop();
  9901. listen_thread.join();
  9902. ASSERT_FALSE(svr.is_running());
  9903. });
  9904. svr.wait_until_ready();
  9905. Client cli(HOST, port);
  9906. auto res = cli.Get("/");
  9907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9908. EXPECT_EQ(StatusCode::OK_200, res->status);
  9909. EXPECT_EQ(body, res->body);
  9910. }
  9911. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9912. Server svr;
  9913. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9914. res.set_content_provider(
  9915. 1024, "text/plain",
  9916. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9917. sink.write("hello", 5);
  9918. sink.done(); // short of the 1024 bytes the response promised
  9919. return true;
  9920. });
  9921. });
  9922. auto port = svr.bind_to_any_port(HOST);
  9923. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9924. auto se = detail::scope_exit([&] {
  9925. svr.stop();
  9926. listen_thread.join();
  9927. ASSERT_FALSE(svr.is_running());
  9928. });
  9929. svr.wait_until_ready();
  9930. Client cli(HOST, port);
  9931. cli.set_read_timeout(5, 0);
  9932. // The response is short of its Content-Length, so the client cannot read a
  9933. // complete body. What matters is that this returns at all: a no-op done()
  9934. // would leave the writer looping over a provider that never makes progress.
  9935. auto res = cli.Get("/");
  9936. EXPECT_FALSE(res);
  9937. }
  9938. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9939. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9940. // The compressed path builds the whole body before connecting, so this
  9941. // fails client-side and never reaches a server.
  9942. Client cli(HOST, PORT);
  9943. cli.set_compress(true);
  9944. auto res = cli.Post(
  9945. "/", 1024,
  9946. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9947. sink.write("hello", 5);
  9948. sink.done(); // short of the 1024 bytes the request announced
  9949. return true;
  9950. },
  9951. "text/plain");
  9952. ASSERT_FALSE(res);
  9953. EXPECT_EQ(Error::Write, res.error());
  9954. }
  9955. #endif
  9956. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9957. Server svr;
  9958. svr.set_error_handler([](Request const &, Response &res) -> void {
  9959. res.set_chunked_content_provider(
  9960. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9961. sink.os << "hello";
  9962. sink.os << "world";
  9963. sink.done();
  9964. return true;
  9965. });
  9966. });
  9967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. listen_thread.join();
  9971. ASSERT_FALSE(svr.is_running());
  9972. });
  9973. svr.wait_until_ready();
  9974. Client cli("localhost", PORT);
  9975. auto res = cli.Get("/");
  9976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9978. EXPECT_EQ("helloworld", res->body);
  9979. }
  9980. TEST(LongPollingTest, ClientCloseDetection) {
  9981. Server svr;
  9982. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9983. res.set_chunked_content_provider(
  9984. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9985. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9986. sink.os << "hello";
  9987. auto count = 10;
  9988. while (count > 0 && sink.is_writable()) {
  9989. this_thread::sleep_for(chrono::milliseconds(10));
  9990. count--;
  9991. }
  9992. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9993. return true;
  9994. });
  9995. });
  9996. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9997. auto se = detail::scope_exit([&] {
  9998. svr.stop();
  9999. listen_thread.join();
  10000. ASSERT_FALSE(svr.is_running());
  10001. });
  10002. svr.wait_until_ready();
  10003. Client cli("localhost", PORT);
  10004. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10005. EXPECT_EQ("hello", string(data, data_length));
  10006. return false; // close the socket immediately.
  10007. });
  10008. ASSERT_FALSE(res);
  10009. }
  10010. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10011. Server svr;
  10012. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10013. res.set_chunked_content_provider(
  10014. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10015. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10016. sink.os << "hello";
  10017. EXPECT_TRUE(sink.os.good());
  10018. // Wait for the client to close the connection
  10019. auto count = 10;
  10020. while (count > 0 && sink.is_writable()) {
  10021. this_thread::sleep_for(chrono::milliseconds(10));
  10022. count--;
  10023. }
  10024. // After client disconnect, write repeatedly until the socket
  10025. // write actually fails (small writes may be absorbed by the
  10026. // kernel buffer)
  10027. std::string chunk(1024, 'x');
  10028. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10029. sink.os << chunk;
  10030. }
  10031. EXPECT_TRUE(sink.os.fail());
  10032. return true;
  10033. });
  10034. });
  10035. auto port = svr.bind_to_any_port("localhost");
  10036. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. listen_thread.join();
  10040. ASSERT_FALSE(svr.is_running());
  10041. });
  10042. svr.wait_until_ready();
  10043. Client cli("localhost", port);
  10044. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10045. EXPECT_EQ("hello", string(data, data_length));
  10046. return false; // close the socket immediately.
  10047. });
  10048. ASSERT_FALSE(res);
  10049. }
  10050. TEST(GetWithParametersTest, GetWithParameters) {
  10051. Server svr;
  10052. svr.Get("/", [&](const Request &req, Response &) {
  10053. EXPECT_EQ("world", req.get_param_value("hello"));
  10054. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10055. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10056. });
  10057. svr.Get("/params", [&](const Request &req, Response &) {
  10058. EXPECT_EQ("world", req.get_param_value("hello"));
  10059. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10060. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10061. });
  10062. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10063. EXPECT_EQ("resource-id", req.matches[1]);
  10064. EXPECT_EQ("foo", req.get_param_value("param1"));
  10065. EXPECT_EQ("bar", req.get_param_value("param2"));
  10066. });
  10067. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10068. EXPECT_EQ("user-id", req.path_params.at("id"));
  10069. EXPECT_EQ("foo", req.get_param_value("param1"));
  10070. EXPECT_EQ("bar", req.get_param_value("param2"));
  10071. });
  10072. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10073. auto se = detail::scope_exit([&] {
  10074. svr.stop();
  10075. listen_thread.join();
  10076. ASSERT_FALSE(svr.is_running());
  10077. });
  10078. svr.wait_until_ready();
  10079. {
  10080. Client cli(HOST, PORT);
  10081. Params params;
  10082. params.emplace("hello", "world");
  10083. params.emplace("hello2", "world2");
  10084. params.emplace("hello3", "world3");
  10085. auto res = cli.Get("/", params, Headers{});
  10086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10087. EXPECT_EQ(StatusCode::OK_200, res->status);
  10088. }
  10089. {
  10090. Client cli(HOST, PORT);
  10091. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10093. EXPECT_EQ(StatusCode::OK_200, res->status);
  10094. }
  10095. {
  10096. Client cli(HOST, PORT);
  10097. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10099. EXPECT_EQ(StatusCode::OK_200, res->status);
  10100. }
  10101. {
  10102. Client cli(HOST, PORT);
  10103. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10105. EXPECT_EQ(StatusCode::OK_200, res->status);
  10106. }
  10107. }
  10108. TEST(GetWithParametersTest, GetWithParameters2) {
  10109. Server svr;
  10110. svr.Get("/", [&](const Request &req, Response &res) {
  10111. auto text = req.get_param_value("hello");
  10112. res.set_content(text, "text/plain");
  10113. });
  10114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10115. auto se = detail::scope_exit([&] {
  10116. svr.stop();
  10117. listen_thread.join();
  10118. ASSERT_FALSE(svr.is_running());
  10119. });
  10120. svr.wait_until_ready();
  10121. Client cli("localhost", PORT);
  10122. Params params;
  10123. params.emplace("hello", "world");
  10124. std::string body;
  10125. auto res = cli.Get("/", params, Headers{},
  10126. [&](const char *data, size_t data_length) {
  10127. body.append(data, data_length);
  10128. return true;
  10129. });
  10130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10131. EXPECT_EQ(StatusCode::OK_200, res->status);
  10132. EXPECT_EQ("world", body);
  10133. }
  10134. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10135. Server svr;
  10136. svr.Get("/search", [&](const Request &req, Response &res) {
  10137. auto q = req.get_param_value("q");
  10138. res.set_content(q, "text/plain");
  10139. });
  10140. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10141. auto se = detail::scope_exit([&] {
  10142. svr.stop();
  10143. listen_thread.join();
  10144. ASSERT_FALSE(svr.is_running());
  10145. });
  10146. svr.wait_until_ready();
  10147. Client cli("localhost", PORT);
  10148. // Verify that Get(path, params) works without requiring Headers argument
  10149. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10151. EXPECT_EQ(StatusCode::OK_200, res->status);
  10152. EXPECT_EQ("cpp-httplib", res->body);
  10153. }
  10154. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10155. auto host = "httpbingo.org";
  10156. auto path = std::string{"/range/32"};
  10157. #ifdef CPPHTTPLIB_SSL_ENABLED
  10158. SSLClient cli(host);
  10159. #else
  10160. Client cli(host);
  10161. #endif
  10162. cli.set_default_headers({make_range_header({{1, 10}})});
  10163. cli.set_connection_timeout(5);
  10164. {
  10165. auto res = cli.Get(path);
  10166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10167. EXPECT_EQ("bcdefghijk", res->body);
  10168. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10169. }
  10170. {
  10171. auto res = cli.Get(path);
  10172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10173. EXPECT_EQ("bcdefghijk", res->body);
  10174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10175. }
  10176. }
  10177. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10178. Server svr;
  10179. svr.set_default_headers({{"Hello", "World"}});
  10180. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10181. res.set_content("ok", "text/plain");
  10182. });
  10183. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10184. auto se = detail::scope_exit([&] {
  10185. svr.stop();
  10186. listen_thread.join();
  10187. ASSERT_FALSE(svr.is_running());
  10188. });
  10189. svr.wait_until_ready();
  10190. Client cli("localhost", PORT);
  10191. auto res = cli.Get("/");
  10192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10193. EXPECT_EQ(StatusCode::OK_200, res->status);
  10194. EXPECT_EQ("ok", res->body);
  10195. EXPECT_EQ("World", res->get_header_value("Hello"));
  10196. }
  10197. #ifdef CPPHTTPLIB_SSL_ENABLED
  10198. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10200. ASSERT_TRUE(svr.is_valid());
  10201. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10202. std::this_thread::sleep_for(std::chrono::seconds(2));
  10203. res.set_content("a", "text/plain");
  10204. });
  10205. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10206. res.set_content("b", "text/plain");
  10207. });
  10208. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10209. auto se = detail::scope_exit([&] {
  10210. svr.stop();
  10211. listen_thread.join();
  10212. ASSERT_FALSE(svr.is_running());
  10213. });
  10214. svr.wait_until_ready();
  10215. SSLClient cli("localhost", PORT);
  10216. cli.enable_server_certificate_verification(false);
  10217. cli.set_keep_alive(true);
  10218. cli.set_read_timeout(std::chrono::seconds(1));
  10219. auto resa = cli.Get("/a");
  10220. ASSERT_TRUE(!resa);
  10221. EXPECT_EQ(Error::Read, resa.error());
  10222. auto resb = cli.Get("/b");
  10223. ASSERT_TRUE(resb);
  10224. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10225. EXPECT_EQ("b", resb->body);
  10226. }
  10227. // Closing an idle keep-alive connection sends close_notify and returns. The
  10228. // server must not wait for the client's close_notify: an idle client never
  10229. // sends one, so the worker would be held until the read timeout expires, and
  10230. // stop() would wait for it.
  10231. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10233. ASSERT_TRUE(svr.is_valid());
  10234. svr.set_keep_alive_timeout(1);
  10235. svr.set_read_timeout(10, 0);
  10236. svr.Get("/", [](const Request &, Response &res) {
  10237. res.set_content("ok", "text/plain");
  10238. });
  10239. auto port = svr.bind_to_any_port(HOST);
  10240. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10241. auto se = detail::scope_exit([&] {
  10242. if (listen_thread.joinable()) {
  10243. svr.stop();
  10244. listen_thread.join();
  10245. }
  10246. });
  10247. svr.wait_until_ready();
  10248. SSLClient cli(HOST, port);
  10249. cli.enable_server_certificate_verification(false);
  10250. cli.set_keep_alive(true);
  10251. auto res = cli.Get("/");
  10252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10253. EXPECT_EQ(StatusCode::OK_200, res->status);
  10254. // Stay idle past the keep-alive timeout so the server closes the connection.
  10255. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10256. auto start = std::chrono::steady_clock::now();
  10257. svr.stop();
  10258. listen_thread.join();
  10259. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10260. std::chrono::steady_clock::now() - start)
  10261. .count();
  10262. EXPECT_LT(elapsed, 3000);
  10263. }
  10264. #endif
  10265. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10266. protected:
  10267. ServerTestWithAI_PASSIVE()
  10268. : cli_(HOST, PORT)
  10269. #ifdef CPPHTTPLIB_SSL_ENABLED
  10270. ,
  10271. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10272. #endif
  10273. {
  10274. #ifdef CPPHTTPLIB_SSL_ENABLED
  10275. cli_.enable_server_certificate_verification(false);
  10276. #endif
  10277. }
  10278. virtual void SetUp() {
  10279. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10280. res.set_content("Hello World!", "text/plain");
  10281. });
  10282. t_ = thread(
  10283. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10284. svr_.wait_until_ready();
  10285. }
  10286. virtual void TearDown() {
  10287. svr_.stop();
  10288. t_.join();
  10289. }
  10290. #ifdef CPPHTTPLIB_SSL_ENABLED
  10291. SSLClient cli_;
  10292. SSLServer svr_;
  10293. #else
  10294. Client cli_;
  10295. Server svr_;
  10296. #endif
  10297. thread t_;
  10298. };
  10299. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10300. auto res = cli_.Get("/hi");
  10301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10302. EXPECT_EQ(StatusCode::OK_200, res->status);
  10303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10304. EXPECT_EQ("Hello World!", res->body);
  10305. }
  10306. class ServerUpDownTest : public ::testing::Test {
  10307. protected:
  10308. ServerUpDownTest() : cli_(HOST, PORT) {}
  10309. virtual void SetUp() {
  10310. t_ = thread([&]() {
  10311. svr_.bind_to_any_port(HOST);
  10312. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10313. ASSERT_TRUE(svr_.listen_after_bind());
  10314. });
  10315. svr_.wait_until_ready();
  10316. }
  10317. virtual void TearDown() {
  10318. svr_.stop();
  10319. t_.join();
  10320. }
  10321. Client cli_;
  10322. Server svr_;
  10323. thread t_;
  10324. };
  10325. TEST_F(ServerUpDownTest, QuickStartStop) {
  10326. // Should not crash, especially when run with
  10327. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10328. }
  10329. class PayloadMaxLengthTest : public ::testing::Test {
  10330. protected:
  10331. PayloadMaxLengthTest()
  10332. : cli_(HOST, PORT)
  10333. #ifdef CPPHTTPLIB_SSL_ENABLED
  10334. ,
  10335. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10336. #endif
  10337. {
  10338. #ifdef CPPHTTPLIB_SSL_ENABLED
  10339. cli_.enable_server_certificate_verification(false);
  10340. #endif
  10341. }
  10342. virtual void SetUp() {
  10343. svr_.set_payload_max_length(8);
  10344. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10345. res.set_content("test", "text/plain");
  10346. });
  10347. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10348. svr_.wait_until_ready();
  10349. }
  10350. virtual void TearDown() {
  10351. svr_.stop();
  10352. t_.join();
  10353. }
  10354. #ifdef CPPHTTPLIB_SSL_ENABLED
  10355. SSLClient cli_;
  10356. SSLServer svr_;
  10357. #else
  10358. Client cli_;
  10359. Server svr_;
  10360. #endif
  10361. thread t_;
  10362. };
  10363. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10364. auto res = cli_.Post("/test", "123456789", "text/plain");
  10365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10366. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10367. res = cli_.Post("/test", "12345678", "text/plain");
  10368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10369. EXPECT_EQ(StatusCode::OK_200, res->status);
  10370. }
  10371. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10372. // Test chunked encoding with payload exceeding the 8-byte limit
  10373. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10374. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10376. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10377. }
  10378. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10379. // Test chunked encoding with payload within the 8-byte limit
  10380. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10381. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10383. EXPECT_EQ(StatusCode::OK_200, res->status);
  10384. }
  10385. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10386. // Test using send_request to send chunked data exceeding payload limit
  10387. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10388. "Host: " +
  10389. std::string(HOST) + ":" + std::to_string(PORT) +
  10390. "\r\n"
  10391. "Transfer-Encoding: chunked\r\n"
  10392. "Connection: close\r\n"
  10393. "\r\n"
  10394. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10395. "0123456789\r\n"
  10396. "0\r\n" // End chunk
  10397. "\r\n";
  10398. std::string response;
  10399. bool result = send_request(1, chunked_request, &response);
  10400. if (!result) {
  10401. // If send_request fails, it might be because the server closed the
  10402. // connection due to payload limit enforcement, which is acceptable
  10403. SUCCEED()
  10404. << "Server rejected oversized chunked request (connection closed)";
  10405. } else {
  10406. // If we got a response, check if it's an error response or connection was
  10407. // closed early Short response length indicates connection was closed due to
  10408. // payload limit
  10409. if (response.length() <= 10) {
  10410. SUCCEED() << "Server closed connection for oversized chunked request";
  10411. } else {
  10412. // Check for error status codes
  10413. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10414. response.find("Payload Too Large") != std::string::npos ||
  10415. response.find("400") != std::string::npos);
  10416. }
  10417. }
  10418. }
  10419. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10420. // Test request without Content-Length header exceeding payload limit
  10421. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10422. "Host: " +
  10423. std::string(HOST) + ":" +
  10424. std::to_string(PORT) +
  10425. "\r\n"
  10426. "Connection: close\r\n"
  10427. "\r\n";
  10428. // Add payload exceeding the 8-byte limit
  10429. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10430. request_without_content_length += large_payload;
  10431. std::string response;
  10432. bool result = send_request(1, request_without_content_length, &response);
  10433. if (!result) {
  10434. // If send_request fails, server likely closed connection due to payload
  10435. // limit
  10436. SUCCEED() << "Server rejected oversized request without Content-Length "
  10437. "(connection closed)";
  10438. } else {
  10439. // Check if server responded with error or closed connection early
  10440. if (response.length() <= 10) {
  10441. SUCCEED() << "Server closed connection for oversized request without "
  10442. "Content-Length";
  10443. } else {
  10444. // Check for error status codes
  10445. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10446. response.find("Payload Too Large") != std::string::npos ||
  10447. response.find("400") != std::string::npos);
  10448. }
  10449. }
  10450. }
  10451. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10452. // Test request without Content-Length header within payload limit
  10453. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10454. "Host: " +
  10455. std::string(HOST) + ":" +
  10456. std::to_string(PORT) +
  10457. "\r\n"
  10458. "Connection: close\r\n"
  10459. "\r\n";
  10460. // Add payload within the 8-byte limit
  10461. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10462. request_without_content_length += small_payload;
  10463. std::string response;
  10464. bool result = send_request(1, request_without_content_length, &response);
  10465. // For requests without Content-Length, the server may have different behavior
  10466. // The key is that it should not reject due to payload limit for small
  10467. // payloads
  10468. if (result) {
  10469. // Check for any HTTP response (success or error, but not connection closed)
  10470. if (response.length() > 10) {
  10471. SUCCEED()
  10472. << "Server processed request without Content-Length within limit";
  10473. } else {
  10474. // Short response might indicate connection closed, which is acceptable
  10475. SUCCEED() << "Server closed connection for request without "
  10476. "Content-Length (acceptable behavior)";
  10477. }
  10478. } else {
  10479. // Connection failure might be due to protocol requirements
  10480. SUCCEED() << "Connection issue with request without Content-Length "
  10481. "(environment-specific)";
  10482. }
  10483. }
  10484. class LargePayloadMaxLengthTest : public ::testing::Test {
  10485. protected:
  10486. LargePayloadMaxLengthTest()
  10487. : cli_(HOST, PORT)
  10488. #ifdef CPPHTTPLIB_SSL_ENABLED
  10489. ,
  10490. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10491. #endif
  10492. {
  10493. #ifdef CPPHTTPLIB_SSL_ENABLED
  10494. cli_.enable_server_certificate_verification(false);
  10495. #endif
  10496. }
  10497. virtual void SetUp() {
  10498. // Set 10MB payload limit
  10499. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10500. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10501. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10502. res.set_content("Large payload test", "text/plain");
  10503. });
  10504. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10505. svr_.wait_until_ready();
  10506. }
  10507. virtual void TearDown() {
  10508. svr_.stop();
  10509. t_.join();
  10510. }
  10511. #ifdef CPPHTTPLIB_SSL_ENABLED
  10512. SSLClient cli_;
  10513. SSLServer svr_;
  10514. #else
  10515. Client cli_;
  10516. Server svr_;
  10517. #endif
  10518. thread t_;
  10519. };
  10520. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10521. // Test chunked encoding with payload within 10MB limit
  10522. std::string medium_payload(5 * 1024 * 1024,
  10523. 'A'); // 5MB payload, within 10MB limit
  10524. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10526. EXPECT_EQ(StatusCode::OK_200, res->status);
  10527. }
  10528. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10529. // Test chunked encoding with payload exceeding 10MB limit
  10530. std::string large_payload(12 * 1024 * 1024,
  10531. 'B'); // 12MB payload, exceeds 10MB limit
  10532. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10533. // Server may either return 413 or close the connection
  10534. if (res) {
  10535. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10536. } else {
  10537. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10538. }
  10539. }
  10540. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10541. // Test request without Content-Length header within 10MB limit
  10542. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10543. "Host: " +
  10544. std::string(HOST) + ":" +
  10545. std::to_string(PORT) +
  10546. "\r\n"
  10547. "Connection: close\r\n"
  10548. "\r\n";
  10549. // Add 1MB payload (within 10MB limit)
  10550. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10551. request_without_content_length += medium_payload;
  10552. std::string response;
  10553. bool result = send_request(5, request_without_content_length, &response);
  10554. if (result) {
  10555. // Should get a proper HTTP response for payloads within limit
  10556. if (response.length() > 10) {
  10557. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10558. "10MB limit";
  10559. } else {
  10560. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10561. "Content-Length)";
  10562. }
  10563. } else {
  10564. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10565. }
  10566. }
  10567. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10568. // Test request without Content-Length header exceeding 10MB limit
  10569. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10570. "Host: " +
  10571. std::string(HOST) + ":" +
  10572. std::to_string(PORT) +
  10573. "\r\n"
  10574. "Connection: close\r\n"
  10575. "\r\n";
  10576. // Add 12MB payload (exceeds 10MB limit)
  10577. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10578. request_without_content_length += large_payload;
  10579. std::string response;
  10580. bool result = send_request(10, request_without_content_length, &response);
  10581. if (!result) {
  10582. // Server should close connection due to payload limit
  10583. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10584. "(connection closed)";
  10585. } else {
  10586. // Check for error response
  10587. if (response.length() <= 10) {
  10588. SUCCEED()
  10589. << "Server closed connection for 12MB request exceeding 10MB limit";
  10590. } else {
  10591. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10592. response.find("Payload Too Large") != std::string::npos ||
  10593. response.find("400") != std::string::npos);
  10594. }
  10595. }
  10596. }
  10597. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10598. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10599. // path.
  10600. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10601. Server svr;
  10602. const size_t LIMIT = 64 * 1024; // 64KB
  10603. svr.set_payload_max_length(LIMIT);
  10604. size_t total = 0;
  10605. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10606. const ContentReader &content_reader) {
  10607. content_reader([&](const char * /*data*/, size_t len) {
  10608. total += len;
  10609. return true;
  10610. });
  10611. res.status = 200;
  10612. res.set_content("stream_ok", "text/plain");
  10613. });
  10614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10615. auto se = detail::scope_exit([&] {
  10616. svr.stop();
  10617. thread.join();
  10618. ASSERT_FALSE(svr.is_running());
  10619. });
  10620. svr.wait_until_ready();
  10621. // Prepare 256KB raw data and gzip-compress it
  10622. std::string raw(256 * 1024, 'A');
  10623. std::string gz;
  10624. {
  10625. z_stream zs{};
  10626. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10627. Z_DEFAULT_STRATEGY);
  10628. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10629. zs.avail_in = static_cast<uInt>(raw.size());
  10630. char outbuf[4096];
  10631. int ret;
  10632. do {
  10633. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10634. zs.avail_out = sizeof(outbuf);
  10635. ret = deflate(&zs, Z_FINISH);
  10636. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10637. } while (ret != Z_STREAM_END);
  10638. deflateEnd(&zs);
  10639. }
  10640. Client cli(HOST, PORT);
  10641. cli.set_connection_timeout(std::chrono::seconds(5));
  10642. Headers headers = {{"Content-Encoding", "gzip"}};
  10643. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10644. "application/octet-stream");
  10645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10646. // Server must reject oversized decompressed payloads with 413.
  10647. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10648. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10649. EXPECT_LE(total, LIMIT);
  10650. }
  10651. #ifndef CPPHTTPLIB_SSL_ENABLED
  10652. // For a request with neither Content-Length nor Transfer-Encoding, the
  10653. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10654. // compressed wire bytes straight to the ContentReader without ever routing
  10655. // them through the decompressor, so payload_max_length_ only bounded the
  10656. // compressed size on the wire, not the decompressed size.
  10657. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10658. Server svr;
  10659. const size_t LIMIT = 64 * 1024; // 64KB
  10660. svr.set_payload_max_length(LIMIT);
  10661. size_t total = 0;
  10662. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10663. const ContentReader &content_reader) {
  10664. content_reader([&](const char * /*data*/, size_t len) {
  10665. total += len;
  10666. return true;
  10667. });
  10668. res.status = 200;
  10669. res.set_content("stream_ok", "text/plain");
  10670. });
  10671. auto port = svr.bind_to_any_port(HOST);
  10672. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10673. auto se = detail::scope_exit([&] {
  10674. svr.stop();
  10675. thread.join();
  10676. ASSERT_FALSE(svr.is_running());
  10677. });
  10678. svr.wait_until_ready();
  10679. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10680. // StreamingGzipDecompression test above.
  10681. std::string raw(256 * 1024, 'A');
  10682. std::string gz;
  10683. {
  10684. httplib::detail::gzip_compressor compressor;
  10685. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10686. [&](const char *chunk, size_t len) {
  10687. gz.append(chunk, len);
  10688. return true;
  10689. });
  10690. ASSERT_TRUE(result);
  10691. }
  10692. // Send the gzip body over raw TCP with neither Content-Length nor
  10693. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10694. // kicks in.
  10695. std::string req = "POST /stream HTTP/1.1\r\n"
  10696. "Host: " +
  10697. std::string(HOST) + ":" + std::to_string(port) +
  10698. "\r\n"
  10699. "Content-Encoding: gzip\r\n"
  10700. "Connection: close\r\n"
  10701. "\r\n" +
  10702. gz;
  10703. std::string response;
  10704. ASSERT_TRUE(send_request(5, req, &response, port));
  10705. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10706. EXPECT_LE(total, LIMIT);
  10707. }
  10708. #endif
  10709. #endif
  10710. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10711. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10712. // the payload must be passed through untouched instead of being rejected.
  10713. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10714. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10715. Server svr;
  10716. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10717. res.set_content(body, "image/jpeg");
  10718. res.set_header("Content-Encoding", "UTF-8");
  10719. });
  10720. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10721. res.set_content(body, "image/jpeg");
  10722. res.set_header("Content-Encoding", "identity");
  10723. });
  10724. svr.Post("/echo", [](const Request &req, Response &res) {
  10725. res.set_content(req.body, "image/jpeg");
  10726. });
  10727. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10728. auto se = detail::scope_exit([&] {
  10729. svr.stop();
  10730. t.join();
  10731. ASSERT_FALSE(svr.is_running());
  10732. });
  10733. svr.wait_until_ready();
  10734. Client cli(HOST, PORT);
  10735. {
  10736. auto res = cli.Get("/image");
  10737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10738. EXPECT_EQ(StatusCode::OK_200, res->status);
  10739. EXPECT_EQ(body, res->body);
  10740. }
  10741. {
  10742. auto res = cli.Get("/identity");
  10743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10744. EXPECT_EQ(StatusCode::OK_200, res->status);
  10745. EXPECT_EQ(body, res->body);
  10746. }
  10747. {
  10748. // The same applies to a request body reaching the server.
  10749. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10750. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10752. EXPECT_EQ(StatusCode::OK_200, res->status);
  10753. EXPECT_EQ(body, res->body);
  10754. }
  10755. }
  10756. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10757. // gzip-encoded response even when the build has no zlib support.
  10758. static const char GZIPPED_HELLO_WORLD[] = {
  10759. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10760. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10761. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10762. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10763. // A content coding is a whole token, not something the field value merely
  10764. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10765. // as "fibre" look like Brotli, and turned a multi-coding value like
  10766. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10767. // it was never meant to see.
  10768. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10769. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10770. Server svr;
  10771. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10772. res.set_content(body, "image/jpeg");
  10773. res.set_header("Content-Encoding", "fibre");
  10774. });
  10775. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10776. res.set_content(body, "image/jpeg");
  10777. res.set_header("Content-Encoding", "gzip, br");
  10778. });
  10779. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10780. res.set_content(body, "image/jpeg");
  10781. res.set_header("Content-Encoding", "x-zstd-ish");
  10782. });
  10783. auto port = svr.bind_to_any_port(HOST);
  10784. thread t = thread([&]() { svr.listen_after_bind(); });
  10785. auto se = detail::scope_exit([&] {
  10786. svr.stop();
  10787. t.join();
  10788. ASSERT_FALSE(svr.is_running());
  10789. });
  10790. svr.wait_until_ready();
  10791. Client cli(HOST, port);
  10792. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10793. auto res = cli.Get(path);
  10794. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10795. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10796. // Not a coding we recognize, so the payload comes back untouched
  10797. EXPECT_EQ(body, res->body) << path;
  10798. }
  10799. }
  10800. // A content coding cpp-httplib recognizes but was not built with must be
  10801. // reported as such. Handing the still-compressed payload back to the caller
  10802. // would silently corrupt it.
  10803. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10804. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10805. Server svr;
  10806. // "image/jpeg" keeps the server from applying a content coding of its own,
  10807. // so the hand-crafted Content-Encoding below survives.
  10808. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10809. res.set_content(gzipped, "image/jpeg");
  10810. res.set_header("Content-Encoding", "gzip");
  10811. });
  10812. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10813. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10814. res.set_content(gzipped, "image/jpeg");
  10815. res.set_header("Content-Encoding", "GZIP");
  10816. });
  10817. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10818. auto se = detail::scope_exit([&] {
  10819. svr.stop();
  10820. t.join();
  10821. ASSERT_FALSE(svr.is_running());
  10822. });
  10823. svr.wait_until_ready();
  10824. Client cli(HOST, PORT);
  10825. {
  10826. auto res = cli.Get("/gzipped");
  10827. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10829. EXPECT_EQ("Hello World!", res->body);
  10830. #else
  10831. ASSERT_FALSE(res);
  10832. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10833. #endif
  10834. }
  10835. {
  10836. // open_stream() must behave the same way.
  10837. auto handle = cli.open_stream("GET", "/gzipped");
  10838. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10839. ASSERT_TRUE(handle.is_valid());
  10840. std::string received;
  10841. char buf[256];
  10842. ssize_t n;
  10843. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10844. received.append(buf, static_cast<size_t>(n));
  10845. }
  10846. EXPECT_EQ("Hello World!", received);
  10847. #else
  10848. EXPECT_FALSE(handle.is_valid());
  10849. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10850. #endif
  10851. }
  10852. {
  10853. // A differently-cased coding must not be mistaken for an unknown one, or
  10854. // the body would be handed back still compressed.
  10855. auto res = cli.Get("/gzipped-uppercase");
  10856. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10858. EXPECT_EQ("Hello World!", res->body);
  10859. #else
  10860. ASSERT_FALSE(res);
  10861. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10862. #endif
  10863. }
  10864. }
  10865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10866. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10867. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10868. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10869. // body a second time and appending a second Content-Encoding field line, so
  10870. // clients that decode one coding per listed value handed back raw gzip bytes.
  10871. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10872. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10873. Server svr;
  10874. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10875. // keeps the server from applying a coding of its own.
  10876. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10877. res.set_content(gzipped, "text/plain");
  10878. res.set_header("Content-Encoding", "gzip");
  10879. });
  10880. auto port = svr.bind_to_any_port(HOST);
  10881. thread t = thread([&]() { svr.listen_after_bind(); });
  10882. auto se = detail::scope_exit([&] {
  10883. svr.stop();
  10884. t.join();
  10885. ASSERT_FALSE(svr.is_running());
  10886. });
  10887. svr.wait_until_ready();
  10888. Client cli(HOST, port);
  10889. Headers headers = {{"Accept-Encoding", "gzip"}};
  10890. auto res = cli.Get("/pre-gzipped", headers);
  10891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10892. EXPECT_EQ(StatusCode::OK_200, res->status);
  10893. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10894. EXPECT_EQ("Hello World!", res->body);
  10895. }
  10896. // A chunked provider settles its coding where the headers are written and
  10897. // reuses it at write time. Both ends of that have to hold: a handler's own
  10898. // Content-Encoding suppresses the coding, and a response without one is still
  10899. // compressed as it always was.
  10900. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10901. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10902. const std::string plain = "Hello World! Hello World! Hello World!";
  10903. Server svr;
  10904. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10905. res.set_header("Content-Encoding", "gzip");
  10906. res.set_chunked_content_provider(
  10907. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10908. sink.write(gzipped.data(), gzipped.size());
  10909. sink.done();
  10910. return true;
  10911. });
  10912. });
  10913. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10914. res.set_chunked_content_provider(
  10915. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10916. sink.write(plain.data(), plain.size());
  10917. sink.done();
  10918. return true;
  10919. });
  10920. });
  10921. auto port = svr.bind_to_any_port(HOST);
  10922. thread t = thread([&]() { svr.listen_after_bind(); });
  10923. auto se = detail::scope_exit([&] {
  10924. svr.stop();
  10925. t.join();
  10926. ASSERT_FALSE(svr.is_running());
  10927. });
  10928. svr.wait_until_ready();
  10929. Client cli(HOST, port);
  10930. Headers headers = {{"Accept-Encoding", "gzip"}};
  10931. {
  10932. auto res = cli.Get("/pre-gzipped", headers);
  10933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10934. EXPECT_EQ(StatusCode::OK_200, res->status);
  10935. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10936. EXPECT_EQ("Hello World!", res->body);
  10937. }
  10938. {
  10939. auto res = cli.Get("/negotiated", headers);
  10940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10941. EXPECT_EQ(StatusCode::OK_200, res->status);
  10942. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10943. EXPECT_EQ(plain, res->body);
  10944. }
  10945. }
  10946. #endif
  10947. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10948. // the same message as the comma-joined one, so both have to be read the same
  10949. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10950. // single gzip coding, and a body the sender says was encoded twice was handed
  10951. // back after one pass, still compressed but presented as decoded.
  10952. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10953. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10954. Server svr;
  10955. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10956. res.set_content(body, "image/jpeg");
  10957. res.headers.emplace("Content-Encoding", "gzip");
  10958. res.headers.emplace("Content-Encoding", "gzip");
  10959. });
  10960. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10961. res.set_content(body, "image/jpeg");
  10962. res.set_header("Content-Encoding", "gzip, gzip");
  10963. });
  10964. auto port = svr.bind_to_any_port(HOST);
  10965. thread t = thread([&]() { svr.listen_after_bind(); });
  10966. auto se = detail::scope_exit([&] {
  10967. svr.stop();
  10968. t.join();
  10969. ASSERT_FALSE(svr.is_running());
  10970. });
  10971. svr.wait_until_ready();
  10972. Client cli(HOST, port);
  10973. // Two codings is not something cpp-httplib decodes, so both representations
  10974. // take the pass-through path rather than one of them being gunzipped once.
  10975. for (const char *path : {"/split", "/joined"}) {
  10976. auto res = cli.Get(path);
  10977. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10978. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10979. EXPECT_EQ(body, res->body) << path;
  10980. }
  10981. }
  10982. // Regression test for DoS vulnerability: a malicious server sending a response
  10983. // without Content-Length header must not cause unbounded memory consumption on
  10984. // the client side. The client should stop reading after a reasonable limit,
  10985. // similar to the server-side set_payload_max_length protection.
  10986. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10987. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10988. #ifndef _WIN32
  10989. signal(SIGPIPE, SIG_IGN);
  10990. #endif
  10991. auto server_thread = std::thread([] {
  10992. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10993. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10994. default_socket_options(srv);
  10995. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10996. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10997. sockaddr_in addr{};
  10998. addr.sin_family = AF_INET;
  10999. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11000. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11001. int opt = 1;
  11002. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11003. #ifdef _WIN32
  11004. reinterpret_cast<const char *>(&opt),
  11005. #else
  11006. &opt,
  11007. #endif
  11008. sizeof(opt));
  11009. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11010. ::listen(srv, 1);
  11011. sockaddr_in cli_addr{};
  11012. socklen_t cli_len = sizeof(cli_addr);
  11013. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11014. if (cli != INVALID_SOCKET) {
  11015. char buf[4096];
  11016. ::recv(cli, buf, sizeof(buf), 0);
  11017. // Malicious response: no Content-Length, no chunked encoding
  11018. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11019. "Connection: close\r\n"
  11020. "\r\n";
  11021. ::send(cli,
  11022. #ifdef _WIN32
  11023. static_cast<const char *>(response_header.c_str()),
  11024. static_cast<int>(response_header.size()),
  11025. #else
  11026. response_header.c_str(), response_header.size(),
  11027. #endif
  11028. 0);
  11029. // Send 10MB of data
  11030. std::string chunk(64 * 1024, 'A');
  11031. size_t total_sent = 0;
  11032. while (total_sent < MALICIOUS_DATA_SIZE) {
  11033. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11034. auto sent = ::send(cli,
  11035. #ifdef _WIN32
  11036. static_cast<const char *>(chunk.c_str()),
  11037. static_cast<int>(to_send),
  11038. #else
  11039. chunk.c_str(), to_send,
  11040. #endif
  11041. 0);
  11042. if (sent <= 0) break;
  11043. total_sent += static_cast<size_t>(sent);
  11044. }
  11045. detail::close_socket(cli);
  11046. }
  11047. detail::close_socket(srv);
  11048. });
  11049. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11050. size_t total_read = 0;
  11051. {
  11052. Client cli("127.0.0.1", PORT + 2);
  11053. cli.set_read_timeout(5, 0);
  11054. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11055. auto stream = cli.open_stream("GET", "/malicious");
  11056. ASSERT_TRUE(stream.is_valid());
  11057. char buffer[64 * 1024];
  11058. ssize_t n;
  11059. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11060. total_read += static_cast<size_t>(n);
  11061. }
  11062. } // StreamHandle and Client destroyed here, closing the socket
  11063. server_thread.join();
  11064. // With set_payload_max_length, the client must stop reading before consuming
  11065. // all 10MB. The read loop should be cut off at or near the configured limit.
  11066. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11067. << "Client read " << total_read << " bytes, exceeding the configured "
  11068. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11069. }
  11070. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11071. // the entire response body without truncation.
  11072. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11073. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11074. #ifndef _WIN32
  11075. signal(SIGPIPE, SIG_IGN);
  11076. #endif
  11077. auto server_thread = std::thread([] {
  11078. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11079. default_socket_options(srv);
  11080. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11081. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11082. sockaddr_in addr{};
  11083. addr.sin_family = AF_INET;
  11084. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11085. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11086. int opt = 1;
  11087. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11088. #ifdef _WIN32
  11089. reinterpret_cast<const char *>(&opt),
  11090. #else
  11091. &opt,
  11092. #endif
  11093. sizeof(opt));
  11094. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11095. ::listen(srv, 1);
  11096. sockaddr_in cli_addr{};
  11097. socklen_t cli_len = sizeof(cli_addr);
  11098. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11099. if (cli != INVALID_SOCKET) {
  11100. char buf[4096];
  11101. ::recv(cli, buf, sizeof(buf), 0);
  11102. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11103. "Connection: close\r\n"
  11104. "\r\n";
  11105. ::send(cli,
  11106. #ifdef _WIN32
  11107. static_cast<const char *>(response_header.c_str()),
  11108. static_cast<int>(response_header.size()),
  11109. #else
  11110. response_header.c_str(), response_header.size(),
  11111. #endif
  11112. 0);
  11113. std::string chunk(64 * 1024, 'A');
  11114. size_t total_sent = 0;
  11115. while (total_sent < DATA_SIZE) {
  11116. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11117. auto sent = ::send(cli,
  11118. #ifdef _WIN32
  11119. static_cast<const char *>(chunk.c_str()),
  11120. static_cast<int>(to_send),
  11121. #else
  11122. chunk.c_str(), to_send,
  11123. #endif
  11124. 0);
  11125. if (sent <= 0) break;
  11126. total_sent += static_cast<size_t>(sent);
  11127. }
  11128. #ifdef _WIN32
  11129. ::shutdown(cli, SD_SEND);
  11130. #else
  11131. ::shutdown(cli, SHUT_WR);
  11132. #endif
  11133. // Drain until the client closes its end, ensuring all data is delivered
  11134. char drain[1024];
  11135. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11136. detail::close_socket(cli);
  11137. }
  11138. detail::close_socket(srv);
  11139. });
  11140. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11141. size_t total_read = 0;
  11142. {
  11143. Client cli("127.0.0.1", PORT + 2);
  11144. cli.set_read_timeout(5, 0);
  11145. cli.set_payload_max_length(0); // 0 means no limit
  11146. auto stream = cli.open_stream("GET", "/data");
  11147. ASSERT_TRUE(stream.is_valid());
  11148. char buffer[64 * 1024];
  11149. ssize_t n;
  11150. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11151. total_read += static_cast<size_t>(n);
  11152. }
  11153. }
  11154. server_thread.join();
  11155. EXPECT_EQ(total_read, DATA_SIZE)
  11156. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11157. << " bytes without truncation, but only read " << total_read << " bytes.";
  11158. }
  11159. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11160. // enormous Content-Length must not cause the client to pre-allocate a huge
  11161. // response body buffer. The reservation is capped at payload_max_length_, and
  11162. // the read itself fails when the body exceeds the limit.
  11163. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11164. #ifndef _WIN32
  11165. signal(SIGPIPE, SIG_IGN);
  11166. #endif
  11167. auto server_thread = std::thread([] {
  11168. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11169. default_socket_options(srv);
  11170. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11171. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11172. sockaddr_in addr{};
  11173. addr.sin_family = AF_INET;
  11174. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11175. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11176. int opt = 1;
  11177. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11178. #ifdef _WIN32
  11179. reinterpret_cast<const char *>(&opt),
  11180. #else
  11181. &opt,
  11182. #endif
  11183. sizeof(opt));
  11184. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11185. ::listen(srv, 1);
  11186. sockaddr_in cli_addr{};
  11187. socklen_t cli_len = sizeof(cli_addr);
  11188. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11189. if (cli != INVALID_SOCKET) {
  11190. char buf[4096];
  11191. ::recv(cli, buf, sizeof(buf), 0);
  11192. // Malicious response: claim a 20GB body but send only a tiny payload.
  11193. std::string response = "HTTP/1.1 200 OK\r\n"
  11194. "Content-Length: 20000000000\r\n"
  11195. "\r\n"
  11196. "abc";
  11197. ::send(cli,
  11198. #ifdef _WIN32
  11199. static_cast<const char *>(response.c_str()),
  11200. static_cast<int>(response.size()),
  11201. #else
  11202. response.c_str(), response.size(),
  11203. #endif
  11204. 0);
  11205. detail::close_socket(cli);
  11206. }
  11207. detail::close_socket(srv);
  11208. });
  11209. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11210. {
  11211. Client cli("127.0.0.1", PORT + 2);
  11212. cli.set_read_timeout(5, 0);
  11213. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11214. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11215. // (server claims more bytes than payload_max_length permits), but it must
  11216. // not exhaust memory before getting there.
  11217. auto res = cli.Get("/malicious");
  11218. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11219. }
  11220. server_thread.join();
  11221. }
  11222. // Verify that content_receiver bypasses the default payload_max_length,
  11223. // allowing streaming downloads larger than 100MB without requiring an explicit
  11224. // set_payload_max_length call.
  11225. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11226. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11227. #ifndef _WIN32
  11228. signal(SIGPIPE, SIG_IGN);
  11229. #endif
  11230. auto server_thread = std::thread([] {
  11231. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11232. default_socket_options(srv);
  11233. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11234. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11235. sockaddr_in addr{};
  11236. addr.sin_family = AF_INET;
  11237. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11238. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11239. int opt = 1;
  11240. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11241. #ifdef _WIN32
  11242. reinterpret_cast<const char *>(&opt),
  11243. #else
  11244. &opt,
  11245. #endif
  11246. sizeof(opt));
  11247. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11248. ::listen(srv, 1);
  11249. sockaddr_in cli_addr{};
  11250. socklen_t cli_len = sizeof(cli_addr);
  11251. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11252. if (cli != INVALID_SOCKET) {
  11253. char buf[4096];
  11254. ::recv(cli, buf, sizeof(buf), 0);
  11255. // Response with Content-Length larger than default 100MB limit
  11256. auto content_length = std::to_string(DATA_SIZE);
  11257. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11258. "Content-Length: " +
  11259. content_length +
  11260. "\r\n"
  11261. "Connection: close\r\n"
  11262. "\r\n";
  11263. ::send(cli,
  11264. #ifdef _WIN32
  11265. static_cast<const char *>(response_header.c_str()),
  11266. static_cast<int>(response_header.size()),
  11267. #else
  11268. response_header.c_str(), response_header.size(),
  11269. #endif
  11270. 0);
  11271. std::string chunk(64 * 1024, 'A');
  11272. size_t total_sent = 0;
  11273. while (total_sent < DATA_SIZE) {
  11274. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11275. auto sent = ::send(cli,
  11276. #ifdef _WIN32
  11277. static_cast<const char *>(chunk.c_str()),
  11278. static_cast<int>(to_send),
  11279. #else
  11280. chunk.c_str(), to_send,
  11281. #endif
  11282. 0);
  11283. if (sent <= 0) break;
  11284. total_sent += static_cast<size_t>(sent);
  11285. }
  11286. detail::close_socket(cli);
  11287. }
  11288. detail::close_socket(srv);
  11289. });
  11290. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11291. size_t total_received = 0;
  11292. {
  11293. Client cli("127.0.0.1", PORT + 2);
  11294. cli.set_read_timeout(10, 0);
  11295. // Do NOT call set_payload_max_length — use the default 100MB limit
  11296. auto res =
  11297. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11298. total_received += data_length;
  11299. return true;
  11300. });
  11301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11302. EXPECT_EQ(StatusCode::OK_200, res->status);
  11303. }
  11304. server_thread.join();
  11305. EXPECT_EQ(total_received, DATA_SIZE)
  11306. << "With content_receiver, the client should read all " << DATA_SIZE
  11307. << " bytes despite the default 100MB payload_max_length, but only read "
  11308. << total_received << " bytes.";
  11309. }
  11310. // Verify that an explicit set_payload_max_length smaller than the response is
  11311. // enforced even when a content_receiver is used.
  11312. TEST(ClientVulnerabilityTest,
  11313. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11314. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11315. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11316. #ifndef _WIN32
  11317. signal(SIGPIPE, SIG_IGN);
  11318. #endif
  11319. auto server_thread = std::thread([] {
  11320. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11321. default_socket_options(srv);
  11322. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11323. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11324. sockaddr_in addr{};
  11325. addr.sin_family = AF_INET;
  11326. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11327. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11328. int opt = 1;
  11329. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11330. #ifdef _WIN32
  11331. reinterpret_cast<const char *>(&opt),
  11332. #else
  11333. &opt,
  11334. #endif
  11335. sizeof(opt));
  11336. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11337. ::listen(srv, 1);
  11338. sockaddr_in cli_addr{};
  11339. socklen_t cli_len = sizeof(cli_addr);
  11340. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11341. if (cli != INVALID_SOCKET) {
  11342. char buf[4096];
  11343. ::recv(cli, buf, sizeof(buf), 0);
  11344. auto content_length = std::to_string(DATA_SIZE);
  11345. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11346. "Content-Length: " +
  11347. content_length +
  11348. "\r\n"
  11349. "Connection: close\r\n"
  11350. "\r\n";
  11351. ::send(cli,
  11352. #ifdef _WIN32
  11353. static_cast<const char *>(response_header.c_str()),
  11354. static_cast<int>(response_header.size()),
  11355. #else
  11356. response_header.c_str(), response_header.size(),
  11357. #endif
  11358. 0);
  11359. std::string chunk(64 * 1024, 'A');
  11360. size_t total_sent = 0;
  11361. while (total_sent < DATA_SIZE) {
  11362. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11363. auto sent = ::send(cli,
  11364. #ifdef _WIN32
  11365. static_cast<const char *>(chunk.c_str()),
  11366. static_cast<int>(to_send),
  11367. #else
  11368. chunk.c_str(), to_send,
  11369. #endif
  11370. 0);
  11371. if (sent <= 0) break;
  11372. total_sent += static_cast<size_t>(sent);
  11373. }
  11374. detail::close_socket(cli);
  11375. }
  11376. detail::close_socket(srv);
  11377. });
  11378. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11379. size_t total_received = 0;
  11380. {
  11381. Client cli("127.0.0.1", PORT + 2);
  11382. cli.set_read_timeout(10, 0);
  11383. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11384. auto res =
  11385. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11386. total_received += data_length;
  11387. return true;
  11388. });
  11389. // Should fail because 200MB exceeds the explicit 150MB limit
  11390. EXPECT_FALSE(res);
  11391. }
  11392. server_thread.join();
  11393. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11394. << "Client with content_receiver should respect the explicit "
  11395. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11396. << total_received << " bytes.";
  11397. }
  11398. // Verify that an explicit set_payload_max_length larger than the response
  11399. // allows the content_receiver to read all data successfully.
  11400. TEST(ClientVulnerabilityTest,
  11401. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11402. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11403. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11404. #ifndef _WIN32
  11405. signal(SIGPIPE, SIG_IGN);
  11406. #endif
  11407. auto server_thread = std::thread([] {
  11408. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11409. default_socket_options(srv);
  11410. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11411. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11412. sockaddr_in addr{};
  11413. addr.sin_family = AF_INET;
  11414. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11415. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11416. int opt = 1;
  11417. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11418. #ifdef _WIN32
  11419. reinterpret_cast<const char *>(&opt),
  11420. #else
  11421. &opt,
  11422. #endif
  11423. sizeof(opt));
  11424. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11425. ::listen(srv, 1);
  11426. sockaddr_in cli_addr{};
  11427. socklen_t cli_len = sizeof(cli_addr);
  11428. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11429. if (cli != INVALID_SOCKET) {
  11430. char buf[4096];
  11431. ::recv(cli, buf, sizeof(buf), 0);
  11432. auto content_length = std::to_string(DATA_SIZE);
  11433. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11434. "Content-Length: " +
  11435. content_length +
  11436. "\r\n"
  11437. "Connection: close\r\n"
  11438. "\r\n";
  11439. ::send(cli,
  11440. #ifdef _WIN32
  11441. static_cast<const char *>(response_header.c_str()),
  11442. static_cast<int>(response_header.size()),
  11443. #else
  11444. response_header.c_str(), response_header.size(),
  11445. #endif
  11446. 0);
  11447. std::string chunk(64 * 1024, 'A');
  11448. size_t total_sent = 0;
  11449. while (total_sent < DATA_SIZE) {
  11450. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11451. auto sent = ::send(cli,
  11452. #ifdef _WIN32
  11453. static_cast<const char *>(chunk.c_str()),
  11454. static_cast<int>(to_send),
  11455. #else
  11456. chunk.c_str(), to_send,
  11457. #endif
  11458. 0);
  11459. if (sent <= 0) break;
  11460. total_sent += static_cast<size_t>(sent);
  11461. }
  11462. #ifdef _WIN32
  11463. ::shutdown(cli, SD_SEND);
  11464. #else
  11465. ::shutdown(cli, SHUT_WR);
  11466. #endif
  11467. char drain[1024];
  11468. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11469. detail::close_socket(cli);
  11470. }
  11471. detail::close_socket(srv);
  11472. });
  11473. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11474. size_t total_received = 0;
  11475. {
  11476. Client cli("127.0.0.1", PORT + 2);
  11477. cli.set_read_timeout(10, 0);
  11478. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11479. auto res =
  11480. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11481. total_received += data_length;
  11482. return true;
  11483. });
  11484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11485. EXPECT_EQ(StatusCode::OK_200, res->status);
  11486. }
  11487. server_thread.join();
  11488. EXPECT_EQ(total_received, DATA_SIZE)
  11489. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11490. << " bytes (larger than " << DATA_SIZE
  11491. << " bytes response), content_receiver should read all data, but only "
  11492. "read "
  11493. << total_received << " bytes.";
  11494. }
  11495. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11496. // Regression test for "zip bomb" attack on the client side: a malicious server
  11497. // sends a small gzip-compressed response that decompresses to a huge payload.
  11498. // The client must enforce payload_max_length on the decompressed size.
  11499. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11500. constexpr size_t DECOMPRESSED_SIZE =
  11501. 10 * 1024 * 1024; // 10MB after decompression
  11502. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11503. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11504. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11505. std::string compressed;
  11506. {
  11507. httplib::detail::gzip_compressor compressor;
  11508. bool ok =
  11509. compressor.compress(uncompressed.data(), uncompressed.size(),
  11510. /*last=*/true, [&](const char *buf, size_t len) {
  11511. compressed.append(buf, len);
  11512. return true;
  11513. });
  11514. ASSERT_TRUE(ok);
  11515. }
  11516. // Sanity: compressed data should be much smaller than the decompressed size
  11517. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11518. #ifndef _WIN32
  11519. signal(SIGPIPE, SIG_IGN);
  11520. #endif
  11521. // Set up the listening socket in the main thread so the server is guaranteed
  11522. // to be ready before the client connects (eliminates race condition).
  11523. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11524. default_socket_options(srv);
  11525. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11526. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11527. sockaddr_in addr{};
  11528. addr.sin_family = AF_INET;
  11529. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11530. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11531. int opt = 1;
  11532. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11533. #ifdef _WIN32
  11534. reinterpret_cast<const char *>(&opt),
  11535. #else
  11536. &opt,
  11537. #endif
  11538. sizeof(opt));
  11539. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11540. ASSERT_EQ(0, ::listen(srv, 1));
  11541. auto server_thread = std::thread([&compressed, srv] {
  11542. sockaddr_in cli_addr{};
  11543. socklen_t cli_len = sizeof(cli_addr);
  11544. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11545. if (cli != INVALID_SOCKET) {
  11546. // Read the full HTTP request (until \r\n\r\n)
  11547. char buf[4096];
  11548. size_t total = 0;
  11549. while (total < sizeof(buf)) {
  11550. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11551. if (n <= 0) break;
  11552. total += static_cast<size_t>(n);
  11553. // Check for end of headers
  11554. if (total >= 4) {
  11555. std::string req(buf, total);
  11556. if (req.find("\r\n\r\n") != std::string::npos) break;
  11557. }
  11558. }
  11559. // Malicious response: gzip-compressed body, no Content-Length
  11560. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11561. "Content-Encoding: gzip\r\n"
  11562. "Connection: close\r\n"
  11563. "\r\n";
  11564. ::send(cli,
  11565. #ifdef _WIN32
  11566. static_cast<const char *>(response_header.c_str()),
  11567. static_cast<int>(response_header.size()),
  11568. #else
  11569. response_header.c_str(), response_header.size(),
  11570. #endif
  11571. 0);
  11572. // Send the compressed payload (small on the wire, huge when decompressed)
  11573. size_t total_sent = 0;
  11574. while (total_sent < compressed.size()) {
  11575. auto to_send = std::min(compressed.size() - total_sent,
  11576. static_cast<size_t>(64 * 1024));
  11577. auto sent =
  11578. ::send(cli,
  11579. #ifdef _WIN32
  11580. static_cast<const char *>(compressed.c_str() + total_sent),
  11581. static_cast<int>(to_send),
  11582. #else
  11583. compressed.c_str() + total_sent, to_send,
  11584. #endif
  11585. 0);
  11586. if (sent <= 0) break;
  11587. total_sent += static_cast<size_t>(sent);
  11588. }
  11589. detail::close_socket(cli);
  11590. }
  11591. });
  11592. auto se = detail::scope_exit([&] {
  11593. detail::close_socket(srv);
  11594. server_thread.join();
  11595. });
  11596. size_t total_decompressed = 0;
  11597. {
  11598. Client cli("127.0.0.1", PORT + 3);
  11599. cli.set_read_timeout(5, 0);
  11600. cli.set_decompress(true);
  11601. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11602. auto stream = cli.open_stream("GET", "/zipbomb");
  11603. ASSERT_TRUE(stream.is_valid());
  11604. char buffer[64 * 1024];
  11605. ssize_t n;
  11606. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11607. total_decompressed += static_cast<size_t>(n);
  11608. }
  11609. }
  11610. // The decompressed size must be capped by payload_max_length. Without
  11611. // protection, the client would decompress the full 10MB from a tiny
  11612. // compressed payload, enabling a zip bomb DoS attack.
  11613. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11614. << "Client decompressed " << total_decompressed
  11615. << " bytes from a gzip response. The decompressed size should be "
  11616. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11617. }
  11618. #endif
  11619. TEST(HostAndPortPropertiesTest, NoSSL) {
  11620. httplib::Client cli("www.google.com", 1234);
  11621. ASSERT_EQ("www.google.com", cli.host());
  11622. ASSERT_EQ(1234, cli.port());
  11623. }
  11624. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11625. httplib::Client cli("www.google.com:1234");
  11626. ASSERT_EQ("www.google.com", cli.host());
  11627. ASSERT_EQ(1234, cli.port());
  11628. }
  11629. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11630. // Port number that overflows int — should not crash, client becomes invalid
  11631. httplib::Client cli("http://www.google.com:99999999999999999999");
  11632. ASSERT_FALSE(cli.is_valid());
  11633. }
  11634. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11635. // Port 99999 exceeds valid range (1-65535) — should not crash
  11636. httplib::Client cli("http://www.google.com:99999");
  11637. ASSERT_FALSE(cli.is_valid());
  11638. }
  11639. #ifdef CPPHTTPLIB_SSL_ENABLED
  11640. TEST(HostAndPortPropertiesTest, SSL) {
  11641. httplib::SSLClient cli("www.google.com");
  11642. ASSERT_EQ("www.google.com", cli.host());
  11643. ASSERT_EQ(443, cli.port());
  11644. }
  11645. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11646. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11647. std::string cert;
  11648. read_file(CA_CERT_FILE, cert);
  11649. httplib::SSLClient httplib_client("www.google.com");
  11650. // Load CA store first time
  11651. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11652. // Load CA store second time (update)
  11653. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11654. // Verify client is still valid and can make connections
  11655. httplib_client.enable_server_certificate_verification(true);
  11656. auto res = httplib_client.Get("/");
  11657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11658. // Google may return 200 or 301 depending on various factors
  11659. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11660. res->status == StatusCode::MovedPermanently_301);
  11661. }
  11662. TEST(SSLClientTest, ServerNameIndication_Online) {
  11663. auto host = "httpbingo.org";
  11664. auto path = std::string{"/get"};
  11665. SSLClient cli(host, 443);
  11666. auto res = cli.Get(path);
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. ASSERT_EQ(StatusCode::OK_200, res->status);
  11669. }
  11670. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11671. // Use a site that will cause SSL verification failure due to self-signed cert
  11672. SSLClient cli("self-signed.badssl.com", 443);
  11673. cli.enable_server_certificate_verification(true);
  11674. auto res = cli.Get("/");
  11675. ASSERT_TRUE(!res);
  11676. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11677. // Verify backend error is captured for SSLServerVerification
  11678. // This occurs when certificate verification fails
  11679. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11680. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11681. EXPECT_NE(0UL, res.ssl_backend_error());
  11682. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11683. // For OpenSSL, ssl_error is 0 for verification errors
  11684. EXPECT_EQ(0, res.ssl_error());
  11685. #if !defined(_WIN32) || \
  11686. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11687. // On non-Windows or when Windows Schannel is disabled, the error comes
  11688. // from OpenSSL's verification
  11689. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11690. res.ssl_backend_error());
  11691. #endif
  11692. #endif
  11693. }
  11694. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11695. // Use a site where hostname doesn't match the certificate
  11696. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11697. SSLClient cli("wrong.host.badssl.com", 443);
  11698. cli.enable_server_certificate_verification(true);
  11699. cli.enable_server_hostname_verification(true);
  11700. auto res = cli.Get("/");
  11701. ASSERT_TRUE(!res);
  11702. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11703. // Verify backend error is captured for hostname verification failure
  11704. EXPECT_NE(0UL, res.ssl_backend_error());
  11705. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11706. // For OpenSSL, ssl_error is 0 for verification errors
  11707. EXPECT_EQ(0, res.ssl_error());
  11708. #if !defined(_WIN32) || \
  11709. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11710. // On non-Windows or when Windows Schannel is disabled, the error comes
  11711. // from OpenSSL's hostname verification
  11712. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11713. res.ssl_backend_error());
  11714. #endif
  11715. #endif
  11716. }
  11717. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11718. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11719. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11720. SSLClient cli("www.google.com", 443);
  11721. cli.enable_server_certificate_verification(true);
  11722. auto res = cli.Get("/");
  11723. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11724. }
  11725. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11726. SSLClient cli("www.google.com", 443);
  11727. cli.enable_server_certificate_verification(true);
  11728. cli.enable_windows_certificate_verification(false);
  11729. auto res = cli.Get("/");
  11730. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11731. }
  11732. #endif
  11733. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11734. Client cli("https://google.com");
  11735. auto res = cli.Get("/");
  11736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11737. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11738. }
  11739. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11740. SSLClient cli("google.com");
  11741. cli.set_ca_cert_path(CA_CERT_FILE);
  11742. auto res = cli.Get("/");
  11743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11744. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11745. }
  11746. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11747. SSLClient cli("google.com");
  11748. cli.enable_server_certificate_verification(true);
  11749. cli.set_ca_cert_path("hello");
  11750. auto res = cli.Get("/");
  11751. ASSERT_TRUE(!res);
  11752. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11753. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11754. // should be set
  11755. EXPECT_EQ(0, res.ssl_error());
  11756. // Verify backend error is captured for SSLLoadingCerts
  11757. // This error occurs when loading CA certificates fails
  11758. EXPECT_NE(0UL, res.ssl_backend_error());
  11759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11760. // OpenSSL specific error codes:
  11761. // > openssl errstr 0x80000002
  11762. // error:80000002:system library::No such file or directory
  11763. // > openssl errstr 0xA000126
  11764. // error:0A000126:SSL routines::unexpected eof while reading
  11765. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11766. res.ssl_backend_error() == 0xA000126);
  11767. #endif
  11768. }
  11769. TEST(SSLClientTest, ServerCertificateVerification4) {
  11770. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11771. ASSERT_TRUE(svr.is_valid());
  11772. svr.Get("/test", [&](const Request &, Response &res) {
  11773. res.set_content("test", "text/plain");
  11774. svr.stop();
  11775. ASSERT_TRUE(true);
  11776. });
  11777. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11778. auto se = detail::scope_exit([&] {
  11779. t.join();
  11780. ASSERT_FALSE(svr.is_running());
  11781. });
  11782. svr.wait_until_ready();
  11783. SSLClient cli("127.0.0.1", PORT);
  11784. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11785. cli.enable_server_certificate_verification(true);
  11786. cli.set_connection_timeout(30);
  11787. auto res = cli.Get("/test");
  11788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11789. ASSERT_EQ(StatusCode::OK_200, res->status);
  11790. }
  11791. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11792. std::string cert;
  11793. read_file(CA_CERT_FILE, cert);
  11794. SSLClient cli("google.com");
  11795. cli.load_ca_cert_store(cert.data(), cert.size());
  11796. const auto res = cli.Get("/");
  11797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11798. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11799. }
  11800. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11801. // clang-format off
  11802. static constexpr char cert[] =
  11803. "GlobalSign Root CA\n"
  11804. "==================\n"
  11805. "-----BEGIN CERTIFICATE-----\n"
  11806. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11807. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11808. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11809. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11810. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11811. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11812. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11813. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11814. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11815. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11816. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11817. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11818. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11819. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11820. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11821. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11822. "-----END CERTIFICATE-----\n";
  11823. // clang-format on
  11824. SSLClient cli("google.com");
  11825. cli.load_ca_cert_store(cert, sizeof(cert));
  11826. const auto res = cli.Get("/");
  11827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11828. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11829. }
  11830. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11831. SSLClient cli("www.youtube.com");
  11832. cli.set_ca_cert_path(CA_CERT_FILE);
  11833. cli.enable_server_certificate_verification(true);
  11834. cli.set_follow_location(true);
  11835. auto res = cli.Get("/");
  11836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11837. ASSERT_EQ(StatusCode::OK_200, res->status);
  11838. }
  11839. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11840. SSLClient cli("wWw.YouTube.Com");
  11841. cli.set_ca_cert_path(CA_CERT_FILE);
  11842. cli.enable_server_certificate_verification(true);
  11843. cli.enable_server_hostname_verification(true);
  11844. cli.set_follow_location(true);
  11845. auto res = cli.Get("/");
  11846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11847. ASSERT_EQ(StatusCode::OK_200, res->status);
  11848. }
  11849. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11850. SSLClient cli("gOoGlE.COm");
  11851. cli.enable_server_certificate_verification(true);
  11852. cli.enable_server_hostname_verification(true);
  11853. cli.set_follow_location(true);
  11854. auto res = cli.Get("/");
  11855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11856. ASSERT_EQ(StatusCode::OK_200, res->status);
  11857. }
  11858. TEST(SSLClientTest, Issue2004_Online) {
  11859. Client client("https://google.com");
  11860. client.set_follow_location(true);
  11861. auto res = client.Get("/");
  11862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11863. ASSERT_EQ(StatusCode::OK_200, res->status);
  11864. auto body = res->body;
  11865. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11866. }
  11867. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11868. // Create SSLClient with invalid cert/key to make is_valid() return false
  11869. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11870. "nonexistent_key.pem");
  11871. // is_valid() should be false due to cert loading failure
  11872. ASSERT_FALSE(cli.is_valid());
  11873. auto res = cli.Get("/");
  11874. ASSERT_FALSE(res);
  11875. EXPECT_EQ(Error::SSLConnection, res.error());
  11876. }
  11877. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11878. // Test for Issue #2251: SSL error not properly reported when client cert
  11879. // and key paths are swapped or mismatched
  11880. // This simulates the scenario where user accidentally swaps the cert and key
  11881. // files
  11882. // Using client cert file as private key and vice versa (completely wrong)
  11883. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11884. // Should fail validation due to cert/key mismatch
  11885. ASSERT_FALSE(cli.is_valid());
  11886. // Attempt to make a request should fail with proper error
  11887. auto res = cli.Get("/");
  11888. ASSERT_FALSE(res);
  11889. EXPECT_EQ(Error::SSLConnection, res.error());
  11890. // SSL error should be recorded in the Result object (this is the key fix for
  11891. // Issue #2251)
  11892. auto backend_error = res.ssl_backend_error();
  11893. EXPECT_NE(0u, backend_error);
  11894. }
  11895. // Tests cert/key mismatch detection at the TLS context level
  11896. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11897. // Test that using mismatched cert/key causes connection failure.
  11898. // We verify this at the SSLClient level rather than through internal
  11899. // TLS API functions.
  11900. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11901. cli.enable_server_certificate_verification(false);
  11902. cli.set_connection_timeout(2);
  11903. // The mismatch should cause a connection or handshake error
  11904. auto res = cli.Get("/test");
  11905. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11906. // Either way, the request should fail
  11907. EXPECT_FALSE(res);
  11908. }
  11909. #endif
  11910. #if 0
  11911. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11912. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11913. ASSERT_TRUE(cli != nullptr);
  11914. cli->set_address_family(AF_INET6);
  11915. cli->set_interface("en0");
  11916. auto res = cli->Get("/get");
  11917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11918. ASSERT_EQ(StatusCode::OK_200, res->status);
  11919. }
  11920. #endif
  11921. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11922. #ifdef CPPHTTPLIB_SSL_ENABLED
  11923. void ClientCertPresent(
  11924. const std::string &client_cert_file,
  11925. const std::string &client_private_key_file,
  11926. const std::string &client_encrypted_private_key_pass = std::string()) {
  11927. using namespace httplib::tls;
  11928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11929. CLIENT_CA_CERT_DIR);
  11930. ASSERT_TRUE(svr.is_valid());
  11931. svr.Get("/test", [&](const Request &req, Response &res) {
  11932. res.set_content("test", "text/plain");
  11933. auto cert = req.peer_cert();
  11934. ASSERT_TRUE(static_cast<bool>(cert));
  11935. std::string common_name = cert.subject_cn();
  11936. EXPECT_EQ("Common Name", common_name);
  11937. });
  11938. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11939. auto se = detail::scope_exit([&] {
  11940. svr.stop();
  11941. t.join();
  11942. ASSERT_FALSE(svr.is_running());
  11943. });
  11944. svr.wait_until_ready();
  11945. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11946. client_encrypted_private_key_pass);
  11947. cli.enable_server_certificate_verification(false);
  11948. cli.set_connection_timeout(30);
  11949. auto res = cli.Get("/test");
  11950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11951. ASSERT_EQ(StatusCode::OK_200, res->status);
  11952. }
  11953. TEST(SSLClientServerTest, ClientCertPresent) {
  11954. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11955. }
  11956. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11957. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11958. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11959. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11960. }
  11961. // PEM memory-based constructor tests (works with all TLS backends)
  11962. void PemMemoryClientCertPresent(
  11963. const std::string &client_cert_file,
  11964. const std::string &client_private_key_file,
  11965. const std::string &client_encrypted_private_key_pass = std::string()) {
  11966. // Read PEM files into memory
  11967. std::string server_cert_pem, server_key_pem;
  11968. std::string client_ca_pem;
  11969. std::string client_cert_pem, client_key_pem;
  11970. read_file(SERVER_CERT_FILE, server_cert_pem);
  11971. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11972. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11973. read_file(client_cert_file, client_cert_pem);
  11974. read_file(client_private_key_file, client_key_pem);
  11975. // Create server with PEM memory
  11976. SSLServer::PemMemory server_pem = {
  11977. server_cert_pem.c_str(),
  11978. server_cert_pem.size(),
  11979. server_key_pem.c_str(),
  11980. server_key_pem.size(),
  11981. client_ca_pem.c_str(),
  11982. client_ca_pem.size(),
  11983. nullptr // no password for server key
  11984. };
  11985. SSLServer svr(server_pem);
  11986. ASSERT_TRUE(svr.is_valid());
  11987. svr.Get("/test", [&](const Request &, Response &res) {
  11988. res.set_content("test", "text/plain");
  11989. });
  11990. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11991. auto se = detail::scope_exit([&] {
  11992. svr.stop();
  11993. t.join();
  11994. ASSERT_FALSE(svr.is_running());
  11995. });
  11996. svr.wait_until_ready();
  11997. // Create client with PEM memory
  11998. const char *password = client_encrypted_private_key_pass.empty()
  11999. ? nullptr
  12000. : client_encrypted_private_key_pass.c_str();
  12001. SSLClient::PemMemory client_pem = {
  12002. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12003. client_key_pem.size(), password};
  12004. SSLClient cli(HOST, PORT, client_pem);
  12005. cli.enable_server_certificate_verification(false);
  12006. cli.set_connection_timeout(30);
  12007. auto res = cli.Get("/test");
  12008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12009. ASSERT_EQ(StatusCode::OK_200, res->status);
  12010. }
  12011. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12012. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12013. }
  12014. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12015. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12016. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12017. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12018. }
  12019. TEST(SSLClientServerTest, ClientCertMissing) {
  12020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12021. CLIENT_CA_CERT_DIR);
  12022. ASSERT_TRUE(svr.is_valid());
  12023. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12024. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12025. auto se = detail::scope_exit([&] {
  12026. svr.stop();
  12027. t.join();
  12028. ASSERT_FALSE(svr.is_running());
  12029. });
  12030. svr.wait_until_ready();
  12031. SSLClient cli(HOST, PORT);
  12032. cli.set_connection_timeout(30);
  12033. auto res = cli.Get("/test");
  12034. ASSERT_TRUE(!res);
  12035. // When client cert is missing and server requires it, connection fails
  12036. // Error type depends on backend implementation
  12037. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12038. res.error() == Error::SSLConnection);
  12039. // Verify backend error is captured
  12040. // Note: This test may have different error codes depending on the exact
  12041. // verification failure
  12042. EXPECT_NE(0UL, res.ssl_backend_error());
  12043. }
  12044. TEST(SSLClientServerTest, TrustDirOptional) {
  12045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12046. ASSERT_TRUE(svr.is_valid());
  12047. svr.Get("/test", [&](const Request &, Response &res) {
  12048. res.set_content("test", "text/plain");
  12049. });
  12050. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12051. auto se = detail::scope_exit([&] {
  12052. svr.stop();
  12053. t.join();
  12054. ASSERT_FALSE(svr.is_running());
  12055. });
  12056. svr.wait_until_ready();
  12057. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12058. cli.enable_server_certificate_verification(false);
  12059. cli.set_connection_timeout(30);
  12060. auto res = cli.Get("/test");
  12061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12062. ASSERT_EQ(StatusCode::OK_200, res->status);
  12063. }
  12064. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12065. class NoListenSSLServer : public SSLServer {
  12066. public:
  12067. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12068. const char *client_ca_cert_file_path,
  12069. const char *client_ca_cert_dir_path = nullptr)
  12070. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12071. client_ca_cert_dir_path),
  12072. stop_(false) {}
  12073. std::atomic_bool stop_;
  12074. private:
  12075. bool process_and_close_socket(socket_t /*sock*/) override {
  12076. // Don't create SSL context
  12077. while (!stop_.load()) {
  12078. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12079. }
  12080. return true;
  12081. }
  12082. };
  12083. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12084. CLIENT_CA_CERT_FILE);
  12085. ASSERT_TRUE(svr.is_valid());
  12086. svr.Get("/test", [&](const Request &, Response &res) {
  12087. res.set_content("test", "text/plain");
  12088. });
  12089. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12090. auto se = detail::scope_exit([&] {
  12091. svr.stop_ = true;
  12092. svr.stop();
  12093. t.join();
  12094. ASSERT_FALSE(svr.is_running());
  12095. });
  12096. svr.wait_until_ready();
  12097. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12098. cli.enable_server_certificate_verification(false);
  12099. cli.set_connection_timeout(1);
  12100. auto res = cli.Get("/test");
  12101. ASSERT_TRUE(!res);
  12102. EXPECT_EQ(Error::SSLConnection, res.error());
  12103. // Timeout results in WantRead error code (maps to backend-specific value)
  12104. EXPECT_NE(0, res.ssl_error());
  12105. }
  12106. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12107. // Test SSLServer with client certificate verification using the standard
  12108. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12110. CLIENT_CA_CERT_DIR);
  12111. ASSERT_TRUE(svr.is_valid());
  12112. svr.Get("/test", [&](const Request &req, Response &res) {
  12113. res.set_content("test", "text/plain");
  12114. auto cert = req.peer_cert();
  12115. ASSERT_TRUE(static_cast<bool>(cert));
  12116. auto common_name = cert.subject_cn();
  12117. EXPECT_EQ("Common Name", common_name);
  12118. });
  12119. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12120. auto se = detail::scope_exit([&] {
  12121. svr.stop();
  12122. t.join();
  12123. ASSERT_FALSE(svr.is_running());
  12124. });
  12125. svr.wait_until_ready();
  12126. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12127. cli.enable_server_certificate_verification(false);
  12128. cli.set_connection_timeout(30);
  12129. auto res = cli.Get("/test");
  12130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12131. ASSERT_EQ(StatusCode::OK_200, res->status);
  12132. }
  12133. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12134. // Verifies that wildcard matching and exact matching work consistently
  12135. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12136. using namespace httplib::tls;
  12137. // We need a running server to test against
  12138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12139. ASSERT_TRUE(svr.is_valid());
  12140. svr.Get("/test", [](const Request &, Response &res) {
  12141. res.set_content("ok", "text/plain");
  12142. });
  12143. thread t([&]() { svr.listen(HOST, PORT); });
  12144. auto se = detail::scope_exit([&] {
  12145. svr.stop();
  12146. t.join();
  12147. });
  12148. svr.wait_until_ready();
  12149. bool verify_callback_called = false;
  12150. bool verify_result_wrong = false;
  12151. SSLClient cli(HOST, PORT);
  12152. cli.enable_server_certificate_verification(true);
  12153. cli.set_ca_cert_path(CA_CERT_FILE);
  12154. cli.set_connection_timeout(5);
  12155. // Note: Test certificate has CN="Common Name", not "localhost"
  12156. bool verify_result_cn = false;
  12157. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12158. verify_callback_called = true;
  12159. if (!ctx.cert) return false;
  12160. // Test 1: "Common Name" should match (our test server cert CN)
  12161. verify_result_cn = ctx.check_hostname("Common Name");
  12162. // Test 2: wrong hostname should not match
  12163. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12164. return true; // Accept for the purpose of this test
  12165. });
  12166. auto res = cli.Get("/test");
  12167. // The request may succeed or fail depending on cert configuration
  12168. // but the callback should have been called
  12169. ASSERT_TRUE(verify_callback_called)
  12170. << "Verify callback should have been called";
  12171. // CN="Common Name" should match our test certificate
  12172. //
  12173. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12174. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12175. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12176. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12177. // <openssl/base.h>, which is included transitively when
  12178. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12179. #if defined(OPENSSL_IS_BORINGSSL)
  12180. EXPECT_FALSE(verify_result_cn)
  12181. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12182. #else
  12183. EXPECT_TRUE(verify_result_cn)
  12184. << "verify_hostname should match 'Common Name' (certificate CN)";
  12185. #endif
  12186. // Wrong hostname should not match
  12187. EXPECT_FALSE(verify_result_wrong)
  12188. << "verify_hostname should not match 'wronghost.example.com'";
  12189. }
  12190. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12191. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12192. // X509_check_ip behavior and must hold for every backend.
  12193. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12194. using namespace httplib::tls;
  12195. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12196. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12197. ASSERT_TRUE(svr.is_valid());
  12198. svr.Get("/test", [](const Request &, Response &res) {
  12199. res.set_content("ok", "text/plain");
  12200. });
  12201. thread t([&]() { svr.listen(HOST, PORT); });
  12202. auto se = detail::scope_exit([&] {
  12203. svr.stop();
  12204. t.join();
  12205. });
  12206. svr.wait_until_ready();
  12207. bool verify_callback_called = false;
  12208. bool ip_matched_via_cn = true;
  12209. SSLClient cli(HOST, PORT);
  12210. cli.enable_server_certificate_verification(true);
  12211. cli.set_ca_cert_path(CA_CERT_FILE);
  12212. cli.set_connection_timeout(5);
  12213. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12214. verify_callback_called = true;
  12215. if (!ctx.cert) return false;
  12216. // The IP appears only in the CN, so it must NOT be accepted.
  12217. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12218. return true; // Accept for the purpose of this test
  12219. });
  12220. cli.Get("/test");
  12221. ASSERT_TRUE(verify_callback_called)
  12222. << "Verify callback should have been called";
  12223. EXPECT_FALSE(ip_matched_via_cn)
  12224. << "An IP host must not be authenticated via the certificate CN";
  12225. }
  12226. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12227. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12228. using namespace httplib::tls;
  12229. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12230. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12231. ASSERT_TRUE(svr.is_valid());
  12232. svr.Get("/test", [](const Request &, Response &res) {
  12233. res.set_content("ok", "text/plain");
  12234. });
  12235. thread t([&]() { svr.listen(HOST, PORT); });
  12236. auto se = detail::scope_exit([&] {
  12237. svr.stop();
  12238. t.join();
  12239. });
  12240. svr.wait_until_ready();
  12241. bool verify_callback_called = false;
  12242. bool san_matched = false;
  12243. bool wrong_ipv6_matched = true;
  12244. bool cn_ipv6_matched = true;
  12245. SSLClient cli(HOST, PORT);
  12246. cli.enable_server_certificate_verification(true);
  12247. cli.set_ca_cert_path(CA_CERT_FILE);
  12248. cli.set_connection_timeout(5);
  12249. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12250. verify_callback_called = true;
  12251. if (!ctx.cert) return false;
  12252. // Matches the IPv6 iPAddress SAN.
  12253. san_matched = ctx.check_hostname("2001:db8::1");
  12254. // A different IPv6 address must not match.
  12255. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12256. // "::1" lives only in the CN, so it must not be accepted.
  12257. cn_ipv6_matched = ctx.check_hostname("::1");
  12258. return true; // Accept for the purpose of this test
  12259. });
  12260. cli.Get("/test");
  12261. ASSERT_TRUE(verify_callback_called)
  12262. << "Verify callback should have been called";
  12263. EXPECT_TRUE(san_matched)
  12264. << "verify_hostname should match an IPv6 iPAddress SAN";
  12265. EXPECT_FALSE(wrong_ipv6_matched)
  12266. << "verify_hostname should not match a non-matching IPv6 address";
  12267. EXPECT_FALSE(cn_ipv6_matched)
  12268. << "An IPv6 host must not be authenticated via the certificate CN";
  12269. }
  12270. #endif
  12271. // mbedTLS-specific callback constructor test
  12272. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12273. #ifdef CPPHTTPLIB_SSL_ENABLED
  12274. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12276. ASSERT_TRUE(svr.is_valid());
  12277. // Set up a handler to verify client certificate is present
  12278. bool client_cert_verified = false;
  12279. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12280. // Verify that client certificate was provided
  12281. client_cert_verified = true;
  12282. res.set_content("success", "text/plain");
  12283. });
  12284. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12285. auto se = detail::scope_exit([&] {
  12286. svr.stop();
  12287. t.join();
  12288. ASSERT_FALSE(svr.is_running());
  12289. });
  12290. svr.wait_until_ready();
  12291. // Client with certificate
  12292. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12293. cli.enable_server_certificate_verification(false);
  12294. cli.set_connection_timeout(30);
  12295. auto res = cli.Get("/test");
  12296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12297. ASSERT_EQ(StatusCode::OK_200, res->status);
  12298. ASSERT_TRUE(client_cert_verified);
  12299. EXPECT_EQ("success", res->body);
  12300. }
  12301. #endif
  12302. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12303. // backends
  12304. #ifdef CPPHTTPLIB_SSL_ENABLED
  12305. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12306. using namespace httplib::tls;
  12307. // Test that when client CA cert file is provided,
  12308. // the server properly requests and validates client certificates
  12309. // Create a server with client authentication
  12310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12311. ASSERT_TRUE(svr.is_valid());
  12312. bool handler_called = false;
  12313. svr.Get("/test", [&](const Request &req, Response &res) {
  12314. handler_called = true;
  12315. // Verify that a client certificate was provided
  12316. auto cert = req.peer_cert();
  12317. ASSERT_TRUE(static_cast<bool>(cert));
  12318. // Get the issuer name
  12319. std::string issuer_str = cert.issuer_name();
  12320. ASSERT_FALSE(issuer_str.empty());
  12321. // The client certificate should be issued by our test CA
  12322. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12323. res.set_content("authenticated", "text/plain");
  12324. });
  12325. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12326. auto se = detail::scope_exit([&] {
  12327. svr.stop();
  12328. t.join();
  12329. ASSERT_FALSE(svr.is_running());
  12330. });
  12331. svr.wait_until_ready();
  12332. // Connect with a client certificate issued by the CA
  12333. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12334. cli.enable_server_certificate_verification(false);
  12335. cli.set_connection_timeout(30);
  12336. auto res = cli.Get("/test");
  12337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12338. ASSERT_EQ(StatusCode::OK_200, res->status);
  12339. ASSERT_TRUE(handler_called);
  12340. EXPECT_EQ("authenticated", res->body);
  12341. }
  12342. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12343. using namespace httplib::tls;
  12344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12345. ASSERT_TRUE(svr.is_valid());
  12346. svr.Get("/test", [](const Request &, Response &res) {
  12347. res.set_content("ok", "text/plain");
  12348. });
  12349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12350. auto se = detail::scope_exit([&] {
  12351. svr.stop();
  12352. t.join();
  12353. });
  12354. svr.wait_until_ready();
  12355. SSLClient cli(HOST, PORT);
  12356. cli.enable_server_certificate_verification(false);
  12357. cli.set_connection_timeout(30);
  12358. bool cert_checked = false;
  12359. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12360. if (ctx.cert) {
  12361. auto sans = ctx.sans();
  12362. // Test certificate may or may not have SANs - just verify the API
  12363. // works If SANs exist, verify the types are valid
  12364. for (const auto &san : sans) {
  12365. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12366. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12367. san.type == SanType::OTHER);
  12368. EXPECT_FALSE(san.value.empty());
  12369. }
  12370. cert_checked = true;
  12371. }
  12372. return true;
  12373. });
  12374. auto res = cli.Get("/test");
  12375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12376. EXPECT_TRUE(cert_checked);
  12377. }
  12378. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12379. using namespace httplib::tls;
  12380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12381. ASSERT_TRUE(svr.is_valid());
  12382. svr.Get("/test", [](const Request &, Response &res) {
  12383. res.set_content("ok", "text/plain");
  12384. });
  12385. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12386. auto se = detail::scope_exit([&] {
  12387. svr.stop();
  12388. t.join();
  12389. });
  12390. svr.wait_until_ready();
  12391. SSLClient cli(HOST, PORT);
  12392. cli.enable_server_certificate_verification(false);
  12393. cli.set_connection_timeout(30);
  12394. bool validity_checked = false;
  12395. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12396. if (ctx.cert) {
  12397. time_t not_before = 0, not_after = 0;
  12398. bool result = ctx.validity(not_before, not_after);
  12399. EXPECT_TRUE(result);
  12400. // Verify that not_before < now < not_after for a valid cert
  12401. time_t now = time(nullptr);
  12402. EXPECT_LT(not_before, now);
  12403. EXPECT_GT(not_after, now);
  12404. validity_checked = true;
  12405. }
  12406. return true;
  12407. });
  12408. auto res = cli.Get("/test");
  12409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12410. EXPECT_TRUE(validity_checked);
  12411. }
  12412. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12413. using namespace httplib::tls;
  12414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12415. ASSERT_TRUE(svr.is_valid());
  12416. svr.Get("/test", [](const Request &, Response &res) {
  12417. res.set_content("ok", "text/plain");
  12418. });
  12419. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12420. auto se = detail::scope_exit([&] {
  12421. svr.stop();
  12422. t.join();
  12423. });
  12424. svr.wait_until_ready();
  12425. SSLClient cli(HOST, PORT);
  12426. cli.enable_server_certificate_verification(false);
  12427. cli.set_connection_timeout(30);
  12428. bool serial_checked = false;
  12429. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12430. if (ctx.cert) {
  12431. std::string serial = ctx.serial();
  12432. EXPECT_FALSE(serial.empty());
  12433. // Serial should be a hex string
  12434. for (char c : serial) {
  12435. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12436. (c >= 'a' && c <= 'f'));
  12437. }
  12438. serial_checked = true;
  12439. }
  12440. return true;
  12441. });
  12442. auto res = cli.Get("/test");
  12443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12444. EXPECT_TRUE(serial_checked);
  12445. }
  12446. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12447. // Test 1: Valid CA file - no error should be recorded
  12448. {
  12449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12450. CLIENT_CA_CERT_FILE);
  12451. ASSERT_TRUE(svr.is_valid());
  12452. // With valid setup, last_ssl_error should be 0
  12453. EXPECT_EQ(0, svr.ssl_last_error());
  12454. }
  12455. // Test 2: Invalid CA file content
  12456. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12457. {
  12458. // Create a temporary file with completely invalid content
  12459. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12460. {
  12461. std::ofstream ofs(temp_invalid_ca);
  12462. ofs << "This is not a certificate file at all\n";
  12463. ofs << "Just plain text content\n";
  12464. }
  12465. // Create server with invalid CA file
  12466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12467. // Clean up temporary file
  12468. std::remove(temp_invalid_ca);
  12469. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12470. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12471. // Note: SSL_CTX_load_verify_locations typically fails first,
  12472. // but our error handling code path is still exercised
  12473. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12474. }
  12475. }
  12476. TEST(VerifyCallbackTest, VerifyContextFields) {
  12477. using namespace httplib::tls;
  12478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12479. ASSERT_TRUE(svr.is_valid());
  12480. svr.Get("/test", [](const Request &, Response &res) {
  12481. res.set_content("ok", "text/plain");
  12482. });
  12483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12484. auto se = detail::scope_exit([&] {
  12485. svr.stop();
  12486. t.join();
  12487. });
  12488. svr.wait_until_ready();
  12489. SSLClient cli(HOST, PORT);
  12490. cli.enable_server_certificate_verification(false);
  12491. cli.set_connection_timeout(30);
  12492. int callback_count = 0;
  12493. bool saw_leaf_cert = false;
  12494. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12495. if (ctx.cert) {
  12496. callback_count++;
  12497. // We should see at least one certificate (the leaf)
  12498. std::string cn = ctx.subject_cn();
  12499. if (!cn.empty()) { saw_leaf_cert = true; }
  12500. // Verify context fields are populated
  12501. EXPECT_NE(ctx.session, nullptr);
  12502. EXPECT_GE(ctx.depth, 0);
  12503. }
  12504. return true;
  12505. });
  12506. auto res = cli.Get("/test");
  12507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12508. EXPECT_GT(callback_count, 0);
  12509. EXPECT_TRUE(saw_leaf_cert);
  12510. }
  12511. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12512. using httplib::tls::TlsError;
  12513. // Test that verify_error_to_string returns empty for success
  12514. std::string success_str = TlsError::verify_error_to_string(0);
  12515. EXPECT_TRUE(success_str.empty());
  12516. // Test that verify_error_to_string returns non-empty for error codes
  12517. // Using a common error code (certificate expired)
  12518. std::string error_str =
  12519. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12520. EXPECT_FALSE(error_str.empty());
  12521. }
  12522. TEST(SessionVerifierTest, CertificateAccepted) {
  12523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12524. ASSERT_TRUE(svr.is_valid());
  12525. svr.Get("/test", [](const Request &, Response &res) {
  12526. res.set_content("ok", "text/plain");
  12527. });
  12528. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12529. auto se = detail::scope_exit([&] {
  12530. svr.stop();
  12531. t.join();
  12532. });
  12533. svr.wait_until_ready();
  12534. SSLClient cli(HOST, PORT);
  12535. cli.enable_server_certificate_verification(false);
  12536. cli.set_connection_timeout(30);
  12537. bool callback_called = false;
  12538. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12539. EXPECT_NE(session, nullptr);
  12540. callback_called = true;
  12541. return SSLVerifierResponse::CertificateAccepted;
  12542. });
  12543. auto res = cli.Get("/test");
  12544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12545. EXPECT_EQ(200, res->status);
  12546. EXPECT_TRUE(callback_called);
  12547. }
  12548. TEST(SessionVerifierTest, CertificateRejected) {
  12549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12550. ASSERT_TRUE(svr.is_valid());
  12551. svr.Get("/test", [](const Request &, Response &res) {
  12552. res.set_content("ok", "text/plain");
  12553. });
  12554. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12555. auto se = detail::scope_exit([&] {
  12556. svr.stop();
  12557. t.join();
  12558. });
  12559. svr.wait_until_ready();
  12560. SSLClient cli(HOST, PORT);
  12561. cli.enable_server_certificate_verification(false);
  12562. cli.set_connection_timeout(30);
  12563. bool callback_called = false;
  12564. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12565. EXPECT_NE(session, nullptr);
  12566. callback_called = true;
  12567. return SSLVerifierResponse::CertificateRejected;
  12568. });
  12569. auto res = cli.Get("/test");
  12570. EXPECT_FALSE(res);
  12571. EXPECT_TRUE(callback_called);
  12572. }
  12573. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12575. ASSERT_TRUE(svr.is_valid());
  12576. svr.Get("/test", [](const Request &, Response &res) {
  12577. res.set_content("ok", "text/plain");
  12578. });
  12579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12580. auto se = detail::scope_exit([&] {
  12581. svr.stop();
  12582. t.join();
  12583. });
  12584. svr.wait_until_ready();
  12585. // NoDecisionMade with verification disabled should succeed (no default check)
  12586. SSLClient cli(HOST, PORT);
  12587. cli.enable_server_certificate_verification(false);
  12588. cli.set_connection_timeout(30);
  12589. bool callback_called = false;
  12590. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12591. EXPECT_NE(session, nullptr);
  12592. callback_called = true;
  12593. return SSLVerifierResponse::NoDecisionMade;
  12594. });
  12595. auto res = cli.Get("/test");
  12596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12597. EXPECT_EQ(200, res->status);
  12598. EXPECT_TRUE(callback_called);
  12599. }
  12600. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12602. ASSERT_TRUE(svr.is_valid());
  12603. svr.Get("/test", [](const Request &, Response &res) {
  12604. res.set_content("ok", "text/plain");
  12605. });
  12606. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12607. auto se = detail::scope_exit([&] {
  12608. svr.stop();
  12609. t.join();
  12610. });
  12611. svr.wait_until_ready();
  12612. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12613. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12614. // so we only check that the request fails, not whether the callback was
  12615. // called.
  12616. SSLClient cli(HOST, PORT);
  12617. cli.enable_server_certificate_verification(true);
  12618. cli.set_connection_timeout(30);
  12619. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12620. EXPECT_NE(session, nullptr);
  12621. return SSLVerifierResponse::NoDecisionMade;
  12622. });
  12623. auto res = cli.Get("/test");
  12624. EXPECT_FALSE(res);
  12625. }
  12626. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12627. // Test SSL server using PemMemory constructor with client CA certificates
  12628. // Read PEM files
  12629. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12630. read_file(SERVER_CERT_FILE, server_cert_pem);
  12631. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12632. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12633. // Create SSLServer with PemMemory constructor including client CA
  12634. SSLServer::PemMemory server_pem = {
  12635. server_cert_pem.c_str(),
  12636. server_cert_pem.size(),
  12637. server_key_pem.c_str(),
  12638. server_key_pem.size(),
  12639. client_ca_pem.c_str(),
  12640. client_ca_pem.size(),
  12641. nullptr // no password for server key
  12642. };
  12643. SSLServer svr(server_pem);
  12644. ASSERT_TRUE(svr.is_valid());
  12645. // No SSL error should be recorded for valid setup
  12646. EXPECT_EQ(0, svr.ssl_last_error());
  12647. // Set up server endpoints
  12648. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12649. res.set_content("ok", "text/plain");
  12650. });
  12651. // Start server in a thread
  12652. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12653. svr.wait_until_ready();
  12654. // Connect with client certificate (using constructor with paths)
  12655. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12656. cli.enable_server_certificate_verification(false);
  12657. auto res = cli.Get("/test-pem-ca");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. EXPECT_EQ(200, res->status);
  12660. EXPECT_EQ("ok", res->body);
  12661. svr.stop();
  12662. server_thread.join();
  12663. }
  12664. #endif
  12665. #ifdef _WIN32
  12666. TEST(CleanupTest, WSACleanup) {
  12667. int ret = WSACleanup();
  12668. ASSERT_EQ(0, ret);
  12669. }
  12670. #endif
  12671. #ifndef CPPHTTPLIB_SSL_ENABLED
  12672. TEST(NoSSLSupport, SimpleInterface) {
  12673. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12674. }
  12675. #endif
  12676. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12677. TEST(InvalidScheme, SimpleInterface) {
  12678. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12679. }
  12680. #endif
  12681. TEST(NoScheme, SimpleInterface) {
  12682. Client cli("yahoo.com:80");
  12683. ASSERT_TRUE(cli.is_valid());
  12684. }
  12685. TEST(SendAPI, SimpleInterface_Online) {
  12686. Client cli("http://yahoo.com");
  12687. Request req;
  12688. req.method = "GET";
  12689. req.path = "/";
  12690. auto res = cli.send(req);
  12691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12692. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12693. }
  12694. TEST(SendAPI, WithParamsInRequest) {
  12695. Server svr;
  12696. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12697. EXPECT_TRUE(req.has_param("test"));
  12698. EXPECT_EQ("test_value", req.get_param_value("test"));
  12699. });
  12700. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12701. auto se = detail::scope_exit([&] {
  12702. svr.stop();
  12703. t.join();
  12704. ASSERT_FALSE(svr.is_running());
  12705. });
  12706. svr.wait_until_ready();
  12707. Client cli(HOST, PORT);
  12708. {
  12709. Request req;
  12710. req.method = "GET";
  12711. req.path = "/";
  12712. req.params.emplace("test", "test_value");
  12713. auto res = cli.send(req);
  12714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12715. }
  12716. {
  12717. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12719. }
  12720. }
  12721. TEST(ClientImplMethods, GetSocketTest) {
  12722. httplib::Server svr;
  12723. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12724. res.status = StatusCode::OK_200;
  12725. });
  12726. auto port = svr.bind_to_any_port("127.0.0.1");
  12727. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12728. auto se = detail::scope_exit([&] {
  12729. svr.stop();
  12730. thread.join();
  12731. ASSERT_FALSE(svr.is_running());
  12732. });
  12733. svr.wait_until_ready();
  12734. {
  12735. httplib::Client cli("127.0.0.1", port);
  12736. cli.set_keep_alive(true);
  12737. // Use the behavior of cpp-httplib of opening the connection
  12738. // only when the first request happens. If that changes,
  12739. // this test would be obsolete.
  12740. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12741. // This also implicitly tests the server. But other tests would fail much
  12742. // earlier than this one to be considered.
  12743. auto res = cli.Get("/");
  12744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12745. EXPECT_EQ(StatusCode::OK_200, res->status);
  12746. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12747. }
  12748. }
  12749. #ifdef CPPHTTPLIB_SSL_ENABLED
  12750. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12751. Client cli("http://yahoo.com");
  12752. auto res = cli.Get("/");
  12753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12754. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12755. cli.set_follow_location(true);
  12756. res = cli.Get("/");
  12757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12758. EXPECT_EQ(StatusCode::OK_200, res->status);
  12759. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12760. }
  12761. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12762. Client cli("https://yahoo.com");
  12763. auto res = cli.Get("/");
  12764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12766. cli.set_follow_location(true);
  12767. res = cli.Get("/");
  12768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12769. EXPECT_EQ(StatusCode::OK_200, res->status);
  12770. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12771. }
  12772. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12773. Client cli("https://yahoo.com");
  12774. auto res = cli.Get("/");
  12775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12776. ASSERT_FALSE(!res);
  12777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12778. ASSERT_FALSE(res == nullptr);
  12779. ASSERT_TRUE(res != nullptr);
  12780. EXPECT_EQ(Error::Success, res.error());
  12781. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12782. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12783. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12784. cli.set_follow_location(true);
  12785. res = cli.Get("/");
  12786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12787. EXPECT_EQ(Error::Success, res.error());
  12788. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12789. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12790. EXPECT_EQ(StatusCode::OK_200, res->status);
  12791. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12792. }
  12793. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12794. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12795. Client cli("https://cdnjs.cloudflare.com");
  12796. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12797. Headers{{"Accept-Encoding", "br"}});
  12798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12799. EXPECT_EQ(StatusCode::OK_200, res->status);
  12800. EXPECT_EQ(287630U, res->body.size());
  12801. EXPECT_EQ("application/javascript; charset=utf-8",
  12802. res->get_header_value("Content-Type"));
  12803. }
  12804. #endif
  12805. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12806. #undef REDIR_HOST // Silence compiler warning
  12807. #define REDIR_HOST "https://httpbingo.org"
  12808. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12809. Client cli(REDIR_HOST);
  12810. cli.set_follow_location(true);
  12811. auto res =
  12812. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12814. EXPECT_EQ(StatusCode::OK_200, res->status);
  12815. }
  12816. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12817. Client cli(REDIR_HOST);
  12818. cli.set_follow_location(true);
  12819. Params params;
  12820. params.emplace("url", "http://example.com");
  12821. params.emplace("status_code", "302");
  12822. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12824. EXPECT_EQ(StatusCode::OK_200, res->status);
  12825. }
  12826. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12827. Client cli(REDIR_HOST);
  12828. cli.set_follow_location(true);
  12829. Params params;
  12830. params.emplace("url", "http://example.com");
  12831. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12833. EXPECT_EQ(StatusCode::OK_200, res->status);
  12834. }
  12835. TEST(HttpToHttpsRedirectTest, CertFile) {
  12836. auto ssl_port = PORT + 1;
  12837. Server svr;
  12838. ASSERT_TRUE(svr.is_valid());
  12839. svr.Get("/index", [&](const Request &, Response &res) {
  12840. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12841. "/index");
  12842. svr.stop();
  12843. });
  12844. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12845. ASSERT_TRUE(ssl_svr.is_valid());
  12846. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12847. res.set_content("test", "text/plain");
  12848. ssl_svr.stop();
  12849. });
  12850. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12851. thread t2 =
  12852. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12853. auto se = detail::scope_exit([&] {
  12854. t2.join();
  12855. t.join();
  12856. ASSERT_FALSE(svr.is_running());
  12857. });
  12858. svr.wait_until_ready();
  12859. ssl_svr.wait_until_ready();
  12860. Client cli("127.0.0.1", PORT);
  12861. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12862. cli.enable_server_certificate_verification(true);
  12863. cli.set_follow_location(true);
  12864. cli.set_connection_timeout(30);
  12865. auto res = cli.Get("/index");
  12866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12867. ASSERT_EQ(StatusCode::OK_200, res->status);
  12868. }
  12869. TEST(SSLClientRedirectTest, CertFile) {
  12870. auto ssl_port = PORT + 1;
  12871. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12872. ASSERT_TRUE(ssl_svr1.is_valid());
  12873. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12874. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12875. "/index");
  12876. ssl_svr1.stop();
  12877. });
  12878. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12879. ASSERT_TRUE(ssl_svr2.is_valid());
  12880. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12881. res.set_content("test", "text/plain");
  12882. ssl_svr2.stop();
  12883. });
  12884. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12885. thread t2 =
  12886. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12887. auto se = detail::scope_exit([&] {
  12888. t2.join();
  12889. t.join();
  12890. ASSERT_FALSE(ssl_svr1.is_running());
  12891. });
  12892. ssl_svr1.wait_until_ready();
  12893. ssl_svr2.wait_until_ready();
  12894. SSLClient cli("127.0.0.1", PORT);
  12895. std::string cert;
  12896. read_file(SERVER_CERT2_FILE, cert);
  12897. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12898. cli.enable_server_certificate_verification(true);
  12899. cli.set_follow_location(true);
  12900. cli.set_connection_timeout(30);
  12901. auto res = cli.Get("/index");
  12902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12903. ASSERT_EQ(StatusCode::OK_200, res->status);
  12904. }
  12905. #endif
  12906. #ifdef CPPHTTPLIB_SSL_ENABLED
  12907. // Test that set_ca_cert_store() skips system certs (consistent with
  12908. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12909. // should be trusted - system certs should NOT be loaded.
  12910. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12911. // Load a specific cert that is NOT a system CA cert
  12912. std::string cert;
  12913. read_file(SERVER_CERT2_FILE, cert);
  12914. SSLClient cli("google.com");
  12915. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12916. cli.enable_server_certificate_verification(true);
  12917. // This should FAIL because:
  12918. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12919. // 2. System certs should NOT be loaded when custom store is set
  12920. // If system certs WERE loaded, this would succeed
  12921. auto res = cli.Get("/");
  12922. ASSERT_FALSE(res);
  12923. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12924. }
  12925. // Same as above, but through the native store handle path. Regression test:
  12926. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12927. // merged system certs into the user-provided store.
  12928. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12929. std::string cert;
  12930. read_file(SERVER_CERT2_FILE, cert);
  12931. SSLClient cli("google.com");
  12932. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12933. cli.enable_server_certificate_verification(true);
  12934. auto res = cli.Get("/");
  12935. ASSERT_FALSE(res);
  12936. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12937. }
  12938. // A custom store set via the native handle must still verify a server whose
  12939. // cert it does contain.
  12940. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12941. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12942. ASSERT_TRUE(svr.is_valid());
  12943. svr.Get("/test", [&](const Request &, Response &res) {
  12944. res.set_content("test", "text/plain");
  12945. });
  12946. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12947. auto se = detail::scope_exit([&] {
  12948. svr.stop();
  12949. t.join();
  12950. ASSERT_FALSE(svr.is_running());
  12951. });
  12952. svr.wait_until_ready();
  12953. SSLClient cli("127.0.0.1", PORT);
  12954. std::string cert;
  12955. read_file(SERVER_CERT2_FILE, cert);
  12956. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12957. cli.enable_server_certificate_verification(true);
  12958. cli.set_connection_timeout(30);
  12959. auto res = cli.Get("/test");
  12960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12961. ASSERT_EQ(StatusCode::OK_200, res->status);
  12962. }
  12963. // CA certs loaded through the universal Client must be transferred to the
  12964. // client created internally for following an HTTPS redirect. Regression test:
  12965. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12966. // the CA data for redirect transfer.
  12967. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12968. auto ssl_port = PORT + 1;
  12969. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12970. ASSERT_TRUE(ssl_svr1.is_valid());
  12971. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12972. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12973. "/index");
  12974. });
  12975. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12976. ASSERT_TRUE(ssl_svr2.is_valid());
  12977. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12978. res.set_content("test", "text/plain");
  12979. });
  12980. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12981. thread t2 =
  12982. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12983. auto se = detail::scope_exit([&] {
  12984. ssl_svr2.stop();
  12985. ssl_svr1.stop();
  12986. t2.join();
  12987. t.join();
  12988. ASSERT_FALSE(ssl_svr1.is_running());
  12989. });
  12990. ssl_svr1.wait_until_ready();
  12991. ssl_svr2.wait_until_ready();
  12992. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12993. std::string cert;
  12994. read_file(SERVER_CERT2_FILE, cert);
  12995. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12996. cli.enable_server_certificate_verification(true);
  12997. cli.set_follow_location(true);
  12998. cli.set_connection_timeout(30);
  12999. auto res = cli.Get("/index");
  13000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13001. ASSERT_EQ(StatusCode::OK_200, res->status);
  13002. }
  13003. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13004. // so a host signed by a system CA verifies even though a custom CA is set
  13005. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13006. std::string cert;
  13007. read_file(SERVER_CERT2_FILE, cert);
  13008. SSLClient cli("google.com");
  13009. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13010. cli.enable_system_ca(true);
  13011. cli.enable_server_certificate_verification(true);
  13012. auto res = cli.Get("/");
  13013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13014. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13015. }
  13016. // The custom CA remains effective when combined with the system CA
  13017. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13018. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13019. ASSERT_TRUE(svr.is_valid());
  13020. svr.Get("/test", [&](const Request &, Response &res) {
  13021. res.set_content("test", "text/plain");
  13022. });
  13023. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13024. auto se = detail::scope_exit([&] {
  13025. svr.stop();
  13026. t.join();
  13027. ASSERT_FALSE(svr.is_running());
  13028. });
  13029. svr.wait_until_ready();
  13030. SSLClient cli("127.0.0.1", PORT);
  13031. std::string cert;
  13032. read_file(SERVER_CERT2_FILE, cert);
  13033. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13034. cli.enable_system_ca(true);
  13035. cli.enable_server_certificate_verification(true);
  13036. cli.set_connection_timeout(30);
  13037. auto res = cli.Get("/test");
  13038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13039. ASSERT_EQ(StatusCode::OK_200, res->status);
  13040. }
  13041. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13042. // skip chain verification entirely (only the certificate identity was
  13043. // checked), so a server presenting an untrusted certificate with a matching
  13044. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13045. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13046. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13047. ASSERT_TRUE(svr.is_valid());
  13048. svr.Get("/test", [&](const Request &, Response &res) {
  13049. res.set_content("test", "text/plain");
  13050. });
  13051. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13052. auto se = detail::scope_exit([&] {
  13053. svr.stop();
  13054. t.join();
  13055. ASSERT_FALSE(svr.is_running());
  13056. });
  13057. svr.wait_until_ready();
  13058. SSLClient cli("127.0.0.1", PORT);
  13059. std::string cert;
  13060. // A trusted CA that did not sign the server certificate. The server cert
  13061. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13062. // this connection.
  13063. read_file(CLIENT_CA_CERT_FILE, cert);
  13064. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13065. cli.enable_server_certificate_verification(true);
  13066. cli.set_connection_timeout(30);
  13067. auto res = cli.Get("/test");
  13068. ASSERT_FALSE(res);
  13069. }
  13070. // enable_system_ca(false) prevents system CA loading entirely
  13071. TEST(SSLClientTest, DisableSystemCa_Online) {
  13072. SSLClient cli("google.com");
  13073. cli.enable_system_ca(false);
  13074. cli.enable_server_certificate_verification(true);
  13075. auto res = cli.Get("/");
  13076. ASSERT_FALSE(res);
  13077. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13078. // itself when the CA chain is empty
  13079. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13080. res.error() == Error::SSLConnection);
  13081. }
  13082. // The universal Client forwards enable_system_ca()
  13083. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13084. std::string cert;
  13085. read_file(SERVER_CERT2_FILE, cert);
  13086. Client cli("https://google.com");
  13087. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13088. cli.enable_system_ca(true);
  13089. cli.enable_server_certificate_verification(true);
  13090. auto res = cli.Get("/");
  13091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13093. }
  13094. // The system CA policy must carry over to the client created internally for
  13095. // following a cross-host HTTPS redirect
  13096. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13097. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13098. ASSERT_TRUE(svr.is_valid());
  13099. svr.Get("/index", [&](const Request &, Response &res) {
  13100. res.set_redirect("https://www.google.com/");
  13101. });
  13102. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13103. auto se = detail::scope_exit([&] {
  13104. svr.stop();
  13105. t.join();
  13106. ASSERT_FALSE(svr.is_running());
  13107. });
  13108. svr.wait_until_ready();
  13109. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13110. std::string cert;
  13111. read_file(SERVER_CERT2_FILE, cert);
  13112. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13113. cli.enable_system_ca(true);
  13114. cli.enable_server_certificate_verification(true);
  13115. cli.set_follow_location(true);
  13116. cli.set_connection_timeout(30);
  13117. // Receiving any response proves the redirect client completed the TLS
  13118. // handshake with a system-CA-signed host
  13119. auto res = cli.Get("/index");
  13120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13121. }
  13122. TEST(MultipartFormDataTest, LargeData) {
  13123. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13124. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13125. const ContentReader &content_reader) {
  13126. if (req.is_multipart_form_data()) {
  13127. std::vector<FormData> items;
  13128. content_reader(
  13129. [&](const FormData &file) {
  13130. items.push_back(file);
  13131. return true;
  13132. },
  13133. [&](const char *data, size_t data_length) {
  13134. items.back().content.append(data, data_length);
  13135. return true;
  13136. });
  13137. EXPECT_TRUE(std::string(items[0].name) == "document");
  13138. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13139. EXPECT_TRUE(items[0].filename == "2MB_data");
  13140. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13141. EXPECT_TRUE(items[1].name == "hello");
  13142. EXPECT_TRUE(items[1].content == "world");
  13143. EXPECT_TRUE(items[1].filename == "");
  13144. EXPECT_TRUE(items[1].content_type == "");
  13145. } else {
  13146. std::string body;
  13147. content_reader([&](const char *data, size_t data_length) {
  13148. body.append(data, data_length);
  13149. return true;
  13150. });
  13151. }
  13152. });
  13153. auto port = svr.bind_to_any_port(HOST);
  13154. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13155. auto se = detail::scope_exit([&] {
  13156. svr.stop();
  13157. t.join();
  13158. ASSERT_FALSE(svr.is_running());
  13159. });
  13160. svr.wait_until_ready();
  13161. {
  13162. std::string data(1024 * 1024 * 2, '.');
  13163. std::stringstream buffer;
  13164. buffer << data;
  13165. SSLClient cli(HOST, port);
  13166. cli.enable_server_certificate_verification(false);
  13167. UploadFormDataItems items{
  13168. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13169. {"hello", "world", "", ""},
  13170. };
  13171. auto res = cli.Post("/post", items);
  13172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13173. ASSERT_EQ(StatusCode::OK_200, res->status);
  13174. }
  13175. }
  13176. TEST(MultipartFormDataTest, DataProviderItems) {
  13177. std::random_device seed_gen;
  13178. std::mt19937 random(seed_gen());
  13179. std::string rand1;
  13180. rand1.resize(1000);
  13181. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13182. std::string rand2;
  13183. rand2.resize(3000);
  13184. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13186. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13187. const ContentReader &content_reader) {
  13188. ASSERT_FALSE(req.is_multipart_form_data());
  13189. std::string body;
  13190. content_reader([&](const char *data, size_t data_length) {
  13191. body.append(data, data_length);
  13192. return true;
  13193. });
  13194. EXPECT_EQ(body, "");
  13195. });
  13196. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13197. const ContentReader &content_reader) {
  13198. ASSERT_TRUE(req.is_multipart_form_data());
  13199. std::vector<FormData> items;
  13200. content_reader(
  13201. [&](const FormData &file) {
  13202. items.push_back(file);
  13203. return true;
  13204. },
  13205. [&](const char *data, size_t data_length) {
  13206. items.back().content.append(data, data_length);
  13207. return true;
  13208. });
  13209. ASSERT_TRUE(items.size() == 2);
  13210. EXPECT_EQ(std::string(items[0].name), "name1");
  13211. EXPECT_EQ(items[0].content, "Testing123");
  13212. EXPECT_EQ(items[0].filename, "filename1");
  13213. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13214. EXPECT_EQ(items[1].name, "name2");
  13215. EXPECT_EQ(items[1].content, "Testing456");
  13216. EXPECT_EQ(items[1].filename, "");
  13217. EXPECT_EQ(items[1].content_type, "");
  13218. });
  13219. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13220. const ContentReader &content_reader) {
  13221. ASSERT_TRUE(req.is_multipart_form_data());
  13222. std::vector<FormData> items;
  13223. content_reader(
  13224. [&](const FormData &file) {
  13225. items.push_back(file);
  13226. return true;
  13227. },
  13228. [&](const char *data, size_t data_length) {
  13229. items.back().content.append(data, data_length);
  13230. return true;
  13231. });
  13232. ASSERT_TRUE(items.size() == 2);
  13233. EXPECT_EQ(items[0].name, "name3");
  13234. EXPECT_EQ(items[0].content, rand1);
  13235. EXPECT_EQ(items[0].filename, "filename3");
  13236. EXPECT_EQ(items[0].content_type, "");
  13237. EXPECT_EQ(items[1].name, "name4");
  13238. EXPECT_EQ(items[1].content, rand2);
  13239. EXPECT_EQ(items[1].filename, "filename4");
  13240. EXPECT_EQ(items[1].content_type, "");
  13241. });
  13242. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13243. const ContentReader &content_reader) {
  13244. ASSERT_TRUE(req.is_multipart_form_data());
  13245. std::vector<FormData> items;
  13246. content_reader(
  13247. [&](const FormData &file) {
  13248. items.push_back(file);
  13249. return true;
  13250. },
  13251. [&](const char *data, size_t data_length) {
  13252. items.back().content.append(data, data_length);
  13253. return true;
  13254. });
  13255. ASSERT_TRUE(items.size() == 4);
  13256. EXPECT_EQ(std::string(items[0].name), "name1");
  13257. EXPECT_EQ(items[0].content, "Testing123");
  13258. EXPECT_EQ(items[0].filename, "filename1");
  13259. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13260. EXPECT_EQ(items[1].name, "name2");
  13261. EXPECT_EQ(items[1].content, "Testing456");
  13262. EXPECT_EQ(items[1].filename, "");
  13263. EXPECT_EQ(items[1].content_type, "");
  13264. EXPECT_EQ(items[2].name, "name3");
  13265. EXPECT_EQ(items[2].content, rand1);
  13266. EXPECT_EQ(items[2].filename, "filename3");
  13267. EXPECT_EQ(items[2].content_type, "");
  13268. EXPECT_EQ(items[3].name, "name4");
  13269. EXPECT_EQ(items[3].content, rand2);
  13270. EXPECT_EQ(items[3].filename, "filename4");
  13271. EXPECT_EQ(items[3].content_type, "");
  13272. });
  13273. auto port = svr.bind_to_any_port("localhost");
  13274. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13275. auto se = detail::scope_exit([&] {
  13276. svr.stop();
  13277. t.join();
  13278. ASSERT_FALSE(svr.is_running());
  13279. });
  13280. svr.wait_until_ready();
  13281. {
  13282. SSLClient cli("localhost", port);
  13283. cli.enable_server_certificate_verification(false);
  13284. UploadFormDataItems items{
  13285. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13286. {"name2", "Testing456", "", ""}, // not a file
  13287. };
  13288. {
  13289. auto res = cli.Post("/post-none", {}, {}, {});
  13290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13291. ASSERT_EQ(StatusCode::OK_200, res->status);
  13292. }
  13293. FormDataProviderItems providers;
  13294. {
  13295. auto res =
  13296. cli.Post("/post-items", {}, items, providers); // empty providers
  13297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13298. ASSERT_EQ(StatusCode::OK_200, res->status);
  13299. }
  13300. providers.push_back({"name3",
  13301. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13302. // test the offset is given correctly at each step
  13303. if (!offset)
  13304. sink.os.write(rand1.data(), 30);
  13305. else if (offset == 30)
  13306. sink.os.write(rand1.data() + 30, 300);
  13307. else if (offset == 330)
  13308. sink.os.write(rand1.data() + 330, 670);
  13309. else if (offset == rand1.size())
  13310. sink.done();
  13311. return true;
  13312. },
  13313. "filename3",
  13314. {}});
  13315. providers.push_back({"name4",
  13316. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13317. // test the offset is given correctly at each step
  13318. if (!offset)
  13319. sink.os.write(rand2.data(), 2000);
  13320. else if (offset == 2000)
  13321. sink.os.write(rand2.data() + 2000, 1);
  13322. else if (offset == 2001)
  13323. sink.os.write(rand2.data() + 2001, 999);
  13324. else if (offset == rand2.size())
  13325. sink.done();
  13326. return true;
  13327. },
  13328. "filename4",
  13329. {}});
  13330. {
  13331. auto res = cli.Post("/post-providers", {}, {}, providers);
  13332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13333. ASSERT_EQ(StatusCode::OK_200, res->status);
  13334. }
  13335. {
  13336. auto res = cli.Post("/post-both", {}, items, providers);
  13337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13338. ASSERT_EQ(StatusCode::OK_200, res->status);
  13339. }
  13340. }
  13341. }
  13342. TEST(MultipartFormDataTest, BadHeader) {
  13343. Server svr;
  13344. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13345. res.set_content("ok", "text/plain");
  13346. });
  13347. thread t = thread([&] { svr.listen(HOST, PORT); });
  13348. auto se = detail::scope_exit([&] {
  13349. svr.stop();
  13350. t.join();
  13351. ASSERT_FALSE(svr.is_running());
  13352. });
  13353. svr.wait_until_ready();
  13354. const std::string body =
  13355. "This is the preamble. It is to be ignored, though it\r\n"
  13356. "is a handy place for composition agents to include an\r\n"
  13357. "explanatory note to non-MIME conformant readers.\r\n"
  13358. "\r\n"
  13359. "\r\n"
  13360. "--simple boundary\r\n"
  13361. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13362. ": BAD...\r\n"
  13363. "\r\n"
  13364. "value1\r\n"
  13365. "--simple boundary\r\n"
  13366. "Content-Disposition: form-data; name=\"field2\"; "
  13367. "filename=\"example.txt\"\r\n"
  13368. "\r\n"
  13369. "value2\r\n"
  13370. "--simple boundary--\r\n"
  13371. "This is the epilogue. It is also to be ignored.\r\n";
  13372. std::string content_type =
  13373. R"(multipart/form-data; boundary="simple boundary")";
  13374. Client cli(HOST, PORT);
  13375. auto res = cli.Post("/post", body, content_type.c_str());
  13376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13377. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13378. }
  13379. TEST(MultipartFormDataTest, WithPreamble) {
  13380. Server svr;
  13381. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13382. res.set_content("ok", "text/plain");
  13383. });
  13384. thread t = thread([&] { svr.listen(HOST, PORT); });
  13385. auto se = detail::scope_exit([&] {
  13386. svr.stop();
  13387. t.join();
  13388. ASSERT_FALSE(svr.is_running());
  13389. });
  13390. svr.wait_until_ready();
  13391. const std::string body =
  13392. "This is the preamble. It is to be ignored, though it\r\n"
  13393. "is a handy place for composition agents to include an\r\n"
  13394. "explanatory note to non-MIME conformant readers.\r\n"
  13395. "\r\n"
  13396. "\r\n"
  13397. "--simple boundary\r\n"
  13398. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13399. "\r\n"
  13400. "value1\r\n"
  13401. "--simple boundary\r\n"
  13402. "Content-Disposition: form-data; name=\"field2\"; "
  13403. "filename=\"example.txt\"\r\n"
  13404. "\r\n"
  13405. "value2\r\n"
  13406. "--simple boundary--\r\n"
  13407. "This is the epilogue. It is also to be ignored.\r\n";
  13408. std::string content_type =
  13409. R"(multipart/form-data; boundary="simple boundary")";
  13410. Client cli(HOST, PORT);
  13411. auto res = cli.Post("/post", body, content_type.c_str());
  13412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13413. EXPECT_EQ(StatusCode::OK_200, res->status);
  13414. }
  13415. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13417. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13418. const ContentReader &content_reader) {
  13419. if (req.is_multipart_form_data()) {
  13420. std::vector<FormData> items;
  13421. content_reader(
  13422. [&](const FormData &file) {
  13423. items.push_back(file);
  13424. return true;
  13425. },
  13426. [&](const char *data, size_t data_length) {
  13427. items.back().content.append(data, data_length);
  13428. return true;
  13429. });
  13430. EXPECT_TRUE(std::string(items[0].name) == "document");
  13431. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13432. EXPECT_TRUE(items[0].filename == "2MB_data");
  13433. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13434. EXPECT_TRUE(items[1].name == "hello");
  13435. EXPECT_TRUE(items[1].content == "world");
  13436. EXPECT_TRUE(items[1].filename == "");
  13437. EXPECT_TRUE(items[1].content_type == "");
  13438. } else {
  13439. std::string body;
  13440. content_reader([&](const char *data, size_t data_length) {
  13441. body.append(data, data_length);
  13442. return true;
  13443. });
  13444. }
  13445. });
  13446. auto port = svr.bind_to_any_port("localhost");
  13447. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13448. auto se = detail::scope_exit([&] {
  13449. svr.stop();
  13450. t.join();
  13451. ASSERT_FALSE(svr.is_running());
  13452. });
  13453. svr.wait_until_ready();
  13454. {
  13455. std::string data(1024 * 1024 * 2, '.');
  13456. std::stringstream buffer;
  13457. buffer << data;
  13458. SSLClient cli("localhost", port);
  13459. cli.enable_server_certificate_verification(false);
  13460. UploadFormDataItems items{
  13461. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13462. {"hello", "world", "", ""},
  13463. };
  13464. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13466. ASSERT_EQ(StatusCode::OK_200, res->status);
  13467. }
  13468. }
  13469. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13470. std::string data(1024 * 1024 * 2, '&');
  13471. std::stringstream buffer;
  13472. buffer << data;
  13473. Client cli("https://localhost:8080");
  13474. UploadFormDataItems items{
  13475. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13476. {"hello", "world", "", ""},
  13477. };
  13478. for (const char &c : " \t\r\n") {
  13479. auto res =
  13480. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13481. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13482. ASSERT_FALSE(res);
  13483. }
  13484. }
  13485. TEST(MultipartFormDataTest, PutFormData) {
  13486. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13487. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13488. const ContentReader &content_reader) {
  13489. if (req.is_multipart_form_data()) {
  13490. std::vector<FormData> items;
  13491. content_reader(
  13492. [&](const FormData &file) {
  13493. items.push_back(file);
  13494. return true;
  13495. },
  13496. [&](const char *data, size_t data_length) {
  13497. items.back().content.append(data, data_length);
  13498. return true;
  13499. });
  13500. EXPECT_TRUE(std::string(items[0].name) == "document");
  13501. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13502. EXPECT_TRUE(items[0].filename == "2MB_data");
  13503. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13504. EXPECT_TRUE(items[1].name == "hello");
  13505. EXPECT_TRUE(items[1].content == "world");
  13506. EXPECT_TRUE(items[1].filename == "");
  13507. EXPECT_TRUE(items[1].content_type == "");
  13508. } else {
  13509. std::string body;
  13510. content_reader([&](const char *data, size_t data_length) {
  13511. body.append(data, data_length);
  13512. return true;
  13513. });
  13514. }
  13515. });
  13516. auto port = svr.bind_to_any_port("localhost");
  13517. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13518. auto se = detail::scope_exit([&] {
  13519. svr.stop();
  13520. t.join();
  13521. ASSERT_FALSE(svr.is_running());
  13522. });
  13523. svr.wait_until_ready();
  13524. {
  13525. std::string data(1024 * 1024 * 2, '&');
  13526. std::stringstream buffer;
  13527. buffer << data;
  13528. SSLClient cli("localhost", port);
  13529. cli.enable_server_certificate_verification(false);
  13530. UploadFormDataItems items{
  13531. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13532. {"hello", "world", "", ""},
  13533. };
  13534. auto res = cli.Put("/put", items);
  13535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13536. ASSERT_EQ(StatusCode::OK_200, res->status);
  13537. }
  13538. }
  13539. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13541. svr.Put("/put_customboundary",
  13542. [&](const Request &req, const Response & /*res*/,
  13543. const ContentReader &content_reader) {
  13544. if (req.is_multipart_form_data()) {
  13545. std::vector<FormData> items;
  13546. content_reader(
  13547. [&](const FormData &file) {
  13548. items.push_back(file);
  13549. return true;
  13550. },
  13551. [&](const char *data, size_t data_length) {
  13552. items.back().content.append(data, data_length);
  13553. return true;
  13554. });
  13555. EXPECT_TRUE(std::string(items[0].name) == "document");
  13556. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13557. EXPECT_TRUE(items[0].filename == "2MB_data");
  13558. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13559. EXPECT_TRUE(items[1].name == "hello");
  13560. EXPECT_TRUE(items[1].content == "world");
  13561. EXPECT_TRUE(items[1].filename == "");
  13562. EXPECT_TRUE(items[1].content_type == "");
  13563. } else {
  13564. std::string body;
  13565. content_reader([&](const char *data, size_t data_length) {
  13566. body.append(data, data_length);
  13567. return true;
  13568. });
  13569. }
  13570. });
  13571. auto port = svr.bind_to_any_port("localhost");
  13572. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13573. auto se = detail::scope_exit([&] {
  13574. svr.stop();
  13575. t.join();
  13576. ASSERT_FALSE(svr.is_running());
  13577. });
  13578. svr.wait_until_ready();
  13579. {
  13580. std::string data(1024 * 1024 * 2, '&');
  13581. std::stringstream buffer;
  13582. buffer << data;
  13583. SSLClient cli("localhost", port);
  13584. cli.enable_server_certificate_verification(false);
  13585. UploadFormDataItems items{
  13586. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13587. {"hello", "world", "", ""},
  13588. };
  13589. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13591. ASSERT_EQ(StatusCode::OK_200, res->status);
  13592. }
  13593. }
  13594. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13595. std::string data(1024 * 1024 * 2, '&');
  13596. std::stringstream buffer;
  13597. buffer << data;
  13598. Client cli("https://localhost:8080");
  13599. cli.enable_server_certificate_verification(false);
  13600. UploadFormDataItems items{
  13601. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13602. {"hello", "world", "", ""},
  13603. };
  13604. for (const char &c : " \t\r\n") {
  13605. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13606. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13607. ASSERT_FALSE(res);
  13608. }
  13609. }
  13610. TEST(MultipartFormDataTest, AlternateFilename) {
  13611. auto handled = false;
  13612. Server svr;
  13613. svr.Post("/test", [&](const Request &req, Response &res) {
  13614. ASSERT_EQ(2u, req.form.files.size());
  13615. ASSERT_EQ(1u, req.form.fields.size());
  13616. // Test files
  13617. const auto &file1 = req.form.get_file("file1");
  13618. ASSERT_EQ("file1", file1.name);
  13619. ASSERT_EQ("A.txt", file1.filename);
  13620. ASSERT_EQ("text/plain", file1.content_type);
  13621. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13622. const auto &file2 = req.form.get_file("file2");
  13623. ASSERT_EQ("file2", file2.name);
  13624. ASSERT_EQ("a.html", file2.filename);
  13625. ASSERT_EQ("text/html", file2.content_type);
  13626. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13627. file2.content);
  13628. // Test text field
  13629. const auto &text = req.form.get_field("text");
  13630. ASSERT_EQ("text default", text);
  13631. res.set_content("ok", "text/plain");
  13632. handled = true;
  13633. });
  13634. thread t = thread([&] { svr.listen(HOST, PORT); });
  13635. auto se = detail::scope_exit([&] {
  13636. svr.stop();
  13637. t.join();
  13638. ASSERT_FALSE(svr.is_running());
  13639. ASSERT_TRUE(handled);
  13640. });
  13641. svr.wait_until_ready();
  13642. auto req = "POST /test HTTP/1.1\r\n"
  13643. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13644. "Content-Length: 399\r\n"
  13645. "\r\n"
  13646. "----------\r\n"
  13647. "Content-Disposition: form-data; name=\"text\"\r\n"
  13648. "\r\n"
  13649. "text default\r\n"
  13650. "----------\r\n"
  13651. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13652. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13653. "Content-Type: text/plain\r\n"
  13654. "\r\n"
  13655. "Content of a.txt.\r\n"
  13656. "\r\n"
  13657. "----------\r\n"
  13658. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13659. "\"a.html\"\r\n"
  13660. "Content-Type: text/html\r\n"
  13661. "\r\n"
  13662. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13663. "\r\n"
  13664. "------------\r\n";
  13665. ASSERT_TRUE(send_request(1, req));
  13666. }
  13667. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13668. auto handled = false;
  13669. Server svr;
  13670. svr.Post("/test", [&](const Request &req, Response &res) {
  13671. // Case-insensitive "utf-8''" prefix with a long value
  13672. const auto &file = req.form.get_file("file1");
  13673. ASSERT_EQ("file1", file.name);
  13674. // 8000 chars exercises both the Content-Disposition parser and the
  13675. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13676. // Prior to the fix, std::regex_match on this header would cause O(N)
  13677. // stack recursion in libstdc++, leading to SIGSEGV.
  13678. std::string expected_filename(8000, 'A');
  13679. ASSERT_EQ(expected_filename, file.filename);
  13680. res.set_content("ok", "text/plain");
  13681. handled = true;
  13682. });
  13683. thread t = thread([&] { svr.listen(HOST, PORT); });
  13684. auto se = detail::scope_exit([&] {
  13685. svr.stop();
  13686. t.join();
  13687. ASSERT_FALSE(svr.is_running());
  13688. ASSERT_TRUE(handled);
  13689. });
  13690. svr.wait_until_ready();
  13691. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13692. // Regression test for GHSA-qq6v-r583-3h69
  13693. std::string long_filename(8000, 'A');
  13694. std::string body = "----------\r\n"
  13695. "Content-Disposition: form-data; name=\"file1\"; "
  13696. "filename*=\"Utf-8''" +
  13697. long_filename +
  13698. "\"\r\n"
  13699. "\r\n"
  13700. "hello\r\n"
  13701. "------------\r\n";
  13702. auto req = "POST /test HTTP/1.1\r\n"
  13703. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13704. "Content-Length: " +
  13705. std::to_string(body.size()) + "\r\n\r\n" + body;
  13706. ASSERT_TRUE(send_request(1, req));
  13707. }
  13708. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13709. auto handled = false;
  13710. Server svr;
  13711. svr.Post("/test", [&](const Request &req, Response &) {
  13712. ASSERT_EQ(2u, req.form.fields.size());
  13713. const auto &text1 = req.form.get_field("text1");
  13714. ASSERT_EQ("text1", text1);
  13715. const auto &text2 = req.form.get_field("text2");
  13716. ASSERT_EQ("text2", text2);
  13717. handled = true;
  13718. });
  13719. thread t = thread([&] { svr.listen(HOST, PORT); });
  13720. auto se = detail::scope_exit([&] {
  13721. svr.stop();
  13722. t.join();
  13723. ASSERT_FALSE(svr.is_running());
  13724. ASSERT_TRUE(handled);
  13725. });
  13726. svr.wait_until_ready();
  13727. auto req = "POST /test HTTP/1.1\r\n"
  13728. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13729. "Content-Length: 146\r\n"
  13730. "\r\n----------\r\n"
  13731. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13732. "\r\n"
  13733. "text1"
  13734. "\r\n----------\r\n"
  13735. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13736. "\r\n"
  13737. "text2"
  13738. "\r\n------------";
  13739. std::string response;
  13740. ASSERT_TRUE(send_request(1, req, &response));
  13741. ASSERT_EQ("200", response.substr(9, 3));
  13742. }
  13743. TEST(MultipartFormDataTest, ContentLength) {
  13744. auto handled = false;
  13745. Server svr;
  13746. svr.Post("/test", [&](const Request &req, Response &) {
  13747. ASSERT_EQ(2u, req.form.fields.size());
  13748. const auto &text1 = req.form.get_field("text1");
  13749. ASSERT_EQ("text1", text1);
  13750. const auto &text2 = req.form.get_field("text2");
  13751. ASSERT_EQ("text2", text2);
  13752. handled = true;
  13753. });
  13754. thread t = thread([&] { svr.listen(HOST, PORT); });
  13755. auto se = detail::scope_exit([&] {
  13756. svr.stop();
  13757. t.join();
  13758. ASSERT_FALSE(svr.is_running());
  13759. ASSERT_TRUE(handled);
  13760. });
  13761. svr.wait_until_ready();
  13762. auto req = "POST /test HTTP/1.1\r\n"
  13763. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13764. "Content-Length: 167\r\n"
  13765. "\r\n----------\r\n"
  13766. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13767. "Content-Length: 5\r\n"
  13768. "\r\n"
  13769. "text1"
  13770. "\r\n----------\r\n"
  13771. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13772. "\r\n"
  13773. "text2"
  13774. "\r\n------------\r\n";
  13775. std::string response;
  13776. ASSERT_TRUE(send_request(1, req, &response));
  13777. ASSERT_EQ("200", response.substr(9, 3));
  13778. }
  13779. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13780. auto handled = false;
  13781. Server svr;
  13782. svr.Post("/test", [&](const Request &req, Response &) {
  13783. ASSERT_EQ(2u, req.form.fields.size());
  13784. const auto &text1 = req.form.get_field("text1");
  13785. ASSERT_EQ("text1", text1);
  13786. // TODO: Add header access for text fields if needed
  13787. const auto &text2 = req.form.get_field("text2");
  13788. ASSERT_EQ("text2", text2);
  13789. // TODO: Header access for text fields needs to be implemented
  13790. // auto &headers = it->second.headers;
  13791. // ASSERT_EQ(3U, headers.size());
  13792. // auto custom_header = headers.find("x-whatever");
  13793. // ASSERT_TRUE(custom_header != headers.end());
  13794. // ASSERT_NE("customvalue", custom_header->second);
  13795. // ASSERT_EQ("CustomValue", custom_header->second);
  13796. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13797. handled = true;
  13798. });
  13799. thread t = thread([&] { svr.listen(HOST, PORT); });
  13800. auto se = detail::scope_exit([&] {
  13801. svr.stop();
  13802. t.join();
  13803. ASSERT_FALSE(svr.is_running());
  13804. ASSERT_TRUE(handled);
  13805. });
  13806. svr.wait_until_ready();
  13807. auto req = "POST /test HTTP/1.1\r\n"
  13808. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13809. "Content-Length: 232\r\n"
  13810. "\r\n----------\r\n"
  13811. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13812. "Content-Length: 5\r\n"
  13813. "X-Test: 1\r\n"
  13814. "\r\n"
  13815. "text1"
  13816. "\r\n----------\r\n"
  13817. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13818. "Content-Type: text/plain\r\n"
  13819. "X-Whatever: CustomValue\r\n"
  13820. "\r\n"
  13821. "text2"
  13822. "\r\n------------\r\n"
  13823. "That should be disregarded. Not even read";
  13824. std::string response;
  13825. ASSERT_TRUE(send_request(1, req, &response));
  13826. ASSERT_EQ("200", response.substr(9, 3));
  13827. }
  13828. TEST(MultipartFormDataTest, LargeHeader) {
  13829. auto handled = false;
  13830. Server svr;
  13831. svr.Post("/test", [&](const Request &req, Response &) {
  13832. ASSERT_EQ(1u, req.form.fields.size());
  13833. const auto &text = req.form.get_field("name1");
  13834. ASSERT_EQ("text1", text);
  13835. handled = true;
  13836. });
  13837. thread t = thread([&] { svr.listen(HOST, PORT); });
  13838. auto se = detail::scope_exit([&] {
  13839. svr.stop();
  13840. t.join();
  13841. ASSERT_FALSE(svr.is_running());
  13842. ASSERT_TRUE(handled);
  13843. });
  13844. svr.wait_until_ready();
  13845. auto boundary = std::string("cpp-httplib-multipart-data");
  13846. std::string content = "--" + boundary +
  13847. "\r\n"
  13848. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13849. "\r\n"
  13850. "text1\r\n"
  13851. "--" +
  13852. boundary + "--\r\n";
  13853. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13854. "Content-Type: multipart/form-data;boundary=" +
  13855. boundary +
  13856. "\r\n"
  13857. "Content-Length: " +
  13858. std::to_string(content.size()) +
  13859. "\r\n"
  13860. "Dummy-Header: ";
  13861. std::string header_suffix = "\r\n"
  13862. "\r\n";
  13863. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13864. size_t header_dummy_size =
  13865. read_buff_size -
  13866. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13867. auto header_dummy = std::string(header_dummy_size, '@');
  13868. auto req = header_prefix + header_dummy + header_suffix + content;
  13869. std::string response;
  13870. ASSERT_TRUE(send_request(1, req, &response));
  13871. ASSERT_EQ("200", response.substr(9, 3));
  13872. }
  13873. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13874. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13875. // (not chunked Transfer-Encoding) after the streaming refactor.
  13876. auto handled = false;
  13877. Server svr;
  13878. svr.Post("/upload", [&](const Request &req, Response &res) {
  13879. auto cl_it = req.headers.find("Content-Length");
  13880. EXPECT_TRUE(cl_it != req.headers.end());
  13881. auto te_it = req.headers.find("Transfer-Encoding");
  13882. EXPECT_TRUE(te_it == req.headers.end());
  13883. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13884. res.set_content("ok", "text/plain");
  13885. handled = true;
  13886. });
  13887. auto port = svr.bind_to_any_port(HOST);
  13888. auto t = thread([&] { svr.listen_after_bind(); });
  13889. auto se = detail::scope_exit([&] {
  13890. svr.stop();
  13891. t.join();
  13892. ASSERT_FALSE(svr.is_running());
  13893. ASSERT_TRUE(handled);
  13894. });
  13895. svr.wait_until_ready();
  13896. UploadFormDataItems items = {
  13897. {"field1", "hello", "", "text/plain"},
  13898. {"file1", "world", "test.txt", "application/octet-stream"},
  13899. };
  13900. Client cli(HOST, port);
  13901. auto res = cli.Post("/upload", {}, items);
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. EXPECT_EQ(StatusCode::OK_200, res->status);
  13904. }
  13905. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13906. // Verify that make_multipart_content_provider coalesces many small segments
  13907. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13908. constexpr size_t kItemCount = 1000;
  13909. UploadFormDataItems items;
  13910. items.reserve(kItemCount);
  13911. for (size_t i = 0; i < kItemCount; i++) {
  13912. items.push_back(
  13913. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13914. }
  13915. const std::string boundary = "----test-boundary";
  13916. auto content_length = detail::get_multipart_content_length(items, boundary);
  13917. auto provider = detail::make_multipart_content_provider(items, boundary);
  13918. // Drive the provider the same way write_content_with_progress does
  13919. size_t write_count = 0;
  13920. size_t total_bytes = 0;
  13921. DataSink sink;
  13922. size_t offset = 0;
  13923. sink.write = [&](const char *d, size_t l) -> bool {
  13924. (void)d;
  13925. write_count++;
  13926. total_bytes += l;
  13927. offset += l;
  13928. return true;
  13929. };
  13930. sink.is_writable = []() -> bool { return true; };
  13931. while (offset < content_length) {
  13932. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13933. }
  13934. EXPECT_EQ(content_length, total_bytes);
  13935. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13936. // With buffering into 64KB blocks, write_count should be much smaller.
  13937. auto segment_count = 3 * kItemCount + 1;
  13938. EXPECT_LT(write_count, segment_count / 10);
  13939. }
  13940. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13941. // Integration test: send many UploadFormDataItems and verify the server
  13942. // receives all of them correctly (#2410).
  13943. constexpr size_t kItemCount = 500;
  13944. auto handled = false;
  13945. Server svr;
  13946. svr.Post("/upload", [&](const Request &req, Response &res) {
  13947. EXPECT_EQ(kItemCount, req.form.fields.size());
  13948. for (size_t i = 0; i < kItemCount; i++) {
  13949. auto key = "field" + std::to_string(i);
  13950. auto val = "value" + std::to_string(i);
  13951. auto it = req.form.fields.find(key);
  13952. if (it != req.form.fields.end()) {
  13953. EXPECT_EQ(val, it->second.content);
  13954. } else {
  13955. ADD_FAILURE() << "Missing field: " << key;
  13956. }
  13957. }
  13958. res.set_content("ok", "text/plain");
  13959. handled = true;
  13960. });
  13961. auto port = svr.bind_to_any_port(HOST);
  13962. auto t = thread([&] { svr.listen_after_bind(); });
  13963. auto se = detail::scope_exit([&] {
  13964. svr.stop();
  13965. t.join();
  13966. ASSERT_FALSE(svr.is_running());
  13967. ASSERT_TRUE(handled);
  13968. });
  13969. svr.wait_until_ready();
  13970. UploadFormDataItems items;
  13971. items.reserve(kItemCount);
  13972. for (size_t i = 0; i < kItemCount; i++) {
  13973. items.push_back(
  13974. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13975. }
  13976. Client cli(HOST, port);
  13977. auto res = cli.Post("/upload", items);
  13978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13979. EXPECT_EQ(StatusCode::OK_200, res->status);
  13980. }
  13981. TEST(MultipartFormDataTest, MakeFileProvider) {
  13982. // Verify make_file_provider sends a file's contents correctly.
  13983. const std::string file_content(4096, 'Z');
  13984. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13985. {
  13986. std::ofstream ofs(tmp_path, std::ios::binary);
  13987. ofs.write(file_content.data(),
  13988. static_cast<std::streamsize>(file_content.size()));
  13989. }
  13990. auto handled = false;
  13991. Server svr;
  13992. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13993. const ContentReader &content_reader) {
  13994. ASSERT_TRUE(req.is_multipart_form_data());
  13995. std::vector<FormData> items;
  13996. content_reader(
  13997. [&](const FormData &file) {
  13998. items.push_back(file);
  13999. return true;
  14000. },
  14001. [&](const char *data, size_t data_length) {
  14002. items.back().content.append(data, data_length);
  14003. return true;
  14004. });
  14005. ASSERT_EQ(1u, items.size());
  14006. EXPECT_EQ("myfile", items[0].name);
  14007. EXPECT_EQ("data.bin", items[0].filename);
  14008. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14009. EXPECT_EQ(file_content, items[0].content);
  14010. handled = true;
  14011. });
  14012. auto port = svr.bind_to_any_port(HOST);
  14013. auto t = thread([&] { svr.listen_after_bind(); });
  14014. auto se = detail::scope_exit([&] {
  14015. svr.stop();
  14016. t.join();
  14017. ASSERT_FALSE(svr.is_running());
  14018. ASSERT_TRUE(handled);
  14019. std::remove(tmp_path.c_str());
  14020. });
  14021. svr.wait_until_ready();
  14022. FormDataProviderItems providers;
  14023. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14024. "application/octet-stream"));
  14025. Client cli(HOST, port);
  14026. auto res = cli.Post("/upload", {}, {}, providers);
  14027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14028. EXPECT_EQ(StatusCode::OK_200, res->status);
  14029. }
  14030. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14031. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14032. // (100) headers is rejected with a 400 Bad Request response.
  14033. Server svr;
  14034. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14035. res.set_content("ok", "text/plain");
  14036. });
  14037. thread t = thread([&] { svr.listen(HOST, PORT); });
  14038. auto se = detail::scope_exit([&] {
  14039. svr.stop();
  14040. t.join();
  14041. ASSERT_FALSE(svr.is_running());
  14042. });
  14043. svr.wait_until_ready();
  14044. // Build a multipart part with 101 custom headers (exceeding
  14045. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14046. std::stringstream body;
  14047. body << "--simpleboundary\r\n"
  14048. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14049. for (int i = 0; i < 101; i++) {
  14050. body << "X-Custom-Header-" << i << ": value\r\n";
  14051. }
  14052. body << "\r\n"
  14053. << "value1\r\n"
  14054. << "--simpleboundary--\r\n";
  14055. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14056. Client cli(HOST, PORT);
  14057. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14059. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14060. }
  14061. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14062. // A body that never contains the declared boundary must not be accumulated
  14063. // while the parser waits for it. Buffering it would also make every read
  14064. // rescan everything seen so far, which is quadratic in the body size.
  14065. Server svr;
  14066. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14067. res.set_content("ok", "text/plain");
  14068. });
  14069. auto port = svr.bind_to_any_port(HOST);
  14070. thread t = thread([&] { svr.listen_after_bind(); });
  14071. auto se = detail::scope_exit([&] {
  14072. svr.stop();
  14073. t.join();
  14074. ASSERT_FALSE(svr.is_running());
  14075. });
  14076. svr.wait_until_ready();
  14077. Client cli(HOST, port);
  14078. cli.set_read_timeout(60, 0);
  14079. cli.set_write_timeout(60, 0);
  14080. // '-' is the worst case: it matches the first character of the boundary, so
  14081. // every position has to be checked against it.
  14082. auto post_dashes = [&](size_t size) {
  14083. const std::string body(size, '-');
  14084. auto start = std::chrono::steady_clock::now();
  14085. auto res =
  14086. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14087. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14088. std::chrono::steady_clock::now() - start)
  14089. .count();
  14090. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14091. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14092. return ms;
  14093. };
  14094. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14095. // Windows.
  14096. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14097. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14098. // Comparing the two sizes rather than checking an absolute duration keeps
  14099. // this meaningful across build types and CI load, both of which move the
  14100. // absolute numbers by more than an order of magnitude. Four times the bytes
  14101. // costs about four times the time when parsing is linear, and about sixteen
  14102. // times when the body is buffered and rescanned.
  14103. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14104. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14105. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14106. << "ms, which suggests the body is being buffered and rescanned";
  14107. }
  14108. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14109. // A boundary can only be followed by CRLF or by "--", so anything else is
  14110. // malformed no matter what comes next. The parser must say so right away
  14111. // instead of buffering the rest of the declared body.
  14112. Server svr;
  14113. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14114. res.set_content("ok", "text/plain");
  14115. });
  14116. auto port = svr.bind_to_any_port(HOST);
  14117. thread t = thread([&] { svr.listen_after_bind(); });
  14118. auto se = detail::scope_exit([&] {
  14119. svr.stop();
  14120. t.join();
  14121. ASSERT_FALSE(svr.is_running());
  14122. });
  14123. svr.wait_until_ready();
  14124. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14125. // buffers instead of failing would still be waiting for the remaining bytes.
  14126. const std::string body = "--zzzz\r\n"
  14127. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14128. "\r\n"
  14129. "text1"
  14130. "\r\n--zzzzXX";
  14131. const std::string req = "POST /post HTTP/1.1\r\n"
  14132. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14133. "Content-Length: 1048576\r\n"
  14134. "\r\n" +
  14135. body;
  14136. std::string response;
  14137. ASSERT_TRUE(send_request(3, req, &response, port));
  14138. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14139. EXPECT_EQ("400", response.substr(9, 3));
  14140. }
  14141. // Posts a multipart body split into two writes, so that the server sees the
  14142. // split at whatever offset the caller chose, and expects the single "text1"
  14143. // field to come through.
  14144. static void expect_split_multipart_ok(const std::string &body1,
  14145. const std::string &body2) {
  14146. auto handled = false;
  14147. Server svr;
  14148. svr.Post("/post", [&](const Request &req, Response &) {
  14149. EXPECT_EQ(1u, req.form.fields.size());
  14150. EXPECT_EQ("text1", req.form.get_field("text1"));
  14151. handled = true;
  14152. });
  14153. auto port = svr.bind_to_any_port(HOST);
  14154. thread t = thread([&] { svr.listen_after_bind(); });
  14155. auto se = detail::scope_exit([&] {
  14156. svr.stop();
  14157. t.join();
  14158. ASSERT_FALSE(svr.is_running());
  14159. ASSERT_TRUE(handled);
  14160. });
  14161. svr.wait_until_ready();
  14162. // "Connection: close" makes the server close once it has answered, so the
  14163. // response drain ends immediately instead of idling until the read timeout.
  14164. const std::string head =
  14165. "POST /post HTTP/1.1\r\n"
  14166. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14167. "Connection: close\r\n"
  14168. "Content-Length: " +
  14169. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14170. std::string response;
  14171. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14172. ASSERT_GE(response.size(), 12u) << "no response";
  14173. EXPECT_EQ("200", response.substr(9, 3));
  14174. }
  14175. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14176. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14177. // ignored, including when it does not arrive in the same read as the
  14178. // close-delimiter itself.
  14179. expect_split_multipart_ok("--zzzz\r\n"
  14180. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14181. "\r\n"
  14182. "text1"
  14183. "\r\n--zzzz--",
  14184. "\r\nthis epilogue must be ignored\r\n");
  14185. }
  14186. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14187. // The initial boundary may be preceded by a preamble of any length and may
  14188. // straddle a read boundary. Discarding data while waiting for it must not
  14189. // throw away a partial boundary sitting at the end of the buffer.
  14190. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14191. "zz\r\n"
  14192. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14193. "\r\n"
  14194. "text1"
  14195. "\r\n--zzzz--\r\n");
  14196. }
  14197. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14198. // The received boundary was only checked for being non-empty, so it could be
  14199. // as long as a header is allowed to be. The parser scans the body for
  14200. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14201. // costs a nearly full comparison at nearly every position, making the
  14202. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14203. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14204. Server svr;
  14205. svr.Post("/post", [](const Request &req, Response &res) {
  14206. EXPECT_EQ(1u, req.form.fields.size());
  14207. EXPECT_EQ("text1", req.form.get_field("text1"));
  14208. res.set_content("ok", "text/plain");
  14209. });
  14210. auto port = svr.bind_to_any_port(HOST);
  14211. thread t = thread([&] { svr.listen_after_bind(); });
  14212. auto se = detail::scope_exit([&] {
  14213. svr.stop();
  14214. t.join();
  14215. ASSERT_FALSE(svr.is_running());
  14216. });
  14217. svr.wait_until_ready();
  14218. Client cli(HOST, port);
  14219. auto post_with_boundary_of_length = [&](size_t len) {
  14220. const std::string boundary(len, 'a');
  14221. const std::string body =
  14222. "--" + boundary +
  14223. "\r\n"
  14224. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14225. "\r\n"
  14226. "text1"
  14227. "\r\n--" +
  14228. boundary + "--\r\n";
  14229. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14230. };
  14231. auto res = post_with_boundary_of_length(70);
  14232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14233. EXPECT_EQ(StatusCode::OK_200, res->status);
  14234. res = post_with_boundary_of_length(71);
  14235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14236. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14237. }
  14238. TEST(MakeFileBodyTest, Basic) {
  14239. const std::string file_content(4096, 'Z');
  14240. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14241. {
  14242. std::ofstream ofs(tmp_path, std::ios::binary);
  14243. ofs.write(file_content.data(),
  14244. static_cast<std::streamsize>(file_content.size()));
  14245. }
  14246. auto handled = false;
  14247. Server svr;
  14248. svr.Post("/upload", [&](const Request &req, Response &res) {
  14249. EXPECT_EQ(file_content, req.body);
  14250. handled = true;
  14251. res.status = StatusCode::OK_200;
  14252. });
  14253. auto port = svr.bind_to_any_port(HOST);
  14254. auto t = thread([&] { svr.listen_after_bind(); });
  14255. auto se = detail::scope_exit([&] {
  14256. svr.stop();
  14257. t.join();
  14258. ASSERT_FALSE(svr.is_running());
  14259. ASSERT_TRUE(handled);
  14260. std::remove(tmp_path.c_str());
  14261. });
  14262. svr.wait_until_ready();
  14263. auto fb = make_file_body(tmp_path);
  14264. ASSERT_GT(fb.first, 0u);
  14265. Client cli(HOST, port);
  14266. auto res =
  14267. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14269. EXPECT_EQ(StatusCode::OK_200, res->status);
  14270. }
  14271. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14272. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14273. {
  14274. std::ofstream ofs(path, std::ios::binary);
  14275. const std::string content(100, 'A');
  14276. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14277. }
  14278. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14279. auto body = make_file_body(path);
  14280. ASSERT_EQ(100u, body.first);
  14281. ASSERT_TRUE(static_cast<bool>(body.second));
  14282. // Rewritten shorter after its length was measured - and, on a server, after
  14283. // that length has already gone out as Content-Length.
  14284. {
  14285. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14286. const std::string content(10, 'A');
  14287. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14288. }
  14289. std::string written;
  14290. DataSink sink;
  14291. sink.write = [&](const char *d, size_t l) {
  14292. written.append(d, l);
  14293. return true;
  14294. };
  14295. // The provider has to report failure. write_content_with_progress() advances
  14296. // its offset only by what was written, so a provider that returns true
  14297. // without completing the length it promised is called again straight away,
  14298. // and again.
  14299. EXPECT_FALSE(body.second(0, body.first, sink));
  14300. EXPECT_EQ(std::string(10, 'A'), written);
  14301. }
  14302. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14303. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14304. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14305. {
  14306. std::ofstream ofs(path, std::ios::binary);
  14307. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14308. }
  14309. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14310. auto body = make_file_body(path);
  14311. ASSERT_EQ(content.size(), body.first);
  14312. ASSERT_TRUE(static_cast<bool>(body.second));
  14313. std::string written;
  14314. DataSink sink;
  14315. sink.write = [&](const char *d, size_t l) {
  14316. written.append(d, l);
  14317. return true;
  14318. };
  14319. EXPECT_TRUE(body.second(0, body.first, sink));
  14320. EXPECT_EQ(content, written);
  14321. }
  14322. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14323. static constexpr unsigned int number_of_tasks{1000000};
  14324. std::atomic_uint count{0};
  14325. std::unique_ptr<TaskQueue> task_queue{
  14326. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14327. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14328. auto queued = task_queue->enqueue(
  14329. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14330. EXPECT_TRUE(queued);
  14331. }
  14332. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14333. task_queue->shutdown();
  14334. #else
  14335. EXPECT_NO_THROW(task_queue->shutdown());
  14336. #endif
  14337. EXPECT_EQ(number_of_tasks, count.load());
  14338. }
  14339. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14340. static constexpr unsigned int number_of_tasks{1000000};
  14341. static constexpr unsigned int qlimit{2};
  14342. unsigned int queued_count{0};
  14343. std::atomic_uint count{0};
  14344. std::unique_ptr<TaskQueue> task_queue{
  14345. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14346. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14347. if (task_queue->enqueue(
  14348. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14349. queued_count++;
  14350. }
  14351. }
  14352. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14353. task_queue->shutdown();
  14354. #else
  14355. EXPECT_NO_THROW(task_queue->shutdown());
  14356. #endif
  14357. EXPECT_EQ(queued_count, count.load());
  14358. EXPECT_TRUE(queued_count <= number_of_tasks);
  14359. EXPECT_TRUE(queued_count >= qlimit);
  14360. }
  14361. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14362. // Use a short idle timeout so a dynamic thread spawns, times out and
  14363. // exits during the test, and the pool keeps working afterwards.
  14364. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14365. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14366. /*idle_timeout_sec=*/1}};
  14367. std::atomic_uint count{0};
  14368. std::condition_variable cv;
  14369. std::mutex mtx;
  14370. bool release = false;
  14371. // Block the base thread so the second task spawns a dynamic thread.
  14372. EXPECT_TRUE(task_queue->enqueue([&] {
  14373. std::unique_lock<std::mutex> lock(mtx);
  14374. while (!release) {
  14375. cv.wait(lock);
  14376. }
  14377. count++;
  14378. }));
  14379. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14380. // Let the dynamic thread finish its task and exceed the idle timeout.
  14381. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14382. {
  14383. std::unique_lock<std::mutex> lock(mtx);
  14384. release = true;
  14385. }
  14386. cv.notify_all();
  14387. // The pool must still accept and run tasks after the dynamic thread exited.
  14388. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14389. task_queue->shutdown();
  14390. EXPECT_EQ(3u, count.load());
  14391. }
  14392. TEST(TaskQueueTest, MaxQueuedRequests) {
  14393. static constexpr unsigned int qlimit{3};
  14394. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14395. std::condition_variable sem_cv;
  14396. std::mutex sem_mtx;
  14397. int credits = 0;
  14398. bool queued;
  14399. /* Fill up the queue with tasks that will block until we give them credits to
  14400. * complete. */
  14401. for (unsigned int n = 0; n <= qlimit;) {
  14402. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14403. std::unique_lock<std::mutex> lock(sem_mtx);
  14404. while (credits <= 0) {
  14405. sem_cv.wait(lock);
  14406. }
  14407. /* Consume the credit and signal the test code if they are all gone. */
  14408. if (--credits == 0) { sem_cv.notify_one(); }
  14409. });
  14410. if (n < qlimit) {
  14411. /* The first qlimit enqueues must succeed. */
  14412. EXPECT_TRUE(queued);
  14413. } else {
  14414. /* The last one will succeed only when the worker thread
  14415. * starts and dequeues the first blocking task. Although
  14416. * not necessary for the correctness of this test, we sleep for
  14417. * a short while to avoid busy waiting. */
  14418. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14419. }
  14420. if (queued) { n++; }
  14421. }
  14422. /* Further enqueues must fail since the queue is full. */
  14423. for (auto i = 0; i < 4; i++) {
  14424. queued = task_queue->enqueue([] {});
  14425. EXPECT_FALSE(queued);
  14426. }
  14427. /* Give the credits to allow the previous tasks to complete. */
  14428. {
  14429. std::unique_lock<std::mutex> lock(sem_mtx);
  14430. credits += qlimit + 1;
  14431. }
  14432. sem_cv.notify_all();
  14433. /* Wait for all the credits to be consumed. */
  14434. {
  14435. std::unique_lock<std::mutex> lock(sem_mtx);
  14436. while (credits > 0) {
  14437. sem_cv.wait(lock);
  14438. }
  14439. }
  14440. /* Check that we are able again to enqueue at least qlimit tasks. */
  14441. for (unsigned int i = 0; i < qlimit; i++) {
  14442. queued = task_queue->enqueue([] {});
  14443. EXPECT_TRUE(queued);
  14444. }
  14445. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14446. task_queue->shutdown();
  14447. #else
  14448. EXPECT_NO_THROW(task_queue->shutdown());
  14449. #endif
  14450. }
  14451. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14452. Server svr;
  14453. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14454. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14455. });
  14456. svr.Get("/hello", [](const Request &req, Response &res) {
  14457. res.set_content(req.get_param_value("key"), "text/plain");
  14458. });
  14459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14460. auto se = detail::scope_exit([&] {
  14461. svr.stop();
  14462. thread.join();
  14463. ASSERT_FALSE(svr.is_running());
  14464. });
  14465. svr.wait_until_ready();
  14466. {
  14467. Client cli(HOST, PORT);
  14468. cli.set_follow_location(true);
  14469. auto res = cli.Get("/");
  14470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14471. EXPECT_EQ(StatusCode::OK_200, res->status);
  14472. EXPECT_EQ("val&key2=val2", res->body);
  14473. }
  14474. }
  14475. #endif
  14476. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14477. Server svr;
  14478. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14479. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14480. });
  14481. svr.Get("/hello", [](const Request &req, Response &res) {
  14482. res.set_content(req.get_param_value("key"), "text/plain");
  14483. });
  14484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14485. auto se = detail::scope_exit([&] {
  14486. svr.stop();
  14487. thread.join();
  14488. ASSERT_FALSE(svr.is_running());
  14489. });
  14490. svr.wait_until_ready();
  14491. {
  14492. Client cli(HOST, PORT);
  14493. cli.set_follow_location(true);
  14494. auto res = cli.Get("/");
  14495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14496. EXPECT_EQ(StatusCode::OK_200, res->status);
  14497. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14498. }
  14499. }
  14500. TEST(RedirectTest, RedirectWithPlusInPath) {
  14501. Server svr;
  14502. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14503. res.set_redirect("/a+b");
  14504. });
  14505. // Route pattern uses regex; escape + as \\+
  14506. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14507. res.set_content(req.path, "text/plain");
  14508. });
  14509. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14510. auto se = detail::scope_exit([&] {
  14511. svr.stop();
  14512. thread.join();
  14513. ASSERT_FALSE(svr.is_running());
  14514. });
  14515. svr.wait_until_ready();
  14516. {
  14517. Client cli(HOST, PORT);
  14518. cli.set_follow_location(true);
  14519. auto res = cli.Get("/");
  14520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14521. EXPECT_EQ(StatusCode::OK_200, res->status);
  14522. EXPECT_EQ("/a+b", res->body);
  14523. }
  14524. }
  14525. TEST(RedirectTest, ResolveRelativeLocation) {
  14526. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14527. const std::vector<std::pair<std::string, std::string>> cases = {
  14528. {"g", "/b/c/g"},
  14529. {"./g", "/b/c/g"},
  14530. {"g/", "/b/c/g/"},
  14531. {"?y", "/b/c/d;p?y"},
  14532. {"g?y", "/b/c/g?y"},
  14533. {"#s", "/b/c/d;p?q#s"},
  14534. {"g#s", "/b/c/g#s"},
  14535. {"g?y#s", "/b/c/g?y#s"},
  14536. {";x", "/b/c/;x"},
  14537. {"g;x", "/b/c/g;x"},
  14538. {".", "/b/c/"},
  14539. {"./", "/b/c/"},
  14540. {"..", "/b/"},
  14541. {"../", "/b/"},
  14542. {"../g", "/b/g"},
  14543. {"../..", "/"},
  14544. {"../../", "/"},
  14545. {"../../g", "/g"},
  14546. {"../../../g", "/g"},
  14547. {"g.", "/b/c/g."},
  14548. {".g", "/b/c/.g"},
  14549. {"g..", "/b/c/g.."},
  14550. {"..g", "/b/c/..g"},
  14551. {"./../g", "/b/g"},
  14552. {"./g/.", "/b/c/g/"},
  14553. {"g/./h", "/b/c/g/h"},
  14554. {"g/../h", "/b/c/h"},
  14555. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14556. {"g;x=1/../y", "/b/c/y"},
  14557. {"g?y/./x", "/b/c/g?y/./x"},
  14558. {"g#s/../x", "/b/c/g#s/../x"},
  14559. // Not relative-path references, so left for parse_url.
  14560. {"/g", "/g"},
  14561. {"//g", "//g"},
  14562. {"http://g/x", "http://g/x"},
  14563. {"g:h", "g:h"},
  14564. };
  14565. for (const auto &c : cases) {
  14566. EXPECT_EQ(c.second,
  14567. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14568. << c.first;
  14569. }
  14570. }
  14571. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14572. Server svr;
  14573. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14574. res.set_redirect(req.get_param_value("to"));
  14575. });
  14576. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14577. res.set_content(req.target, "text/plain");
  14578. });
  14579. svr.Get("/other", [](const Request &req, Response &res) {
  14580. res.set_content(req.target, "text/plain");
  14581. });
  14582. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14583. auto se = detail::scope_exit([&] {
  14584. svr.stop();
  14585. thread.join();
  14586. ASSERT_FALSE(svr.is_running());
  14587. });
  14588. svr.wait_until_ready();
  14589. const std::vector<std::pair<std::string, std::string>> cases = {
  14590. {"next", "/dir/next"},
  14591. {"./next?x=1", "/dir/next?x=1"},
  14592. {"../other", "/other"},
  14593. };
  14594. for (const auto &c : cases) {
  14595. Client cli(HOST, PORT);
  14596. cli.set_follow_location(true);
  14597. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14598. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14599. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14600. EXPECT_EQ(c.second, res->body) << c.first;
  14601. }
  14602. }
  14603. #ifdef CPPHTTPLIB_SSL_ENABLED
  14604. TEST(RedirectTest, Issue2185_Online) {
  14605. SSLClient client("github.com");
  14606. client.set_follow_location(true);
  14607. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14608. "Coollab-Windows.zip");
  14609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14610. EXPECT_EQ(StatusCode::OK_200, res->status);
  14611. EXPECT_EQ(9920427U, res->body.size());
  14612. }
  14613. #endif
  14614. TEST(VulnerabilityTest, CRLFInjection) {
  14615. Server svr;
  14616. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14617. res.set_content("Hello 1", "text/plain");
  14618. });
  14619. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14620. res.set_content("Hello 2", "text/plain");
  14621. });
  14622. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14623. res.set_content("Hello 3", "text/plain");
  14624. });
  14625. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14626. res.set_content("Hello 4", "text/plain");
  14627. });
  14628. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14629. for (const auto &x : req.headers) {
  14630. auto key = x.first;
  14631. EXPECT_STRNE("evil", key.c_str());
  14632. }
  14633. });
  14634. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14635. auto se = detail::scope_exit([&] {
  14636. svr.stop();
  14637. thread.join();
  14638. ASSERT_FALSE(svr.is_running());
  14639. });
  14640. svr.wait_until_ready();
  14641. {
  14642. Client cli(HOST, PORT);
  14643. cli.Post("/test1", "A=B",
  14644. "application/x-www-form-urlencoded\r\nevil: hello1");
  14645. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14646. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14647. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14648. }
  14649. }
  14650. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14651. auto server_thread = std::thread([] {
  14652. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14653. default_socket_options(srv);
  14654. sockaddr_in addr{};
  14655. addr.sin_family = AF_INET;
  14656. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14657. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14658. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14659. ::listen(srv, 1);
  14660. sockaddr_in cli_addr{};
  14661. socklen_t cli_len = sizeof(cli_addr);
  14662. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14663. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14664. std::string buf_all;
  14665. char buf[2048];
  14666. ssize_t n;
  14667. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14668. buf_all.append(buf, static_cast<size_t>(n));
  14669. size_t pos;
  14670. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14671. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14672. auto e = request_block.find("\r\n");
  14673. if (e != std::string::npos) {
  14674. auto request_line = request_block.substr(0, e);
  14675. std::string msg =
  14676. "CRLF injection detected in request line: '" + request_line + "'";
  14677. EXPECT_FALSE(true) << msg;
  14678. }
  14679. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14680. ::send(cli,
  14681. #ifdef _WIN32
  14682. static_cast<const char *>(resp.c_str()),
  14683. static_cast<int>(resp.size()),
  14684. #else
  14685. resp.c_str(), resp.size(),
  14686. #endif
  14687. 0);
  14688. buf_all.erase(0, pos + 4);
  14689. }
  14690. }
  14691. detail::close_socket(cli);
  14692. detail::close_socket(srv);
  14693. });
  14694. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14695. auto cli = Client("127.0.0.1", PORT + 1);
  14696. auto headers = Headers{
  14697. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14698. {"Connection", "keep-alive"}};
  14699. auto res = cli.Get("/hi", headers);
  14700. EXPECT_FALSE(res);
  14701. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14702. server_thread.join();
  14703. }
  14704. // A request rejected before any byte reaches the socket must fail right away
  14705. // instead of waiting for a response the server will never send.
  14706. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  14707. // The kernel completes the TCP handshake from the listen backlog, so the
  14708. // client connects, but nothing ever reads, responds or closes.
  14709. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14710. default_socket_options(srv);
  14711. sockaddr_in addr{};
  14712. addr.sin_family = AF_INET;
  14713. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14714. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14715. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14716. ASSERT_EQ(0, ::listen(srv, 8));
  14717. auto cli = Client("127.0.0.1", PORT + 1);
  14718. cli.set_read_timeout(10, 0);
  14719. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  14720. return std::chrono::duration_cast<std::chrono::milliseconds>(
  14721. std::chrono::steady_clock::now() - start)
  14722. .count();
  14723. };
  14724. {
  14725. Request req;
  14726. req.method = "GE T";
  14727. req.path = "/";
  14728. auto start = std::chrono::steady_clock::now();
  14729. auto res = cli.send(req);
  14730. EXPECT_FALSE(res);
  14731. EXPECT_EQ(Error::Write, res.error());
  14732. EXPECT_LT(elapsed_ms(start), 1000);
  14733. }
  14734. {
  14735. auto start = std::chrono::steady_clock::now();
  14736. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  14737. EXPECT_FALSE(res);
  14738. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14739. EXPECT_LT(elapsed_ms(start), 1000);
  14740. }
  14741. EXPECT_FALSE(cli.is_socket_open());
  14742. detail::close_socket(srv);
  14743. }
  14744. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  14745. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14746. default_socket_options(srv);
  14747. sockaddr_in addr{};
  14748. addr.sin_family = AF_INET;
  14749. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14750. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14751. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14752. ASSERT_EQ(0, ::listen(srv, 1));
  14753. std::string received;
  14754. auto server_thread = std::thread([&] {
  14755. auto sock = ::accept(srv, nullptr, nullptr);
  14756. if (sock == INVALID_SOCKET) { return; }
  14757. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  14758. char buf[2048];
  14759. ssize_t n;
  14760. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  14761. received.append(buf, static_cast<size_t>(n));
  14762. }
  14763. detail::close_socket(sock);
  14764. });
  14765. {
  14766. auto cli = Client("127.0.0.1", PORT + 1);
  14767. // "Z" sorts after the default headers, so writing straight to the socket
  14768. // would have sent the request line and those headers before the rejection.
  14769. auto handle =
  14770. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  14771. EXPECT_FALSE(handle.is_valid());
  14772. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  14773. }
  14774. server_thread.join();
  14775. detail::close_socket(srv);
  14776. EXPECT_TRUE(received.empty()) << received;
  14777. }
  14778. TEST(PathParamsTest, StaticMatch) {
  14779. const auto pattern = "/users/all";
  14780. detail::PathParamsMatcher matcher(pattern);
  14781. Request request;
  14782. request.path = "/users/all";
  14783. ASSERT_TRUE(matcher.match(request));
  14784. std::unordered_map<std::string, std::string> expected_params = {};
  14785. EXPECT_EQ(request.path_params, expected_params);
  14786. }
  14787. TEST(PathParamsTest, StaticMismatch) {
  14788. const auto pattern = "/users/all";
  14789. detail::PathParamsMatcher matcher(pattern);
  14790. Request request;
  14791. request.path = "/users/1";
  14792. ASSERT_FALSE(matcher.match(request));
  14793. }
  14794. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14795. const auto pattern = "/users/:id/subscriptions";
  14796. detail::PathParamsMatcher matcher(pattern);
  14797. Request request;
  14798. request.path = "/users/42/subscriptions";
  14799. ASSERT_TRUE(matcher.match(request));
  14800. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14801. EXPECT_EQ(request.path_params, expected_params);
  14802. }
  14803. TEST(PathParamsTest, SingleParamInTheEnd) {
  14804. const auto pattern = "/users/:id";
  14805. detail::PathParamsMatcher matcher(pattern);
  14806. Request request;
  14807. request.path = "/users/24";
  14808. ASSERT_TRUE(matcher.match(request));
  14809. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14810. EXPECT_EQ(request.path_params, expected_params);
  14811. }
  14812. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14813. const auto pattern = "/users/:id/";
  14814. detail::PathParamsMatcher matcher(pattern);
  14815. Request request;
  14816. request.path = "/users/42/";
  14817. ASSERT_TRUE(matcher.match(request));
  14818. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14819. EXPECT_EQ(request.path_params, expected_params);
  14820. }
  14821. TEST(PathParamsTest, EmptyParam) {
  14822. const auto pattern = "/users/:id/";
  14823. detail::PathParamsMatcher matcher(pattern);
  14824. Request request;
  14825. request.path = "/users//";
  14826. ASSERT_TRUE(matcher.match(request));
  14827. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14828. EXPECT_EQ(request.path_params, expected_params);
  14829. }
  14830. TEST(PathParamsTest, FragmentMismatch) {
  14831. const auto pattern = "/users/:id/";
  14832. detail::PathParamsMatcher matcher(pattern);
  14833. Request request;
  14834. request.path = "/admins/24/";
  14835. ASSERT_FALSE(matcher.match(request));
  14836. }
  14837. TEST(PathParamsTest, ExtraFragments) {
  14838. const auto pattern = "/users/:id";
  14839. detail::PathParamsMatcher matcher(pattern);
  14840. Request request;
  14841. request.path = "/users/42/subscriptions";
  14842. ASSERT_FALSE(matcher.match(request));
  14843. }
  14844. TEST(PathParamsTest, MissingTrailingParam) {
  14845. const auto pattern = "/users/:id";
  14846. detail::PathParamsMatcher matcher(pattern);
  14847. Request request;
  14848. request.path = "/users";
  14849. ASSERT_FALSE(matcher.match(request));
  14850. }
  14851. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14852. const auto pattern = "/users/:id/subscriptions";
  14853. detail::PathParamsMatcher matcher(pattern);
  14854. Request request;
  14855. request.path = "/users/subscriptions";
  14856. ASSERT_FALSE(matcher.match(request));
  14857. }
  14858. TEST(PathParamsTest, MultipleParams) {
  14859. const auto pattern = "/users/:userid/subscriptions/:subid";
  14860. detail::PathParamsMatcher matcher(pattern);
  14861. Request request;
  14862. request.path = "/users/42/subscriptions/2";
  14863. ASSERT_TRUE(matcher.match(request));
  14864. std::unordered_map<std::string, std::string> expected_params = {
  14865. {"userid", "42"}, {"subid", "2"}};
  14866. EXPECT_EQ(request.path_params, expected_params);
  14867. }
  14868. TEST(PathParamsTest, SequenceOfParams) {
  14869. const auto pattern = "/values/:x/:y/:z";
  14870. detail::PathParamsMatcher matcher(pattern);
  14871. Request request;
  14872. request.path = "/values/1/2/3";
  14873. ASSERT_TRUE(matcher.match(request));
  14874. std::unordered_map<std::string, std::string> expected_params = {
  14875. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14876. EXPECT_EQ(request.path_params, expected_params);
  14877. }
  14878. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14879. const auto pattern = "/prefix:suffix";
  14880. detail::PathParamsMatcher matcher(pattern);
  14881. Request request;
  14882. request.path = "/prefix:suffix";
  14883. ASSERT_TRUE(matcher.match(request));
  14884. const std::unordered_map<std::string, std::string> expected_params = {};
  14885. EXPECT_EQ(request.path_params, expected_params);
  14886. }
  14887. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14888. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14889. // calling thread's stack on a long enough path for a quantified pattern;
  14890. // RegexMatcher must refuse to run regex matching on paths beyond
  14891. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14892. detail::RegexMatcher matcher("/files/(.*)");
  14893. Request within_limit;
  14894. within_limit.path = "/files/" + std::string(10, 'A');
  14895. EXPECT_TRUE(matcher.match(within_limit));
  14896. Request over_limit;
  14897. over_limit.path =
  14898. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14899. EXPECT_FALSE(matcher.match(over_limit));
  14900. }
  14901. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14902. Server svr;
  14903. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14904. res.set_content("ok", "text/plain");
  14905. });
  14906. auto port = svr.bind_to_any_port(HOST);
  14907. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14908. auto se = detail::scope_exit([&] {
  14909. svr.stop();
  14910. thread.join();
  14911. ASSERT_FALSE(svr.is_running());
  14912. });
  14913. svr.wait_until_ready();
  14914. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14915. // request URI limit; this used to be able to crash the process.
  14916. std::string path =
  14917. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14918. std::string req = "GET " + path +
  14919. " HTTP/1.1\r\n"
  14920. "Host: " +
  14921. std::string(HOST) + ":" + std::to_string(port) +
  14922. "\r\n"
  14923. "Connection: close\r\n"
  14924. "\r\n";
  14925. std::string response;
  14926. ASSERT_TRUE(send_request(5, req, &response, port));
  14927. EXPECT_NE(std::string::npos, response.find("404"));
  14928. }
  14929. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14930. Server svr;
  14931. auto handler = [](const Request & /*req*/, Response &res) {
  14932. res.set_content("hit", "text/plain");
  14933. };
  14934. // No regex metacharacter, so this one is compared literally
  14935. svr.Get("/literal/route", handler);
  14936. // '.' is a regex metacharacter, so this one must keep regex semantics
  14937. svr.Get("/a.c", handler);
  14938. auto port = svr.bind_to_any_port(HOST);
  14939. std::thread t([&]() { svr.listen_after_bind(); });
  14940. auto se = detail::scope_exit([&] {
  14941. svr.stop();
  14942. t.join();
  14943. ASSERT_FALSE(svr.is_running());
  14944. });
  14945. svr.wait_until_ready();
  14946. Client cli(HOST, port);
  14947. struct {
  14948. const char *path;
  14949. int status;
  14950. } cases[] = {
  14951. {"/literal/route", StatusCode::OK_200},
  14952. {"/literal/routes", StatusCode::NotFound_404},
  14953. {"/literal/rout", StatusCode::NotFound_404},
  14954. {"/abc", StatusCode::OK_200},
  14955. {"/a.c", StatusCode::OK_200},
  14956. };
  14957. for (const auto &x : cases) {
  14958. auto res = cli.Get(x.path);
  14959. ASSERT_TRUE(res) << x.path;
  14960. EXPECT_EQ(x.status, res->status) << x.path;
  14961. }
  14962. }
  14963. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14964. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14965. // from exhausting the stack, so it must only constrain routes that actually
  14966. // run a regular expression. A literal route is matched by comparison and
  14967. // stays usable at any length.
  14968. Server svr;
  14969. const std::string pattern =
  14970. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14971. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14972. res.set_content("hit", "text/plain");
  14973. });
  14974. auto port = svr.bind_to_any_port(HOST);
  14975. std::thread t([&]() { svr.listen_after_bind(); });
  14976. auto se = detail::scope_exit([&] {
  14977. svr.stop();
  14978. t.join();
  14979. ASSERT_FALSE(svr.is_running());
  14980. });
  14981. svr.wait_until_ready();
  14982. Client cli(HOST, port);
  14983. auto res = cli.Get(pattern);
  14984. ASSERT_TRUE(res);
  14985. EXPECT_EQ(StatusCode::OK_200, res->status);
  14986. }
  14987. TEST(ParseUrlTest, VariousPatterns) {
  14988. {
  14989. detail::UrlComponents uc;
  14990. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14991. EXPECT_EQ("http", uc.scheme);
  14992. EXPECT_EQ("example.com", uc.host);
  14993. EXPECT_EQ("8080", uc.port);
  14994. EXPECT_EQ("/path", uc.path);
  14995. EXPECT_EQ("?q=1", uc.query);
  14996. }
  14997. {
  14998. detail::UrlComponents uc;
  14999. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15000. EXPECT_EQ("https", uc.scheme);
  15001. EXPECT_EQ("example.com", uc.host);
  15002. EXPECT_TRUE(uc.port.empty());
  15003. EXPECT_EQ("/path", uc.path);
  15004. }
  15005. {
  15006. detail::UrlComponents uc;
  15007. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15008. EXPECT_EQ("::1", uc.host);
  15009. EXPECT_EQ("8080", uc.port);
  15010. EXPECT_EQ("/path", uc.path);
  15011. }
  15012. {
  15013. detail::UrlComponents uc;
  15014. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15015. }
  15016. {
  15017. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15018. // the path while the connection still targets the bracketed host.
  15019. detail::UrlComponents uc;
  15020. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15021. }
  15022. {
  15023. detail::UrlComponents uc;
  15024. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15025. }
  15026. {
  15027. detail::UrlComponents uc;
  15028. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15029. EXPECT_EQ("::1", uc.host);
  15030. EXPECT_TRUE(uc.port.empty());
  15031. EXPECT_EQ("/path", uc.path);
  15032. }
  15033. {
  15034. detail::UrlComponents uc;
  15035. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15036. EXPECT_TRUE(uc.scheme.empty());
  15037. EXPECT_EQ("example.com", uc.host);
  15038. EXPECT_EQ("/path", uc.path);
  15039. EXPECT_EQ("?q=1", uc.query);
  15040. }
  15041. {
  15042. detail::UrlComponents uc;
  15043. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15044. EXPECT_TRUE(uc.host.empty());
  15045. EXPECT_EQ("/path", uc.path);
  15046. EXPECT_EQ("?q=1", uc.query);
  15047. }
  15048. {
  15049. detail::UrlComponents uc;
  15050. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15051. EXPECT_EQ("example.com", uc.host);
  15052. EXPECT_EQ("8080", uc.port);
  15053. }
  15054. {
  15055. // Unix socket path — must not be parsed as host
  15056. detail::UrlComponents uc;
  15057. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15058. EXPECT_TRUE(uc.host.empty());
  15059. }
  15060. {
  15061. detail::UrlComponents uc;
  15062. ASSERT_TRUE(detail::parse_url("", uc));
  15063. EXPECT_TRUE(uc.host.empty());
  15064. EXPECT_TRUE(uc.path.empty());
  15065. }
  15066. {
  15067. detail::UrlComponents uc;
  15068. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15069. }
  15070. {
  15071. detail::UrlComponents uc;
  15072. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15073. }
  15074. {
  15075. // Accepted by parse_url; callers restrict to http/https
  15076. detail::UrlComponents uc;
  15077. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15078. EXPECT_EQ("ftp", uc.scheme);
  15079. }
  15080. {
  15081. detail::UrlComponents uc;
  15082. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15083. }
  15084. {
  15085. detail::UrlComponents uc;
  15086. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15087. }
  15088. }
  15089. TEST(ParseUrlTest, FragmentHandling) {
  15090. {
  15091. detail::UrlComponents uc;
  15092. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15093. EXPECT_EQ("/path", uc.path);
  15094. EXPECT_TRUE(uc.query.empty());
  15095. }
  15096. {
  15097. detail::UrlComponents uc;
  15098. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15099. EXPECT_TRUE(uc.path.empty());
  15100. EXPECT_TRUE(uc.query.empty());
  15101. }
  15102. }
  15103. TEST(ParseUrlTest, UserinfoHandling) {
  15104. // Userinfo with @ but no colon — host includes @
  15105. detail::UrlComponents uc;
  15106. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15107. EXPECT_EQ("user@host.com", uc.host);
  15108. EXPECT_EQ("/path", uc.path);
  15109. }
  15110. TEST(ParseUrlTest, IPv6EdgeCases) {
  15111. {
  15112. detail::UrlComponents uc;
  15113. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15114. EXPECT_TRUE(uc.scheme.empty());
  15115. EXPECT_EQ("::1", uc.host);
  15116. EXPECT_EQ("8080", uc.port);
  15117. }
  15118. {
  15119. // Zone ID '%25' is not in [a-fA-F0-9:]
  15120. detail::UrlComponents uc;
  15121. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15122. }
  15123. }
  15124. TEST(ParseUrlTest, SchemeEdgeCases) {
  15125. {
  15126. detail::UrlComponents uc;
  15127. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15128. }
  15129. {
  15130. detail::UrlComponents uc;
  15131. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15132. }
  15133. {
  15134. detail::UrlComponents uc;
  15135. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15136. }
  15137. }
  15138. TEST(ParseUrlTest, PortEdgeCases) {
  15139. {
  15140. detail::UrlComponents uc;
  15141. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15142. EXPECT_TRUE(uc.port.empty());
  15143. EXPECT_EQ("/path", uc.path);
  15144. }
  15145. {
  15146. // parse_url accepts any port string; validation is done by parse_port
  15147. detail::UrlComponents uc;
  15148. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15149. EXPECT_EQ("abc", uc.port);
  15150. }
  15151. }
  15152. TEST(ParseUrlTest, WebSocketPatterns) {
  15153. {
  15154. detail::UrlComponents uc;
  15155. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15156. EXPECT_EQ("ws", uc.scheme);
  15157. EXPECT_EQ("echo.example.com", uc.host);
  15158. EXPECT_EQ("8080", uc.port);
  15159. EXPECT_EQ("/ws", uc.path);
  15160. }
  15161. {
  15162. detail::UrlComponents uc;
  15163. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15164. EXPECT_EQ("wss", uc.scheme);
  15165. EXPECT_EQ("echo.example.com", uc.host);
  15166. EXPECT_TRUE(uc.port.empty());
  15167. EXPECT_EQ("/ws", uc.path);
  15168. }
  15169. }
  15170. TEST(ParseUrlTest, QueryOnly) {
  15171. detail::UrlComponents uc;
  15172. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15173. EXPECT_TRUE(uc.host.empty());
  15174. EXPECT_TRUE(uc.path.empty());
  15175. EXPECT_EQ("?q=1&r=2", uc.query);
  15176. }
  15177. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15178. detail::UrlComponents uc;
  15179. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15180. EXPECT_TRUE(uc.scheme.empty());
  15181. EXPECT_EQ("example.com", uc.host);
  15182. EXPECT_EQ("443", uc.port);
  15183. EXPECT_EQ("/path", uc.path);
  15184. }
  15185. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15186. // If ipv6 regex working, regex match codepath is taken.
  15187. // else port will default to 80 in Client impl
  15188. int clientImplMagicPort = 80;
  15189. int port = 4321;
  15190. // above ports must be different to avoid false negative
  15191. EXPECT_NE(clientImplMagicPort, port);
  15192. std::string ipV6TestURL = "http://[ff06::c3]";
  15193. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15194. CLIENT_PRIVATE_KEY_FILE);
  15195. EXPECT_EQ(cli.port(), port);
  15196. }
  15197. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15198. auto file_path = "./www/dir/index.html";
  15199. auto dir_path = "./www/dir";
  15200. detail::FileStat stat_file(file_path);
  15201. EXPECT_TRUE(stat_file.is_file());
  15202. EXPECT_FALSE(stat_file.is_dir());
  15203. detail::FileStat stat_dir(dir_path);
  15204. EXPECT_FALSE(stat_dir.is_file());
  15205. EXPECT_TRUE(stat_dir.is_dir());
  15206. }
  15207. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15208. // IPv4 with default HTTP port (80)
  15209. EXPECT_EQ("example.com",
  15210. detail::make_host_and_port_string("example.com", 80, false));
  15211. // IPv4 with default HTTPS port (443)
  15212. EXPECT_EQ("example.com",
  15213. detail::make_host_and_port_string("example.com", 443, true));
  15214. // IPv4 with non-default HTTP port
  15215. EXPECT_EQ("example.com:8080",
  15216. detail::make_host_and_port_string("example.com", 8080, false));
  15217. // IPv4 with non-default HTTPS port
  15218. EXPECT_EQ("example.com:8443",
  15219. detail::make_host_and_port_string("example.com", 8443, true));
  15220. // IPv6 with default HTTP port (80)
  15221. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15222. // IPv6 with default HTTPS port (443)
  15223. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15224. // IPv6 with non-default HTTP port
  15225. EXPECT_EQ("[::1]:8080",
  15226. detail::make_host_and_port_string("::1", 8080, false));
  15227. // IPv6 with non-default HTTPS port
  15228. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15229. // IPv6 full address with default port
  15230. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15231. detail::make_host_and_port_string(
  15232. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15233. // IPv6 full address with non-default port
  15234. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15235. detail::make_host_and_port_string(
  15236. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15237. // IPv6 localhost with non-default port
  15238. EXPECT_EQ("[::1]:3000",
  15239. detail::make_host_and_port_string("::1", 3000, false));
  15240. // IPv6 with zone ID (link-local address) with default port
  15241. EXPECT_EQ("[fe80::1%eth0]",
  15242. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15243. // IPv6 with zone ID (link-local address) with non-default port
  15244. EXPECT_EQ("[fe80::1%eth0]:8080",
  15245. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15246. // Edge case: Port 443 with is_ssl=false (should add port)
  15247. EXPECT_EQ("example.com:443",
  15248. detail::make_host_and_port_string("example.com", 443, false));
  15249. // Edge case: Port 80 with is_ssl=true (should add port)
  15250. EXPECT_EQ("example.com:80",
  15251. detail::make_host_and_port_string("example.com", 80, true));
  15252. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15253. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15254. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15255. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15256. // Security fix: Already bracketed IPv6 should not get double brackets
  15257. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15258. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15259. EXPECT_EQ("[::1]:8080",
  15260. detail::make_host_and_port_string("[::1]", 8080, false));
  15261. EXPECT_EQ("[2001:db8::1]:8080",
  15262. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15263. EXPECT_EQ("[fe80::1%eth0]",
  15264. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15265. EXPECT_EQ("[fe80::1%eth0]:8080",
  15266. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15267. // Edge case: Empty host (should return as-is)
  15268. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15269. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15270. // This is a known limitation but shouldn't crash
  15271. EXPECT_EQ("[host:name]",
  15272. detail::make_host_and_port_string("host:name", 80, false));
  15273. // Port number edge cases (no validation, but should not crash)
  15274. EXPECT_EQ("example.com:0",
  15275. detail::make_host_and_port_string("example.com", 0, false));
  15276. EXPECT_EQ("example.com:-1",
  15277. detail::make_host_and_port_string("example.com", -1, false));
  15278. EXPECT_EQ("example.com:65535",
  15279. detail::make_host_and_port_string("example.com", 65535, false));
  15280. EXPECT_EQ("example.com:65536",
  15281. detail::make_host_and_port_string("example.com", 65536, false));
  15282. }
  15283. #ifdef CPPHTTPLIB_SSL_ENABLED
  15284. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15285. httplib::SSLClient cli("roblox.com", 443);
  15286. cli.set_follow_location(true);
  15287. auto res = cli.Get("/");
  15288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15289. EXPECT_EQ(StatusCode::OK_200, res->status);
  15290. }
  15291. #endif
  15292. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15293. Server svr;
  15294. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15295. EXPECT_EQ(res.status, 400);
  15296. });
  15297. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15298. auto se = detail::scope_exit([&] {
  15299. svr.stop();
  15300. thread.join();
  15301. ASSERT_FALSE(svr.is_running());
  15302. });
  15303. svr.wait_until_ready();
  15304. Client cli(HOST, PORT);
  15305. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15306. }
  15307. TEST(InvalidHeaderCharsTest, is_field_name) {
  15308. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15309. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15310. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15311. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15312. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15313. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15314. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15315. EXPECT_FALSE(detail::fields::is_field_name(""));
  15316. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15317. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15318. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15319. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15320. }
  15321. TEST(InvalidHeaderCharsTest, is_field_value) {
  15322. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15323. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15324. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15325. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15326. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15327. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15328. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15329. EXPECT_TRUE(detail::fields::is_field_value(""));
  15330. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15331. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15332. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15333. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15334. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15335. }
  15336. TEST(InvalidHeaderCharsTest, OnServer) {
  15337. Server svr;
  15338. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15339. std::string header = "Not Set";
  15340. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15341. res.set_header(header, "value");
  15342. res.set_content("Page Content Page Content", "text/plain");
  15343. });
  15344. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15345. std::string header = "Not Set";
  15346. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15347. res.set_header("X-Test", header);
  15348. res.set_content("Page Content Page Content", "text/plain");
  15349. });
  15350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15351. auto se = detail::scope_exit([&] {
  15352. svr.stop();
  15353. thread.join();
  15354. ASSERT_FALSE(svr.is_running());
  15355. });
  15356. svr.wait_until_ready();
  15357. Client cli(HOST, PORT);
  15358. {
  15359. auto res = cli.Get(
  15360. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15362. EXPECT_EQ("Page Content Page Content", res->body);
  15363. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15364. }
  15365. {
  15366. auto res = cli.Get(
  15367. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15369. EXPECT_EQ("Page Content Page Content", res->body);
  15370. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15371. }
  15372. }
  15373. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15374. auto handled = false;
  15375. Server svr;
  15376. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15377. thread t = thread([&] { svr.listen(HOST, PORT); });
  15378. auto se = detail::scope_exit([&] {
  15379. svr.stop();
  15380. t.join();
  15381. ASSERT_FALSE(svr.is_running());
  15382. ASSERT_FALSE(handled);
  15383. });
  15384. svr.wait_until_ready();
  15385. auto req = "POST /test HTTP/1.1\r\n"
  15386. "Content-Length: x\r\n"
  15387. "\r\n";
  15388. std::string response;
  15389. ASSERT_TRUE(send_request(1, req, &response));
  15390. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15391. response.substr(0, response.find("\r\n")));
  15392. }
  15393. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15394. // case-insensitive, and a server that receives a 100-continue expectation in
  15395. // an HTTP/1.0 request MUST ignore it.
  15396. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15397. std::string response;
  15398. ASSERT_TRUE(send_request(1, req, &response, port));
  15399. *got_100 = response.find("100 Continue") != std::string::npos;
  15400. }
  15401. class ExpectTokenTest : public ::testing::Test {
  15402. protected:
  15403. void SetUp() override {
  15404. svr_.Post("/p", [](const Request &, Response &res) {
  15405. res.set_content("ok", "text/plain");
  15406. });
  15407. port_ = svr_.bind_to_any_port(HOST);
  15408. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15409. svr_.wait_until_ready();
  15410. }
  15411. void TearDown() override {
  15412. svr_.stop();
  15413. if (thread_.joinable()) { thread_.join(); }
  15414. }
  15415. std::string request(const char *version, const char *expect_value) const {
  15416. return std::string("POST /p ") + version +
  15417. "\r\n"
  15418. "Host: localhost\r\n"
  15419. "Content-Length: 2\r\n"
  15420. "Connection: close\r\n"
  15421. "Expect: " +
  15422. expect_value +
  15423. "\r\n"
  15424. "\r\n"
  15425. "hi";
  15426. }
  15427. Server svr_;
  15428. int port_ = 0;
  15429. thread thread_;
  15430. };
  15431. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15432. bool got_100 = false;
  15433. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15434. EXPECT_TRUE(got_100);
  15435. }
  15436. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15437. bool got_100 = true;
  15438. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15439. EXPECT_FALSE(got_100);
  15440. }
  15441. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15442. bool got_100 = false;
  15443. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15444. EXPECT_TRUE(got_100);
  15445. }
  15446. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15447. bool got_100 = false;
  15448. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15449. EXPECT_TRUE(got_100);
  15450. }
  15451. // `100 Continue` is sent only when the server starts reading the body, so a
  15452. // request rejected before that never invites the client to send it. The
  15453. // requests below carry the expectation but withhold the body, as a client
  15454. // waiting for `100 Continue` would.
  15455. // A POST that expects `100 Continue` and withholds its two-byte body.
  15456. static std::string expect_headers_only(const std::string &path) {
  15457. return "POST " + path +
  15458. " HTTP/1.1\r\n"
  15459. "Host: localhost\r\n"
  15460. "Content-Length: 2\r\n"
  15461. "Expect: 100-continue\r\n"
  15462. "\r\n";
  15463. }
  15464. class ExpectLazyContinueTest : public ::testing::Test {
  15465. protected:
  15466. void SetUp() override {
  15467. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15468. if (req.path == "/pre-routing") {
  15469. res.status = StatusCode::Unauthorized_401;
  15470. return Server::HandlerResponse::Handled;
  15471. }
  15472. return Server::HandlerResponse::Unhandled;
  15473. });
  15474. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15475. if (req.matched_route == "/pre-request") {
  15476. res.status = StatusCode::Forbidden_403;
  15477. return Server::HandlerResponse::Handled;
  15478. }
  15479. return Server::HandlerResponse::Unhandled;
  15480. });
  15481. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15482. res.set_content("ok", "text/plain");
  15483. });
  15484. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15485. res.set_content("ok", "text/plain");
  15486. });
  15487. svr_.Post("/reader-used", [](const Request &, Response &res,
  15488. const ContentReader &content_reader) {
  15489. std::string body;
  15490. content_reader([&](const char *data, size_t len) {
  15491. body.append(data, len);
  15492. return true;
  15493. });
  15494. res.set_content(body, "text/plain");
  15495. });
  15496. svr_.Post("/reader-unused",
  15497. [](const Request &, Response &res, const ContentReader &) {
  15498. res.set_content("ignored", "text/plain");
  15499. });
  15500. port_ = svr_.bind_to_any_port(HOST);
  15501. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15502. svr_.wait_until_ready();
  15503. }
  15504. void TearDown() override {
  15505. svr_.stop();
  15506. if (thread_.joinable()) { thread_.join(); }
  15507. }
  15508. // Sends `req` and reads until the server closes the connection. Returns
  15509. // false if the read had to wait for the client-side timeout instead.
  15510. bool send_until_closed(const std::string &req, std::string *resp) const {
  15511. auto start = std::chrono::steady_clock::now();
  15512. if (!send_request(3, req, resp, port_)) { return false; }
  15513. auto elapsed = std::chrono::steady_clock::now() - start;
  15514. return elapsed < std::chrono::seconds(2);
  15515. }
  15516. // The final response comes without `100 Continue`, and the server closes
  15517. // the connection since the body may or may not follow.
  15518. void expect_final_without_interim(const std::string &path,
  15519. const char *status_line) const {
  15520. std::string resp;
  15521. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15522. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15523. EXPECT_EQ(0u, resp.find(status_line));
  15524. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15525. }
  15526. Server svr_;
  15527. int port_ = 0;
  15528. thread thread_;
  15529. };
  15530. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15531. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15532. }
  15533. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15534. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15535. }
  15536. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15537. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15538. }
  15539. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15540. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15541. }
  15542. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15543. // The body follows once `100 Continue` has had time to arrive.
  15544. auto req = expect_headers_only("/reader-used");
  15545. req.insert(req.size() - 2, "Connection: close\r\n");
  15546. std::string resp;
  15547. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15548. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15549. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15550. EXPECT_NE(std::string::npos, resp.find("hi"));
  15551. }
  15552. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15553. // Large enough for the client to add `Expect: 100-continue` itself.
  15554. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15555. std::atomic<bool> body_sent{false};
  15556. Client cli(HOST, port_);
  15557. auto res = cli.Post(
  15558. "/pre-request", length,
  15559. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15560. body_sent = true;
  15561. std::string chunk(len, 'x');
  15562. sink.write(chunk.data(), chunk.size());
  15563. return true;
  15564. },
  15565. "application/octet-stream");
  15566. ASSERT_TRUE(res);
  15567. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15568. EXPECT_FALSE(body_sent);
  15569. }
  15570. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15571. Server svr;
  15572. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15573. return StatusCode::ExpectationFailed_417;
  15574. });
  15575. svr.Post("/p", [](const Request &, Response &res) {
  15576. res.set_content("ok", "text/plain");
  15577. });
  15578. auto port = svr.bind_to_any_port(HOST);
  15579. thread t = thread([&] { svr.listen_after_bind(); });
  15580. auto se = detail::scope_exit([&] {
  15581. svr.stop();
  15582. t.join();
  15583. });
  15584. svr.wait_until_ready();
  15585. std::string resp;
  15586. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15587. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15588. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15589. // Exactly one response: the route handler must not run after the 417.
  15590. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15591. }
  15592. #ifndef _WIN32
  15593. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15594. static constexpr char reject[] = "Unauthorized";
  15595. static constexpr char accept[] = "Upload accepted";
  15596. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15597. Server svr;
  15598. svr.set_expect_100_continue_handler(
  15599. [](const Request & /*req*/, Response &res) {
  15600. res.status = StatusCode::Unauthorized_401;
  15601. res.set_content(reject, "text/plain");
  15602. return res.status;
  15603. });
  15604. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15605. res.set_content(accept, "text/plain");
  15606. });
  15607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15608. auto se = detail::scope_exit([&] {
  15609. svr.stop();
  15610. thread.join();
  15611. ASSERT_FALSE(svr.is_running());
  15612. });
  15613. svr.wait_until_ready();
  15614. {
  15615. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15616. curl_easy_init(), &curl_easy_cleanup};
  15617. ASSERT_NE(curl, nullptr);
  15618. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15619. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15620. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15621. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15622. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15623. &curl_slist_free_all};
  15624. ASSERT_NE(list, nullptr);
  15625. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15626. struct read_data {
  15627. size_t read_size;
  15628. size_t total_size;
  15629. } data = {0, total_size};
  15630. using read_callback_t =
  15631. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15632. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15633. void *userdata) -> size_t {
  15634. read_data *d = (read_data *)userdata;
  15635. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15636. std::fill_n(ptr, size * nmemb, 'A');
  15637. d->read_size += size * nmemb;
  15638. return size * nmemb;
  15639. };
  15640. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15641. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15642. std::vector<char> buffer;
  15643. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15644. using write_callback_t =
  15645. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15646. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15647. void *userdata) -> size_t {
  15648. std::vector<char> *buf = (std::vector<char> *)userdata;
  15649. buf->reserve(buf->size() + size * nmemb + 1);
  15650. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15651. return size * nmemb;
  15652. };
  15653. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15654. {
  15655. const auto res = curl_easy_perform(curl.get());
  15656. ASSERT_EQ(res, CURLE_OK);
  15657. }
  15658. {
  15659. auto response_code = long{};
  15660. const auto res =
  15661. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15662. ASSERT_EQ(res, CURLE_OK);
  15663. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15664. }
  15665. {
  15666. auto dl = curl_off_t{};
  15667. const auto res =
  15668. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15669. ASSERT_EQ(res, CURLE_OK);
  15670. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15671. }
  15672. {
  15673. buffer.push_back('\0');
  15674. ASSERT_STRCASEEQ(buffer.data(), reject);
  15675. }
  15676. }
  15677. }
  15678. #endif
  15679. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15680. // Regression test for #2458.
  15681. //
  15682. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15683. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15684. // ticket can make the client socket spuriously readable during the
  15685. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15686. // the client withholds the body and then blocks reading a response that never
  15687. // comes, failing with `Failed to read connection`.
  15688. //
  15689. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15690. // within the timeout. This raw OpenSSL server deliberately never sends
  15691. // `100 Continue`; the client must still deliver the body and receive 200.
  15692. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15693. signal(SIGPIPE, SIG_IGN);
  15694. const auto port = PORT + 4;
  15695. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15696. ASSERT_NE(srv, INVALID_SOCKET);
  15697. int opt = 1;
  15698. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15699. sockaddr_in addr{};
  15700. addr.sin_family = AF_INET;
  15701. addr.sin_port = htons(static_cast<uint16_t>(port));
  15702. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15703. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15704. ASSERT_EQ(0, ::listen(srv, 1));
  15705. std::atomic<size_t> server_body_bytes{0};
  15706. auto server_thread = std::thread([&] {
  15707. sockaddr_in cli_addr{};
  15708. socklen_t cli_len = sizeof(cli_addr);
  15709. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15710. if (cli == INVALID_SOCKET) { return; }
  15711. // Bound the lifetime of the server side so a buggy client (which never
  15712. // sends the body) cannot make this thread block forever on join.
  15713. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15714. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15715. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15716. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15717. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15718. SSL *ssl = SSL_new(ctx);
  15719. SSL_set_fd(ssl, static_cast<int>(cli));
  15720. if (SSL_accept(ssl) > 0) {
  15721. // Read the request headers. Reading here also flushes the TLS 1.3
  15722. // session tickets to the client. Deliberately do NOT send
  15723. // `100 Continue`.
  15724. std::string buf;
  15725. char tmp[1024];
  15726. while (buf.find("\r\n\r\n") == std::string::npos) {
  15727. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15728. if (n <= 0) { break; }
  15729. buf.append(tmp, static_cast<size_t>(n));
  15730. }
  15731. // A correct client sends the body now; count what arrives.
  15732. auto pos = buf.find("\r\n\r\n");
  15733. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15734. while (body < 4096) {
  15735. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15736. if (n <= 0) { break; }
  15737. body += static_cast<size_t>(n);
  15738. }
  15739. server_body_bytes = body;
  15740. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15741. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15742. SSL_shutdown(ssl);
  15743. }
  15744. SSL_free(ssl);
  15745. detail::close_socket(cli);
  15746. SSL_CTX_free(ctx);
  15747. });
  15748. auto se = detail::scope_exit([&] {
  15749. server_thread.join();
  15750. detail::close_socket(srv);
  15751. });
  15752. SSLClient cli("127.0.0.1", port);
  15753. cli.enable_server_certificate_verification(false);
  15754. cli.set_connection_timeout(5, 0);
  15755. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15756. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15757. std::string body(4096, 'A');
  15758. auto res = cli.Put("/api/test", body, "application/json");
  15759. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15760. EXPECT_EQ(StatusCode::OK_200, res->status);
  15761. EXPECT_EQ(body.size(), server_body_bytes.load());
  15762. }
  15763. #endif
  15764. template <typename S, typename C>
  15765. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15766. svr.Get("/stream", [&](const Request &, Response &res) {
  15767. auto data = new std::string("01234567890123456789");
  15768. res.set_content_provider(
  15769. data->size(), "text/plain",
  15770. [&, data](size_t offset, size_t length, DataSink &sink) {
  15771. const size_t DATA_CHUNK_SIZE = 4;
  15772. const auto &d = *data;
  15773. std::this_thread::sleep_for(std::chrono::seconds(1));
  15774. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15775. return true;
  15776. },
  15777. [data](bool success) {
  15778. EXPECT_FALSE(success);
  15779. delete data;
  15780. });
  15781. });
  15782. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15783. auto i = new size_t(0);
  15784. res.set_content_provider(
  15785. "text/plain",
  15786. [i](size_t, DataSink &sink) {
  15787. if (*i < 5) {
  15788. std::this_thread::sleep_for(std::chrono::seconds(1));
  15789. sink.write("abcd", 4);
  15790. (*i)++;
  15791. } else {
  15792. sink.done();
  15793. }
  15794. return true;
  15795. },
  15796. [i](bool success) {
  15797. EXPECT_FALSE(success);
  15798. delete i;
  15799. });
  15800. });
  15801. svr.Get("/chunked", [&](const Request &, Response &res) {
  15802. auto i = new size_t(0);
  15803. res.set_chunked_content_provider(
  15804. "text/plain",
  15805. [i](size_t, DataSink &sink) {
  15806. if (*i < 5) {
  15807. std::this_thread::sleep_for(std::chrono::seconds(1));
  15808. sink.os << "abcd";
  15809. (*i)++;
  15810. } else {
  15811. sink.done();
  15812. }
  15813. return true;
  15814. },
  15815. [i](bool success) {
  15816. EXPECT_FALSE(success);
  15817. delete i;
  15818. });
  15819. });
  15820. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15821. auto se = detail::scope_exit([&] {
  15822. svr.stop();
  15823. listen_thread.join();
  15824. ASSERT_FALSE(svr.is_running());
  15825. });
  15826. svr.wait_until_ready();
  15827. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15828. {
  15829. auto start = std::chrono::steady_clock::now();
  15830. auto res = cli.Get("/stream");
  15831. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15832. std::chrono::steady_clock::now() - start)
  15833. .count();
  15834. ASSERT_FALSE(res);
  15835. EXPECT_EQ(Error::Read, res.error());
  15836. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15837. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15838. }
  15839. {
  15840. auto start = std::chrono::steady_clock::now();
  15841. auto res = cli.Get("/stream_without_length");
  15842. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15843. std::chrono::steady_clock::now() - start)
  15844. .count();
  15845. ASSERT_FALSE(res);
  15846. EXPECT_EQ(Error::Read, res.error());
  15847. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15848. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15849. }
  15850. {
  15851. auto start = std::chrono::steady_clock::now();
  15852. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15853. EXPECT_EQ("abcd", string(data, data_length));
  15854. return true;
  15855. });
  15856. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15857. std::chrono::steady_clock::now() - start)
  15858. .count();
  15859. ASSERT_FALSE(res);
  15860. EXPECT_EQ(Error::Read, res.error());
  15861. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15862. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15863. }
  15864. }
  15865. TEST(MaxTimeoutTest, ContentStream) {
  15866. time_t timeout = 2000;
  15867. time_t threshold = 200;
  15868. Server svr;
  15869. Client cli("localhost", PORT);
  15870. max_timeout_test(svr, cli, timeout, threshold);
  15871. }
  15872. #ifdef CPPHTTPLIB_SSL_ENABLED
  15873. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15874. time_t timeout = 2000;
  15875. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15877. SSLClient cli("localhost", PORT);
  15878. cli.enable_server_certificate_verification(false);
  15879. max_timeout_test(svr, cli, timeout, threshold);
  15880. }
  15881. #endif
  15882. class EventDispatcher {
  15883. public:
  15884. EventDispatcher() {}
  15885. bool wait_event(DataSink *sink) {
  15886. unique_lock<mutex> lk(m_);
  15887. int id = id_;
  15888. // Wait with timeout to prevent hanging if client disconnects
  15889. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15890. [&] { return cid_ == id; })) {
  15891. return false; // Timeout occurred
  15892. }
  15893. sink->write(message_.data(), message_.size());
  15894. return true;
  15895. }
  15896. void send_event(const string &message) {
  15897. lock_guard<mutex> lk(m_);
  15898. cid_ = id_++;
  15899. message_ = message;
  15900. cv_.notify_all();
  15901. }
  15902. private:
  15903. mutex m_;
  15904. condition_variable cv_;
  15905. atomic_int id_{0};
  15906. atomic_int cid_{-1};
  15907. string message_;
  15908. };
  15909. TEST(ClientInThreadTest, Issue2068) {
  15910. EventDispatcher ed;
  15911. Server svr;
  15912. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15913. res.set_chunked_content_provider("text/event-stream",
  15914. [&](size_t /*offset*/, DataSink &sink) {
  15915. return ed.wait_event(&sink);
  15916. });
  15917. });
  15918. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15919. svr.wait_until_ready();
  15920. thread event_thread([&] {
  15921. int id = 0;
  15922. while (svr.is_running()) {
  15923. this_thread::sleep_for(chrono::milliseconds(500));
  15924. std::stringstream ss;
  15925. ss << "data: " << id << "\n\n";
  15926. ed.send_event(ss.str());
  15927. id++;
  15928. }
  15929. });
  15930. auto se = detail::scope_exit([&] {
  15931. svr.stop();
  15932. listen_thread.join();
  15933. event_thread.join();
  15934. ASSERT_FALSE(svr.is_running());
  15935. });
  15936. {
  15937. auto client = detail::make_unique<Client>(HOST, PORT);
  15938. client->set_read_timeout(std::chrono::minutes(10));
  15939. std::atomic<bool> stop{false};
  15940. std::thread t([&] {
  15941. client->Get("/event1",
  15942. [&](const char *, size_t) -> bool { return !stop; });
  15943. });
  15944. std::this_thread::sleep_for(std::chrono::seconds(2));
  15945. stop = true;
  15946. client->stop();
  15947. t.join();
  15948. // Reset client after thread has finished
  15949. client.reset();
  15950. }
  15951. }
  15952. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15953. auto handled = false;
  15954. Server svr;
  15955. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15956. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15957. auto se = detail::scope_exit([&] {
  15958. svr.stop();
  15959. t.join();
  15960. ASSERT_FALSE(svr.is_running());
  15961. ASSERT_FALSE(handled);
  15962. });
  15963. svr.wait_until_ready();
  15964. // Two Content-Length headers with different values — must be rejected
  15965. auto req = "POST /test HTTP/1.1\r\n"
  15966. "Content-Length: 5\r\n"
  15967. "Content-Length: 10\r\n"
  15968. "\r\n"
  15969. "hello";
  15970. std::string response;
  15971. ASSERT_TRUE(send_request(1, req, &response));
  15972. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15973. response.substr(0, response.find("\r\n")));
  15974. }
  15975. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15976. auto handled = false;
  15977. Server svr;
  15978. svr.Post("/test", [&](const Request &, Response &res) {
  15979. handled = true;
  15980. res.set_content("ok", "text/plain");
  15981. });
  15982. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15983. auto se = detail::scope_exit([&] {
  15984. svr.stop();
  15985. t.join();
  15986. ASSERT_FALSE(svr.is_running());
  15987. ASSERT_TRUE(handled);
  15988. });
  15989. svr.wait_until_ready();
  15990. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15991. auto req = "POST /test HTTP/1.1\r\n"
  15992. "Content-Length: 5\r\n"
  15993. "Content-Length: 5\r\n"
  15994. "\r\n"
  15995. "hello";
  15996. std::string response;
  15997. ASSERT_TRUE(send_request(1, req, &response));
  15998. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15999. }
  16000. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16001. Server svr;
  16002. svr.Get("/", [](const Request &req, Response &res) {
  16003. EXPECT_EQ(2U, req.trailers.size());
  16004. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16005. // Denied
  16006. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16007. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16008. // Accepted
  16009. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16010. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16011. EXPECT_TRUE(req.has_trailer("X-World"));
  16012. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16013. res.set_content("ok", "text/plain");
  16014. });
  16015. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16016. auto se = detail::scope_exit([&] {
  16017. svr.stop();
  16018. t.join();
  16019. ASSERT_FALSE(svr.is_running());
  16020. });
  16021. svr.wait_until_ready();
  16022. const std::string req = "GET / HTTP/1.1\r\n"
  16023. "Transfer-Encoding: chunked\r\n"
  16024. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16025. "\r\n"
  16026. "0\r\n"
  16027. "Content-Length: 10\r\n"
  16028. "Host: internal.local\r\n"
  16029. "Content-Type: malicious/content\r\n"
  16030. "Cookie: any\r\n"
  16031. "Set-Cookie: any\r\n"
  16032. "X-Forwarded-For: attacker.com\r\n"
  16033. "X-Real-Ip: 1.1.1.1\r\n"
  16034. "X-Hello: hello\r\n"
  16035. "X-World: world\r\n"
  16036. "\r\n";
  16037. std::string res;
  16038. ASSERT_TRUE(send_request(1, req, &res));
  16039. }
  16040. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16041. // several field lines, and the combined value is what has to be parsed. A
  16042. // Trailer field split across lines therefore declares every name it lists;
  16043. // reading only the first line silently drops the trailers the later lines
  16044. // declare. The prohibited-trailer filter still applies to every line.
  16045. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16046. Server svr;
  16047. size_t observed_trailer_count = 0;
  16048. std::string observed_hello;
  16049. std::string observed_world;
  16050. bool observed_content_length = true;
  16051. svr.Get("/", [&](const Request &req, Response &res) {
  16052. observed_trailer_count = req.trailers.size();
  16053. observed_hello = req.get_trailer_value("X-Hello");
  16054. observed_world = req.get_trailer_value("X-World");
  16055. observed_content_length = req.has_trailer("Content-Length");
  16056. res.set_content("ok", "text/plain");
  16057. });
  16058. auto port = svr.bind_to_any_port(HOST);
  16059. thread t = thread([&]() { svr.listen_after_bind(); });
  16060. auto se = detail::scope_exit([&] {
  16061. svr.stop();
  16062. t.join();
  16063. ASSERT_FALSE(svr.is_running());
  16064. });
  16065. svr.wait_until_ready();
  16066. const std::string req = "GET / HTTP/1.1\r\n"
  16067. "Transfer-Encoding: chunked\r\n"
  16068. "Trailer: X-Hello\r\n"
  16069. "Trailer: X-World, Content-Length\r\n"
  16070. "\r\n"
  16071. "0\r\n"
  16072. "X-Hello: hello\r\n"
  16073. "X-World: world\r\n"
  16074. "Content-Length: 10\r\n"
  16075. "\r\n";
  16076. std::string res;
  16077. ASSERT_TRUE(send_request(1, req, &res, port));
  16078. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16079. // Accepted: both field lines contribute to the declared set
  16080. EXPECT_EQ(2U, observed_trailer_count);
  16081. EXPECT_EQ(observed_hello, "hello");
  16082. EXPECT_EQ(observed_world, "world");
  16083. // Denied: a prohibited name stays prohibited on a later field line
  16084. EXPECT_FALSE(observed_content_length);
  16085. }
  16086. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16087. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16088. // unbounded run of fields that are never declared, because the counter would
  16089. // only advance for declared fields.
  16090. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16091. Server svr;
  16092. bool handler_called = false;
  16093. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16094. handler_called = true;
  16095. res.set_content("ok", "text/plain");
  16096. });
  16097. auto port = svr.bind_to_any_port(HOST);
  16098. thread t = thread([&]() { svr.listen_after_bind(); });
  16099. auto se = detail::scope_exit([&] {
  16100. svr.stop();
  16101. t.join();
  16102. ASSERT_FALSE(svr.is_running());
  16103. });
  16104. svr.wait_until_ready();
  16105. // Declare nothing, then send far more undeclared trailer fields than the
  16106. // header-count limit. Parsing must stop and reject the request rather than
  16107. // read every line.
  16108. std::string req = "GET / HTTP/1.1\r\n"
  16109. "Transfer-Encoding: chunked\r\n"
  16110. "\r\n"
  16111. "0\r\n";
  16112. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16113. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16114. }
  16115. req += "\r\n";
  16116. std::string res;
  16117. ASSERT_TRUE(send_request(1, req, &res, port));
  16118. // The request is rejected before the handler runs.
  16119. EXPECT_FALSE(handler_called);
  16120. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16121. }
  16122. // The set of declared trailer names is capped so a peer cannot grow it without
  16123. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16124. // declared past the cap is not honored, even if the field is actually sent.
  16125. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16126. Server svr;
  16127. // One name inside the cap and one past it, so the test tracks the cap rather
  16128. // than a fixed count.
  16129. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16130. const std::string within_cap_name = "X-T-0";
  16131. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16132. bool observed_within_cap = false;
  16133. bool observed_past_cap = false;
  16134. svr.Get("/", [&](const Request &req, Response &res) {
  16135. observed_within_cap = req.has_trailer(within_cap_name);
  16136. observed_past_cap = req.has_trailer(past_cap_name);
  16137. res.set_content("ok", "text/plain");
  16138. });
  16139. auto port = svr.bind_to_any_port(HOST);
  16140. thread t = thread([&]() { svr.listen_after_bind(); });
  16141. auto se = detail::scope_exit([&] {
  16142. svr.stop();
  16143. t.join();
  16144. ASSERT_FALSE(svr.is_running());
  16145. });
  16146. svr.wait_until_ready();
  16147. // Declare more trailer names than the cap in a single Trailer field, then
  16148. // actually send the first (within the cap) and the last (past it).
  16149. std::string trailer_decl = "Trailer: ";
  16150. for (int i = 0; i < declared_count; i++) {
  16151. if (i != 0) { trailer_decl += ", "; }
  16152. trailer_decl += "X-T-" + std::to_string(i);
  16153. }
  16154. trailer_decl += "\r\n";
  16155. const std::string req = "GET / HTTP/1.1\r\n"
  16156. "Transfer-Encoding: chunked\r\n" +
  16157. trailer_decl +
  16158. "\r\n"
  16159. "0\r\n" +
  16160. within_cap_name + ": a\r\n" + past_cap_name +
  16161. ": b\r\n"
  16162. "\r\n";
  16163. std::string res;
  16164. ASSERT_TRUE(send_request(1, req, &res, port));
  16165. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16166. // A name within the cap is honored; one declared past the cap is dropped.
  16167. EXPECT_TRUE(observed_within_cap);
  16168. EXPECT_FALSE(observed_past_cap);
  16169. }
  16170. // A direct client that is not listed in trusted_proxies must not be able to
  16171. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16172. // the peer address on the actual TCP connection determines whether the
  16173. // header is honored.
  16174. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16175. Server svr;
  16176. // Deliberately does NOT include the loopback address the test client
  16177. // actually connects from, so the direct connection is not a trusted proxy.
  16178. svr.set_trusted_proxies({"203.0.113.66"});
  16179. std::string observed_remote_addr;
  16180. svr.Get("/ip", [&](const Request &req, Response &res) {
  16181. observed_remote_addr = req.remote_addr;
  16182. res.set_content("ok", "text/plain");
  16183. });
  16184. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16185. auto se = detail::scope_exit([&] {
  16186. svr.stop();
  16187. t.join();
  16188. ASSERT_FALSE(svr.is_running());
  16189. });
  16190. svr.wait_until_ready();
  16191. Client cli(HOST, PORT);
  16192. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16194. EXPECT_EQ(StatusCode::OK_200, res->status);
  16195. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16196. // ignored entirely and the real connection-level address retained.
  16197. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16198. observed_remote_addr == "127.0.0.1");
  16199. }
  16200. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16201. Server svr;
  16202. std::string observed_remote_addr;
  16203. std::string observed_xff;
  16204. svr.Get("/ip", [&](const Request &req, Response &res) {
  16205. observed_remote_addr = req.remote_addr;
  16206. observed_xff = req.get_header_value("X-Forwarded-For");
  16207. res.set_content("ok", "text/plain");
  16208. });
  16209. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16210. auto se = detail::scope_exit([&] {
  16211. svr.stop();
  16212. t.join();
  16213. ASSERT_FALSE(svr.is_running());
  16214. });
  16215. svr.wait_until_ready();
  16216. Client cli(HOST, PORT);
  16217. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16219. EXPECT_EQ(StatusCode::OK_200, res->status);
  16220. EXPECT_EQ(observed_xff, "203.0.113.66");
  16221. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16222. observed_remote_addr == "127.0.0.1");
  16223. }
  16224. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16225. Server svr;
  16226. svr.set_trusted_proxies({"203.0.113.66"});
  16227. std::string observed_remote_addr;
  16228. std::string observed_xff;
  16229. svr.Get("/ip", [&](const Request &req, Response &res) {
  16230. observed_remote_addr = req.remote_addr;
  16231. observed_xff = req.get_header_value("X-Forwarded-For");
  16232. res.set_content("ok", "text/plain");
  16233. });
  16234. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16235. auto se = detail::scope_exit([&] {
  16236. svr.stop();
  16237. t.join();
  16238. ASSERT_FALSE(svr.is_running());
  16239. });
  16240. svr.wait_until_ready();
  16241. Client cli(HOST, PORT);
  16242. auto res = cli.Get("/ip");
  16243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16244. EXPECT_EQ(StatusCode::OK_200, res->status);
  16245. EXPECT_EQ(observed_xff, "");
  16246. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16247. observed_remote_addr == "127.0.0.1");
  16248. }
  16249. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16250. Server svr;
  16251. // Include the loopback address the test client actually connects from, so
  16252. // the direct connection itself is recognized as the trusted proxy hop.
  16253. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16254. std::string observed_remote_addr;
  16255. std::string observed_xff;
  16256. svr.Get("/ip", [&](const Request &req, Response &res) {
  16257. observed_remote_addr = req.remote_addr;
  16258. observed_xff = req.get_header_value("X-Forwarded-For");
  16259. res.set_content("ok", "text/plain");
  16260. });
  16261. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16262. auto se = detail::scope_exit([&] {
  16263. svr.stop();
  16264. t.join();
  16265. ASSERT_FALSE(svr.is_running());
  16266. });
  16267. svr.wait_until_ready();
  16268. Client cli(HOST, PORT);
  16269. auto res = cli.Get(
  16270. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16272. EXPECT_EQ(StatusCode::OK_200, res->status);
  16273. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16274. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16275. }
  16276. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16277. Server svr;
  16278. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16279. std::string observed_remote_addr;
  16280. std::string observed_xff;
  16281. svr.Get("/ip", [&](const Request &req, Response &res) {
  16282. observed_remote_addr = req.remote_addr;
  16283. observed_xff = req.get_header_value("X-Forwarded-For");
  16284. res.set_content("ok", "text/plain");
  16285. });
  16286. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16287. auto se = detail::scope_exit([&] {
  16288. svr.stop();
  16289. t.join();
  16290. ASSERT_FALSE(svr.is_running());
  16291. });
  16292. svr.wait_until_ready();
  16293. Client cli(HOST, PORT);
  16294. auto res = cli.Get(
  16295. "/ip",
  16296. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16298. EXPECT_EQ(StatusCode::OK_200, res->status);
  16299. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16300. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16301. }
  16302. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16303. Server svr;
  16304. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16305. std::string observed_remote_addr;
  16306. std::string observed_xff;
  16307. svr.Get("/ip", [&](const Request &req, Response &res) {
  16308. observed_remote_addr = req.remote_addr;
  16309. observed_xff = req.get_header_value("X-Forwarded-For");
  16310. res.set_content("ok", "text/plain");
  16311. });
  16312. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16313. auto se = detail::scope_exit([&] {
  16314. svr.stop();
  16315. t.join();
  16316. ASSERT_FALSE(svr.is_running());
  16317. });
  16318. svr.wait_until_ready();
  16319. Client cli(HOST, PORT);
  16320. auto res = cli.Get(
  16321. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16323. EXPECT_EQ(StatusCode::OK_200, res->status);
  16324. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16325. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16326. // and must not be selected.
  16327. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16328. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16329. }
  16330. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16331. Server svr;
  16332. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16333. std::string observed_remote_addr;
  16334. svr.Get("/ip", [&](const Request &req, Response &res) {
  16335. observed_remote_addr = req.remote_addr;
  16336. res.set_content("ok", "text/plain");
  16337. });
  16338. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16339. auto se = detail::scope_exit([&] {
  16340. svr.stop();
  16341. t.join();
  16342. ASSERT_FALSE(svr.is_running());
  16343. });
  16344. svr.wait_until_ready();
  16345. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16346. // a forged address and the trusted proxy's own address; the forged value must
  16347. // not win over the address the trusted proxy actually recorded.
  16348. Client cli(HOST, PORT);
  16349. auto res = cli.Get(
  16350. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16352. EXPECT_EQ(StatusCode::OK_200, res->status);
  16353. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16354. }
  16355. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16356. Server svr;
  16357. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16358. std::string observed_remote_addr;
  16359. std::string observed_xff;
  16360. svr.Get("/ip", [&](const Request &req, Response &res) {
  16361. observed_remote_addr = req.remote_addr;
  16362. observed_xff = req.get_header_value("X-Forwarded-For");
  16363. res.set_content("ok", "text/plain");
  16364. });
  16365. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16366. auto se = detail::scope_exit([&] {
  16367. svr.stop();
  16368. t.join();
  16369. ASSERT_FALSE(svr.is_running());
  16370. });
  16371. svr.wait_until_ready();
  16372. Client cli(HOST, PORT);
  16373. auto res = cli.Get(
  16374. "/ip",
  16375. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16377. EXPECT_EQ(StatusCode::OK_200, res->status);
  16378. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16379. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16380. }
  16381. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16382. Server svr;
  16383. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16384. std::string observed_remote_addr;
  16385. std::string observed_xff;
  16386. svr.Get("/ip", [&](const Request &req, Response &res) {
  16387. observed_remote_addr = req.remote_addr;
  16388. observed_xff = req.get_header_value("X-Forwarded-For");
  16389. res.set_content("ok", "text/plain");
  16390. });
  16391. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16392. auto se = detail::scope_exit([&] {
  16393. svr.stop();
  16394. t.join();
  16395. ASSERT_FALSE(svr.is_running());
  16396. });
  16397. svr.wait_until_ready();
  16398. std::string raw_req =
  16399. "GET /ip HTTP/1.1\r\n"
  16400. "Host: localhost\r\n"
  16401. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16402. "Connection: close\r\n"
  16403. "\r\n";
  16404. std::string out;
  16405. ASSERT_TRUE(send_request(5, raw_req, &out));
  16406. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16407. // Header parser trims surrounding whitespace of the header value
  16408. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16409. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16410. }
  16411. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16412. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16413. // their own X-Forwarded-For as a separate field line rather than extending the
  16414. // one the client sent, so every occurrence has to be taken into account.
  16415. // Reading only the first one hands back the address the client chose.
  16416. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16417. Server svr;
  16418. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16419. std::string observed_remote_addr;
  16420. size_t observed_xff_count = 0;
  16421. svr.Get("/ip", [&](const Request &req, Response &res) {
  16422. observed_remote_addr = req.remote_addr;
  16423. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16424. res.set_content("ok", "text/plain");
  16425. });
  16426. auto port = svr.bind_to_any_port(HOST);
  16427. thread t = thread([&]() { svr.listen_after_bind(); });
  16428. auto se = detail::scope_exit([&] {
  16429. svr.stop();
  16430. t.join();
  16431. ASSERT_FALSE(svr.is_running());
  16432. });
  16433. svr.wait_until_ready();
  16434. // The client supplies the first field line; the trusted proxy appends the
  16435. // address it observed as a second one.
  16436. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16437. "Host: localhost\r\n"
  16438. "X-Forwarded-For: 1.2.3.4\r\n"
  16439. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16440. "Connection: close\r\n"
  16441. "\r\n";
  16442. std::string out;
  16443. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16444. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16445. EXPECT_EQ(observed_xff_count, 2U);
  16446. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16447. // The same chain spread over one field line per hop derives the same client
  16448. // address, i.e. the split and the comma-joined representations agree.
  16449. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16450. "Host: localhost\r\n"
  16451. "X-Forwarded-For: 1.2.3.4\r\n"
  16452. "X-Forwarded-For: 198.51.100.23\r\n"
  16453. "X-Forwarded-For: 192.0.2.45\r\n"
  16454. "Connection: close\r\n"
  16455. "\r\n";
  16456. out.clear();
  16457. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16458. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16459. EXPECT_EQ(observed_xff_count, 3U);
  16460. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16461. }
  16462. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16463. // crash the server (it used to call front() on an empty vector inside
  16464. // get_client_ip). The connection-level remote address must be retained instead.
  16465. static void run_malformed_xff_test(const std::string &xff_value) {
  16466. Server svr;
  16467. svr.set_trusted_proxies({"192.0.2.45"});
  16468. std::string observed_remote_addr;
  16469. svr.Get("/ip", [&](const Request &req, Response &res) {
  16470. observed_remote_addr = req.remote_addr;
  16471. res.set_content("ok", "text/plain");
  16472. });
  16473. int port = 0;
  16474. thread t = thread([&]() {
  16475. port = svr.bind_to_any_port(HOST);
  16476. svr.listen_after_bind();
  16477. });
  16478. auto se = detail::scope_exit([&] {
  16479. svr.stop();
  16480. t.join();
  16481. ASSERT_FALSE(svr.is_running());
  16482. });
  16483. svr.wait_until_ready();
  16484. Client cli(HOST, port);
  16485. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16487. EXPECT_EQ(StatusCode::OK_200, res->status);
  16488. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16489. observed_remote_addr == "127.0.0.1");
  16490. }
  16491. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16492. run_malformed_xff_test("");
  16493. }
  16494. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16495. run_malformed_xff_test(",");
  16496. }
  16497. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16498. run_malformed_xff_test(", , ,");
  16499. }
  16500. // The same rule applies to Accept: a request whose acceptable types are spread
  16501. // over several field lines must be negotiated against all of them.
  16502. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16503. // case-insensitive connection options. Comparing the whole field value against
  16504. // one option misses a client that sends several of them, and misses every
  16505. // casing but the one written in the comparison.
  16506. //
  16507. // Sends req, reads the response, then reuses the same socket for a second
  16508. // request to find out whether the server kept the connection.
  16509. static void probe_connection_reuse(int port, const std::string &req,
  16510. bool *announced_close, bool *reusable) {
  16511. auto error = Error::Success;
  16512. auto sock = detail::create_client_socket(
  16513. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16514. /*connection_timeout_sec=*/5, 0,
  16515. /*read_timeout_sec=*/1, 0,
  16516. /*write_timeout_sec=*/5, 0, std::string(), error);
  16517. ASSERT_NE(sock, INVALID_SOCKET);
  16518. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16519. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16520. "Host: localhost\r\n"
  16521. "Connection: close\r\n"
  16522. "\r\n";
  16523. std::string first_response;
  16524. std::string second_response;
  16525. detail::process_client_socket(
  16526. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16527. [&](Stream &strm) {
  16528. if (strm.write(req.data(), req.size()) !=
  16529. static_cast<ssize_t>(req.size())) {
  16530. return false;
  16531. }
  16532. char buf[512];
  16533. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16534. // Headers plus the two-byte body of the handler below
  16535. while (reader.getline()) {
  16536. first_response += reader.ptr();
  16537. if (first_response.find("ok") != std::string::npos) { break; }
  16538. }
  16539. if (strm.write(second.data(), second.size()) !=
  16540. static_cast<ssize_t>(second.size())) {
  16541. return true;
  16542. }
  16543. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16544. while (reader2.getline()) {
  16545. second_response += reader2.ptr();
  16546. if (second_response.find("ok") != std::string::npos) { break; }
  16547. }
  16548. return true;
  16549. });
  16550. *announced_close =
  16551. first_response.find("Connection: close") != std::string::npos;
  16552. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16553. }
  16554. class ConnectionTokenTest : public ::testing::Test {
  16555. protected:
  16556. void SetUp() override {
  16557. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16558. res.set_content("ok", "text/plain");
  16559. });
  16560. port_ = svr_.bind_to_any_port(HOST);
  16561. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16562. svr_.wait_until_ready();
  16563. }
  16564. void TearDown() override {
  16565. svr_.stop();
  16566. if (thread_.joinable()) { thread_.join(); }
  16567. }
  16568. Server svr_;
  16569. int port_ = 0;
  16570. thread thread_;
  16571. };
  16572. // "close" alongside another option still closes the connection, and the
  16573. // response says so rather than leaving the peer to discover it.
  16574. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16575. bool announced_close = false;
  16576. bool reusable = true;
  16577. probe_connection_reuse(port_,
  16578. "GET /keepalive HTTP/1.1\r\n"
  16579. "Host: localhost\r\n"
  16580. "Connection: keep-alive, close\r\n"
  16581. "\r\n",
  16582. &announced_close, &reusable);
  16583. EXPECT_TRUE(announced_close);
  16584. EXPECT_FALSE(reusable);
  16585. }
  16586. // "close" split over two field lines is the same list, so it is honored too.
  16587. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16588. bool announced_close = false;
  16589. bool reusable = true;
  16590. probe_connection_reuse(port_,
  16591. "GET /keepalive HTTP/1.1\r\n"
  16592. "Host: localhost\r\n"
  16593. "Connection: keep-alive\r\n"
  16594. "Connection: close\r\n"
  16595. "\r\n",
  16596. &announced_close, &reusable);
  16597. EXPECT_TRUE(announced_close);
  16598. EXPECT_FALSE(reusable);
  16599. }
  16600. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16601. // keep-alive in the spelling everyone actually sends keeps its connection.
  16602. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16603. bool announced_close = false;
  16604. bool reusable = false;
  16605. probe_connection_reuse(port_,
  16606. "GET /keepalive HTTP/1.0\r\n"
  16607. "Host: localhost\r\n"
  16608. "Connection: keep-alive\r\n"
  16609. "\r\n",
  16610. &announced_close, &reusable);
  16611. EXPECT_FALSE(announced_close);
  16612. EXPECT_TRUE(reusable);
  16613. }
  16614. // A token the value merely contains is not the token itself.
  16615. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16616. bool announced_close = false;
  16617. bool reusable = false;
  16618. probe_connection_reuse(port_,
  16619. "GET /keepalive HTTP/1.1\r\n"
  16620. "Host: localhost\r\n"
  16621. "Connection: notclose\r\n"
  16622. "\r\n",
  16623. &announced_close, &reusable);
  16624. EXPECT_FALSE(announced_close);
  16625. EXPECT_TRUE(reusable);
  16626. }
  16627. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16628. Server svr;
  16629. std::vector<std::string> observed_types;
  16630. svr.Get("/", [&](const Request &req, Response &res) {
  16631. observed_types = req.accept_content_types;
  16632. res.set_content("ok", "text/plain");
  16633. });
  16634. auto port = svr.bind_to_any_port(HOST);
  16635. thread t = thread([&]() { svr.listen_after_bind(); });
  16636. auto se = detail::scope_exit([&] {
  16637. svr.stop();
  16638. t.join();
  16639. ASSERT_FALSE(svr.is_running());
  16640. });
  16641. svr.wait_until_ready();
  16642. Client cli(HOST, port);
  16643. Headers headers;
  16644. headers.emplace("Accept", "text/plain;q=0.5");
  16645. headers.emplace("Accept", "application/json");
  16646. auto res = cli.Get("/", headers);
  16647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16648. EXPECT_EQ(StatusCode::OK_200, res->status);
  16649. // Sorted by q-value, so the second field line's type comes first
  16650. ASSERT_EQ(2U, observed_types.size());
  16651. EXPECT_EQ("application/json", observed_types[0]);
  16652. EXPECT_EQ("text/plain", observed_types[1]);
  16653. }
  16654. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16655. // empty field line must not contribute a bare comma to the combined value.
  16656. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16657. Server svr;
  16658. std::vector<std::string> observed_types;
  16659. svr.Get("/", [&](const Request &req, Response &res) {
  16660. observed_types = req.accept_content_types;
  16661. res.set_content("ok", "text/plain");
  16662. });
  16663. auto port = svr.bind_to_any_port(HOST);
  16664. thread t = thread([&]() { svr.listen_after_bind(); });
  16665. auto se = detail::scope_exit([&] {
  16666. svr.stop();
  16667. t.join();
  16668. ASSERT_FALSE(svr.is_running());
  16669. });
  16670. svr.wait_until_ready();
  16671. // Empty first field line, then a real one
  16672. std::string raw_req = "GET / HTTP/1.1\r\n"
  16673. "Host: localhost\r\n"
  16674. "Accept:\r\n"
  16675. "Accept: application/json\r\n"
  16676. "Connection: close\r\n"
  16677. "\r\n";
  16678. std::string out;
  16679. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16680. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16681. ASSERT_EQ(1U, observed_types.size());
  16682. EXPECT_EQ("application/json", observed_types[0]);
  16683. }
  16684. // The skip in get_combined_header_value() is what keeps an empty field line
  16685. // from contributing a bare comma. Only a trailing empty field line exercises
  16686. // it: a leading one is already covered by the "combined is still empty" check,
  16687. // and parse_accept_header() now ignores the empty element either way, so the
  16688. // request-level test above can no longer tell the two apart.
  16689. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16690. Headers headers;
  16691. headers.emplace("Accept", "text/html");
  16692. headers.emplace("Accept", "");
  16693. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16694. headers.clear();
  16695. headers.emplace("Accept", "");
  16696. headers.emplace("Accept", "application/json");
  16697. EXPECT_EQ("application/json",
  16698. detail::get_combined_header_value(headers, "Accept"));
  16699. }
  16700. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16701. // An encoding offered on a later Accept-Encoding field line is still offered.
  16702. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16703. Server svr;
  16704. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16705. res.set_content(std::string(1024, 'x'), "text/plain");
  16706. });
  16707. auto port = svr.bind_to_any_port(HOST);
  16708. thread t = thread([&]() { svr.listen_after_bind(); });
  16709. auto se = detail::scope_exit([&] {
  16710. svr.stop();
  16711. t.join();
  16712. ASSERT_FALSE(svr.is_running());
  16713. });
  16714. svr.wait_until_ready();
  16715. Client cli(HOST, port);
  16716. cli.set_decompress(false);
  16717. Headers headers;
  16718. headers.emplace("Accept-Encoding", "identity");
  16719. headers.emplace("Accept-Encoding", "gzip");
  16720. auto res = cli.Get("/", headers);
  16721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16722. EXPECT_EQ(StatusCode::OK_200, res->status);
  16723. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16724. }
  16725. #endif
  16726. #ifndef _WIN32
  16727. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16728. Server svr;
  16729. svr.Post("/post", [&](const Request &req, Response &res) {
  16730. res.set_content(req.body, "text/plain");
  16731. });
  16732. svr.Put("/put", [&](const Request &req, Response &res) {
  16733. res.set_content(req.body, "text/plain");
  16734. });
  16735. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16736. res.set_content(req.body, "text/plain");
  16737. });
  16738. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16739. res.set_content(req.body, "text/plain");
  16740. });
  16741. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16742. auto se = detail::scope_exit([&] {
  16743. svr.stop();
  16744. t.join();
  16745. ASSERT_FALSE(svr.is_running());
  16746. });
  16747. svr.wait_until_ready();
  16748. std::string resp;
  16749. // POST without Content-Length
  16750. ASSERT_TRUE(send_request(5,
  16751. "POST /post HTTP/1.1\r\n"
  16752. "Host: localhost\r\n"
  16753. "Connection: close\r\n"
  16754. "\r\n",
  16755. &resp));
  16756. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16757. // PUT without Content-Length
  16758. resp.clear();
  16759. ASSERT_TRUE(send_request(5,
  16760. "PUT /put HTTP/1.1\r\n"
  16761. "Host: localhost\r\n"
  16762. "Connection: close\r\n"
  16763. "\r\n",
  16764. &resp));
  16765. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16766. // PATCH without Content-Length
  16767. resp.clear();
  16768. ASSERT_TRUE(send_request(5,
  16769. "PATCH /patch HTTP/1.1\r\n"
  16770. "Host: localhost\r\n"
  16771. "Connection: close\r\n"
  16772. "\r\n",
  16773. &resp));
  16774. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16775. // DELETE without Content-Length
  16776. resp.clear();
  16777. ASSERT_TRUE(send_request(5,
  16778. "DELETE /delete HTTP/1.1\r\n"
  16779. "Host: localhost\r\n"
  16780. "Connection: close\r\n"
  16781. "\r\n",
  16782. &resp));
  16783. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16784. }
  16785. #endif
  16786. //==============================================================================
  16787. // open_stream() Tests
  16788. //==============================================================================
  16789. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16790. std::string result;
  16791. char buf[8192];
  16792. ssize_t n;
  16793. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16794. result.append(buf, static_cast<size_t>(n));
  16795. }
  16796. return result;
  16797. }
  16798. // Mock stream for unit tests
  16799. class MockStream : public Stream {
  16800. public:
  16801. std::string data;
  16802. size_t pos = 0;
  16803. ssize_t error_after = -1; // -1 = no error
  16804. explicit MockStream(const std::string &d, ssize_t err = -1)
  16805. : data(d), error_after(err) {}
  16806. bool is_readable() const override { return true; }
  16807. bool wait_readable() const override { return true; }
  16808. bool wait_writable() const override { return true; }
  16809. ssize_t read(char *ptr, size_t size) override {
  16810. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16811. if (pos >= data.size()) return 0;
  16812. size_t limit =
  16813. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16814. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16815. std::memcpy(ptr, data.data() + pos, to_read);
  16816. pos += to_read;
  16817. return static_cast<ssize_t>(to_read);
  16818. }
  16819. ssize_t write(const char *, size_t) override { return -1; }
  16820. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16821. ip = "127.0.0.1";
  16822. port = 0;
  16823. }
  16824. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16825. ip = "127.0.0.1";
  16826. port = 0;
  16827. }
  16828. socket_t socket() const override { return INVALID_SOCKET; }
  16829. time_t duration() const override { return 0; }
  16830. };
  16831. TEST(StreamHandleTest, Basic) {
  16832. ClientImpl::StreamHandle handle;
  16833. EXPECT_FALSE(handle.is_valid());
  16834. handle.response = detail::make_unique<Response>();
  16835. handle.error = Error::Connection;
  16836. EXPECT_FALSE(handle.is_valid());
  16837. handle.error = Error::Success;
  16838. EXPECT_TRUE(handle.is_valid());
  16839. }
  16840. TEST(BodyReaderTest, Basic) {
  16841. MockStream stream("Hello, World!");
  16842. detail::BodyReader reader;
  16843. reader.stream = &stream;
  16844. reader.content_length = 13;
  16845. char buf[32];
  16846. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16847. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16848. EXPECT_TRUE(reader.eof);
  16849. }
  16850. TEST(BodyReaderTest, NoStream) {
  16851. detail::BodyReader reader;
  16852. char buf[32];
  16853. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16854. EXPECT_EQ(Error::Connection, reader.last_error);
  16855. }
  16856. TEST(BodyReaderTest, Error) {
  16857. MockStream stream("Hello, World!", 5);
  16858. detail::BodyReader reader;
  16859. reader.stream = &stream;
  16860. reader.content_length = 13;
  16861. char buf[32];
  16862. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16863. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16864. EXPECT_EQ(Error::Read, reader.last_error);
  16865. }
  16866. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16867. // Mock-based StreamHandle tests relying on private internals are removed.
  16868. class OpenStreamTest : public ::testing::Test {
  16869. protected:
  16870. void SetUp() override {
  16871. svr_.Get("/hello", [](const Request &, Response &res) {
  16872. res.set_content("Hello World!", "text/plain");
  16873. });
  16874. svr_.Get("/large", [](const Request &, Response &res) {
  16875. res.set_content(std::string(10000, 'X'), "text/plain");
  16876. });
  16877. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16878. res.set_content("Hello World!", "image/jpeg");
  16879. res.set_header("Content-Encoding", "UTF-8");
  16880. });
  16881. svr_.Get("/chunked", [](const Request &, Response &res) {
  16882. res.set_chunked_content_provider("text/plain",
  16883. [](size_t offset, DataSink &sink) {
  16884. if (offset < 15) {
  16885. sink.write("chunk", 5);
  16886. return true;
  16887. }
  16888. sink.done();
  16889. return true;
  16890. });
  16891. });
  16892. svr_.Get("/compressible", [](const Request &, Response &res) {
  16893. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16894. DataSink &sink) {
  16895. if (offset < 100 * 1024) {
  16896. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16897. sink.write(chunk.data(), chunk.size());
  16898. return true;
  16899. }
  16900. sink.done();
  16901. return true;
  16902. });
  16903. });
  16904. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16905. [](const Request & /*req*/, Response &res) {
  16906. auto i = new int(0);
  16907. res.set_header("Trailer", "Content-Length, X-Allowed");
  16908. res.set_chunked_content_provider(
  16909. "text/plain",
  16910. [i](size_t /*offset*/, DataSink &sink) {
  16911. switch (*i) {
  16912. case 0: sink.os << "123"; break;
  16913. case 1: sink.os << "456"; break;
  16914. case 2: sink.os << "789"; break;
  16915. case 3: {
  16916. sink.done_with_trailer(
  16917. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16918. } break;
  16919. }
  16920. (*i)++;
  16921. return true;
  16922. },
  16923. [i](bool success) {
  16924. EXPECT_TRUE(success);
  16925. delete i;
  16926. });
  16927. });
  16928. // Echo headers endpoint for header-related tests
  16929. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16930. std::string body;
  16931. for (const auto &h : req.headers) {
  16932. body.append(h.first);
  16933. body.push_back(':');
  16934. body.append(h.second);
  16935. body.push_back('\n');
  16936. }
  16937. res.set_content(body, "text/plain");
  16938. });
  16939. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16940. std::string body;
  16941. for (const auto &h : req.headers) {
  16942. body.append(h.first);
  16943. body.push_back(':');
  16944. body.append(h.second);
  16945. body.push_back('\n');
  16946. }
  16947. res.set_content(body, "text/plain");
  16948. });
  16949. port_ = svr_.bind_to_any_port("127.0.0.1");
  16950. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16951. svr_.wait_until_ready();
  16952. }
  16953. void TearDown() override {
  16954. svr_.stop();
  16955. if (thread_.joinable()) thread_.join();
  16956. }
  16957. Server svr_;
  16958. std::thread thread_;
  16959. int port_ = 0;
  16960. };
  16961. TEST_F(OpenStreamTest, Basic) {
  16962. Client cli("127.0.0.1", port_);
  16963. auto handle = cli.open_stream("GET", "/hello");
  16964. EXPECT_TRUE(handle.is_valid());
  16965. EXPECT_EQ("Hello World!", read_all(handle));
  16966. }
  16967. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16968. Client cli("127.0.0.1", port_);
  16969. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16970. ASSERT_TRUE(handle.is_valid());
  16971. EXPECT_EQ("Hello World!", read_all(handle));
  16972. }
  16973. TEST_F(OpenStreamTest, SmallBuffer) {
  16974. Client cli("127.0.0.1", port_);
  16975. auto handle = cli.open_stream("GET", "/hello");
  16976. std::string result;
  16977. char buf[4];
  16978. ssize_t n;
  16979. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16980. result.append(buf, static_cast<size_t>(n));
  16981. EXPECT_EQ("Hello World!", result);
  16982. }
  16983. TEST_F(OpenStreamTest, DefaultHeaders) {
  16984. Client cli("127.0.0.1", port_);
  16985. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16986. {
  16987. auto handle = cli.open_stream("GET", "/echo-headers");
  16988. ASSERT_TRUE(handle.is_valid());
  16989. auto body = read_all(handle);
  16990. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16991. std::string::npos);
  16992. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16993. std::string::npos);
  16994. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16995. }
  16996. // open_stream POST with body and no explicit content_type should NOT add
  16997. // text/plain Content-Type (behavior differs from non-streaming path), but
  16998. // should include Content-Length
  16999. {
  17000. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17001. ASSERT_TRUE(handle.is_valid());
  17002. auto body = read_all(handle);
  17003. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17004. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17005. }
  17006. // open_stream POST with explicit Content-Type should preserve it
  17007. {
  17008. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17009. {{"Content-Type", "application/custom"}},
  17010. "{}", "application/custom");
  17011. ASSERT_TRUE(handle.is_valid());
  17012. auto body = read_all(handle);
  17013. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17014. }
  17015. // User-specified User-Agent must not be overwritten for stream API
  17016. {
  17017. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17018. {{"User-Agent", "MyAgent/1.2"}});
  17019. ASSERT_TRUE(handle.is_valid());
  17020. auto body = read_all(handle);
  17021. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17022. }
  17023. }
  17024. TEST_F(OpenStreamTest, Large) {
  17025. Client cli("127.0.0.1", port_);
  17026. auto handle = cli.open_stream("GET", "/large");
  17027. EXPECT_EQ(10000u, read_all(handle).size());
  17028. }
  17029. TEST_F(OpenStreamTest, ConnectionError) {
  17030. Client cli("127.0.0.1", 9999);
  17031. auto handle = cli.open_stream("GET", "/hello");
  17032. EXPECT_FALSE(handle.is_valid());
  17033. }
  17034. TEST_F(OpenStreamTest, Chunked) {
  17035. Client cli("127.0.0.1", port_);
  17036. auto handle = cli.open_stream("GET", "/chunked");
  17037. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17038. "Transfer-Encoding") == "chunked");
  17039. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17040. }
  17041. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17042. Client cli("127.0.0.1", port_);
  17043. auto handle =
  17044. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17045. ASSERT_TRUE(handle.is_valid());
  17046. // Consume body to allow trailers to be received/parsed
  17047. auto body = read_all(handle);
  17048. // Explicitly parse trailers (ensure trailers are available for assertion)
  17049. handle.parse_trailers_if_needed();
  17050. EXPECT_EQ(std::string("123456789"), body);
  17051. // The response should include a Trailer header declaring both names
  17052. ASSERT_TRUE(handle.response);
  17053. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17054. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17055. handle.response->get_header_value("Trailer"));
  17056. // Prohibited trailer must not be present
  17057. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17058. // Allowed trailer should be present
  17059. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17060. EXPECT_EQ(std::string("yes"),
  17061. handle.response->get_trailer_value("X-Allowed"));
  17062. // Verify trailers are NOT present as regular headers
  17063. EXPECT_EQ(std::string(""),
  17064. handle.response->get_header_value("Content-Length"));
  17065. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17066. }
  17067. static std::thread serve_single_response(std::promise<int> &port_promise,
  17068. const std::string &response) {
  17069. return std::thread([&port_promise, response] {
  17070. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17071. default_socket_options(srv);
  17072. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17073. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17074. sockaddr_in addr{};
  17075. addr.sin_family = AF_INET;
  17076. addr.sin_port = htons(0); // Let OS assign a free port
  17077. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17078. int opt = 1;
  17079. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17080. #ifdef _WIN32
  17081. reinterpret_cast<const char *>(&opt),
  17082. #else
  17083. &opt,
  17084. #endif
  17085. sizeof(opt));
  17086. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17087. ::listen(srv, 1) != 0) {
  17088. port_promise.set_value(-1);
  17089. detail::close_socket(srv);
  17090. return;
  17091. }
  17092. socklen_t addr_len = sizeof(addr);
  17093. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17094. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17095. sockaddr_in cli_addr{};
  17096. socklen_t cli_len = sizeof(cli_addr);
  17097. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17098. if (cli != INVALID_SOCKET) {
  17099. // Read the complete HTTP request (until the blank line that terminates
  17100. // headers) before sending the response. If the server closes the socket
  17101. // while the client's request data is still unread in the kernel receive
  17102. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17103. // connection on both sides: it discards the client's receive buffer
  17104. // (which already holds our response) and causes any in-progress write on
  17105. // the client to fail with ECONNRESET. Reading all request data first
  17106. // ensures close() emits a graceful FIN.
  17107. {
  17108. char rbuf[256];
  17109. std::string req;
  17110. while (req.find("\r\n\r\n") == std::string::npos) {
  17111. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17112. if (n <= 0) { break; }
  17113. req.append(rbuf, static_cast<size_t>(n));
  17114. }
  17115. }
  17116. ::send(cli,
  17117. #ifdef _WIN32
  17118. static_cast<const char *>(response.c_str()),
  17119. static_cast<int>(response.size()),
  17120. #else
  17121. response.c_str(), response.size(),
  17122. #endif
  17123. 0);
  17124. detail::close_socket(cli);
  17125. }
  17126. detail::close_socket(srv);
  17127. });
  17128. }
  17129. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17130. #ifndef _WIN32
  17131. signal(SIGPIPE, SIG_IGN);
  17132. #endif
  17133. std::promise<int> port_promise;
  17134. auto port_future = port_promise.get_future();
  17135. auto server_thread =
  17136. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17137. "Content-Type: text/plain\r\n"
  17138. "Content-Length: not-a-number\r\n"
  17139. "Connection: close\r\n"
  17140. "\r\n"
  17141. "hello");
  17142. auto port = port_future.get();
  17143. ASSERT_GT(port, 0);
  17144. Client cli("127.0.0.1", port);
  17145. auto handle = cli.open_stream("GET", "/");
  17146. EXPECT_FALSE(handle.is_valid());
  17147. server_thread.join();
  17148. }
  17149. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17150. #ifndef _WIN32
  17151. signal(SIGPIPE, SIG_IGN);
  17152. #endif
  17153. std::promise<int> port_promise;
  17154. auto port_future = port_promise.get_future();
  17155. auto server_thread = serve_single_response(
  17156. port_promise, "HTTP/1.1 200 OK\r\n"
  17157. "Content-Type: text/plain\r\n"
  17158. "Content-Length: 99999999999999999999999999\r\n"
  17159. "Connection: close\r\n"
  17160. "\r\n"
  17161. "hello");
  17162. auto port = port_future.get();
  17163. ASSERT_GT(port, 0);
  17164. // Historically std::stoull would throw std::out_of_range here and crash
  17165. // the process, then parsing silently clamped to a bogus framing length and
  17166. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17167. // so the stream fails to open, matching the not-a-number case above. The
  17168. // process still must NOT terminate.
  17169. Client cli("127.0.0.1", port);
  17170. auto handle = cli.open_stream("GET", "/");
  17171. EXPECT_FALSE(handle.is_valid());
  17172. server_thread.join();
  17173. }
  17174. // Serves `response` to the single request `fn` makes with a fresh client.
  17175. template <typename Fn>
  17176. static void with_single_response(const std::string &response, Fn fn) {
  17177. #ifndef _WIN32
  17178. signal(SIGPIPE, SIG_IGN);
  17179. #endif
  17180. std::promise<int> port_promise;
  17181. auto port_future = port_promise.get_future();
  17182. auto server_thread = serve_single_response(port_promise, response);
  17183. auto se = detail::scope_exit([&] { server_thread.join(); });
  17184. auto port = port_future.get();
  17185. ASSERT_GT(port, 0);
  17186. Client cli("127.0.0.1", port);
  17187. fn(cli);
  17188. }
  17189. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17190. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17191. // the chunked coding and drop Content-Length, so a front-end that trusts
  17192. // Content-Length would disagree about where the body ends (response
  17193. // smuggling). The client must reject such a response.
  17194. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17195. for (const char *te : {"chunked", "gzip, chunked"}) {
  17196. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17197. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17198. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17199. "5\r\nhello\r\n0\r\n\r\n";
  17200. with_single_response(response, [&](Client &cli) {
  17201. auto res = cli.Get("/");
  17202. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17203. EXPECT_EQ(Error::Read, res.error()) << te;
  17204. });
  17205. with_single_response(response, [&](Client &cli) {
  17206. auto handle = cli.open_stream("GET", "/");
  17207. EXPECT_FALSE(handle.is_valid()) << te;
  17208. EXPECT_EQ(Error::Read, handle.error) << te;
  17209. });
  17210. }
  17211. }
  17212. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17213. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17214. // closing the connection (unlike a request, which must be rejected).
  17215. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17216. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17217. "Transfer-Encoding: chunked\r\n"
  17218. "Connection: close\r\n"
  17219. "\r\n"
  17220. "5\r\nhello\r\n0\r\n\r\n",
  17221. "HTTP/1.1 200 OK\r\n"
  17222. "Transfer-Encoding: gzip\r\n"
  17223. "Connection: close\r\n"
  17224. "\r\n"
  17225. "hello"}) {
  17226. with_single_response(response, [&](Client &cli) {
  17227. auto res = cli.Get("/");
  17228. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17229. EXPECT_EQ("hello", res->body);
  17230. });
  17231. with_single_response(response, [&](Client &cli) {
  17232. auto handle = cli.open_stream("GET", "/");
  17233. ASSERT_TRUE(handle.is_valid()) << response;
  17234. EXPECT_EQ("hello", read_all(handle));
  17235. });
  17236. }
  17237. }
  17238. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17239. // framing headers describe nothing to read and must not be rejected.
  17240. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17241. const std::string framing = "Content-Length: 5\r\n"
  17242. "Transfer-Encoding: chunked\r\n"
  17243. "Connection: close\r\n"
  17244. "\r\n";
  17245. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17246. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17247. });
  17248. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17249. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17250. });
  17251. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17252. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17253. with_single_response(response, [&](Client &cli) {
  17254. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17255. });
  17256. with_single_response(response, [&](Client &cli) {
  17257. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17258. });
  17259. }
  17260. }
  17261. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17262. TEST_F(OpenStreamTest, Gzip) {
  17263. Client cli("127.0.0.1", port_);
  17264. auto handle = cli.open_stream("GET", "/compressible", {},
  17265. {{"Accept-Encoding", "gzip"}});
  17266. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17267. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17268. }
  17269. #endif
  17270. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17271. TEST_F(OpenStreamTest, Brotli) {
  17272. Client cli("127.0.0.1", port_);
  17273. auto handle =
  17274. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17275. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17276. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17277. }
  17278. #endif
  17279. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17280. TEST_F(OpenStreamTest, Zstd) {
  17281. Client cli("127.0.0.1", port_);
  17282. auto handle = cli.open_stream("GET", "/compressible", {},
  17283. {{"Accept-Encoding", "zstd"}});
  17284. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17285. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17286. }
  17287. #endif
  17288. #ifdef CPPHTTPLIB_SSL_ENABLED
  17289. class SSLOpenStreamTest : public ::testing::Test {
  17290. protected:
  17291. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17292. void SetUp() override {
  17293. svr_.Get("/hello", [](const Request &, Response &res) {
  17294. res.set_content("Hello SSL World!", "text/plain");
  17295. });
  17296. svr_.Get("/chunked", [](const Request &, Response &res) {
  17297. res.set_chunked_content_provider("text/plain",
  17298. [](size_t offset, DataSink &sink) {
  17299. if (offset < 15) {
  17300. sink.write("chunk", 5);
  17301. return true;
  17302. }
  17303. sink.done();
  17304. return true;
  17305. });
  17306. });
  17307. svr_.Post("/echo", [](const Request &req, Response &res) {
  17308. res.set_content(req.body, req.get_header_value("Content-Type"));
  17309. });
  17310. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17311. std::string body = req.body;
  17312. res.set_chunked_content_provider(
  17313. "text/plain", [body](size_t offset, DataSink &sink) {
  17314. if (offset < body.size()) {
  17315. sink.write(body.data() + offset, body.size() - offset);
  17316. }
  17317. sink.done();
  17318. return true;
  17319. });
  17320. });
  17321. port_ = svr_.bind_to_any_port("127.0.0.1");
  17322. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17323. svr_.wait_until_ready();
  17324. }
  17325. void TearDown() override {
  17326. svr_.stop();
  17327. if (thread_.joinable()) thread_.join();
  17328. }
  17329. SSLServer svr_;
  17330. std::thread thread_;
  17331. int port_ = 0;
  17332. };
  17333. TEST_F(SSLOpenStreamTest, Basic) {
  17334. SSLClient cli("127.0.0.1", port_);
  17335. cli.enable_server_certificate_verification(false);
  17336. auto handle = cli.open_stream("GET", "/hello");
  17337. ASSERT_TRUE(handle.is_valid());
  17338. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17339. }
  17340. TEST_F(SSLOpenStreamTest, Chunked) {
  17341. SSLClient cli("127.0.0.1", port_);
  17342. cli.enable_server_certificate_verification(false);
  17343. auto handle = cli.open_stream("GET", "/chunked");
  17344. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17345. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17346. "Transfer-Encoding") == "chunked");
  17347. auto body = read_all(handle);
  17348. EXPECT_EQ("chunkchunkchunk", body);
  17349. }
  17350. TEST_F(SSLOpenStreamTest, Post) {
  17351. SSLClient cli("127.0.0.1", port_);
  17352. cli.enable_server_certificate_verification(false);
  17353. auto handle =
  17354. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17355. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17356. EXPECT_EQ(200, handle.response->status);
  17357. auto body = read_all(handle);
  17358. EXPECT_EQ("Hello SSL POST", body);
  17359. }
  17360. TEST_F(SSLOpenStreamTest, PostChunked) {
  17361. SSLClient cli("127.0.0.1", port_);
  17362. cli.enable_server_certificate_verification(false);
  17363. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17364. "Chunked SSL Data", "text/plain");
  17365. ASSERT_TRUE(handle.is_valid());
  17366. EXPECT_EQ(200, handle.response->status);
  17367. auto body = read_all(handle);
  17368. EXPECT_EQ("Chunked SSL Data", body);
  17369. }
  17370. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17371. // Content-Length is terminated by the server closing the connection. When the
  17372. // SSL peer sends a close_notify after the body, the client must treat it as a
  17373. // clean EOF and return a successful response rather than an error.
  17374. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17375. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17376. ASSERT_TRUE(svr.is_valid());
  17377. svr.set_keep_alive_max_count(1);
  17378. const std::string expected_body = "Hello from connection-close response!";
  17379. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17380. res.set_content_provider("text/plain",
  17381. [&](size_t offset, DataSink &sink) -> bool {
  17382. if (offset < expected_body.size()) {
  17383. sink.write(expected_body.data() + offset,
  17384. expected_body.size() - offset);
  17385. }
  17386. sink.done();
  17387. return true;
  17388. });
  17389. });
  17390. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17391. auto se = detail::scope_exit([&] {
  17392. svr.stop();
  17393. listen_thread.join();
  17394. ASSERT_FALSE(svr.is_running());
  17395. });
  17396. svr.wait_until_ready();
  17397. SSLClient cli(HOST, PORT);
  17398. cli.enable_server_certificate_verification(false);
  17399. auto res = cli.Get("/no-content-length");
  17400. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17401. EXPECT_EQ(StatusCode::OK_200, res->status);
  17402. EXPECT_EQ(expected_body, res->body);
  17403. }
  17404. #endif // CPPHTTPLIB_SSL_ENABLED
  17405. //==============================================================================
  17406. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17407. // results for various scenarios.
  17408. //==============================================================================
  17409. TEST(ParityTest, GetVsOpenStream) {
  17410. Server svr;
  17411. const std::string path = "/parity";
  17412. const std::string content = "Parity test content: hello world";
  17413. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17414. res.set_content(content, "text/plain");
  17415. });
  17416. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17417. auto se = detail::scope_exit([&] {
  17418. svr.stop();
  17419. t.join();
  17420. ASSERT_FALSE(svr.is_running());
  17421. });
  17422. svr.wait_until_ready();
  17423. Client cli(HOST, PORT);
  17424. // Non-stream path
  17425. auto r1 = cli.Get(path);
  17426. ASSERT_TRUE(r1);
  17427. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17428. // Stream path
  17429. auto h = cli.open_stream("GET", path);
  17430. ASSERT_TRUE(h.is_valid());
  17431. EXPECT_EQ(r1->body, read_all(h));
  17432. }
  17433. // Helper to compress data with provided compressor type T
  17434. template <typename Compressor>
  17435. static std::string compress_payload_for_parity(const std::string &in) {
  17436. std::string out;
  17437. Compressor compressor;
  17438. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17439. [&](const char *data, size_t n) {
  17440. out.append(data, n);
  17441. return true;
  17442. });
  17443. EXPECT_TRUE(ok);
  17444. return out;
  17445. }
  17446. // Helper function for compression parity tests
  17447. template <typename Compressor>
  17448. static void test_compression_parity(const std::string &original,
  17449. const std::string &path,
  17450. const std::string &encoding) {
  17451. const std::string compressed =
  17452. compress_payload_for_parity<Compressor>(original);
  17453. Server svr;
  17454. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17455. res.set_content(compressed, "application/octet-stream");
  17456. res.set_header("Content-Encoding", encoding);
  17457. });
  17458. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17459. auto se = detail::scope_exit([&] {
  17460. svr.stop();
  17461. t.join();
  17462. ASSERT_FALSE(svr.is_running());
  17463. });
  17464. svr.wait_until_ready();
  17465. Client cli(HOST, PORT);
  17466. // Non-streaming
  17467. {
  17468. auto res = cli.Get(path);
  17469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17470. EXPECT_EQ(StatusCode::OK_200, res->status);
  17471. EXPECT_EQ(original, res->body);
  17472. }
  17473. // Streaming
  17474. {
  17475. auto h = cli.open_stream("GET", path);
  17476. ASSERT_TRUE(h.is_valid());
  17477. EXPECT_EQ(original, read_all(h));
  17478. }
  17479. }
  17480. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17481. TEST(ParityTest, Gzip) {
  17482. test_compression_parity<detail::gzip_compressor>(
  17483. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17484. }
  17485. #endif
  17486. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17487. TEST(ParityTest, Brotli) {
  17488. test_compression_parity<detail::brotli_compressor>(
  17489. "Hello, brotli parity test payload", "/parity-br", "br");
  17490. }
  17491. #endif
  17492. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17493. TEST(ParityTest, Zstd) {
  17494. test_compression_parity<detail::zstd_compressor>(
  17495. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17496. }
  17497. #endif
  17498. //==============================================================================
  17499. // New Stream API Tests
  17500. //==============================================================================
  17501. inline std::string read_body(httplib::stream::Result &result) {
  17502. std::string body;
  17503. while (result.next()) {
  17504. body.append(result.data(), result.size());
  17505. }
  17506. return body;
  17507. }
  17508. TEST(ClientConnectionTest, Basic) {
  17509. httplib::ClientConnection conn;
  17510. EXPECT_FALSE(conn.is_open());
  17511. conn.sock = 1;
  17512. EXPECT_TRUE(conn.is_open());
  17513. httplib::ClientConnection conn2(std::move(conn));
  17514. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17515. conn2.sock = INVALID_SOCKET;
  17516. }
  17517. // Unified test server for all stream::* tests
  17518. class StreamApiTest : public ::testing::Test {
  17519. protected:
  17520. void SetUp() override {
  17521. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17522. res.set_content("Hello World!", "text/plain");
  17523. });
  17524. svr_.Get("/echo-params",
  17525. [](const httplib::Request &req, httplib::Response &res) {
  17526. std::string r;
  17527. for (const auto &p : req.params) {
  17528. if (!r.empty()) r += "&";
  17529. r += p.first + "=" + p.second;
  17530. }
  17531. res.set_content(r, "text/plain");
  17532. });
  17533. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17534. res.set_content(req.body, req.get_header_value("Content-Type"));
  17535. });
  17536. svr_.Post("/echo-headers",
  17537. [](const httplib::Request &req, httplib::Response &res) {
  17538. std::string r;
  17539. for (const auto &h : req.headers)
  17540. r += h.first + ": " + h.second + "\n";
  17541. res.set_content(r, "text/plain");
  17542. });
  17543. svr_.Post("/echo-params",
  17544. [](const httplib::Request &req, httplib::Response &res) {
  17545. std::string r = "params:";
  17546. for (const auto &p : req.params)
  17547. r += p.first + "=" + p.second + ";";
  17548. res.set_content(r + " body:" + req.body, "text/plain");
  17549. });
  17550. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17551. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17552. });
  17553. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17554. res.set_content("PUT:" + req.body, "text/plain");
  17555. });
  17556. svr_.Patch("/echo",
  17557. [](const httplib::Request &req, httplib::Response &res) {
  17558. res.set_content("PATCH:" + req.body, "text/plain");
  17559. });
  17560. svr_.Delete(
  17561. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17562. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17563. "text/plain");
  17564. });
  17565. svr_.Get("/head-test",
  17566. [](const httplib::Request &, httplib::Response &res) {
  17567. res.set_content("body for HEAD", "text/plain");
  17568. });
  17569. svr_.Options("/options",
  17570. [](const httplib::Request &, httplib::Response &res) {
  17571. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17572. });
  17573. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17574. svr_.wait_until_ready();
  17575. }
  17576. void TearDown() override {
  17577. svr_.stop();
  17578. if (thread_.joinable()) thread_.join();
  17579. }
  17580. httplib::Server svr_;
  17581. std::thread thread_;
  17582. };
  17583. // stream::Get tests
  17584. TEST_F(StreamApiTest, GetBasic) {
  17585. httplib::Client cli(HOST, PORT);
  17586. auto result = httplib::stream::Get(cli, "/hello");
  17587. ASSERT_TRUE(result.is_valid());
  17588. EXPECT_EQ(200, result.status());
  17589. EXPECT_EQ("Hello World!", read_body(result));
  17590. }
  17591. TEST_F(StreamApiTest, GetWithParams) {
  17592. httplib::Client cli(HOST, PORT);
  17593. httplib::Params params{{"foo", "bar"}};
  17594. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17595. ASSERT_TRUE(result.is_valid());
  17596. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17597. }
  17598. TEST_F(StreamApiTest, GetConnectionError) {
  17599. httplib::Client cli(HOST, 9999);
  17600. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17601. }
  17602. TEST_F(StreamApiTest, Get404) {
  17603. httplib::Client cli(HOST, PORT);
  17604. auto result = httplib::stream::Get(cli, "/nonexistent");
  17605. EXPECT_TRUE(result.is_valid());
  17606. EXPECT_EQ(404, result.status());
  17607. }
  17608. // stream::Post tests
  17609. TEST_F(StreamApiTest, PostBasic) {
  17610. httplib::Client cli(HOST, PORT);
  17611. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17612. "application/json");
  17613. ASSERT_TRUE(result.is_valid());
  17614. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17615. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17616. }
  17617. TEST_F(StreamApiTest, PostWithHeaders) {
  17618. httplib::Client cli(HOST, PORT);
  17619. httplib::Headers headers{{"X-Custom", "value"}};
  17620. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17621. "text/plain");
  17622. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17623. }
  17624. TEST_F(StreamApiTest, PostWithParams) {
  17625. httplib::Client cli(HOST, PORT);
  17626. httplib::Params params{{"k", "v"}};
  17627. auto result =
  17628. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17629. auto body = read_body(result);
  17630. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17631. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17632. }
  17633. TEST_F(StreamApiTest, PostLarge) {
  17634. httplib::Client cli(HOST, PORT);
  17635. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17636. size_t total = 0;
  17637. while (result.next()) {
  17638. total += result.size();
  17639. }
  17640. EXPECT_EQ(100u * 1024u, total);
  17641. }
  17642. // stream::Put/Patch tests
  17643. TEST_F(StreamApiTest, PutAndPatch) {
  17644. httplib::Client cli(HOST, PORT);
  17645. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17646. EXPECT_EQ("PUT:test", read_body(put));
  17647. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17648. EXPECT_EQ("PATCH:test", read_body(patch));
  17649. }
  17650. // stream::Delete tests
  17651. TEST_F(StreamApiTest, Delete) {
  17652. httplib::Client cli(HOST, PORT);
  17653. auto del1 = httplib::stream::Delete(cli, "/resource");
  17654. EXPECT_EQ("Deleted", read_body(del1));
  17655. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17656. EXPECT_EQ("Deleted:data", read_body(del2));
  17657. }
  17658. // stream::Head/Options tests
  17659. TEST_F(StreamApiTest, HeadAndOptions) {
  17660. httplib::Client cli(HOST, PORT);
  17661. auto head = httplib::stream::Head(cli, "/head-test");
  17662. EXPECT_TRUE(head.is_valid());
  17663. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17664. auto opts = httplib::stream::Options(cli, "/options");
  17665. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17666. }
  17667. // SSL stream::* tests
  17668. #ifdef CPPHTTPLIB_SSL_ENABLED
  17669. class SSLStreamApiTest : public ::testing::Test {
  17670. protected:
  17671. void SetUp() override {
  17672. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17673. res.set_content("Hello SSL!", "text/plain");
  17674. });
  17675. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17676. res.set_content(req.body, "text/plain");
  17677. });
  17678. port_ = svr_.bind_to_any_port("127.0.0.1");
  17679. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17680. svr_.wait_until_ready();
  17681. }
  17682. void TearDown() override {
  17683. svr_.stop();
  17684. if (thread_.joinable()) thread_.join();
  17685. }
  17686. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17687. std::thread thread_;
  17688. int port_ = 0;
  17689. };
  17690. TEST_F(SSLStreamApiTest, GetAndPost) {
  17691. httplib::SSLClient cli("127.0.0.1", port_);
  17692. cli.enable_server_certificate_verification(false);
  17693. auto get = httplib::stream::Get(cli, "/hello");
  17694. EXPECT_EQ("Hello SSL!", read_body(get));
  17695. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17696. EXPECT_EQ("test", read_body(post));
  17697. }
  17698. #endif
  17699. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17700. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17701. // BodyReader
  17702. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17703. // Test that read timeout during streaming is detected
  17704. // Use a large content-length response where server delays mid-stream
  17705. Server svr;
  17706. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17707. // Send a large response with delay in the middle
  17708. res.set_content_provider(
  17709. 1000, // content_length
  17710. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17711. if (offset < 100) {
  17712. // Send first 100 bytes immediately
  17713. std::string data(100, 'A');
  17714. sink.write(data.c_str(), data.size());
  17715. return true;
  17716. }
  17717. // Then delay longer than client timeout
  17718. std::this_thread::sleep_for(std::chrono::seconds(3));
  17719. std::string data(900, 'B');
  17720. sink.write(data.c_str(), data.size());
  17721. return true;
  17722. });
  17723. });
  17724. auto port = 8091;
  17725. std::thread t([&]() { svr.listen("localhost", port); });
  17726. svr.wait_until_ready();
  17727. Client cli("localhost", port);
  17728. cli.set_read_timeout(1, 0); // 1 second timeout
  17729. auto handle = cli.open_stream("GET", "/slow-stream");
  17730. ASSERT_TRUE(handle.is_valid());
  17731. char buf[256];
  17732. ssize_t total = 0;
  17733. ssize_t n;
  17734. bool got_error = false;
  17735. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17736. total += n;
  17737. }
  17738. if (n < 0) {
  17739. got_error = true;
  17740. // Should be timeout or read error
  17741. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17742. handle.get_read_error() == Error::Read)
  17743. << "Actual error: " << to_string(handle.get_read_error());
  17744. }
  17745. // Either we got an error, or we got less data than expected
  17746. EXPECT_TRUE(got_error || total < 1000)
  17747. << "Expected timeout but got all " << total << " bytes";
  17748. svr.stop();
  17749. t.join();
  17750. }
  17751. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17752. // Test connection closed detection via BodyReader
  17753. Server svr;
  17754. std::atomic<bool> close_now{false};
  17755. svr.Get("/will-close", [&](const Request &, Response &res) {
  17756. res.set_content_provider(
  17757. 10000, // Large content_length that we won't fully send
  17758. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17759. if (offset < 100) {
  17760. std::string data(100, 'X');
  17761. sink.write(data.c_str(), data.size());
  17762. return true;
  17763. }
  17764. // Wait for signal then abort
  17765. while (!close_now) {
  17766. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17767. }
  17768. return false; // Abort - server will close connection
  17769. });
  17770. });
  17771. auto port = 8092;
  17772. std::thread t([&]() { svr.listen("localhost", port); });
  17773. svr.wait_until_ready();
  17774. Client cli("localhost", port);
  17775. auto handle = cli.open_stream("GET", "/will-close");
  17776. ASSERT_TRUE(handle.is_valid());
  17777. char buf[256];
  17778. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17779. EXPECT_GT(n, 0) << "First read should succeed";
  17780. // Signal server to close
  17781. close_now = true;
  17782. // Keep reading until error or EOF
  17783. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17784. // Keep reading
  17785. }
  17786. // Should get an error since content_length wasn't satisfied
  17787. if (n < 0) {
  17788. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17789. handle.get_read_error() == Error::Read)
  17790. << "Actual error: " << to_string(handle.get_read_error());
  17791. }
  17792. svr.stop();
  17793. t.join();
  17794. }
  17795. #ifdef CPPHTTPLIB_SSL_ENABLED
  17796. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17797. // Test that read timeout during SSL streaming is detected
  17798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17799. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17800. res.set_content_provider(
  17801. 1000, "text/plain",
  17802. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17803. if (offset < 100) {
  17804. std::string data(100, 'A');
  17805. sink.write(data.c_str(), data.size());
  17806. return true;
  17807. }
  17808. std::this_thread::sleep_for(std::chrono::seconds(3));
  17809. std::string data(900, 'B');
  17810. sink.write(data.c_str(), data.size());
  17811. return true;
  17812. });
  17813. });
  17814. auto port = 8093;
  17815. std::thread t([&]() { svr.listen("localhost", port); });
  17816. svr.wait_until_ready();
  17817. SSLClient cli("localhost", port);
  17818. cli.enable_server_certificate_verification(false);
  17819. cli.set_read_timeout(1, 0); // 1 second timeout
  17820. auto handle = cli.open_stream("GET", "/slow-stream");
  17821. ASSERT_TRUE(handle.is_valid());
  17822. char buf[256];
  17823. ssize_t total = 0;
  17824. ssize_t n;
  17825. bool got_error = false;
  17826. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17827. total += n;
  17828. }
  17829. if (n < 0) {
  17830. got_error = true;
  17831. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17832. handle.get_read_error() == Error::Read)
  17833. << "Actual error: " << to_string(handle.get_read_error());
  17834. }
  17835. EXPECT_TRUE(got_error || total < 1000)
  17836. << "Expected timeout but got all " << total << " bytes";
  17837. svr.stop();
  17838. t.join();
  17839. }
  17840. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17841. // Test SSL connection closed detection
  17842. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17843. std::atomic<bool> close_now{false};
  17844. svr.Get("/will-close", [&](const Request &, Response &res) {
  17845. res.set_content_provider(
  17846. 10000, "text/plain",
  17847. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17848. if (offset < 100) {
  17849. std::string data(100, 'X');
  17850. sink.write(data.c_str(), data.size());
  17851. return true;
  17852. }
  17853. while (!close_now) {
  17854. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17855. }
  17856. return false;
  17857. });
  17858. });
  17859. auto port = 8094;
  17860. std::thread t([&]() { svr.listen("localhost", port); });
  17861. svr.wait_until_ready();
  17862. SSLClient cli("localhost", port);
  17863. cli.enable_server_certificate_verification(false);
  17864. auto handle = cli.open_stream("GET", "/will-close");
  17865. ASSERT_TRUE(handle.is_valid());
  17866. char buf[256];
  17867. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17868. EXPECT_GT(n, 0);
  17869. // Signal server to close
  17870. close_now = true;
  17871. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17872. // Keep reading
  17873. }
  17874. if (n < 0) {
  17875. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17876. handle.get_read_error() == Error::Read)
  17877. << "Actual error: " << to_string(handle.get_read_error());
  17878. }
  17879. svr.stop();
  17880. t.join();
  17881. }
  17882. #endif
  17883. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17884. using namespace httplib;
  17885. // Create a test file
  17886. const char *fname = "etag_testfile.txt";
  17887. const char *content = "etag-content";
  17888. {
  17889. std::ofstream ofs(fname);
  17890. ofs << content;
  17891. ASSERT_TRUE(ofs.good());
  17892. }
  17893. Server svr;
  17894. svr.set_mount_point("/static", ".");
  17895. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17896. svr.wait_until_ready();
  17897. Client cli(HOST, PORT);
  17898. // First request: should get 200 with ETag header
  17899. auto res1 = cli.Get("/static/etag_testfile.txt");
  17900. ASSERT_TRUE(res1);
  17901. ASSERT_EQ(200, res1->status);
  17902. ASSERT_TRUE(res1->has_header("ETag"));
  17903. std::string etag = res1->get_header_value("ETag");
  17904. EXPECT_FALSE(etag.empty());
  17905. // Verify ETag format: W/"hex-hex"
  17906. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17907. EXPECT_EQ('W', etag[0]);
  17908. EXPECT_EQ('/', etag[1]);
  17909. EXPECT_EQ('"', etag[2]);
  17910. EXPECT_EQ('"', etag.back());
  17911. // Exact match: expect 304 Not Modified
  17912. Headers h2 = {{"If-None-Match", etag}};
  17913. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17914. ASSERT_TRUE(res2);
  17915. EXPECT_EQ(304, res2->status);
  17916. // Wildcard match: expect 304 Not Modified
  17917. Headers h3 = {{"If-None-Match", "*"}};
  17918. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17919. ASSERT_TRUE(res3);
  17920. EXPECT_EQ(304, res3->status);
  17921. // Non-matching ETag: expect 200
  17922. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17923. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17924. ASSERT_TRUE(res4);
  17925. EXPECT_EQ(200, res4->status);
  17926. // Multiple ETags with one matching: expect 304
  17927. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17928. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17929. ASSERT_TRUE(res5);
  17930. EXPECT_EQ(304, res5->status);
  17931. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17932. // that equivalent to the single comma-separated list above, so the match on
  17933. // the second line must still be found.
  17934. Headers h6;
  17935. h6.emplace("If-None-Match", "W/\"other\"");
  17936. h6.emplace("If-None-Match", etag);
  17937. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17938. ASSERT_TRUE(res6);
  17939. EXPECT_EQ(304, res6->status);
  17940. svr.stop();
  17941. t.join();
  17942. std::remove(fname);
  17943. }
  17944. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17945. using namespace httplib;
  17946. Server svr;
  17947. svr.set_mount_point("/static", ".");
  17948. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17949. svr.wait_until_ready();
  17950. Client cli(HOST, PORT);
  17951. // Send If-None-Match: * to a non-existent file
  17952. Headers h = {{"If-None-Match", "*"}};
  17953. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17955. EXPECT_EQ(404, res->status);
  17956. svr.stop();
  17957. t.join();
  17958. }
  17959. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17960. using namespace httplib;
  17961. // Create a test file
  17962. const char *fname = "etag_boundary_testfile.txt";
  17963. const char *content = "boundary-test";
  17964. {
  17965. std::ofstream ofs(fname);
  17966. ofs << content;
  17967. ASSERT_TRUE(ofs.good());
  17968. }
  17969. Server svr;
  17970. svr.set_mount_point("/static", ".");
  17971. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17972. svr.wait_until_ready();
  17973. Client cli(HOST, PORT);
  17974. // Get the actual ETag
  17975. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17976. ASSERT_TRUE(res1);
  17977. ASSERT_EQ(200, res1->status);
  17978. ASSERT_TRUE(res1->has_header("ETag"));
  17979. std::string etag = res1->get_header_value("ETag");
  17980. // Test 1: Very long ETag value (longer than actual ETag)
  17981. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17982. Headers h1 = {{"If-None-Match", "W/"
  17983. "\"very-long-etag-value-that-is-much-longer-"
  17984. "than-the-actual-etag-value\""}};
  17985. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17986. ASSERT_TRUE(res2);
  17987. EXPECT_EQ(200, res2->status); // Should not match
  17988. // Test 2: Long string followed by wildcard
  17989. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17990. // string)
  17991. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17992. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17993. ASSERT_TRUE(res3);
  17994. EXPECT_EQ(304, res3->status); // Should match on "*"
  17995. // Test 3: Wildcard followed by long string
  17996. // Should match on "*" immediately and return 304
  17997. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17998. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17999. ASSERT_TRUE(res4);
  18000. EXPECT_EQ(304, res4->status); // Should match on "*"
  18001. // Test 4: Multiple long non-matching values
  18002. // Should NOT match and return 200 (test that all comparisons are safe)
  18003. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18004. "W/\"second-long-non-matching-value\", "
  18005. "W/\"third-long-non-matching-value\""}};
  18006. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18007. ASSERT_TRUE(res5);
  18008. EXPECT_EQ(200, res5->status); // Should not match
  18009. // Test 5: Single character that is not "*" (edge case)
  18010. Headers h5 = {{"If-None-Match", "X"}};
  18011. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18012. ASSERT_TRUE(res6);
  18013. EXPECT_EQ(200, res6->status); // Should not match
  18014. svr.stop();
  18015. t.join();
  18016. std::remove(fname);
  18017. }
  18018. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18019. using namespace httplib;
  18020. // Create a test file
  18021. const char *fname = "ims_testfile.txt";
  18022. const char *content = "if-modified-since-test";
  18023. {
  18024. std::ofstream ofs(fname);
  18025. ofs << content;
  18026. ASSERT_TRUE(ofs.good());
  18027. }
  18028. Server svr;
  18029. svr.set_mount_point("/static", ".");
  18030. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18031. svr.wait_until_ready();
  18032. Client cli(HOST, PORT);
  18033. // First request: should get 200 with Last-Modified header
  18034. auto res1 = cli.Get("/static/ims_testfile.txt");
  18035. ASSERT_TRUE(res1);
  18036. ASSERT_EQ(200, res1->status);
  18037. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18038. std::string last_modified = res1->get_header_value("Last-Modified");
  18039. EXPECT_FALSE(last_modified.empty());
  18040. // If-Modified-Since with same time: expect 304
  18041. Headers h2 = {{"If-Modified-Since", last_modified}};
  18042. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18043. ASSERT_TRUE(res2);
  18044. EXPECT_EQ(304, res2->status);
  18045. // If-Modified-Since with future time: expect 304
  18046. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18047. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18048. ASSERT_TRUE(res3);
  18049. EXPECT_EQ(304, res3->status);
  18050. // If-Modified-Since with past time: expect 200
  18051. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18052. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18053. ASSERT_TRUE(res4);
  18054. EXPECT_EQ(200, res4->status);
  18055. // If-None-Match takes precedence over If-Modified-Since
  18056. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18057. ASSERT_TRUE(res1->has_header("ETag"));
  18058. std::string etag = res1->get_header_value("ETag");
  18059. Headers h5 = {{"If-None-Match", etag},
  18060. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18061. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18062. ASSERT_TRUE(res5);
  18063. EXPECT_EQ(304, res5->status);
  18064. svr.stop();
  18065. t.join();
  18066. std::remove(fname);
  18067. }
  18068. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18069. using namespace httplib;
  18070. Server svr;
  18071. // Endpoint that returns compressible content
  18072. svr.Get("/compressible", [](const Request &, Response &res) {
  18073. // Return a large enough body to trigger compression
  18074. std::string body(1000, 'a');
  18075. res.set_content(body, "text/plain");
  18076. });
  18077. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18078. svr.wait_until_ready();
  18079. Client cli(HOST, PORT);
  18080. // Request with gzip support: should get Vary header when compressed
  18081. cli.set_compress(true);
  18082. auto res1 = cli.Get("/compressible");
  18083. ASSERT_TRUE(res1);
  18084. EXPECT_EQ(200, res1->status);
  18085. // If Content-Encoding is set, Vary should also be set
  18086. if (res1->has_header("Content-Encoding")) {
  18087. EXPECT_TRUE(res1->has_header("Vary"));
  18088. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18089. }
  18090. // Request without Accept-Encoding header: should not have compression
  18091. Headers h_no_compress;
  18092. auto res2 = cli.Get("/compressible", h_no_compress);
  18093. ASSERT_TRUE(res2);
  18094. EXPECT_EQ(200, res2->status);
  18095. // Verify Vary header is present when compression is applied
  18096. // (the exact behavior depends on server configuration)
  18097. svr.stop();
  18098. t.join();
  18099. }
  18100. TEST(ETagTest, IfRangeWithETag) {
  18101. using namespace httplib;
  18102. // Create a test file with known content
  18103. const char *fname = "if_range_testfile.txt";
  18104. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18105. {
  18106. std::ofstream ofs(fname);
  18107. ofs << content;
  18108. ASSERT_TRUE(ofs.good());
  18109. }
  18110. Server svr;
  18111. svr.set_mount_point("/static", ".");
  18112. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18113. svr.wait_until_ready();
  18114. Client cli(HOST, PORT);
  18115. // First request: get ETag
  18116. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18117. ASSERT_TRUE(res1);
  18118. ASSERT_EQ(200, res1->status);
  18119. ASSERT_TRUE(res1->has_header("ETag"));
  18120. std::string etag = res1->get_header_value("ETag");
  18121. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18122. // Since our server generates weak ETags (W/"..."), If-Range with our
  18123. // ETag should NOT result in partial content - it should return full content.
  18124. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18125. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18126. ASSERT_TRUE(res2);
  18127. // Weak ETag in If-Range -> full content (200), not partial (206)
  18128. EXPECT_EQ(200, res2->status);
  18129. EXPECT_EQ(content, res2->body);
  18130. EXPECT_FALSE(res2->has_header("Content-Range"));
  18131. // Range request with non-matching If-Range (ETag): should get 200 (full
  18132. // content)
  18133. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18134. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18135. ASSERT_TRUE(res3);
  18136. EXPECT_EQ(200, res3->status);
  18137. EXPECT_EQ(content, res3->body);
  18138. EXPECT_FALSE(res3->has_header("Content-Range"));
  18139. // Range request with strong ETag (hypothetical - our server doesn't generate
  18140. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18141. // should return full content)
  18142. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18143. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18144. ASSERT_TRUE(res4);
  18145. EXPECT_EQ(200, res4->status);
  18146. EXPECT_EQ(content, res4->body);
  18147. EXPECT_FALSE(res4->has_header("Content-Range"));
  18148. svr.stop();
  18149. t.join();
  18150. std::remove(fname);
  18151. }
  18152. TEST(ETagTest, IfRangeWithDate) {
  18153. using namespace httplib;
  18154. // Create a test file
  18155. const char *fname = "if_range_date_testfile.txt";
  18156. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18157. {
  18158. std::ofstream ofs(fname);
  18159. ofs << content;
  18160. ASSERT_TRUE(ofs.good());
  18161. }
  18162. Server svr;
  18163. svr.set_mount_point("/static", ".");
  18164. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18165. svr.wait_until_ready();
  18166. Client cli(HOST, PORT);
  18167. // First request: get Last-Modified
  18168. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18169. ASSERT_TRUE(res1);
  18170. ASSERT_EQ(200, res1->status);
  18171. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18172. std::string last_modified = res1->get_header_value("Last-Modified");
  18173. // Range request with matching If-Range (date): should get 206
  18174. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18175. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18176. ASSERT_TRUE(res2);
  18177. EXPECT_EQ(206, res2->status);
  18178. EXPECT_EQ("FGHIJ", res2->body);
  18179. // Range request with old If-Range date: should get 200 (full content)
  18180. Headers h3 = {{"Range", "bytes=5-9"},
  18181. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18182. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18183. ASSERT_TRUE(res3);
  18184. EXPECT_EQ(200, res3->status);
  18185. EXPECT_EQ(content, res3->body);
  18186. // Range request with future If-Range date: should get 206
  18187. Headers h4 = {{"Range", "bytes=0-4"},
  18188. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18189. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18190. ASSERT_TRUE(res4);
  18191. EXPECT_EQ(206, res4->status);
  18192. EXPECT_EQ("ABCDE", res4->body);
  18193. svr.stop();
  18194. t.join();
  18195. std::remove(fname);
  18196. }
  18197. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18198. using namespace httplib;
  18199. const char *fname = "etag_malformed.txt";
  18200. const char *content = "malformed-etag";
  18201. {
  18202. std::ofstream ofs(fname);
  18203. ofs << content;
  18204. ASSERT_TRUE(ofs.good());
  18205. }
  18206. Server svr;
  18207. svr.set_mount_point("/static", ".");
  18208. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18209. svr.wait_until_ready();
  18210. Client cli(HOST, PORT);
  18211. // baseline: should get 200 and an ETag
  18212. auto res1 = cli.Get("/static/etag_malformed.txt");
  18213. ASSERT_TRUE(res1);
  18214. ASSERT_EQ(200, res1->status);
  18215. ASSERT_TRUE(res1->has_header("ETag"));
  18216. // Malformed ETag value (missing quotes) should be treated as non-matching
  18217. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18218. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18219. ASSERT_TRUE(res_bad);
  18220. EXPECT_EQ(200, res_bad->status);
  18221. // Whitespace-only header value should be considered invalid / non-matching
  18222. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18223. "Host: localhost\r\n"
  18224. "If-None-Match: \r\n"
  18225. "Connection: close\r\n"
  18226. "\r\n";
  18227. std::string out;
  18228. ASSERT_TRUE(send_request(5, raw_req, &out));
  18229. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18230. svr.stop();
  18231. t.join();
  18232. std::remove(fname);
  18233. }
  18234. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18235. using namespace httplib;
  18236. const char *fname = "ims_invalid_format.txt";
  18237. const char *content = "ims-bad-format";
  18238. {
  18239. std::ofstream ofs(fname);
  18240. ofs << content;
  18241. ASSERT_TRUE(ofs.good());
  18242. }
  18243. Server svr;
  18244. svr.set_mount_point("/static", ".");
  18245. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18246. svr.wait_until_ready();
  18247. Client cli(HOST, PORT);
  18248. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18249. ASSERT_TRUE(res1);
  18250. ASSERT_EQ(200, res1->status);
  18251. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18252. // If-Modified-Since with invalid format should not result in 304
  18253. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18254. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18255. ASSERT_TRUE(res_bad);
  18256. EXPECT_EQ(200, res_bad->status);
  18257. // If-Range with invalid date format should be treated as mismatch -> full
  18258. // content (200)
  18259. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18260. {"If-Range", "invalid-date"}};
  18261. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18262. ASSERT_TRUE(res_ifrange);
  18263. EXPECT_EQ(200, res_ifrange->status);
  18264. svr.stop();
  18265. t.join();
  18266. std::remove(fname);
  18267. }
  18268. TEST(ETagTest, IfRangeWithMalformedETag) {
  18269. using namespace httplib;
  18270. const char *fname = "ifrange_malformed.txt";
  18271. const std::string content = "0123456789";
  18272. {
  18273. std::ofstream ofs(fname);
  18274. ofs << content;
  18275. ASSERT_TRUE(ofs.good());
  18276. }
  18277. Server svr;
  18278. svr.set_mount_point("/static", ".");
  18279. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18280. svr.wait_until_ready();
  18281. Client cli(HOST, PORT);
  18282. // First request: get ETag
  18283. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18284. ASSERT_TRUE(res1);
  18285. ASSERT_EQ(200, res1->status);
  18286. ASSERT_TRUE(res1->has_header("ETag"));
  18287. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18288. // full content (200)
  18289. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18290. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18291. ASSERT_TRUE(res2);
  18292. EXPECT_EQ(200, res2->status);
  18293. EXPECT_EQ(content, res2->body);
  18294. svr.stop();
  18295. t.join();
  18296. std::remove(fname);
  18297. }
  18298. TEST(ETagTest, ExtremeLargeDateValues) {
  18299. using namespace httplib;
  18300. const char *fname = "ims_extreme_date.txt";
  18301. const char *content = "ims-extreme-date";
  18302. {
  18303. std::ofstream ofs(fname);
  18304. ofs << content;
  18305. ASSERT_TRUE(ofs.good());
  18306. }
  18307. Server svr;
  18308. svr.set_mount_point("/static", ".");
  18309. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18310. svr.wait_until_ready();
  18311. Client cli(HOST, PORT);
  18312. auto res1 = cli.Get(std::string("/static/") + fname);
  18313. ASSERT_TRUE(res1);
  18314. ASSERT_EQ(200, res1->status);
  18315. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18316. // Extremely large year that may overflow date parsing routines.
  18317. Headers h_large_date = {
  18318. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18319. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18320. ASSERT_TRUE(res_bad);
  18321. // Expect server to treat this as invalid/mismatch and return full content
  18322. EXPECT_EQ(200, res_bad->status);
  18323. // If-Range with extremely large date should be treated as mismatch -> full
  18324. // content (200)
  18325. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18326. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18327. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18328. ASSERT_TRUE(res_ifrange);
  18329. EXPECT_EQ(200, res_ifrange->status);
  18330. svr.stop();
  18331. t.join();
  18332. std::remove(fname);
  18333. }
  18334. TEST(ETagTest, NegativeFileModificationTime) {
  18335. using namespace httplib;
  18336. const char *fname = "ims_negative_mtime.txt";
  18337. const std::string content = "negative-mtime";
  18338. {
  18339. std::ofstream ofs(fname);
  18340. ofs << content;
  18341. ASSERT_TRUE(ofs.good());
  18342. }
  18343. // Try to set file mtime to a negative value. This may fail on some
  18344. // platforms/filesystems; if it fails, the test will still verify server
  18345. // behaves safely by performing a regular conditional request.
  18346. #if defined(__APPLE__) || defined(__linux__)
  18347. bool set_negative = false;
  18348. do {
  18349. struct timeval times[2];
  18350. // access time: now
  18351. times[0].tv_sec = time(nullptr);
  18352. times[0].tv_usec = 0;
  18353. // modification time: negative (e.g., -1)
  18354. times[1].tv_sec = -1;
  18355. times[1].tv_usec = 0;
  18356. if (utimes(fname, times) == 0) { set_negative = true; }
  18357. } while (0);
  18358. #else
  18359. bool set_negative = false;
  18360. #endif
  18361. Server svr;
  18362. svr.set_mount_point("/static", ".");
  18363. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18364. svr.wait_until_ready();
  18365. Client cli(HOST, PORT);
  18366. auto res1 = cli.Get(std::string("/static/") + fname);
  18367. ASSERT_TRUE(res1);
  18368. ASSERT_EQ(200, res1->status);
  18369. bool has_last_modified = res1->has_header("Last-Modified");
  18370. std::string last_modified;
  18371. if (has_last_modified) {
  18372. last_modified = res1->get_header_value("Last-Modified");
  18373. }
  18374. if (set_negative) {
  18375. // If we successfully set a negative mtime, ensure server returns a
  18376. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18377. // with an old date and ensure server handles it without crash.
  18378. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18379. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18380. ASSERT_TRUE(res2);
  18381. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18382. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18383. } else {
  18384. // Could not set negative mtime on this platform; fall back to verifying
  18385. // that normal invalid/malformed dates are treated safely (non-304).
  18386. Headers h_bad_date = {
  18387. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18388. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18389. ASSERT_TRUE(res_bad);
  18390. EXPECT_EQ(200, res_bad->status);
  18391. }
  18392. svr.stop();
  18393. t.join();
  18394. std::remove(fname);
  18395. }
  18396. //==============================================================================
  18397. // SSE Parsing Tests
  18398. //==============================================================================
  18399. class SSEParsingTest : public ::testing::Test {
  18400. protected:
  18401. // Test helper that mimics SSE parsing behavior
  18402. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18403. int &retry_ms) {
  18404. // Blank line signals end of event
  18405. if (line.empty() || line == "\r") { return true; }
  18406. // Lines starting with ':' are comments (ignored)
  18407. if (!line.empty() && line[0] == ':') { return false; }
  18408. // Find the colon separator
  18409. auto colon_pos = line.find(':');
  18410. if (colon_pos == std::string::npos) {
  18411. // Line with no colon is treated as field name with empty value
  18412. return false;
  18413. }
  18414. std::string field = line.substr(0, colon_pos);
  18415. std::string value;
  18416. // Value starts after colon, skip optional single space
  18417. if (colon_pos + 1 < line.size()) {
  18418. size_t value_start = colon_pos + 1;
  18419. if (line[value_start] == ' ') { value_start++; }
  18420. value = line.substr(value_start);
  18421. // Remove trailing \r if present
  18422. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18423. }
  18424. // Handle known fields
  18425. if (field == "event") {
  18426. msg.event = value;
  18427. } else if (field == "data") {
  18428. // Multiple data lines are concatenated with newlines
  18429. if (!msg.data.empty()) { msg.data += "\n"; }
  18430. msg.data += value;
  18431. } else if (field == "id") {
  18432. // Empty id is valid (clears the last event ID)
  18433. msg.id = value;
  18434. } else if (field == "retry") {
  18435. // Parse retry interval in milliseconds
  18436. {
  18437. int v = 0;
  18438. auto res =
  18439. detail::from_chars(value.data(), value.data() + value.size(), v);
  18440. if (res.ec == std::errc{}) { retry_ms = v; }
  18441. }
  18442. }
  18443. // Unknown fields are ignored per SSE spec
  18444. return false;
  18445. }
  18446. };
  18447. // Test: Single-line data
  18448. TEST_F(SSEParsingTest, SingleLineData) {
  18449. sse::SSEMessage msg;
  18450. int retry_ms = 3000;
  18451. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18452. EXPECT_EQ(msg.data, "hello");
  18453. EXPECT_EQ(msg.event, "message");
  18454. // Blank line ends event
  18455. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18456. }
  18457. // Test: Multi-line data
  18458. TEST_F(SSEParsingTest, MultiLineData) {
  18459. sse::SSEMessage msg;
  18460. int retry_ms = 3000;
  18461. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18462. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18463. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18464. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18465. }
  18466. // Test: Custom event types
  18467. TEST_F(SSEParsingTest, CustomEventType) {
  18468. sse::SSEMessage msg;
  18469. int retry_ms = 3000;
  18470. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18471. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18472. EXPECT_EQ(msg.event, "update");
  18473. EXPECT_EQ(msg.data, "payload");
  18474. }
  18475. // Test: Event ID handling
  18476. TEST_F(SSEParsingTest, EventIdHandling) {
  18477. sse::SSEMessage msg;
  18478. int retry_ms = 3000;
  18479. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18480. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18481. EXPECT_EQ(msg.id, "12345");
  18482. }
  18483. // Test: Empty event ID (clears last event ID)
  18484. TEST_F(SSEParsingTest, EmptyEventId) {
  18485. sse::SSEMessage msg;
  18486. msg.id = "previous";
  18487. int retry_ms = 3000;
  18488. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18489. EXPECT_EQ(msg.id, "");
  18490. }
  18491. // Test: Retry field parsing
  18492. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18493. sse::SSEMessage msg;
  18494. int retry_ms = 3000;
  18495. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18496. EXPECT_EQ(retry_ms, 5000);
  18497. }
  18498. // Test: Invalid retry value
  18499. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18500. sse::SSEMessage msg;
  18501. int retry_ms = 3000;
  18502. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18503. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18504. }
  18505. // Test: Comments (lines starting with :)
  18506. TEST_F(SSEParsingTest, CommentsIgnored) {
  18507. sse::SSEMessage msg;
  18508. int retry_ms = 3000;
  18509. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18510. EXPECT_EQ(msg.data, "");
  18511. EXPECT_EQ(msg.event, "message");
  18512. }
  18513. // Test: Colon in value
  18514. TEST_F(SSEParsingTest, ColonInValue) {
  18515. sse::SSEMessage msg;
  18516. int retry_ms = 3000;
  18517. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18518. EXPECT_EQ(msg.data, "hello:world:test");
  18519. }
  18520. // Test: Line with no colon (field name only)
  18521. TEST_F(SSEParsingTest, FieldNameOnly) {
  18522. sse::SSEMessage msg;
  18523. int retry_ms = 3000;
  18524. // According to SSE spec, this is treated as field name with empty value
  18525. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18526. // Since we don't recognize "data" without colon, data should be empty
  18527. EXPECT_EQ(msg.data, "");
  18528. }
  18529. // Test: Trailing \r handling
  18530. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18531. sse::SSEMessage msg;
  18532. int retry_ms = 3000;
  18533. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18534. EXPECT_EQ(msg.data, "hello");
  18535. }
  18536. // Test: Unknown fields ignored
  18537. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18538. sse::SSEMessage msg;
  18539. int retry_ms = 3000;
  18540. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18541. EXPECT_EQ(msg.data, "");
  18542. EXPECT_EQ(msg.event, "message");
  18543. }
  18544. // Test: Space after colon is optional
  18545. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18546. sse::SSEMessage msg1, msg2;
  18547. int retry_ms = 3000;
  18548. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18549. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18550. EXPECT_EQ(msg1.data, "hello");
  18551. EXPECT_EQ(msg2.data, "hello");
  18552. }
  18553. // Test: SSEMessage clear
  18554. TEST_F(SSEParsingTest, MessageClear) {
  18555. sse::SSEMessage msg;
  18556. msg.event = "custom";
  18557. msg.data = "some data";
  18558. msg.id = "123";
  18559. msg.clear();
  18560. EXPECT_EQ(msg.event, "message");
  18561. EXPECT_EQ(msg.data, "");
  18562. EXPECT_EQ(msg.id, "");
  18563. }
  18564. // Test: Complete event parsing
  18565. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18566. sse::SSEMessage msg;
  18567. int retry_ms = 3000;
  18568. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18569. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18570. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18571. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18572. // Blank line ends event
  18573. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18574. EXPECT_EQ(msg.event, "notification");
  18575. EXPECT_EQ(msg.id, "evt-42");
  18576. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18577. EXPECT_EQ(retry_ms, 1000);
  18578. }
  18579. //==============================================================================
  18580. // Integration Tests with Server
  18581. //==============================================================================
  18582. class SSEIntegrationTest : public ::testing::Test {
  18583. protected:
  18584. void SetUp() override {
  18585. stop_server_.store(false);
  18586. events_.clear();
  18587. server_ = httplib::detail::make_unique<Server>();
  18588. setup_server();
  18589. start_server();
  18590. }
  18591. void TearDown() override {
  18592. stop_server_.store(true);
  18593. event_cv_.notify_all();
  18594. server_->stop();
  18595. if (server_thread_.joinable()) { server_thread_.join(); }
  18596. }
  18597. void setup_server() {
  18598. // Simple SSE endpoint
  18599. server_->Get("/events", [this](const Request &req, Response &res) {
  18600. auto last_id = req.get_header_value("Last-Event-ID");
  18601. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18602. res.set_chunked_content_provider(
  18603. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18604. std::unique_lock<std::mutex> lock(event_mutex_);
  18605. if (event_cv_.wait_for(
  18606. lock, std::chrono::milliseconds(200), [this] {
  18607. return !events_.empty() || stop_server_.load();
  18608. })) {
  18609. if (stop_server_.load()) { return false; }
  18610. if (!events_.empty()) {
  18611. std::string event = events_.front();
  18612. events_.erase(events_.begin());
  18613. sink.write(event.data(), event.size());
  18614. return true;
  18615. }
  18616. }
  18617. return !stop_server_.load();
  18618. });
  18619. });
  18620. // Endpoint that returns error
  18621. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18622. res.status = 500;
  18623. res.set_content("Internal Server Error", "text/plain");
  18624. });
  18625. // Endpoint for custom event types
  18626. server_->Get("/custom-events", [](const Request &, Response &res) {
  18627. res.set_chunked_content_provider(
  18628. "text/event-stream", [](size_t offset, DataSink &sink) {
  18629. if (offset == 0) {
  18630. std::string event = "event: update\ndata: updated\n\n"
  18631. "event: delete\ndata: deleted\n\n";
  18632. sink.write(event.data(), event.size());
  18633. }
  18634. return false; // End stream after sending
  18635. });
  18636. });
  18637. }
  18638. void start_server() {
  18639. port_ = server_->bind_to_any_port(HOST);
  18640. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18641. // Wait for server to start
  18642. while (!server_->is_running()) {
  18643. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18644. }
  18645. }
  18646. int get_port() const { return port_; }
  18647. void send_event(const std::string &event) {
  18648. std::lock_guard<std::mutex> lock(event_mutex_);
  18649. events_.push_back(event);
  18650. event_cv_.notify_all();
  18651. }
  18652. std::unique_ptr<Server> server_;
  18653. std::thread server_thread_;
  18654. std::mutex event_mutex_;
  18655. std::condition_variable event_cv_;
  18656. std::vector<std::string> events_;
  18657. std::atomic<bool> stop_server_{false};
  18658. std::string last_received_event_id_;
  18659. int port_ = 0;
  18660. };
  18661. // Test: Successful connection and on_open callback
  18662. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18663. // Add a simple endpoint that sends one event and closes
  18664. server_->Get("/simple-event", [](const Request &, Response &res) {
  18665. res.set_chunked_content_provider(
  18666. "text/event-stream", [](size_t offset, DataSink &sink) {
  18667. if (offset == 0) {
  18668. std::string event = "data: hello\n\n";
  18669. sink.write(event.data(), event.size());
  18670. }
  18671. return false; // Close stream after sending
  18672. });
  18673. });
  18674. Client client("localhost", get_port());
  18675. sse::SSEClient sse(client, "/simple-event");
  18676. std::atomic<bool> open_called{false};
  18677. std::atomic<bool> message_received{false};
  18678. sse.on_open([&open_called]() { open_called.store(true); });
  18679. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18680. if (msg.data == "hello") { message_received.store(true); }
  18681. });
  18682. sse.set_reconnect_interval(100);
  18683. sse.set_max_reconnect_attempts(1);
  18684. // Start async
  18685. sse.start_async();
  18686. // Wait for message to be processed
  18687. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18688. sse.stop();
  18689. EXPECT_TRUE(open_called.load());
  18690. EXPECT_TRUE(message_received.load());
  18691. }
  18692. // Test: on_message callback
  18693. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18694. // Endpoint that sends multiple events then closes
  18695. server_->Get("/multi-event", [](const Request &, Response &res) {
  18696. res.set_chunked_content_provider(
  18697. "text/event-stream", [](size_t offset, DataSink &sink) {
  18698. if (offset == 0) {
  18699. std::string events = "data: message1\n\ndata: message2\n\n";
  18700. sink.write(events.data(), events.size());
  18701. }
  18702. return false;
  18703. });
  18704. });
  18705. Client client("localhost", get_port());
  18706. sse::SSEClient sse(client, "/multi-event");
  18707. std::vector<std::string> received_messages;
  18708. std::mutex messages_mutex;
  18709. sse.on_message([&](const sse::SSEMessage &msg) {
  18710. std::lock_guard<std::mutex> lock(messages_mutex);
  18711. received_messages.push_back(msg.data);
  18712. });
  18713. sse.set_reconnect_interval(100);
  18714. sse.set_max_reconnect_attempts(1);
  18715. sse.start_async();
  18716. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18717. sse.stop();
  18718. std::lock_guard<std::mutex> lock(messages_mutex);
  18719. EXPECT_GE(received_messages.size(), 2u);
  18720. if (received_messages.size() >= 2) {
  18721. EXPECT_EQ(received_messages[0], "message1");
  18722. EXPECT_EQ(received_messages[1], "message2");
  18723. }
  18724. }
  18725. // Test: on_event for specific types
  18726. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18727. Client client("localhost", get_port());
  18728. sse::SSEClient sse(client, "/custom-events");
  18729. std::atomic<bool> update_received{false};
  18730. std::atomic<bool> delete_received{false};
  18731. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18732. if (msg.data == "updated") { update_received.store(true); }
  18733. });
  18734. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18735. if (msg.data == "deleted") { delete_received.store(true); }
  18736. });
  18737. sse.set_max_reconnect_attempts(1);
  18738. sse.start_async();
  18739. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18740. sse.stop();
  18741. EXPECT_TRUE(update_received.load());
  18742. EXPECT_TRUE(delete_received.load());
  18743. }
  18744. // Test: on_error callback on connection failure
  18745. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18746. // Connect to a non-existent port
  18747. Client client("localhost", 59999);
  18748. sse::SSEClient sse(client, "/events");
  18749. std::atomic<bool> error_called{false};
  18750. Error received_error = Error::Success;
  18751. sse.on_error([&](Error err) {
  18752. error_called.store(true);
  18753. received_error = err;
  18754. });
  18755. sse.set_reconnect_interval(50);
  18756. sse.set_max_reconnect_attempts(1);
  18757. sse.start_async();
  18758. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18759. sse.stop();
  18760. EXPECT_TRUE(error_called.load());
  18761. EXPECT_NE(received_error, Error::Success);
  18762. }
  18763. // Test: Last-Event-ID header sent on reconnect
  18764. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18765. // Endpoint that sends event with ID
  18766. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18767. res.set_chunked_content_provider(
  18768. "text/event-stream", [](size_t offset, DataSink &sink) {
  18769. if (offset == 0) {
  18770. std::string event = "id: evt-123\ndata: test\n\n";
  18771. sink.write(event.data(), event.size());
  18772. }
  18773. return false;
  18774. });
  18775. });
  18776. Client client("localhost", get_port());
  18777. sse::SSEClient sse(client, "/event-with-id");
  18778. std::atomic<bool> id_received{false};
  18779. sse.on_message([&](const sse::SSEMessage &msg) {
  18780. if (!msg.id.empty()) { id_received.store(true); }
  18781. });
  18782. sse.set_reconnect_interval(100);
  18783. sse.set_max_reconnect_attempts(1);
  18784. sse.start_async();
  18785. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18786. sse.stop();
  18787. EXPECT_TRUE(id_received.load());
  18788. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18789. }
  18790. // Test: Manual stop
  18791. TEST_F(SSEIntegrationTest, ManualStop) {
  18792. // Endpoint that sends one event and stays open briefly
  18793. std::atomic<bool> handler_running{true};
  18794. server_->Get("/stay-open", [&handler_running](const Request &,
  18795. Response &res) {
  18796. res.set_chunked_content_provider(
  18797. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18798. if (offset == 0) {
  18799. std::string event = "data: connected\n\n";
  18800. sink.write(event.data(), event.size());
  18801. }
  18802. // Keep connection open while handler_running is true
  18803. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18804. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18805. }
  18806. return false;
  18807. });
  18808. });
  18809. Client client("localhost", get_port());
  18810. sse::SSEClient sse(client, "/stay-open");
  18811. std::atomic<bool> connected{false};
  18812. sse.on_open([&connected]() { connected.store(true); });
  18813. sse.set_reconnect_interval(100);
  18814. sse.set_max_reconnect_attempts(1);
  18815. sse.start_async();
  18816. // Wait for connection to establish
  18817. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18818. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18819. }
  18820. EXPECT_TRUE(connected.load());
  18821. EXPECT_TRUE(sse.is_connected());
  18822. // Signal handler to stop
  18823. handler_running.store(false);
  18824. // Stop SSE client
  18825. sse.stop();
  18826. EXPECT_FALSE(sse.is_connected());
  18827. }
  18828. // Test: SSEClient with custom headers
  18829. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18830. // Setup a server endpoint that checks for custom header
  18831. std::atomic<bool> header_received{false};
  18832. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18833. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18834. header_received.store(true);
  18835. }
  18836. res.set_chunked_content_provider("text/event-stream",
  18837. [](size_t, DataSink &) { return false; });
  18838. });
  18839. Client client("localhost", get_port());
  18840. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18841. sse::SSEClient sse(client, "/header-check", headers);
  18842. sse.set_max_reconnect_attempts(1);
  18843. sse.start_async();
  18844. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18845. sse.stop();
  18846. EXPECT_TRUE(header_received.load());
  18847. }
  18848. // Test: Reconnect interval configuration
  18849. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18850. Client client("localhost", get_port());
  18851. sse::SSEClient sse(client, "/events");
  18852. auto &result = sse.set_reconnect_interval(500);
  18853. // Builder pattern should return reference to self
  18854. EXPECT_EQ(&result, &sse);
  18855. }
  18856. // Test: Max reconnect attempts
  18857. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18858. // Connect to non-existent port to force reconnects
  18859. Client client("localhost", 59998);
  18860. sse::SSEClient sse(client, "/events");
  18861. std::atomic<int> error_count{0};
  18862. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18863. sse.set_reconnect_interval(50);
  18864. sse.set_max_reconnect_attempts(2);
  18865. auto start = std::chrono::steady_clock::now();
  18866. sse.start(); // Blocking call
  18867. auto end = std::chrono::steady_clock::now();
  18868. // Should have stopped after 2 failed attempts
  18869. EXPECT_GE(error_count.load(), 2);
  18870. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18871. auto duration =
  18872. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18873. #ifdef _WIN32
  18874. // Windows is much slower for socket connection failures
  18875. EXPECT_LT(duration.count(), 7000);
  18876. #else
  18877. EXPECT_LT(duration.count(), 1000);
  18878. #endif
  18879. }
  18880. // Test: Multi-line data in integration
  18881. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18882. // Endpoint with multi-line data
  18883. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18884. res.set_chunked_content_provider(
  18885. "text/event-stream", [](size_t offset, DataSink &sink) {
  18886. if (offset == 0) {
  18887. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18888. sink.write(event.data(), event.size());
  18889. }
  18890. return false;
  18891. });
  18892. });
  18893. Client client("localhost", get_port());
  18894. sse::SSEClient sse(client, "/multiline-data");
  18895. std::string received_data;
  18896. std::mutex data_mutex;
  18897. sse.on_message([&](const sse::SSEMessage &msg) {
  18898. std::lock_guard<std::mutex> lock(data_mutex);
  18899. received_data = msg.data;
  18900. });
  18901. sse.set_reconnect_interval(100);
  18902. sse.set_max_reconnect_attempts(1);
  18903. sse.start_async();
  18904. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18905. sse.stop();
  18906. std::lock_guard<std::mutex> lock(data_mutex);
  18907. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18908. }
  18909. // Test: Auto-reconnect after server disconnection
  18910. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18911. std::atomic<int> connection_count{0};
  18912. std::atomic<int> message_count{0};
  18913. // Endpoint that sends one event and closes, forcing reconnect
  18914. server_->Get("/reconnect-test",
  18915. [&connection_count](const Request &, Response &res) {
  18916. connection_count.fetch_add(1);
  18917. res.set_chunked_content_provider(
  18918. "text/event-stream", [](size_t offset, DataSink &sink) {
  18919. if (offset == 0) {
  18920. std::string event = "data: hello\n\n";
  18921. sink.write(event.data(), event.size());
  18922. }
  18923. return false; // Close connection after sending
  18924. });
  18925. });
  18926. Client client("localhost", get_port());
  18927. sse::SSEClient sse(client, "/reconnect-test");
  18928. sse.on_message([&message_count](const sse::SSEMessage &) {
  18929. message_count.fetch_add(1);
  18930. });
  18931. sse.set_reconnect_interval(100);
  18932. sse.set_max_reconnect_attempts(3);
  18933. sse.start_async();
  18934. // Wait long enough for multiple reconnects
  18935. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18936. sse.stop();
  18937. // Should have connected multiple times (initial + reconnects)
  18938. EXPECT_GE(connection_count.load(), 2);
  18939. // Should have received messages from multiple connections
  18940. EXPECT_GE(message_count.load(), 2);
  18941. }
  18942. // Test: Last-Event-ID sent on reconnect
  18943. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18944. std::atomic<int> connection_count{0};
  18945. std::vector<std::string> received_last_event_ids;
  18946. std::mutex id_mutex;
  18947. // Endpoint that checks Last-Event-ID header and sends event with ID
  18948. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18949. int conn = connection_count.fetch_add(1);
  18950. // Capture the Last-Event-ID header from each connection
  18951. {
  18952. std::lock_guard<std::mutex> lock(id_mutex);
  18953. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  18954. }
  18955. res.set_chunked_content_provider(
  18956. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  18957. if (offset == 0) {
  18958. std::string event =
  18959. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  18960. sink.write(event.data(), event.size());
  18961. }
  18962. return false;
  18963. });
  18964. });
  18965. Client client("localhost", get_port());
  18966. sse::SSEClient sse(client, "/reconnect-with-id");
  18967. sse.set_reconnect_interval(100);
  18968. sse.set_max_reconnect_attempts(3);
  18969. sse.start_async();
  18970. // Wait for at least 2 connections
  18971. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18972. sse.stop();
  18973. // Verify behavior
  18974. std::lock_guard<std::mutex> lock(id_mutex);
  18975. EXPECT_GE(received_last_event_ids.size(), 2u);
  18976. // First connection should have no Last-Event-ID
  18977. if (!received_last_event_ids.empty()) {
  18978. EXPECT_EQ(received_last_event_ids[0], "");
  18979. }
  18980. // Second connection should have Last-Event-ID from first connection
  18981. if (received_last_event_ids.size() >= 2) {
  18982. EXPECT_EQ(received_last_event_ids[1], "event-0");
  18983. }
  18984. }
  18985. // Test: set_headers updates headers used on reconnect
  18986. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  18987. std::vector<std::string> received_tokens;
  18988. std::mutex token_mutex;
  18989. // Endpoint that captures Authorization header
  18990. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  18991. {
  18992. std::lock_guard<std::mutex> lock(token_mutex);
  18993. received_tokens.push_back(req.get_header_value("Authorization"));
  18994. }
  18995. res.set_chunked_content_provider(
  18996. "text/event-stream", [](size_t offset, DataSink &sink) {
  18997. if (offset == 0) {
  18998. std::string event = "data: hello\n\n";
  18999. sink.write(event.data(), event.size());
  19000. }
  19001. return false; // Close connection to trigger reconnect
  19002. });
  19003. });
  19004. Client client("localhost", get_port());
  19005. Headers headers = {{"Authorization", "Bearer old-token"}};
  19006. sse::SSEClient sse(client, "/auth-check", headers);
  19007. // Update headers on each successful connection
  19008. sse.on_open(
  19009. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19010. sse.set_reconnect_interval(100);
  19011. sse.set_max_reconnect_attempts(3);
  19012. sse.start_async();
  19013. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19014. sse.stop();
  19015. std::lock_guard<std::mutex> lock(token_mutex);
  19016. ASSERT_GE(received_tokens.size(), 2u);
  19017. // First connection uses original header
  19018. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19019. // Second connection uses updated header from set_headers
  19020. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19021. }
  19022. // Test: 401 allows reconnection (so on_error can refresh headers)
  19023. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19024. std::atomic<int> connection_count{0};
  19025. // Endpoint: returns 401 on first attempt, 200 on second
  19026. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19027. int conn = connection_count.fetch_add(1);
  19028. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19029. res.status = StatusCode::Unauthorized_401;
  19030. res.set_content("Unauthorized", "text/plain");
  19031. return;
  19032. }
  19033. res.set_chunked_content_provider(
  19034. "text/event-stream", [](size_t offset, DataSink &sink) {
  19035. if (offset == 0) {
  19036. std::string event = "data: authenticated\n\n";
  19037. sink.write(event.data(), event.size());
  19038. }
  19039. return false;
  19040. });
  19041. });
  19042. Client client("localhost", get_port());
  19043. Headers headers = {{"Authorization", "Bearer expired"}};
  19044. sse::SSEClient sse(client, "/auth-retry", headers);
  19045. std::atomic<bool> message_received{false};
  19046. // Refresh token on error
  19047. sse.on_error(
  19048. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19049. sse.on_message([&](const sse::SSEMessage &msg) {
  19050. if (msg.data == "authenticated") { message_received.store(true); }
  19051. });
  19052. sse.set_reconnect_interval(100);
  19053. sse.set_max_reconnect_attempts(3);
  19054. sse.start_async();
  19055. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19056. sse.stop();
  19057. // Should have reconnected after 401 and succeeded with new token
  19058. EXPECT_GE(connection_count.load(), 2);
  19059. EXPECT_TRUE(message_received.load());
  19060. }
  19061. TEST(Issue2318Test, EmptyHostString) {
  19062. {
  19063. httplib::Client cli_empty("", PORT);
  19064. auto res = cli_empty.Get("/");
  19065. ASSERT_FALSE(res);
  19066. EXPECT_EQ(httplib::Error::Connection, res.error());
  19067. }
  19068. {
  19069. httplib::Client cli(" ", PORT);
  19070. auto res = cli.Get("/");
  19071. ASSERT_FALSE(res);
  19072. EXPECT_EQ(httplib::Error::Connection, res.error());
  19073. }
  19074. }
  19075. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19076. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19077. Server svr;
  19078. // Set a small payload limit (1KB)
  19079. svr.set_payload_max_length(1024);
  19080. svr.Post("/test", [&](const Request &req, Response &res) {
  19081. res.set_content("Body size: " + std::to_string(req.body.size()),
  19082. "text/plain");
  19083. });
  19084. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19085. auto se = detail::scope_exit([&] {
  19086. svr.stop();
  19087. listen_thread.join();
  19088. });
  19089. svr.wait_until_ready();
  19090. // Create data that compresses well but exceeds limit when decompressed
  19091. // 8KB of repeated null bytes compresses to a very small size
  19092. std::string original_data(8 * 1024, '\0');
  19093. // Compress the data using gzip
  19094. std::string compressed_data;
  19095. detail::gzip_compressor compressor;
  19096. compressor.compress(original_data.data(), original_data.size(), true,
  19097. [&](const char *data, size_t size) {
  19098. compressed_data.append(data, size);
  19099. return true;
  19100. });
  19101. // Verify compression worked (compressed should be much smaller)
  19102. ASSERT_LT(compressed_data.size(), original_data.size());
  19103. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19104. // Send compressed data with Content-Encoding: gzip
  19105. Client cli(HOST, PORT);
  19106. Headers headers = {{"Content-Encoding", "gzip"}};
  19107. auto res =
  19108. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19109. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19111. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19112. }
  19113. #endif
  19114. // ============================================================================
  19115. // OpenSSL-Specific Tests
  19116. // ============================================================================
  19117. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19118. X509 *readCertificate(const std::string &strFileName) {
  19119. std::ifstream inStream(strFileName);
  19120. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19121. std::istreambuf_iterator<char>());
  19122. if (strCertPEM.empty()) return (nullptr);
  19123. BIO *pbCert = BIO_new(BIO_s_mem());
  19124. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19125. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19126. BIO_free(pbCert);
  19127. return (pCert);
  19128. }
  19129. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19130. std::ifstream inStream(strFileName);
  19131. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19132. std::istreambuf_iterator<char>());
  19133. if (strPrivateKeyPEM.empty()) return (nullptr);
  19134. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19135. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19136. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19137. BIO_free(pbPrivKey);
  19138. return (pPrivateKey);
  19139. }
  19140. TEST(BindServerTest, UpdateCerts) {
  19141. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19142. int port = svr.bind_to_any_port("0.0.0.0");
  19143. ASSERT_TRUE(svr.is_valid());
  19144. ASSERT_TRUE(port > 0);
  19145. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19146. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19147. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19148. ASSERT_TRUE(cert != nullptr);
  19149. ASSERT_TRUE(ca_cert != nullptr);
  19150. ASSERT_TRUE(key != nullptr);
  19151. X509_STORE *cert_store = X509_STORE_new();
  19152. X509_STORE_add_cert(cert_store, ca_cert);
  19153. // svr.update_certs(cert, key, cert_store); // deprecated
  19154. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19155. CLIENT_CA_CERT_FILE);
  19156. ASSERT_TRUE(svr.is_valid());
  19157. svr.stop();
  19158. X509_STORE_free(cert_store);
  19159. X509_free(cert);
  19160. X509_free(ca_cert);
  19161. EVP_PKEY_free(key);
  19162. }
  19163. // Test that update_certs() updates client CA list correctly
  19164. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19165. // Start with file-based constructor
  19166. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19167. ASSERT_TRUE(svr.is_valid());
  19168. // Initially no client CA list should be set
  19169. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19170. ASSERT_TRUE(ssl_ctx != nullptr);
  19171. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19172. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19173. EXPECT_EQ(0, count_before);
  19174. // Now update with client CA (PEM string)
  19175. std::string cert_pem, key_pem, ca_pem;
  19176. read_file(SERVER_CERT_FILE, cert_pem);
  19177. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19178. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19179. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19180. ASSERT_TRUE(svr.is_valid());
  19181. // Now client CA list should be set
  19182. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19183. ASSERT_TRUE(ca_list_after != nullptr);
  19184. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19185. }
  19186. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19187. // Test that the file-path SSLServer constructor properly sets the client CA
  19188. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19189. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19190. ASSERT_TRUE(svr.is_valid());
  19191. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19192. ASSERT_TRUE(ssl_ctx != nullptr);
  19193. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19194. ASSERT_TRUE(ca_list != nullptr);
  19195. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19196. }
  19197. #endif
  19198. // ============================================================================
  19199. // MbedTLS-Specific Tests
  19200. // ============================================================================
  19201. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19202. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19203. using namespace httplib::tls;
  19204. // Track if callback was invoked
  19205. bool callback_invoked = false;
  19206. // The callback receives void* ctx which is actually MbedTlsContext*
  19207. // We can access the mbedtls_ssl_config via the context
  19208. auto setup_callback = [&callback_invoked](void *ctx) {
  19209. callback_invoked = true;
  19210. // Cast to MbedTlsContext* to access the ssl config
  19211. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19212. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19213. // Use static variables to hold certificate data (simplified for test)
  19214. static mbedtls_x509_crt own_cert;
  19215. static mbedtls_pk_context own_key;
  19216. static mbedtls_x509_crt ca_chain;
  19217. static bool initialized = false;
  19218. if (!initialized) {
  19219. mbedtls_x509_crt_init(&own_cert);
  19220. mbedtls_pk_init(&own_key);
  19221. mbedtls_x509_crt_init(&ca_chain);
  19222. // Load server certificate
  19223. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19224. return false;
  19225. }
  19226. // Load server private key.
  19227. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19228. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19229. #if MBEDTLS_VERSION_MAJOR == 3
  19230. ,
  19231. mbedtls_ctr_drbg_random, nullptr
  19232. #endif
  19233. ) != 0) {
  19234. return false;
  19235. }
  19236. // Load CA chain for client verification
  19237. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19238. return false;
  19239. }
  19240. initialized = true;
  19241. }
  19242. // Configure the SSL config
  19243. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19244. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19245. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19246. // Set minimum TLS version using mbedTLS native API
  19247. #if MBEDTLS_VERSION_MAJOR >= 3
  19248. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19249. #else
  19250. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19251. MBEDTLS_SSL_MINOR_VERSION_3);
  19252. #endif
  19253. return true;
  19254. };
  19255. SSLServer svr(setup_callback);
  19256. ASSERT_TRUE(svr.is_valid());
  19257. ASSERT_TRUE(callback_invoked);
  19258. svr.Get("/test", [&](const Request &req, Response &res) {
  19259. res.set_content("test", "text/plain");
  19260. auto cert = req.peer_cert();
  19261. ASSERT_TRUE(static_cast<bool>(cert));
  19262. auto common_name = cert.subject_cn();
  19263. EXPECT_EQ("Common Name", common_name);
  19264. });
  19265. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19266. auto se = detail::scope_exit([&] {
  19267. svr.stop();
  19268. t.join();
  19269. ASSERT_FALSE(svr.is_running());
  19270. });
  19271. svr.wait_until_ready();
  19272. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19273. cli.enable_server_certificate_verification(false);
  19274. cli.set_connection_timeout(30);
  19275. auto res = cli.Get("/test");
  19276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19277. ASSERT_EQ(StatusCode::OK_200, res->status);
  19278. }
  19279. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19280. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19281. // keep-alive SSL session, which reads through that config in
  19282. // mbedtls_ssl_close_notify.
  19283. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19284. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19285. ASSERT_TRUE(svr.is_valid());
  19286. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19287. res.set_content("test", "text/plain");
  19288. });
  19289. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19290. auto se = detail::scope_exit([&] {
  19291. svr.stop();
  19292. t.join();
  19293. ASSERT_FALSE(svr.is_running());
  19294. });
  19295. svr.wait_until_ready();
  19296. {
  19297. SSLClient cli(HOST, PORT);
  19298. cli.enable_server_certificate_verification(false);
  19299. cli.set_keep_alive(true);
  19300. auto res = cli.Get("/test");
  19301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19302. ASSERT_EQ(StatusCode::OK_200, res->status);
  19303. // cli is destructed here with the keep-alive SSL session still open.
  19304. }
  19305. }
  19306. #endif
  19307. // WebSocket Tests
  19308. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19309. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19310. // defining the meaning of these bits has been negotiated.
  19311. auto make_frame = [](uint8_t first_byte) {
  19312. std::string frame;
  19313. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19314. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19315. frame += "Hello";
  19316. return frame;
  19317. };
  19318. // RSV1 set (0x40)
  19319. {
  19320. detail::BufferStream strm;
  19321. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19322. ws::Opcode opcode;
  19323. std::string payload;
  19324. bool fin;
  19325. EXPECT_EQ(
  19326. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19327. ws::impl::FrameRead::Fail);
  19328. }
  19329. // RSV2 set (0x20)
  19330. {
  19331. detail::BufferStream strm;
  19332. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19333. ws::Opcode opcode;
  19334. std::string payload;
  19335. bool fin;
  19336. EXPECT_EQ(
  19337. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19338. ws::impl::FrameRead::Fail);
  19339. }
  19340. // RSV3 set (0x10)
  19341. {
  19342. detail::BufferStream strm;
  19343. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19344. ws::Opcode opcode;
  19345. std::string payload;
  19346. bool fin;
  19347. EXPECT_EQ(
  19348. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19349. ws::impl::FrameRead::Fail);
  19350. }
  19351. // No RSV bits set - should succeed
  19352. {
  19353. detail::BufferStream strm;
  19354. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19355. ws::Opcode opcode;
  19356. std::string payload;
  19357. bool fin;
  19358. EXPECT_EQ(
  19359. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19360. ws::impl::FrameRead::Ok);
  19361. EXPECT_EQ(ws::Opcode::Text, opcode);
  19362. EXPECT_EQ("Hello", payload);
  19363. EXPECT_TRUE(fin);
  19364. }
  19365. }
  19366. TEST(WebSocketTest, ControlFrameValidation) {
  19367. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19368. // payload length <= 125.
  19369. // Ping with FIN=0 - must be rejected
  19370. {
  19371. detail::BufferStream strm;
  19372. std::string frame;
  19373. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19374. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19375. strm.write(frame.data(), frame.size());
  19376. ws::Opcode opcode;
  19377. std::string payload;
  19378. bool fin;
  19379. EXPECT_EQ(
  19380. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19381. ws::impl::FrameRead::Fail);
  19382. }
  19383. // Close with FIN=0 - must be rejected
  19384. {
  19385. detail::BufferStream strm;
  19386. std::string frame;
  19387. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19388. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19389. strm.write(frame.data(), frame.size());
  19390. ws::Opcode opcode;
  19391. std::string payload;
  19392. bool fin;
  19393. EXPECT_EQ(
  19394. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19395. ws::impl::FrameRead::Fail);
  19396. }
  19397. // Ping with payload_len=126 (extended length) - must be rejected
  19398. {
  19399. detail::BufferStream strm;
  19400. std::string frame;
  19401. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19402. frame += static_cast<char>(126); // payload_len=126 (>125)
  19403. frame += static_cast<char>(0x00); // extended length high byte
  19404. frame += static_cast<char>(126); // extended length low byte
  19405. frame += std::string(126, 'x');
  19406. strm.write(frame.data(), frame.size());
  19407. ws::Opcode opcode;
  19408. std::string payload;
  19409. bool fin;
  19410. EXPECT_EQ(
  19411. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19412. ws::impl::FrameRead::Fail);
  19413. }
  19414. // Ping with FIN=1 and payload_len=125 - should succeed
  19415. {
  19416. detail::BufferStream strm;
  19417. std::string frame;
  19418. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19419. frame += static_cast<char>(125); // payload_len=125
  19420. frame += std::string(125, 'x');
  19421. strm.write(frame.data(), frame.size());
  19422. ws::Opcode opcode;
  19423. std::string payload;
  19424. bool fin;
  19425. EXPECT_EQ(
  19426. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19427. ws::impl::FrameRead::Ok);
  19428. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19429. EXPECT_EQ(125u, payload.size());
  19430. EXPECT_TRUE(fin);
  19431. }
  19432. }
  19433. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19434. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19435. // length MUST be 0.
  19436. // MSB set - must be rejected
  19437. {
  19438. detail::BufferStream strm;
  19439. std::string frame;
  19440. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19441. frame += static_cast<char>(127); // 64-bit extended length
  19442. frame += static_cast<char>(0x80); // MSB set (invalid)
  19443. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19444. strm.write(frame.data(), frame.size());
  19445. ws::Opcode opcode;
  19446. std::string payload;
  19447. bool fin;
  19448. EXPECT_EQ(
  19449. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19450. ws::impl::FrameRead::Fail);
  19451. }
  19452. // MSB clear - should pass length parsing (will be rejected by max_len,
  19453. // but that's a different check; use a small length to verify)
  19454. {
  19455. detail::BufferStream strm;
  19456. std::string frame;
  19457. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19458. frame += static_cast<char>(127); // 64-bit extended length
  19459. frame += std::string(7, '\0'); // high bytes = 0
  19460. frame += static_cast<char>(0x03); // length = 3
  19461. frame += "abc";
  19462. strm.write(frame.data(), frame.size());
  19463. ws::Opcode opcode;
  19464. std::string payload;
  19465. bool fin;
  19466. EXPECT_EQ(
  19467. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19468. ws::impl::FrameRead::Ok);
  19469. EXPECT_EQ(ws::Opcode::Text, opcode);
  19470. EXPECT_EQ("abc", payload);
  19471. }
  19472. }
  19473. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19474. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19475. // Valid UTF-8
  19476. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19477. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19478. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19479. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19480. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19481. // Invalid UTF-8
  19482. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19483. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19484. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19485. EXPECT_FALSE(
  19486. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19487. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19488. }
  19489. TEST(WebSocketTest, ConnectAndDisconnect) {
  19490. Server svr;
  19491. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19492. std::string msg;
  19493. while (ws.read(msg)) {}
  19494. });
  19495. auto port = svr.bind_to_any_port(HOST);
  19496. std::thread t([&]() { svr.listen_after_bind(); });
  19497. svr.wait_until_ready();
  19498. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19499. auto res = client.connect();
  19500. ASSERT_TRUE(res);
  19501. EXPECT_EQ(Error::Success, res.error());
  19502. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19503. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19504. EXPECT_TRUE(client.is_open());
  19505. client.close();
  19506. EXPECT_FALSE(client.is_open());
  19507. svr.stop();
  19508. t.join();
  19509. }
  19510. TEST(WebSocketTest, ValidURL) {
  19511. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19512. EXPECT_TRUE(ws1.is_valid());
  19513. ws::WebSocketClient ws2("ws://example.com/path");
  19514. EXPECT_TRUE(ws2.is_valid());
  19515. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19516. EXPECT_TRUE(ws3.is_valid());
  19517. #ifdef CPPHTTPLIB_SSL_ENABLED
  19518. ws::WebSocketClient wss1("wss://example.com/path");
  19519. EXPECT_TRUE(wss1.is_valid());
  19520. ws::WebSocketClient wss2("wss://example.com:443/path");
  19521. EXPECT_TRUE(wss2.is_valid());
  19522. #endif
  19523. }
  19524. TEST(WebSocketTest, InvalidURL) {
  19525. // No scheme
  19526. ws::WebSocketClient ws1("localhost:8080/path");
  19527. EXPECT_FALSE(ws1.is_valid());
  19528. // No path
  19529. ws::WebSocketClient ws2("ws://localhost:8080");
  19530. EXPECT_FALSE(ws2.is_valid());
  19531. // Empty string
  19532. ws::WebSocketClient ws3("");
  19533. EXPECT_FALSE(ws3.is_valid());
  19534. // Missing host
  19535. ws::WebSocketClient ws4("ws://:8080/path");
  19536. EXPECT_FALSE(ws4.is_valid());
  19537. // Port number overflow — should not crash
  19538. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19539. EXPECT_FALSE(ws5.is_valid());
  19540. // Port out of range
  19541. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19542. EXPECT_FALSE(ws6.is_valid());
  19543. }
  19544. TEST(WebSocketTest, UnsupportedScheme) {
  19545. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19546. ws::WebSocketClient ws1("http://localhost:8080/path");
  19547. EXPECT_FALSE(ws1.is_valid());
  19548. ws::WebSocketClient ws2("https://localhost:8080/path");
  19549. EXPECT_FALSE(ws2.is_valid());
  19550. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19551. EXPECT_FALSE(ws3.is_valid());
  19552. #else
  19553. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19554. std::invalid_argument);
  19555. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19556. std::invalid_argument);
  19557. #endif
  19558. }
  19559. TEST(WebSocketTest, ConnectWhenInvalid) {
  19560. ws::WebSocketClient ws("not a valid url");
  19561. EXPECT_FALSE(ws.is_valid());
  19562. auto res = ws.connect();
  19563. EXPECT_FALSE(res);
  19564. EXPECT_EQ(Error::Connection, res.error());
  19565. EXPECT_EQ(-1, res.status());
  19566. }
  19567. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19568. // Grab a port that is free, then close it again so nothing listens there
  19569. Server svr;
  19570. auto port = svr.bind_to_any_port(HOST);
  19571. svr.stop();
  19572. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19573. auto res = client.connect();
  19574. ASSERT_FALSE(res);
  19575. EXPECT_EQ(Error::Connection, res.error());
  19576. EXPECT_EQ(-1, res.status());
  19577. }
  19578. TEST(WebSocketTest, DefaultPort) {
  19579. ws::WebSocketClient ws1("ws://example.com/path");
  19580. EXPECT_TRUE(ws1.is_valid());
  19581. // ws:// defaults to port 80 (verified by successful parse)
  19582. #ifdef CPPHTTPLIB_SSL_ENABLED
  19583. ws::WebSocketClient ws2("wss://example.com/path");
  19584. EXPECT_TRUE(ws2.is_valid());
  19585. // wss:// defaults to port 443 (verified by successful parse)
  19586. #endif
  19587. }
  19588. TEST(WebSocketTest, IPv6LiteralAddress) {
  19589. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19590. EXPECT_TRUE(ws1.is_valid());
  19591. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19592. EXPECT_TRUE(ws2.is_valid());
  19593. }
  19594. TEST(WebSocketTest, ComplexPath) {
  19595. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19596. EXPECT_TRUE(ws1.is_valid());
  19597. ws::WebSocketClient ws2("ws://localhost:8080/");
  19598. EXPECT_TRUE(ws2.is_valid());
  19599. }
  19600. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19601. Server svr;
  19602. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19603. std::string msg;
  19604. while (ws.read(msg)) {}
  19605. });
  19606. auto port = svr.bind_to_any_port(HOST);
  19607. std::thread t([&]() { svr.listen_after_bind(); });
  19608. svr.wait_until_ready();
  19609. auto another_host = "example.com";
  19610. auto wrong_ip = "192.0.2.1";
  19611. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19612. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19613. ASSERT_TRUE(client.connect());
  19614. EXPECT_TRUE(client.is_open());
  19615. client.close();
  19616. svr.stop();
  19617. t.join();
  19618. }
  19619. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19620. Server svr;
  19621. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19622. std::string msg;
  19623. while (ws.read(msg)) {}
  19624. });
  19625. auto port = svr.bind_to_any_port(HOST);
  19626. std::thread t([&]() { svr.listen_after_bind(); });
  19627. svr.wait_until_ready();
  19628. auto wrong_ip = "192.0.2.1";
  19629. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19630. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19631. client.set_connection_timeout(1);
  19632. client.set_read_timeout(1);
  19633. client.set_write_timeout(1);
  19634. EXPECT_FALSE(client.connect());
  19635. EXPECT_FALSE(client.is_open());
  19636. svr.stop();
  19637. t.join();
  19638. }
  19639. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19640. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19641. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19642. // (RFC 6761) is only a map key and the Host header value.
  19643. auto host = "target.invalid";
  19644. Server svr;
  19645. std::string received_host;
  19646. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19647. received_host = req.get_header_value("Host");
  19648. std::string msg;
  19649. while (ws.read(msg)) {}
  19650. });
  19651. auto port = svr.bind_to_any_port(HOST);
  19652. std::thread t([&]() { svr.listen_after_bind(); });
  19653. // ASSERT_* below returns from the test body, which would leave t joinable
  19654. // and make ~thread call std::terminate.
  19655. auto se = detail::scope_exit([&] {
  19656. svr.stop();
  19657. if (t.joinable()) { t.join(); }
  19658. });
  19659. svr.wait_until_ready();
  19660. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19661. std::to_string(port) + "/ws");
  19662. client.set_hostname_addr_map({{host, HOST}});
  19663. ASSERT_TRUE(client.connect());
  19664. EXPECT_TRUE(client.is_open());
  19665. client.close();
  19666. svr.stop();
  19667. t.join();
  19668. // The mapping only redirects the connection; the identity stays host_.
  19669. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19670. }
  19671. class WebSocketIntegrationTest : public ::testing::Test {
  19672. protected:
  19673. void SetUp() override {
  19674. server_ = httplib::detail::make_unique<Server>();
  19675. setup_server();
  19676. start_server();
  19677. }
  19678. void TearDown() override {
  19679. server_->stop();
  19680. if (server_thread_.joinable()) { server_thread_.join(); }
  19681. }
  19682. void setup_server() {
  19683. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19684. std::string msg;
  19685. ws::ReadResult ret;
  19686. while ((ret = ws.read(msg))) {
  19687. if (ret == ws::Binary) {
  19688. ws.send(msg.data(), msg.size());
  19689. } else {
  19690. ws.send(msg);
  19691. }
  19692. }
  19693. });
  19694. server_->WebSocket("/ws-echo-string",
  19695. [](const Request &, ws::WebSocket &ws) {
  19696. std::string msg;
  19697. while (ws.read(msg)) {
  19698. ws.send("echo: " + msg);
  19699. }
  19700. });
  19701. server_->WebSocket(
  19702. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19703. // Echo back request metadata
  19704. ws.send("path:" + req.path);
  19705. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19706. std::string msg;
  19707. while (ws.read(msg)) {}
  19708. });
  19709. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19710. std::string msg;
  19711. ws.read(msg); // wait for a message
  19712. ws.close();
  19713. });
  19714. server_->WebSocket("/ws-close-status",
  19715. [](const Request &, ws::WebSocket &ws) {
  19716. std::string msg;
  19717. ws.read(msg); // wait for a message
  19718. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19719. });
  19720. server_->WebSocket(
  19721. "/ws-subprotocol",
  19722. [](const Request &, ws::WebSocket &ws) {
  19723. std::string msg;
  19724. while (ws.read(msg)) {
  19725. ws.send(msg);
  19726. }
  19727. },
  19728. [](const std::vector<std::string> &protocols) -> std::string {
  19729. for (const auto &p : protocols) {
  19730. if (p == "graphql-ws") { return p; }
  19731. }
  19732. return "";
  19733. });
  19734. }
  19735. void start_server() {
  19736. port_ = server_->bind_to_any_port(HOST);
  19737. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19738. server_->wait_until_ready();
  19739. }
  19740. std::unique_ptr<Server> server_;
  19741. std::thread server_thread_;
  19742. int port_ = 0;
  19743. };
  19744. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19745. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19746. "/ws-echo");
  19747. ASSERT_TRUE(client.connect());
  19748. ASSERT_TRUE(client.is_open());
  19749. ASSERT_TRUE(client.send("Hello WebSocket"));
  19750. std::string msg;
  19751. EXPECT_EQ(ws::Text, client.read(msg));
  19752. EXPECT_EQ("Hello WebSocket", msg);
  19753. client.close();
  19754. }
  19755. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19756. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19757. "/ws-echo");
  19758. ASSERT_TRUE(client.connect());
  19759. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19760. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19761. std::string msg;
  19762. EXPECT_EQ(ws::Binary, client.read(msg));
  19763. EXPECT_EQ(binary_data, msg);
  19764. client.close();
  19765. }
  19766. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19767. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19768. "/ws-echo");
  19769. ASSERT_TRUE(client.connect());
  19770. for (int i = 0; i < 10; i++) {
  19771. auto text = "message " + std::to_string(i);
  19772. ASSERT_TRUE(client.send(text));
  19773. std::string msg;
  19774. ASSERT_TRUE(client.read(msg));
  19775. EXPECT_EQ(text, msg);
  19776. }
  19777. client.close();
  19778. }
  19779. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19780. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19781. "/ws-close");
  19782. ASSERT_TRUE(client.connect());
  19783. // Send a message to trigger the server to close
  19784. ASSERT_TRUE(client.send("trigger close"));
  19785. // The server will close, so read should return false
  19786. std::string msg;
  19787. EXPECT_FALSE(client.read(msg));
  19788. EXPECT_FALSE(client.is_open());
  19789. }
  19790. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19791. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19792. "/ws-echo");
  19793. ASSERT_TRUE(client.connect());
  19794. // 128KB message
  19795. std::string large_data(128 * 1024, 'X');
  19796. ASSERT_TRUE(client.send(large_data));
  19797. std::string msg;
  19798. ASSERT_TRUE(client.read(msg));
  19799. EXPECT_EQ(large_data, msg);
  19800. client.close();
  19801. }
  19802. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19803. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19804. "/ws-echo");
  19805. ASSERT_TRUE(client.connect());
  19806. const int num_threads = 4;
  19807. std::vector<std::thread> threads;
  19808. std::atomic<int> send_count{0};
  19809. for (int t = 0; t < num_threads; t++) {
  19810. threads.emplace_back([&client, &send_count, t]() {
  19811. for (int i = 0; i < 5; i++) {
  19812. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19813. if (client.send(text)) { send_count++; }
  19814. }
  19815. });
  19816. }
  19817. for (auto &th : threads) {
  19818. th.join();
  19819. }
  19820. int received = 0;
  19821. std::string msg;
  19822. while (received < send_count.load()) {
  19823. if (!client.read(msg)) { break; }
  19824. received++;
  19825. }
  19826. EXPECT_EQ(send_count.load(), received);
  19827. client.close();
  19828. }
  19829. TEST_F(WebSocketIntegrationTest, ReadString) {
  19830. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19831. "/ws-echo-string");
  19832. ASSERT_TRUE(client.connect());
  19833. ASSERT_TRUE(client.send("hello"));
  19834. std::string msg;
  19835. ASSERT_TRUE(client.read(msg));
  19836. EXPECT_EQ("echo: hello", msg);
  19837. ASSERT_TRUE(client.send("world"));
  19838. ASSERT_TRUE(client.read(msg));
  19839. EXPECT_EQ("echo: world", msg);
  19840. client.close();
  19841. }
  19842. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19843. Headers headers = {{"X-Test-Header", "test-value"}};
  19844. ws::WebSocketClient client(
  19845. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19846. ASSERT_TRUE(client.connect());
  19847. std::string msg;
  19848. ASSERT_TRUE(client.read(msg));
  19849. EXPECT_EQ("path:/ws-request-info", msg);
  19850. ASSERT_TRUE(client.read(msg));
  19851. EXPECT_EQ("header:test-value", msg);
  19852. client.close();
  19853. }
  19854. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19855. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19856. "/ws-echo");
  19857. client.set_read_timeout(1, 0); // 1 second
  19858. ASSERT_TRUE(client.connect());
  19859. // Don't send anything — server echo handler waits for a message, so read()
  19860. // should time out. The connection survives it: nothing was consumed.
  19861. std::string msg;
  19862. EXPECT_EQ(client.read(msg), ws::Timeout);
  19863. EXPECT_TRUE(client.is_open());
  19864. // And it is still usable afterwards.
  19865. EXPECT_TRUE(client.send("after timeout"));
  19866. EXPECT_EQ(client.read(msg), ws::Text);
  19867. EXPECT_EQ(msg, "after timeout");
  19868. }
  19869. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19870. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19871. "/ws-echo");
  19872. client.set_read_timeout(1, 0);
  19873. ASSERT_TRUE(client.connect());
  19874. ASSERT_TRUE(client.send("first"));
  19875. std::string msg;
  19876. ASSERT_EQ(client.read(msg), ws::Text);
  19877. ASSERT_EQ(msg, "first");
  19878. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19879. // not be used with a read timeout: it would reprocess the previous message.
  19880. EXPECT_EQ(client.read(msg), ws::Timeout);
  19881. EXPECT_EQ(msg, "first");
  19882. }
  19883. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19884. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19885. "/ws-echo");
  19886. ASSERT_TRUE(client.connect());
  19887. // Setting it once the connection is open reaches the live stream, not just
  19888. // the seed for the next connect().
  19889. client.set_read_timeout(1, 0);
  19890. std::string msg;
  19891. EXPECT_EQ(client.read(msg), ws::Timeout);
  19892. EXPECT_TRUE(client.is_open());
  19893. }
  19894. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19895. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19896. "/ws-echo");
  19897. client.set_read_timeout(5, 0);
  19898. ASSERT_TRUE(client.connect());
  19899. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19900. // The server should reject it and close the connection.
  19901. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19902. client.send(oversized);
  19903. // The server's read() should have failed due to payload limit,
  19904. // so our read() should return false (connection closed).
  19905. std::string msg;
  19906. EXPECT_FALSE(client.read(msg));
  19907. }
  19908. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19909. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19910. "/ws-echo");
  19911. client.set_read_timeout(10, 0);
  19912. ASSERT_TRUE(client.connect());
  19913. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19914. // This should succeed.
  19915. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19916. ASSERT_TRUE(client.send(at_limit));
  19917. std::string msg;
  19918. ASSERT_TRUE(client.read(msg));
  19919. EXPECT_EQ(at_limit.size(), msg.size());
  19920. client.close();
  19921. }
  19922. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19923. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19924. "/nonexistent");
  19925. auto res = client.connect();
  19926. EXPECT_FALSE(res);
  19927. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19928. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19929. EXPECT_FALSE(client.is_open());
  19930. }
  19931. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19932. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19933. "/ws-echo");
  19934. ASSERT_TRUE(client.connect());
  19935. ASSERT_TRUE(client.send(""));
  19936. std::string msg;
  19937. EXPECT_EQ(ws::Text, client.read(msg));
  19938. EXPECT_EQ("", msg);
  19939. client.close();
  19940. }
  19941. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19942. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19943. "/ws-echo");
  19944. // First connection
  19945. ASSERT_TRUE(client.connect());
  19946. ASSERT_TRUE(client.send("first"));
  19947. std::string msg;
  19948. ASSERT_TRUE(client.read(msg));
  19949. EXPECT_EQ("first", msg);
  19950. client.close();
  19951. EXPECT_FALSE(client.is_open());
  19952. // Reconnect using the same client object
  19953. ASSERT_TRUE(client.connect());
  19954. ASSERT_TRUE(client.is_open());
  19955. ASSERT_TRUE(client.send("second"));
  19956. ASSERT_TRUE(client.read(msg));
  19957. EXPECT_EQ("second", msg);
  19958. client.close();
  19959. }
  19960. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  19961. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19962. "/ws-close-status");
  19963. ASSERT_TRUE(client.connect());
  19964. // Trigger the server to close with GoingAway status
  19965. ASSERT_TRUE(client.send("trigger"));
  19966. // read() should return false after receiving the close frame
  19967. std::string msg;
  19968. EXPECT_FALSE(client.read(msg));
  19969. EXPECT_FALSE(client.is_open());
  19970. }
  19971. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  19972. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19973. "/ws-echo");
  19974. ASSERT_TRUE(client.connect());
  19975. client.close(ws::CloseStatus::GoingAway, "client leaving");
  19976. EXPECT_FALSE(client.is_open());
  19977. }
  19978. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  19979. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  19980. ws::WebSocketClient client(
  19981. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19982. ASSERT_TRUE(client.connect());
  19983. // Server should have selected graphql-ws
  19984. EXPECT_EQ("graphql-ws", client.subprotocol());
  19985. client.close();
  19986. }
  19987. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  19988. Headers headers;
  19989. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  19990. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  19991. ws::WebSocketClient client(
  19992. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19993. ASSERT_TRUE(client.connect());
  19994. // The offer on the second field line counts too, so graphql-ws is selected
  19995. EXPECT_EQ("graphql-ws", client.subprotocol());
  19996. client.close();
  19997. }
  19998. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  19999. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20000. ws::WebSocketClient client(
  20001. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20002. ASSERT_TRUE(client.connect());
  20003. // Server should not have selected any subprotocol
  20004. EXPECT_TRUE(client.subprotocol().empty());
  20005. client.close();
  20006. }
  20007. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20008. // Connect without requesting any subprotocol
  20009. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20010. "/ws-subprotocol");
  20011. ASSERT_TRUE(client.connect());
  20012. EXPECT_TRUE(client.subprotocol().empty());
  20013. client.close();
  20014. }
  20015. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20016. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20017. "/ws-echo");
  20018. client.set_tcp_nodelay(true);
  20019. client.set_connection_timeout(3, 0);
  20020. bool socket_options_called = false;
  20021. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20022. ASSERT_TRUE(client.connect());
  20023. ASSERT_TRUE(client.is_open());
  20024. EXPECT_TRUE(socket_options_called);
  20025. ASSERT_TRUE(client.send("hello"));
  20026. std::string msg;
  20027. auto result = client.read(msg);
  20028. EXPECT_EQ(result, ws::ReadResult::Text);
  20029. EXPECT_EQ(msg, "hello");
  20030. client.close();
  20031. }
  20032. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20033. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20034. "/ws-echo");
  20035. client.set_connection_timeout(std::chrono::seconds(3));
  20036. client.set_write_timeout(std::chrono::seconds(3));
  20037. // A sub-second remainder exercises the seconds/microseconds split.
  20038. client.set_read_timeout(std::chrono::milliseconds(1500));
  20039. ASSERT_TRUE(client.connect());
  20040. auto start = std::chrono::steady_clock::now();
  20041. std::string msg;
  20042. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20043. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20044. std::chrono::steady_clock::now() - start)
  20045. .count();
  20046. // Above 1s so that dropping the microseconds half of the split fails here.
  20047. // Ignoring the setter altogether would not reach this line at all: a client
  20048. // waits forever by default.
  20049. EXPECT_GE(elapsed, 1400);
  20050. EXPECT_LT(elapsed, 30000);
  20051. }
  20052. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20053. Server svr;
  20054. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20055. if (!req.has_header("Authorization")) {
  20056. res.status = StatusCode::Unauthorized_401;
  20057. res.set_content("Unauthorized", "text/plain");
  20058. return Server::HandlerResponse::Handled;
  20059. }
  20060. return Server::HandlerResponse::Unhandled;
  20061. });
  20062. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20063. std::string msg;
  20064. while (ws.read(msg)) {
  20065. ws.send(msg);
  20066. }
  20067. });
  20068. auto port = svr.bind_to_any_port("localhost");
  20069. std::thread t([&]() { svr.listen_after_bind(); });
  20070. svr.wait_until_ready();
  20071. // Without Authorization header - should be rejected before upgrade
  20072. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20073. EXPECT_FALSE(client1.connect());
  20074. // The rejection is framed like any other HTTP response
  20075. {
  20076. Client cli("localhost", port);
  20077. Headers headers = {{"Upgrade", "websocket"},
  20078. {"Connection", "Upgrade"},
  20079. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20080. {"Sec-WebSocket-Version", "13"}};
  20081. auto res = cli.Get("/ws", headers);
  20082. ASSERT_TRUE(res);
  20083. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20084. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20085. EXPECT_EQ("Unauthorized", res->body);
  20086. }
  20087. // With Authorization header - should succeed
  20088. Headers headers = {{"Authorization", "Bearer token123"}};
  20089. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20090. headers);
  20091. ASSERT_TRUE(client2.connect());
  20092. ASSERT_TRUE(client2.send("hello"));
  20093. std::string msg;
  20094. ASSERT_TRUE(client2.read(msg));
  20095. EXPECT_EQ("hello", msg);
  20096. client2.close();
  20097. svr.stop();
  20098. t.join();
  20099. }
  20100. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20101. Server svr;
  20102. std::atomic<int> pre_request_calls{0};
  20103. std::atomic<bool> route_matched{false};
  20104. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20105. pre_request_calls++;
  20106. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20107. if (req.get_header_value("Authorization") != "Bearer token123") {
  20108. res.status = StatusCode::Unauthorized_401;
  20109. res.set_content("Unauthorized", "text/plain");
  20110. return Server::HandlerResponse::Handled;
  20111. }
  20112. return Server::HandlerResponse::Unhandled;
  20113. });
  20114. std::atomic<bool> handler_called{false};
  20115. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20116. handler_called = true;
  20117. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20118. });
  20119. auto port = svr.bind_to_any_port("localhost");
  20120. std::thread t([&]() { svr.listen_after_bind(); });
  20121. svr.wait_until_ready();
  20122. // Without Authorization header - should be rejected before upgrade
  20123. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20124. "/ws/1");
  20125. EXPECT_FALSE(client1.connect());
  20126. EXPECT_FALSE(handler_called);
  20127. EXPECT_EQ(1, pre_request_calls);
  20128. EXPECT_TRUE(route_matched);
  20129. // The rejection is an ordinary HTTP response, not a protocol switch
  20130. {
  20131. Client cli("localhost", port);
  20132. Headers headers = {{"Upgrade", "websocket"},
  20133. {"Connection", "Upgrade"},
  20134. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20135. {"Sec-WebSocket-Version", "13"}};
  20136. auto res = cli.Get("/ws/1", headers);
  20137. ASSERT_TRUE(res);
  20138. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20139. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20140. EXPECT_EQ("Unauthorized", res->body);
  20141. }
  20142. EXPECT_FALSE(handler_called);
  20143. // With Authorization header - should succeed
  20144. Headers headers = {{"Authorization", "Bearer token123"}};
  20145. ws::WebSocketClient client2(
  20146. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20147. ASSERT_TRUE(client2.connect());
  20148. std::string msg;
  20149. ASSERT_TRUE(client2.read(msg));
  20150. EXPECT_EQ("/ws/:id 2", msg);
  20151. EXPECT_TRUE(handler_called);
  20152. client2.close();
  20153. svr.stop();
  20154. t.join();
  20155. }
  20156. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20157. Server svr;
  20158. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20159. // A read timeout is how a handler gets control back. Without it, a handler
  20160. // parked in read() can never write on the connection it is reading.
  20161. ws.set_read_timeout(std::chrono::milliseconds(100));
  20162. std::string msg;
  20163. while (ws.is_open()) {
  20164. auto r = ws.read(msg);
  20165. if (r == httplib::ws::Timeout) {
  20166. ws.send("tick");
  20167. continue;
  20168. }
  20169. if (r == httplib::ws::Fail) { break; }
  20170. ws.send(msg);
  20171. }
  20172. });
  20173. auto port = svr.bind_to_any_port("localhost");
  20174. std::thread t([&]() { svr.listen_after_bind(); });
  20175. svr.wait_until_ready();
  20176. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20177. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20178. ASSERT_TRUE(client.connect());
  20179. // The client sends nothing, so anything it receives came out of the
  20180. // handler's timeout path.
  20181. std::string msg;
  20182. ASSERT_EQ(client.read(msg), ws::Text);
  20183. EXPECT_EQ("tick", msg);
  20184. client.close();
  20185. svr.stop();
  20186. t.join();
  20187. }
  20188. // Stream::read may return fewer bytes than asked for. This is that contract at
  20189. // its worst -- one byte per call -- which is what a frame header straddling a
  20190. // read buffer's boundary looks like to the frame parser.
  20191. class WsByteAtATimeStream : public Stream {
  20192. public:
  20193. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20194. bool is_readable() const override { return true; }
  20195. bool wait_readable() const override { return true; }
  20196. bool wait_writable() const override { return true; }
  20197. ssize_t read(char *ptr, size_t size) override {
  20198. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20199. *ptr = data_[pos_++];
  20200. return 1;
  20201. }
  20202. ssize_t write(const char *, size_t size) override {
  20203. return static_cast<ssize_t>(size);
  20204. }
  20205. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20206. ip = "127.0.0.1";
  20207. port = 0;
  20208. }
  20209. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20210. ip = "127.0.0.1";
  20211. port = 0;
  20212. }
  20213. socket_t socket() const override { return INVALID_SOCKET; }
  20214. time_t duration() const override { return 0; }
  20215. private:
  20216. std::string data_;
  20217. size_t pos_ = 0;
  20218. };
  20219. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20220. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20221. // length and the mask key are all multi-byte fields here. Each used to be
  20222. // read with a single read() call, which fails as soon as one is split.
  20223. std::string body(200, 'x');
  20224. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20225. std::string frame;
  20226. frame += static_cast<char>(0x81); // FIN + Text
  20227. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20228. frame += static_cast<char>(body.size() >> 8);
  20229. frame += static_cast<char>(body.size() & 0xff);
  20230. for (size_t i = 0; i < 4; i++) {
  20231. frame += static_cast<char>(mask[i]);
  20232. }
  20233. for (size_t i = 0; i < body.size(); i++) {
  20234. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20235. }
  20236. WsByteAtATimeStream strm(frame);
  20237. ws::Opcode opcode;
  20238. std::string payload;
  20239. bool fin = false;
  20240. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20241. /*expect_masked=*/true, 1024),
  20242. ws::impl::FrameRead::Ok);
  20243. EXPECT_TRUE(fin);
  20244. EXPECT_EQ(opcode, ws::Opcode::Text);
  20245. EXPECT_EQ(payload, body);
  20246. }
  20247. TEST(WebSocketTest, QueryStringInHandshake) {
  20248. Server svr;
  20249. std::mutex mtx;
  20250. std::string received_target;
  20251. std::string received_token;
  20252. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20253. {
  20254. std::lock_guard<std::mutex> lock(mtx);
  20255. received_target = req.target;
  20256. if (req.has_param("token")) {
  20257. received_token = req.get_param_value("token");
  20258. }
  20259. }
  20260. std::string msg;
  20261. while (ws.read(msg)) {
  20262. ws.send(msg);
  20263. }
  20264. });
  20265. auto port = svr.bind_to_any_port("localhost");
  20266. std::thread t([&]() { svr.listen_after_bind(); });
  20267. svr.wait_until_ready();
  20268. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20269. "/ws?token=ABC&session=123");
  20270. ASSERT_TRUE(client.connect());
  20271. // Round-trip ensures the handler has run and captured the request.
  20272. ASSERT_TRUE(client.send("hello"));
  20273. std::string msg;
  20274. ASSERT_TRUE(client.read(msg));
  20275. EXPECT_EQ("hello", msg);
  20276. client.close();
  20277. {
  20278. std::lock_guard<std::mutex> lock(mtx);
  20279. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20280. EXPECT_EQ("ABC", received_token);
  20281. }
  20282. svr.stop();
  20283. t.join();
  20284. }
  20285. // Run a handshake against a throwaway server and hand the request the server
  20286. // received back to the caller, so tests can assert on the headers the client
  20287. // actually put on the wire.
  20288. static void capture_websocket_handshake_request(
  20289. const Headers &client_headers,
  20290. std::function<void(const Request &, int port)> verify) {
  20291. Server svr;
  20292. std::mutex mtx;
  20293. Request received;
  20294. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20295. {
  20296. std::lock_guard<std::mutex> lock(mtx);
  20297. received = req;
  20298. }
  20299. std::string msg;
  20300. while (ws.read(msg)) {
  20301. ws.send(msg);
  20302. }
  20303. });
  20304. auto port = svr.bind_to_any_port("localhost");
  20305. std::thread t([&]() { svr.listen_after_bind(); });
  20306. auto se = detail::scope_exit([&] {
  20307. svr.stop();
  20308. t.join();
  20309. });
  20310. svr.wait_until_ready();
  20311. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20312. client_headers);
  20313. ASSERT_TRUE(client.connect());
  20314. ASSERT_TRUE(client.send("hello"));
  20315. std::string msg;
  20316. ASSERT_TRUE(client.read(msg));
  20317. client.close();
  20318. {
  20319. std::lock_guard<std::mutex> lock(mtx);
  20320. verify(received, port);
  20321. }
  20322. }
  20323. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20324. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20325. // Non-default port must be present in the Host header. Default ports
  20326. // (80/443) are omitted; that logic is covered by
  20327. // MakeHostAndPortStringTest.
  20328. EXPECT_EQ("localhost:" + std::to_string(port),
  20329. req.get_header_value("Host"));
  20330. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20331. req.get_header_value("User-Agent"));
  20332. EXPECT_FALSE(req.has_header("Accept"));
  20333. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20334. EXPECT_FALSE(req.has_header("Content-Length"));
  20335. });
  20336. }
  20337. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20338. capture_websocket_handshake_request(
  20339. {{"Host", "example.com"},
  20340. {"User-Agent", "custom-agent"},
  20341. {"X-Custom", "value"}},
  20342. [](const Request &req, int) {
  20343. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20344. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20345. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20346. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20347. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20348. });
  20349. }
  20350. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20351. capture_websocket_handshake_request(
  20352. {{"Upgrade", "bogus"},
  20353. {"Connection", "close"},
  20354. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20355. {"Sec-WebSocket-Version", "8"}},
  20356. [](const Request &req, int) {
  20357. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20358. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20359. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20360. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20361. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20362. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20363. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20364. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20365. req.get_header_value("Sec-WebSocket-Key"));
  20366. });
  20367. }
  20368. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20369. // A header the client refuses to send must abort the handshake before any
  20370. // part of it reaches the wire; a lone request line would otherwise sit in
  20371. // the peer's buffer as a truncated request.
  20372. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20373. ASSERT_NE(INVALID_SOCKET, srv);
  20374. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20375. sockaddr_in addr{};
  20376. addr.sin_family = AF_INET;
  20377. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20378. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20379. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20380. ASSERT_EQ(0, ::listen(srv, 1));
  20381. sockaddr_in bound{};
  20382. socklen_t bound_len = sizeof(bound);
  20383. ASSERT_EQ(
  20384. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20385. auto port = ntohs(bound.sin_port);
  20386. ssize_t received = -1;
  20387. std::thread t([&] {
  20388. // Bound every blocking call so a regression fails the test with a bad
  20389. // value instead of hanging the suite.
  20390. fd_set rfds;
  20391. FD_ZERO(&rfds);
  20392. FD_SET(srv, &rfds);
  20393. timeval tv{5, 0};
  20394. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20395. 0) {
  20396. return;
  20397. }
  20398. sockaddr_in cli_addr{};
  20399. socklen_t cli_len = sizeof(cli_addr);
  20400. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20401. if (cli == INVALID_SOCKET) { return; }
  20402. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20403. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20404. char buf[4096];
  20405. received = ::recv(cli, buf, sizeof(buf), 0);
  20406. });
  20407. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20408. // connect() has already shut the socket down by the time it returns false,
  20409. // so the peer sees EOF without waiting for the client to be destroyed.
  20410. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20411. {{"X-Bad", "a\r\nInjected: 1"}});
  20412. EXPECT_FALSE(client.connect());
  20413. t.join();
  20414. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20415. EXPECT_EQ(0, received);
  20416. }
  20417. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20418. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20419. // contains "upgrade" as a substring is a different token and must not
  20420. // start a WebSocket handshake.
  20421. auto make_request = [](const std::vector<std::string> &connection_values) {
  20422. Request req;
  20423. req.method = "GET";
  20424. req.headers.emplace("Upgrade", "websocket");
  20425. for (const auto &value : connection_values) {
  20426. req.headers.emplace("Connection", value);
  20427. }
  20428. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20429. req.headers.emplace("Sec-WebSocket-Version", "13");
  20430. return req;
  20431. };
  20432. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20433. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20434. EXPECT_TRUE(
  20435. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20436. EXPECT_TRUE(
  20437. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20438. EXPECT_TRUE(
  20439. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20440. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20441. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20442. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20443. EXPECT_FALSE(
  20444. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20445. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20446. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20447. }
  20448. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20449. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20450. // asks recipients to match each protocol-name case-insensitively, and RFC
  20451. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20452. // client naming websocket alongside another protocol, or on a second field
  20453. // line, is offering websocket; a value that merely contains "websocket" as a
  20454. // substring is a different protocol name and is not.
  20455. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20456. Request req;
  20457. req.method = "GET";
  20458. for (const auto &value : upgrade_values) {
  20459. req.headers.emplace("Upgrade", value);
  20460. }
  20461. req.headers.emplace("Connection", "Upgrade");
  20462. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20463. req.headers.emplace("Sec-WebSocket-Version", "13");
  20464. return req;
  20465. };
  20466. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20467. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20468. EXPECT_TRUE(
  20469. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20470. EXPECT_TRUE(
  20471. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20472. EXPECT_TRUE(
  20473. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20474. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20475. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20476. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20477. EXPECT_FALSE(
  20478. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20479. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20480. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20481. }
  20482. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20483. Server svr;
  20484. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20485. auto port = svr.bind_to_any_port("localhost");
  20486. std::thread t([&]() { svr.listen_after_bind(); });
  20487. auto se = detail::scope_exit([&] {
  20488. svr.stop();
  20489. t.join();
  20490. });
  20491. svr.wait_until_ready();
  20492. Headers headers = {{"Upgrade", "websocket"},
  20493. {"Connection", "notupgrade"},
  20494. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20495. {"Sec-WebSocket-Version", "13"}};
  20496. Client cli("localhost", port);
  20497. auto res = cli.Get("/ws", headers);
  20498. // The route exists only as a WebSocket route, so a request that fails the
  20499. // handshake check falls through to ordinary routing.
  20500. ASSERT_TRUE(res);
  20501. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20502. }
  20503. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20504. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20505. // Connection value is the only thing left for the client to reject.
  20506. Server svr;
  20507. svr.Get("/ws", [](const Request &req, Response &res) {
  20508. res.status = StatusCode::SwitchingProtocol_101;
  20509. res.set_header("Upgrade", "websocket");
  20510. res.set_header("Connection", "notupgrade");
  20511. res.set_header("Sec-WebSocket-Accept",
  20512. detail::websocket_accept_key(
  20513. req.get_header_value("Sec-WebSocket-Key")));
  20514. });
  20515. auto port = svr.bind_to_any_port("localhost");
  20516. std::thread t([&]() { svr.listen_after_bind(); });
  20517. auto se = detail::scope_exit([&] {
  20518. svr.stop();
  20519. t.join();
  20520. });
  20521. svr.wait_until_ready();
  20522. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20523. auto res = client.connect();
  20524. EXPECT_FALSE(res);
  20525. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20526. EXPECT_FALSE(client.is_open());
  20527. }
  20528. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20529. // The socket path doubles as the URL host, so it must not contain '/'.
  20530. const char *shard = getenv("GTEST_SHARD_INDEX");
  20531. const std::string sock_path =
  20532. shard ? std::string("httplib-ws-") + shard + ".sock"
  20533. : std::string("httplib-ws.sock");
  20534. std::remove(sock_path.c_str());
  20535. Server svr;
  20536. std::mutex mtx;
  20537. std::string received_host;
  20538. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20539. {
  20540. std::lock_guard<std::mutex> lock(mtx);
  20541. received_host = req.get_header_value("Host");
  20542. }
  20543. std::string msg;
  20544. while (ws.read(msg)) {
  20545. ws.send(msg);
  20546. }
  20547. });
  20548. svr.set_address_family(AF_UNIX);
  20549. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20550. auto se = detail::scope_exit([&] {
  20551. svr.stop();
  20552. t.join();
  20553. std::remove(sock_path.c_str());
  20554. });
  20555. svr.wait_until_ready();
  20556. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20557. client.set_address_family(AF_UNIX);
  20558. ASSERT_TRUE(client.connect());
  20559. ASSERT_TRUE(client.send("hello"));
  20560. std::string msg;
  20561. ASSERT_TRUE(client.read(msg));
  20562. client.close();
  20563. {
  20564. std::lock_guard<std::mutex> lock(mtx);
  20565. // There is no host:port for a Unix socket, so the same "localhost"
  20566. // placeholder the HTTP client uses is expected.
  20567. EXPECT_EQ("localhost", received_host);
  20568. }
  20569. }
  20570. // Two threads must never parse WebSocket frames from the same stream.
  20571. // close() used to read the peer's Close reply with its own frame read, so it
  20572. // raced a reader thread that was in the middle of a payload: the payload loop
  20573. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20574. // so bytes taken by close() were replaced with bytes from further along the
  20575. // stream. The message kept its length and silently changed content.
  20576. //
  20577. // The raw peer below sends a frame header plus part of the payload, waits for
  20578. // the handler to call close(), and only then sends the rest. Whichever thread
  20579. // would win the race for those bytes, the message must arrive intact, because
  20580. // close() must not touch the stream while read() owns it.
  20581. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20582. #ifndef _WIN32
  20583. signal(SIGPIPE, SIG_IGN);
  20584. #endif
  20585. const size_t payload_len = 120; // fits the 7-bit length field
  20586. const size_t prefix_len = 8;
  20587. const int attempts = 8;
  20588. std::string expected(payload_len, '\0');
  20589. for (size_t i = 0; i < payload_len; i++) {
  20590. expected[i] = static_cast<char>('a' + i % 26);
  20591. }
  20592. std::atomic<bool> peer_stalled{false};
  20593. std::atomic<bool> handler_done{false};
  20594. std::mutex received_mutex;
  20595. std::vector<std::string> received;
  20596. // Bound every wait, so a regression fails the test instead of hanging the
  20597. // suite.
  20598. auto wait_for = [](const std::atomic<bool> &flag) {
  20599. for (int i = 0; i < 500 && !flag; i++) {
  20600. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20601. }
  20602. };
  20603. Server svr;
  20604. svr.set_websocket_ping_interval(0);
  20605. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20606. std::thread reader([&]() {
  20607. std::string msg;
  20608. while (ws.read(msg)) {
  20609. std::lock_guard<std::mutex> guard(received_mutex);
  20610. received.push_back(msg);
  20611. }
  20612. });
  20613. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20614. // inside read_websocket_frame() when close() runs.
  20615. wait_for(peer_stalled);
  20616. ws.close();
  20617. reader.join();
  20618. handler_done = true;
  20619. });
  20620. auto port = svr.bind_to_any_port("127.0.0.1");
  20621. std::thread t([&]() { svr.listen_after_bind(); });
  20622. auto se = detail::scope_exit([&] {
  20623. svr.stop();
  20624. t.join();
  20625. });
  20626. svr.wait_until_ready();
  20627. auto send_bytes = [](socket_t s, const std::string &data) {
  20628. #ifdef _WIN32
  20629. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20630. #else
  20631. auto n = ::send(s, data.data(), data.size(), 0);
  20632. #endif
  20633. return n == static_cast<decltype(n)>(data.size());
  20634. };
  20635. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20636. // Every length used here fits the 7-bit length field.
  20637. auto masked_header = [](uint8_t first_byte, size_t len) {
  20638. std::string h;
  20639. h += static_cast<char>(first_byte);
  20640. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20641. h.append(4, '\0'); // mask key
  20642. return h;
  20643. };
  20644. for (int attempt = 0; attempt < attempts; attempt++) {
  20645. peer_stalled = false;
  20646. handler_done = false;
  20647. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20648. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20649. auto se_sock = detail::scope_exit([&] {
  20650. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20651. });
  20652. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20653. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20654. sockaddr_in addr{};
  20655. addr.sin_family = AF_INET;
  20656. addr.sin_port = htons(static_cast<uint16_t>(port));
  20657. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20658. ASSERT_EQ(
  20659. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20660. << "attempt " << attempt;
  20661. ASSERT_TRUE(send_bytes(sock,
  20662. "GET /ws HTTP/1.1\r\n"
  20663. "Host: 127.0.0.1\r\n"
  20664. "Upgrade: websocket\r\n"
  20665. "Connection: Upgrade\r\n"
  20666. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20667. "Sec-WebSocket-Version: 13\r\n"
  20668. "\r\n"))
  20669. << "attempt " << attempt;
  20670. std::string response;
  20671. while (response.find("\r\n\r\n") == std::string::npos) {
  20672. char buf[512];
  20673. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20674. if (n <= 0) { break; }
  20675. response.append(buf, static_cast<size_t>(n));
  20676. }
  20677. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20678. << "attempt " << attempt;
  20679. // Send the header of a Binary message but only the first prefix_len bytes
  20680. // of its payload, leaving the reader thread stalled inside the payload.
  20681. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20682. expected.substr(0, prefix_len)))
  20683. << "attempt " << attempt;
  20684. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20685. peer_stalled = true;
  20686. // Let close() send its Close frame and park in its own read before the
  20687. // rest of the payload arrives, so both threads are waiting for it.
  20688. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20689. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20690. close_frame += static_cast<char>(0x03); // status 1000
  20691. close_frame += static_cast<char>(0xE8);
  20692. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20693. << "attempt " << attempt;
  20694. // Closing the peer releases the reader thread even on the buggy path,
  20695. // where it waits for bytes another thread already consumed.
  20696. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20697. detail::close_socket(sock);
  20698. sock = INVALID_SOCKET;
  20699. wait_for(handler_done);
  20700. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20701. }
  20702. std::lock_guard<std::mutex> guard(received_mutex);
  20703. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20704. << "a message in flight when close() ran was dropped";
  20705. for (size_t i = 0; i < received.size(); i++) {
  20706. EXPECT_EQ(expected, received[i]) << "message " << i;
  20707. }
  20708. }
  20709. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20710. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20711. protected:
  20712. void SetUp() override {
  20713. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20714. SERVER_PRIVATE_KEY_FILE);
  20715. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20716. std::string msg;
  20717. ws::ReadResult ret;
  20718. while ((ret = ws.read(msg))) {
  20719. if (ret == ws::Binary) {
  20720. ws.send(msg.data(), msg.size());
  20721. } else {
  20722. ws.send(msg);
  20723. }
  20724. }
  20725. });
  20726. port_ = server_->bind_to_any_port(HOST);
  20727. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20728. server_->wait_until_ready();
  20729. }
  20730. void TearDown() override {
  20731. server_->stop();
  20732. if (server_thread_.joinable()) { server_thread_.join(); }
  20733. }
  20734. std::unique_ptr<SSLServer> server_;
  20735. std::thread server_thread_;
  20736. int port_ = 0;
  20737. };
  20738. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20739. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20740. "/ws-echo");
  20741. client.enable_server_certificate_verification(false);
  20742. ASSERT_TRUE(client.connect());
  20743. ASSERT_TRUE(client.is_open());
  20744. ASSERT_TRUE(client.send("Hello WSS"));
  20745. std::string msg;
  20746. EXPECT_EQ(ws::Text, client.read(msg));
  20747. EXPECT_EQ("Hello WSS", msg);
  20748. client.close();
  20749. }
  20750. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20751. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20752. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20753. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20754. // client (without calling close() first) is the only path that runs
  20755. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20756. // bug exactly.
  20757. //
  20758. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20759. // when linked against an instrumented libssl; run under Valgrind to catch it
  20760. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20761. // suite (the freed session otherwise stalls on the close handshake) — this test
  20762. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20763. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20764. {
  20765. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20766. "/ws-echo");
  20767. client.enable_server_certificate_verification(false);
  20768. client.set_read_timeout(2, 0);
  20769. client.set_write_timeout(2, 0);
  20770. ASSERT_TRUE(client.connect());
  20771. ASSERT_TRUE(client.is_open());
  20772. ASSERT_TRUE(client.send("still open"));
  20773. // Intentionally do NOT call client.close(): leaving scope runs
  20774. // shutdown_and_close() with the WebSocket still open, which must send the
  20775. // close frame while the TLS session is still alive.
  20776. }
  20777. }
  20778. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20779. // shutdown_and_close() at the start of connect(), reproducing the same
  20780. // use-after-free within the test body rather than at scope exit. The second
  20781. // connect must succeed and echo, proving the close handshake ran over a live
  20782. // session. See the note above about memory-tool requirements.
  20783. TEST_F(WebSocketSSLIntegrationTest,
  20784. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20785. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20786. "/ws-echo");
  20787. client.enable_server_certificate_verification(false);
  20788. client.set_read_timeout(2, 0);
  20789. client.set_write_timeout(2, 0);
  20790. ASSERT_TRUE(client.connect());
  20791. ASSERT_TRUE(client.is_open());
  20792. ASSERT_TRUE(client.send("still open"));
  20793. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20794. // the still-open connection, which must not touch a freed TLS session.
  20795. ASSERT_TRUE(client.connect());
  20796. ASSERT_TRUE(client.is_open());
  20797. ASSERT_TRUE(client.send("after reconnect"));
  20798. std::string msg;
  20799. EXPECT_EQ(ws::Text, client.read(msg));
  20800. EXPECT_EQ("after reconnect", msg);
  20801. client.close();
  20802. }
  20803. #endif
  20804. #ifdef CPPHTTPLIB_SSL_ENABLED
  20805. class WebSocketSSLCATest : public ::testing::Test {
  20806. protected:
  20807. void SetUp() override {
  20808. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20809. SERVER_PRIVATE_KEY_FILE);
  20810. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20811. std::string msg;
  20812. while (ws.read(msg)) {
  20813. ws.send(msg);
  20814. }
  20815. });
  20816. port_ = server_->bind_to_any_port("127.0.0.1");
  20817. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20818. server_->wait_until_ready();
  20819. }
  20820. void TearDown() override {
  20821. server_->stop();
  20822. if (server_thread_.joinable()) { server_thread_.join(); }
  20823. }
  20824. std::string url() const {
  20825. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20826. }
  20827. std::unique_ptr<SSLServer> server_;
  20828. std::thread server_thread_;
  20829. int port_ = 0;
  20830. };
  20831. // A custom CA loaded as PEM verifies the server with full certificate
  20832. // verification enabled
  20833. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20834. ws::WebSocketClient client(url());
  20835. std::string cert;
  20836. read_file(SERVER_CERT2_FILE, cert);
  20837. client.load_ca_cert_store(cert.c_str(), cert.size());
  20838. ASSERT_TRUE(client.connect());
  20839. ASSERT_TRUE(client.send("hello"));
  20840. std::string msg;
  20841. EXPECT_EQ(ws::Text, client.read(msg));
  20842. EXPECT_EQ("hello", msg);
  20843. client.close();
  20844. }
  20845. // A custom CA that does not cover the server must fail verification (the
  20846. // custom CA is exclusive; system certs are not loaded alongside it)
  20847. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20848. ws::WebSocketClient client(url());
  20849. std::string cert;
  20850. read_file(CLIENT_CA_CERT_FILE, cert);
  20851. client.load_ca_cert_store(cert.c_str(), cert.size());
  20852. auto res = client.connect();
  20853. ASSERT_FALSE(res);
  20854. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20855. EXPECT_EQ(-1, res.status());
  20856. EXPECT_NE(0u, res.ssl_backend_error());
  20857. }
  20858. // The same CA as a file path rather than PEM in memory
  20859. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20860. ws::WebSocketClient client(url());
  20861. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20862. ASSERT_TRUE(client.connect());
  20863. ASSERT_TRUE(client.send("hello"));
  20864. std::string msg;
  20865. EXPECT_EQ(ws::Text, client.read(msg));
  20866. EXPECT_EQ("hello", msg);
  20867. client.close();
  20868. }
  20869. // ...and a CA file that does not cover the server still fails, so it is the
  20870. // path above that decides the outcome
  20871. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20872. ws::WebSocketClient client(url());
  20873. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20874. ASSERT_FALSE(client.connect());
  20875. }
  20876. // Regression test: reconnecting with a native custom CA store used to reuse
  20877. // a store handle the previous TLS context had already freed (use-after-free
  20878. // under the OpenSSL backend). The context now lives as long as the client.
  20879. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20880. ws::WebSocketClient client(url());
  20881. std::string cert;
  20882. read_file(SERVER_CERT2_FILE, cert);
  20883. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20884. ASSERT_TRUE(client.connect());
  20885. client.close();
  20886. ASSERT_TRUE(client.connect());
  20887. ASSERT_TRUE(client.send("again"));
  20888. std::string msg;
  20889. EXPECT_EQ(ws::Text, client.read(msg));
  20890. EXPECT_EQ("again", msg);
  20891. client.close();
  20892. }
  20893. // Regression test: a certificate with a trusted chain but no identity match
  20894. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20895. // verification entirely for IP hosts, so this connection succeeded there.
  20896. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20897. // chain verification while the identity check must still fail.
  20898. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20900. ASSERT_TRUE(svr.is_valid());
  20901. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20902. std::string msg;
  20903. while (ws.read(msg)) {
  20904. ws.send(msg);
  20905. }
  20906. });
  20907. auto port = svr.bind_to_any_port("127.0.0.1");
  20908. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20909. auto se = detail::scope_exit([&] {
  20910. svr.stop();
  20911. t.join();
  20912. });
  20913. svr.wait_until_ready();
  20914. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20915. "/echo");
  20916. std::string cert;
  20917. read_file(SERVER_CERT_FILE, cert);
  20918. client.load_ca_cert_store(cert.c_str(), cert.size());
  20919. ASSERT_FALSE(client.connect());
  20920. }
  20921. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  20922. // SNI, so nothing binds the host name to the TLS session. These bind the
  20923. // server to "localhost" instead, the only shape that exercises the SNI and
  20924. // hostname-verification path with certificate verification left enabled.
  20925. class WebSocketSSLDnsHostTest : public ::testing::Test {
  20926. protected:
  20927. void Start(const char *cert_file) {
  20928. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  20929. SERVER_PRIVATE_KEY_FILE);
  20930. ASSERT_TRUE(server_->is_valid());
  20931. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20932. std::string msg;
  20933. while (ws.read(msg)) {
  20934. ws.send(msg);
  20935. }
  20936. });
  20937. port_ = server_->bind_to_any_port("localhost");
  20938. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20939. server_->wait_until_ready();
  20940. }
  20941. void TearDown() override {
  20942. if (server_) { server_->stop(); }
  20943. if (server_thread_.joinable()) { server_thread_.join(); }
  20944. }
  20945. std::string url() const {
  20946. return "wss://localhost:" + std::to_string(port_) + "/echo";
  20947. }
  20948. std::unique_ptr<SSLServer> server_;
  20949. std::thread server_thread_;
  20950. int port_ = 0;
  20951. };
  20952. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  20953. // out and the connection is usable
  20954. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  20955. Start(SERVER_CERT2_FILE);
  20956. ws::WebSocketClient client(url());
  20957. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20958. ASSERT_TRUE(client.connect());
  20959. ASSERT_TRUE(client.send("hello"));
  20960. std::string msg;
  20961. EXPECT_EQ(ws::Text, client.read(msg));
  20962. EXPECT_EQ("hello", msg);
  20963. client.close();
  20964. }
  20965. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  20966. // while the identity check must still reject "localhost"
  20967. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  20968. Start(SERVER_CERT_FILE);
  20969. ws::WebSocketClient client(url());
  20970. client.set_ca_cert_path(SERVER_CERT_FILE);
  20971. auto res = client.connect();
  20972. ASSERT_FALSE(res);
  20973. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  20974. EXPECT_EQ(-1, res.status());
  20975. }
  20976. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  20977. // disabled: the chain is still checked, only the identity check is skipped
  20978. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  20979. Start(SERVER_CERT_FILE);
  20980. ws::WebSocketClient client(url());
  20981. client.set_ca_cert_path(SERVER_CERT_FILE);
  20982. client.enable_server_hostname_verification(false);
  20983. ASSERT_TRUE(client.connect());
  20984. ASSERT_TRUE(client.send("hello"));
  20985. std::string msg;
  20986. EXPECT_EQ(ws::Text, client.read(msg));
  20987. EXPECT_EQ("hello", msg);
  20988. client.close();
  20989. }
  20990. // A CA that did not sign the server certificate fails the chain, even though
  20991. // the name would match
  20992. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  20993. Start(SERVER_CERT2_FILE);
  20994. ws::WebSocketClient client(url());
  20995. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20996. ASSERT_FALSE(client.connect());
  20997. }
  20998. // With verification disabled, neither the chain nor the name is checked
  20999. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21000. Start(SERVER_CERT_FILE);
  21001. ws::WebSocketClient client(url());
  21002. client.enable_server_certificate_verification(false);
  21003. ASSERT_TRUE(client.connect());
  21004. ASSERT_TRUE(client.send("hello"));
  21005. std::string msg;
  21006. EXPECT_EQ(ws::Text, client.read(msg));
  21007. EXPECT_EQ("hello", msg);
  21008. client.close();
  21009. }
  21010. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21011. protected:
  21012. void SetUp() override {
  21013. server_ = httplib::detail::make_unique<SSLServer>(
  21014. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21015. ASSERT_TRUE(server_->is_valid());
  21016. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21017. std::string msg;
  21018. while (ws.read(msg)) {
  21019. ws.send(msg);
  21020. }
  21021. });
  21022. port_ = server_->bind_to_any_port("localhost");
  21023. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21024. server_->wait_until_ready();
  21025. }
  21026. void TearDown() override {
  21027. server_->stop();
  21028. if (server_thread_.joinable()) { server_thread_.join(); }
  21029. }
  21030. std::string url() const {
  21031. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21032. }
  21033. void ConnectWithClientCert(const std::string &client_cert_file,
  21034. const std::string &client_private_key_file,
  21035. const char *private_key_password) {
  21036. std::string cert_pem, key_pem;
  21037. read_file(client_cert_file, cert_pem);
  21038. read_file(client_private_key_file, key_pem);
  21039. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21040. key_pem.c_str(), key_pem.size(),
  21041. private_key_password};
  21042. ws::WebSocketClient client(url(), pem);
  21043. ASSERT_TRUE(client.is_valid());
  21044. client.enable_server_certificate_verification(false);
  21045. ASSERT_TRUE(client.connect());
  21046. ASSERT_TRUE(client.send("hello"));
  21047. std::string msg;
  21048. EXPECT_EQ(ws::Text, client.read(msg));
  21049. EXPECT_EQ("hello", msg);
  21050. client.close();
  21051. }
  21052. std::unique_ptr<SSLServer> server_;
  21053. std::thread server_thread_;
  21054. int port_ = 0;
  21055. };
  21056. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21057. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21058. }
  21059. // Control for the tests above: the fixture's server really does require a
  21060. // client certificate, so it is the PEM the constructor installed that decides
  21061. // the outcome.
  21062. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21063. ws::WebSocketClient client(url());
  21064. ASSERT_TRUE(client.is_valid());
  21065. client.enable_server_certificate_verification(false);
  21066. EXPECT_FALSE(client.connect());
  21067. }
  21068. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21069. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21070. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21071. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21072. }
  21073. #endif
  21074. #if !defined(_WIN32)
  21075. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21076. auto secret_dir = std::string("./symlink_test_secret");
  21077. auto served_dir = std::string("./symlink_test_served");
  21078. auto secret_file = secret_dir + "/secret.txt";
  21079. auto symlink_path = served_dir + "/escape";
  21080. // Setup: create directories and files
  21081. mkdir(secret_dir.c_str(), 0755);
  21082. mkdir(served_dir.c_str(), 0755);
  21083. {
  21084. std::ofstream ofs(secret_file);
  21085. ofs << "SECRET_DATA";
  21086. }
  21087. // Create symlink using absolute path so it resolves correctly
  21088. #ifdef PATH_MAX
  21089. char abs_secret[PATH_MAX];
  21090. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21091. #else
  21092. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21093. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21094. ASSERT_NE(nullptr, abs_secret);
  21095. #endif
  21096. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21097. auto se = detail::scope_exit([&] {
  21098. unlink(symlink_path.c_str());
  21099. unlink(secret_file.c_str());
  21100. rmdir(served_dir.c_str());
  21101. rmdir(secret_dir.c_str());
  21102. });
  21103. Server svr;
  21104. svr.set_mount_point("/", served_dir);
  21105. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21106. auto se2 = detail::scope_exit([&] {
  21107. svr.stop();
  21108. listen_thread.join();
  21109. });
  21110. svr.wait_until_ready();
  21111. Client cli("localhost", PORT);
  21112. // Symlink pointing outside base dir should be blocked
  21113. auto res = cli.Get("/escape/secret.txt");
  21114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21115. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21116. }
  21117. #endif
  21118. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21119. // A GET request with Content-Length to a static file handler must have its
  21120. // body drained before the keep-alive connection is reused. Otherwise the
  21121. // unread body bytes are interpreted as the next HTTP request.
  21122. //
  21123. // The body is sent AFTER receiving the first response (as in the original
  21124. // PoC) so that the stream_line_reader cannot buffer it together with the
  21125. // headers of the first request.
  21126. Server svr;
  21127. svr.set_mount_point("/", "./www");
  21128. std::atomic<int> smuggled_count(0);
  21129. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21130. smuggled_count++;
  21131. res.set_content("oops", "text/plain");
  21132. });
  21133. auto port = svr.bind_to_any_port("localhost");
  21134. thread t = thread([&] { svr.listen_after_bind(); });
  21135. auto se = detail::scope_exit([&] {
  21136. svr.stop();
  21137. t.join();
  21138. });
  21139. svr.wait_until_ready();
  21140. auto error = Error::Success;
  21141. auto sock = detail::create_client_socket(
  21142. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21143. /*connection_timeout_sec=*/2, 0,
  21144. /*read_timeout_sec=*/2, 0,
  21145. /*write_timeout_sec=*/2, 0, std::string(), error);
  21146. ASSERT_NE(INVALID_SOCKET, sock);
  21147. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21148. // The "smuggled" request will be sent as the body of the outer GET
  21149. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21150. "Host: localhost\r\n"
  21151. "Connection: close\r\n"
  21152. "\r\n";
  21153. // Step 1: Send only the outer request headers (no body yet)
  21154. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  21155. "Host: localhost\r\n"
  21156. "Content-Length: " +
  21157. std::to_string(smuggled.size()) +
  21158. "\r\n"
  21159. "\r\n";
  21160. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  21161. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  21162. // Step 2: Read the first response (server serves file without reading body)
  21163. std::string first_response;
  21164. char buf[4096];
  21165. for (;;) {
  21166. auto n = recv(sock, buf, sizeof(buf), 0);
  21167. if (n <= 0) break;
  21168. first_response.append(buf, static_cast<size_t>(n));
  21169. // Stop once we have a complete response (headers + body)
  21170. auto hdr_end = first_response.find("\r\n\r\n");
  21171. if (hdr_end != std::string::npos) {
  21172. // Check for Content-Length to know when the body is complete
  21173. auto cl_pos = first_response.find("Content-Length:");
  21174. if (cl_pos != std::string::npos) {
  21175. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21176. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21177. auto cl = std::stoul(
  21178. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21179. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21180. } else {
  21181. break; // No Content-Length, assume headers-only response
  21182. }
  21183. }
  21184. }
  21185. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  21186. // Step 3: Now send the body, which looks like a new HTTP request.
  21187. // On a vulnerable server the keep-alive loop reads this as a second request.
  21188. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  21189. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  21190. // Step 4: Try to read a second response (should NOT exist after fix)
  21191. std::string second_response;
  21192. for (;;) {
  21193. auto n = recv(sock, buf, sizeof(buf), 0);
  21194. if (n <= 0) break;
  21195. second_response.append(buf, static_cast<size_t>(n));
  21196. }
  21197. // The smuggled request must NOT have been processed
  21198. EXPECT_EQ(0, smuggled_count.load());
  21199. }
  21200. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21201. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21202. // must be rejected with 400 Bad Request.
  21203. Server svr;
  21204. svr.Post("/test", [&](const Request &, Response &res) {
  21205. res.set_content("ok", "text/plain");
  21206. });
  21207. thread t = thread([&] { svr.listen(HOST, PORT); });
  21208. auto se = detail::scope_exit([&] {
  21209. svr.stop();
  21210. t.join();
  21211. ASSERT_FALSE(svr.is_running());
  21212. });
  21213. svr.wait_until_ready();
  21214. // Exact "chunked"
  21215. {
  21216. auto req = "POST /test HTTP/1.1\r\n"
  21217. "Host: localhost\r\n"
  21218. "Content-Length: 5\r\n"
  21219. "Transfer-Encoding: chunked\r\n"
  21220. "Connection: close\r\n"
  21221. "\r\n"
  21222. "hello";
  21223. std::string response;
  21224. ASSERT_TRUE(send_request(1, req, &response));
  21225. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21226. response.substr(0, response.find("\r\n")));
  21227. }
  21228. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21229. {
  21230. auto req = "POST /test HTTP/1.1\r\n"
  21231. "Host: localhost\r\n"
  21232. "Content-Length: 5\r\n"
  21233. "Transfer-Encoding: gzip, chunked\r\n"
  21234. "Connection: close\r\n"
  21235. "\r\n"
  21236. "hello";
  21237. std::string response;
  21238. ASSERT_TRUE(send_request(1, req, &response));
  21239. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21240. response.substr(0, response.find("\r\n")));
  21241. }
  21242. }
  21243. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21244. Server svr;
  21245. svr.Post("/test", [&](const Request &, Response &res) {
  21246. res.set_content("ok", "text/plain");
  21247. });
  21248. thread t = thread([&] { svr.listen(HOST, PORT); });
  21249. auto se = detail::scope_exit([&] {
  21250. svr.stop();
  21251. t.join();
  21252. ASSERT_FALSE(svr.is_running());
  21253. });
  21254. svr.wait_until_ready();
  21255. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21256. // length cannot be determined, so the server must answer 400 and close
  21257. // rather than treat the request as bodyless and leave the body in the
  21258. // socket for the next request to pick up.
  21259. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21260. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21261. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21262. std::string response;
  21263. ASSERT_TRUE(send_request(1, req, &response));
  21264. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21265. response.substr(0, response.find("\r\n")))
  21266. << transfer_encoding;
  21267. }
  21268. // RFC 9110 5.3: the codings may also be split across several
  21269. // Transfer-Encoding lines, which combine in the order they were received.
  21270. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21271. // just like the single-line "chunked, gzip" above.
  21272. {
  21273. auto req = "POST /test HTTP/1.1\r\n"
  21274. "Host: localhost\r\n"
  21275. "Transfer-Encoding: chunked\r\n"
  21276. "Transfer-Encoding: gzip\r\n"
  21277. "\r\n"
  21278. "0\r\n\r\n";
  21279. std::string response;
  21280. ASSERT_TRUE(send_request(1, req, &response));
  21281. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21282. response.substr(0, response.find("\r\n")));
  21283. }
  21284. // A sequence ending in chunked stays valid.
  21285. auto req = "POST /test HTTP/1.1\r\n"
  21286. "Host: localhost\r\n"
  21287. "Transfer-Encoding: gzip, chunked\r\n"
  21288. "Connection: close\r\n"
  21289. "\r\n"
  21290. "0\r\n\r\n";
  21291. std::string response;
  21292. ASSERT_TRUE(send_request(1, req, &response));
  21293. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21294. // ...including when it is spread over several lines.
  21295. auto split_req = "POST /test HTTP/1.1\r\n"
  21296. "Host: localhost\r\n"
  21297. "Transfer-Encoding: gzip\r\n"
  21298. "Transfer-Encoding: chunked\r\n"
  21299. "Connection: close\r\n"
  21300. "\r\n"
  21301. "0\r\n\r\n";
  21302. std::string split_response;
  21303. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21304. EXPECT_EQ("HTTP/1.1 200 OK",
  21305. split_response.substr(0, split_response.find("\r\n")));
  21306. }
  21307. // Regression for issue #2450: a DELETE without Content-Length on a
  21308. // keep-alive connection must not let the post-response drain consume the
  21309. // next request's bytes.
  21310. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21311. Server svr;
  21312. std::atomic<int> delete_count(0);
  21313. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21314. delete_count++;
  21315. res.status = StatusCode::NoContent_204;
  21316. });
  21317. auto port = svr.bind_to_any_port(HOST);
  21318. thread t = thread([&] { svr.listen_after_bind(); });
  21319. auto se = detail::scope_exit([&] {
  21320. svr.stop();
  21321. t.join();
  21322. });
  21323. svr.wait_until_ready();
  21324. auto error = Error::Success;
  21325. auto sock = detail::create_client_socket(
  21326. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21327. /*connection_timeout_sec=*/2, 0,
  21328. /*read_timeout_sec=*/2, 0,
  21329. /*write_timeout_sec=*/2, 0, std::string(), error);
  21330. ASSERT_NE(INVALID_SOCKET, sock);
  21331. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21332. auto send_request_and_read_response = [&](const std::string &req,
  21333. std::string &out) -> bool {
  21334. auto sent = send(sock, req.data(), req.size(), 0);
  21335. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21336. char buf[4096];
  21337. for (;;) {
  21338. auto n = recv(sock, buf, sizeof(buf), 0);
  21339. if (n <= 0) { return !out.empty(); }
  21340. out.append(buf, static_cast<size_t>(n));
  21341. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21342. }
  21343. };
  21344. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21345. "Host: localhost\r\n"
  21346. "\r\n";
  21347. std::string resp1;
  21348. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21349. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21350. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21351. "Host: localhost\r\n"
  21352. "Connection: close\r\n"
  21353. "\r\n";
  21354. std::string resp2;
  21355. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21356. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21357. EXPECT_EQ(2, delete_count.load());
  21358. }
  21359. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21360. Server svr;
  21361. svr.Post("/ingest", [&](const Request &, Response &res,
  21362. const ContentReader &content_reader) {
  21363. auto consumed = content_reader([](const char *, size_t) { return false; });
  21364. EXPECT_FALSE(consumed);
  21365. res.status = StatusCode::Conflict_409;
  21366. res.set_header("Connection", "close");
  21367. });
  21368. auto port = svr.bind_to_any_port(HOST);
  21369. thread t = thread([&] { svr.listen_after_bind(); });
  21370. auto se = detail::scope_exit([&] {
  21371. svr.stop();
  21372. t.join();
  21373. });
  21374. svr.wait_until_ready();
  21375. auto error = Error::Success;
  21376. auto sock = detail::create_client_socket(
  21377. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21378. /*connection_timeout_sec=*/2, 0,
  21379. /*read_timeout_sec=*/1, 0,
  21380. /*write_timeout_sec=*/2, 0, std::string(), error);
  21381. ASSERT_NE(INVALID_SOCKET, sock);
  21382. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21383. std::string request = "POST /ingest HTTP/1.1\r\n"
  21384. "Host: localhost\r\n"
  21385. "Transfer-Encoding: chunked\r\n"
  21386. "\r\n"
  21387. "4\r\n"
  21388. "data\r\n";
  21389. auto sent = send(sock, request.data(), request.size(), 0);
  21390. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21391. std::string response;
  21392. ssize_t received = 0;
  21393. do {
  21394. char buf[4096];
  21395. received = recv(sock, buf, sizeof(buf), 0);
  21396. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21397. } while (received > 0);
  21398. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21399. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21400. EXPECT_EQ(0, received);
  21401. }
  21402. namespace no_proxy_test {
  21403. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21404. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21405. // calling listen().
  21406. class ScopedServer {
  21407. public:
  21408. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21409. ~ScopedServer() {
  21410. svr_.stop();
  21411. if (th_.joinable()) { th_.join(); }
  21412. }
  21413. Server &svr() { return svr_; }
  21414. int port() const { return port_; }
  21415. void listen() {
  21416. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21417. svr_.wait_until_ready();
  21418. }
  21419. private:
  21420. Server svr_;
  21421. std::thread th_;
  21422. int port_ = 0;
  21423. };
  21424. class ProxyAndTargetServers {
  21425. public:
  21426. ProxyAndTargetServers() {
  21427. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21428. proxy_hits_++;
  21429. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21430. res.set_content("via-proxy", "text/plain");
  21431. });
  21432. target_.Get(".*", [this](const Request &req, Response &res) {
  21433. target_hits_++;
  21434. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21435. res.set_content("direct", "text/plain");
  21436. });
  21437. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21438. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21439. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21440. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21441. proxy_mock_.wait_until_ready();
  21442. target_.wait_until_ready();
  21443. }
  21444. ~ProxyAndTargetServers() {
  21445. proxy_mock_.stop();
  21446. target_.stop();
  21447. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21448. if (target_thread_.joinable()) { target_thread_.join(); }
  21449. }
  21450. Server &proxy_mock() { return proxy_mock_; }
  21451. Server &target() { return target_; }
  21452. int proxy_port() const { return proxy_port_; }
  21453. int target_port() const { return target_port_; }
  21454. int proxy_hits() const { return proxy_hits_.load(); }
  21455. int target_hits() const { return target_hits_.load(); }
  21456. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21457. void reset_counters() {
  21458. proxy_hits_ = 0;
  21459. target_hits_ = 0;
  21460. last_had_proxy_authz_ = false;
  21461. }
  21462. private:
  21463. Server proxy_mock_;
  21464. Server target_;
  21465. std::thread proxy_thread_;
  21466. std::thread target_thread_;
  21467. int proxy_port_ = 0;
  21468. int target_port_ = 0;
  21469. std::atomic<int> proxy_hits_{0};
  21470. std::atomic<int> target_hits_{0};
  21471. std::atomic<bool> last_had_proxy_authz_{false};
  21472. };
  21473. inline std::unique_ptr<Client> make_client(const std::string &host,
  21474. ProxyAndTargetServers &s) {
  21475. auto cli = detail::make_unique<Client>(host, s.target_port());
  21476. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21477. cli->set_proxy("127.0.0.1", s.proxy_port());
  21478. return cli;
  21479. }
  21480. } // namespace no_proxy_test
  21481. using no_proxy_test::make_client;
  21482. using no_proxy_test::ProxyAndTargetServers;
  21483. TEST(NoProxyTest, ExactHostnameBypasses) {
  21484. ProxyAndTargetServers s;
  21485. auto cli = make_client("example.com", s);
  21486. cli->set_no_proxy({"example.com"});
  21487. auto res = cli->Get("/");
  21488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21489. EXPECT_EQ(0, s.proxy_hits());
  21490. EXPECT_EQ(1, s.target_hits());
  21491. }
  21492. TEST(NoProxyTest, SubdomainBypasses) {
  21493. ProxyAndTargetServers s;
  21494. auto cli = make_client("foo.example.com", s);
  21495. cli->set_no_proxy({"example.com"});
  21496. auto res = cli->Get("/");
  21497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21498. EXPECT_EQ(0, s.proxy_hits());
  21499. EXPECT_EQ(1, s.target_hits());
  21500. }
  21501. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21502. // Regression guard: "evilexample.com" must not be considered a subdomain
  21503. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21504. // check would let traffic bypass the proxy and leak credentials direct
  21505. // to the attacker host.
  21506. ProxyAndTargetServers s;
  21507. auto cli = make_client("evilexample.com", s);
  21508. cli->set_no_proxy({"example.com"});
  21509. auto res = cli->Get("/");
  21510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21511. EXPECT_GE(s.proxy_hits(), 1);
  21512. EXPECT_EQ(0, s.target_hits());
  21513. }
  21514. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21515. ProxyAndTargetServers s;
  21516. auto cli = make_client("example.com.evil.com", s);
  21517. cli->set_no_proxy({"example.com"});
  21518. auto res = cli->Get("/");
  21519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21520. EXPECT_GE(s.proxy_hits(), 1);
  21521. EXPECT_EQ(0, s.target_hits());
  21522. }
  21523. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21524. ProxyAndTargetServers s;
  21525. auto cli = make_client("example.com", s);
  21526. cli->set_no_proxy({".example.com"});
  21527. auto res = cli->Get("/");
  21528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21529. EXPECT_EQ(0, s.proxy_hits());
  21530. EXPECT_EQ(1, s.target_hits());
  21531. }
  21532. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21533. ProxyAndTargetServers s;
  21534. auto cli = make_client("Example.COM", s);
  21535. cli->set_no_proxy({"EXAMPLE.com"});
  21536. auto res = cli->Get("/");
  21537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21538. EXPECT_EQ(0, s.proxy_hits());
  21539. EXPECT_EQ(1, s.target_hits());
  21540. }
  21541. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21542. ProxyAndTargetServers s;
  21543. auto cli = make_client("example.com.", s);
  21544. cli->set_no_proxy({"example.com"});
  21545. auto res = cli->Get("/");
  21546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21547. EXPECT_EQ(0, s.proxy_hits());
  21548. EXPECT_EQ(1, s.target_hits());
  21549. }
  21550. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21551. // Trailing dots must be normalized on BOTH sides — host and entry.
  21552. // An implementation that only strips the host-side trailing dot would
  21553. // fail to match host "example.com" against entry "example.com." because
  21554. // a literal substring search would compare 11 chars against 12.
  21555. ProxyAndTargetServers s;
  21556. auto cli = make_client("example.com", s);
  21557. cli->set_no_proxy({"example.com."});
  21558. auto res = cli->Get("/");
  21559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21560. EXPECT_EQ(0, s.proxy_hits());
  21561. EXPECT_EQ(1, s.target_hits());
  21562. }
  21563. TEST(NoProxyTest, WildcardBypassesEverything) {
  21564. ProxyAndTargetServers s;
  21565. auto cli = make_client("anything.invalid.test", s);
  21566. cli->set_no_proxy({"*"});
  21567. auto res = cli->Get("/");
  21568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21569. EXPECT_EQ(0, s.proxy_hits());
  21570. EXPECT_EQ(1, s.target_hits());
  21571. }
  21572. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21573. ProxyAndTargetServers s;
  21574. Client cli("127.0.0.1", s.target_port());
  21575. cli.set_proxy("127.0.0.1", s.proxy_port());
  21576. cli.set_no_proxy({"127.0.0.1"});
  21577. auto res = cli.Get("/");
  21578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21579. EXPECT_EQ(0, s.proxy_hits());
  21580. EXPECT_EQ(1, s.target_hits());
  21581. }
  21582. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21583. ProxyAndTargetServers s;
  21584. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21585. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21586. cli.set_proxy("127.0.0.1", s.proxy_port());
  21587. cli.set_no_proxy({"::1"});
  21588. auto res = cli.Get("/");
  21589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21590. EXPECT_EQ(0, s.proxy_hits());
  21591. EXPECT_EQ(1, s.target_hits());
  21592. }
  21593. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21594. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21595. // must still be recognized as IPv6 for CIDR matching. Implementations
  21596. // that detect IPv6 only when the host begins with '[' would parse the
  21597. // host as a hostname and miss the match.
  21598. ProxyAndTargetServers s;
  21599. Client cli("fe80::1", s.target_port());
  21600. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21601. cli.set_proxy("127.0.0.1", s.proxy_port());
  21602. cli.set_no_proxy({"fe80::/10"});
  21603. auto res = cli.Get("/");
  21604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21605. EXPECT_EQ(0, s.proxy_hits());
  21606. EXPECT_EQ(1, s.target_hits());
  21607. }
  21608. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21609. ProxyAndTargetServers s;
  21610. Client cli("::1", s.target_port());
  21611. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21612. cli.set_proxy("127.0.0.1", s.proxy_port());
  21613. cli.set_no_proxy({"[::1]"});
  21614. auto res = cli.Get("/");
  21615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21616. EXPECT_EQ(0, s.proxy_hits());
  21617. EXPECT_EQ(1, s.target_hits());
  21618. }
  21619. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21620. ProxyAndTargetServers s;
  21621. Client cli("fe80::1", s.target_port());
  21622. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21623. cli.set_proxy("127.0.0.1", s.proxy_port());
  21624. cli.set_no_proxy({"[fe80::]/10"});
  21625. auto res = cli.Get("/");
  21626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21627. EXPECT_EQ(0, s.proxy_hits());
  21628. EXPECT_EQ(1, s.target_hits());
  21629. }
  21630. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21631. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21632. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21633. // tricks via address-family conversion.
  21634. ProxyAndTargetServers s;
  21635. Client cli("::ffff:127.0.0.1", s.target_port());
  21636. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21637. cli.set_proxy("127.0.0.1", s.proxy_port());
  21638. cli.set_no_proxy({"127.0.0.1"});
  21639. auto res = cli.Get("/");
  21640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21641. EXPECT_GE(s.proxy_hits(), 1);
  21642. EXPECT_EQ(0, s.target_hits());
  21643. }
  21644. TEST(NoProxyTest, IPv4CidrMatch) {
  21645. ProxyAndTargetServers s;
  21646. Client cli("127.0.0.1", s.target_port());
  21647. cli.set_proxy("127.0.0.1", s.proxy_port());
  21648. cli.set_no_proxy({"127.0.0.0/8"});
  21649. auto res = cli.Get("/");
  21650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21651. EXPECT_EQ(0, s.proxy_hits());
  21652. EXPECT_EQ(1, s.target_hits());
  21653. }
  21654. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21655. ProxyAndTargetServers s;
  21656. Client cli("127.0.0.1", s.target_port());
  21657. cli.set_proxy("127.0.0.1", s.proxy_port());
  21658. cli.set_no_proxy({"10.0.0.0/8"});
  21659. auto res = cli.Get("/");
  21660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21661. EXPECT_GE(s.proxy_hits(), 1);
  21662. EXPECT_EQ(0, s.target_hits());
  21663. }
  21664. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21665. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21666. // IPv4 target matches.
  21667. ProxyAndTargetServers s;
  21668. Client cli("127.0.0.1", s.target_port());
  21669. cli.set_proxy("127.0.0.1", s.proxy_port());
  21670. cli.set_no_proxy({"0.0.0.0/0"});
  21671. auto res = cli.Get("/");
  21672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21673. EXPECT_EQ(0, s.proxy_hits());
  21674. EXPECT_EQ(1, s.target_hits());
  21675. }
  21676. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21677. ProxyAndTargetServers s;
  21678. Client cli("127.0.0.1", s.target_port());
  21679. cli.set_proxy("127.0.0.1", s.proxy_port());
  21680. cli.set_no_proxy({"127.0.0.1"});
  21681. auto res = cli.Get("/");
  21682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21683. EXPECT_EQ(0, s.proxy_hits());
  21684. EXPECT_EQ(1, s.target_hits());
  21685. }
  21686. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21687. ProxyAndTargetServers s;
  21688. Client cli("127.0.0.1", s.target_port());
  21689. cli.set_proxy("127.0.0.1", s.proxy_port());
  21690. cli.set_no_proxy({"127.0.0.0/33"});
  21691. auto res = cli.Get("/");
  21692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21693. EXPECT_GE(s.proxy_hits(), 1);
  21694. EXPECT_EQ(0, s.target_hits());
  21695. }
  21696. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21697. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21698. ProxyAndTargetServers s;
  21699. Client cli("127.0.0.1", s.target_port());
  21700. cli.set_proxy("127.0.0.1", s.proxy_port());
  21701. cli.set_no_proxy({"127.0.0.1/"});
  21702. auto res = cli.Get("/");
  21703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21704. EXPECT_GE(s.proxy_hits(), 1);
  21705. EXPECT_EQ(0, s.target_hits());
  21706. }
  21707. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21708. ProxyAndTargetServers s;
  21709. auto cli = make_client("internal.corp", s);
  21710. cli->set_proxy_basic_auth("u", "p");
  21711. cli->set_no_proxy({"internal.corp"});
  21712. auto res = cli->Get("/");
  21713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21714. EXPECT_EQ(1, s.target_hits());
  21715. EXPECT_EQ(0, s.proxy_hits());
  21716. EXPECT_FALSE(s.last_had_proxy_authz())
  21717. << "Proxy-Authorization must not be sent direct to the target";
  21718. }
  21719. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21720. ProxyAndTargetServers s;
  21721. auto cli = make_client("public.example", s);
  21722. cli->set_proxy_basic_auth("u", "p");
  21723. cli->set_no_proxy({"internal.corp"}); // does not match
  21724. auto res = cli->Get("/");
  21725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21726. EXPECT_GE(s.proxy_hits(), 1);
  21727. EXPECT_TRUE(s.last_had_proxy_authz());
  21728. }
  21729. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21730. ProxyAndTargetServers s;
  21731. auto cli = make_client("anything.test", s);
  21732. auto res = cli->Get("/");
  21733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21734. EXPECT_GE(s.proxy_hits(), 1);
  21735. EXPECT_EQ(0, s.target_hits());
  21736. }
  21737. TEST(NoProxyTest, PortSpecificEntryRejected) {
  21738. ProxyAndTargetServers s;
  21739. auto cli = make_client("example.com", s);
  21740. cli->set_no_proxy({"example.com:8080"});
  21741. auto res = cli->Get("/");
  21742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21743. EXPECT_GE(s.proxy_hits(), 1);
  21744. EXPECT_EQ(0, s.target_hits());
  21745. }
  21746. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21747. ProxyAndTargetServers s;
  21748. auto cli = make_client("anything.test", s);
  21749. cli->set_no_proxy({"", " ", "\t"});
  21750. auto res = cli->Get("/");
  21751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21752. EXPECT_GE(s.proxy_hits(), 1);
  21753. EXPECT_EQ(0, s.target_hits());
  21754. }
  21755. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21756. // An entry with leading/trailing whitespace must still match — env-style
  21757. // values are commonly pasted with stray spaces and an implementation
  21758. // that feeds the raw token directly to inet_pton would fail to match
  21759. // valid CIDRs because of the spaces.
  21760. ProxyAndTargetServers s;
  21761. Client cli("127.0.0.1", s.target_port());
  21762. cli.set_proxy("127.0.0.1", s.proxy_port());
  21763. cli.set_no_proxy({" 127.0.0.0/8 "});
  21764. auto res = cli.Get("/");
  21765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21766. EXPECT_EQ(0, s.proxy_hits());
  21767. EXPECT_EQ(1, s.target_hits());
  21768. }
  21769. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21770. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21771. // go direct and must NOT carry Proxy-Authorization.
  21772. std::atomic<int> proxy_hits{0};
  21773. std::atomic<int> target_hits{0};
  21774. std::atomic<bool> target_saw_authz{false};
  21775. no_proxy_test::ScopedServer proxy_mock, target;
  21776. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21777. proxy_hits++;
  21778. res.status = 302;
  21779. res.set_header("Location", "http://127.0.0.1:" +
  21780. std::to_string(target.port()) + "/landed");
  21781. });
  21782. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21783. target_hits++;
  21784. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21785. res.set_content("direct", "text/plain");
  21786. });
  21787. proxy_mock.listen();
  21788. target.listen();
  21789. Client cli("public.example", target.port());
  21790. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21791. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21792. cli.set_proxy_basic_auth("u", "p");
  21793. cli.set_no_proxy({"127.0.0.1"});
  21794. cli.set_follow_location(true);
  21795. auto res = cli.Get("/redir");
  21796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21797. EXPECT_GE(proxy_hits.load(), 1);
  21798. EXPECT_GE(target_hits.load(), 1);
  21799. EXPECT_FALSE(target_saw_authz.load());
  21800. }
  21801. #ifdef CPPHTTPLIB_SSL_ENABLED
  21802. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21803. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21804. // proxy creds would be sent to the (possibly hostile) origin.
  21805. std::atomic<int> target_hits{0};
  21806. std::atomic<bool> target_saw_proxy_authz{false};
  21807. no_proxy_test::ScopedServer target;
  21808. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21809. target_hits++;
  21810. if (req.has_header("Proxy-Authorization")) {
  21811. target_saw_proxy_authz = true;
  21812. }
  21813. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21814. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  21815. "nonce=\"abc\", algorithm=MD5");
  21816. });
  21817. target.listen();
  21818. // The proxy address is set to the target's port: the bypass MUST kick in;
  21819. // if it doesn't, the test still routes "via proxy" to the same server and
  21820. // the Proxy-Authorization assertion below catches the leak.
  21821. Client cli("evil.example", target.port());
  21822. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  21823. cli.set_proxy("127.0.0.1", target.port());
  21824. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21825. cli.set_no_proxy({"evil.example"});
  21826. auto res = cli.Get("/x");
  21827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21828. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21829. EXPECT_EQ(1, target_hits.load());
  21830. EXPECT_FALSE(target_saw_proxy_authz.load());
  21831. }
  21832. #endif
  21833. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  21834. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  21835. std::atomic<int> proxy_hits{0};
  21836. std::atomic<int> bypass_hits{0};
  21837. std::atomic<bool> proxy_saw_c_url{false};
  21838. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  21839. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  21840. proxy_hits++;
  21841. if (req.path.find("/start") != std::string::npos) {
  21842. res.status = 302;
  21843. res.set_header("Location", "http://127.0.0.1:" +
  21844. std::to_string(bypass_server.port()) +
  21845. "/middle");
  21846. return;
  21847. }
  21848. if (req.path.find("/end") != std::string::npos) {
  21849. proxy_saw_c_url = true;
  21850. res.set_content("c-via-proxy", "text/plain");
  21851. return;
  21852. }
  21853. res.set_content("unexpected", "text/plain");
  21854. });
  21855. // public.example's "advertised" port is arbitrary (the request never lands
  21856. // there — it goes through the proxy), but use a dynamic value to stay
  21857. // friendly with sharded parallel runs.
  21858. int public_port = bypass_server.port();
  21859. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  21860. bypass_hits++;
  21861. res.status = 302;
  21862. res.set_header("Location", "http://public.example:" +
  21863. std::to_string(public_port) + "/end");
  21864. });
  21865. proxy_mock.listen();
  21866. bypass_server.listen();
  21867. Client cli("public.example", public_port);
  21868. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21869. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21870. cli.set_no_proxy({"127.0.0.1"});
  21871. cli.set_follow_location(true);
  21872. auto res = cli.Get("/start");
  21873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21874. EXPECT_EQ(StatusCode::OK_200, res->status);
  21875. EXPECT_EQ("c-via-proxy", res->body);
  21876. EXPECT_GE(proxy_hits.load(), 2);
  21877. EXPECT_GE(bypass_hits.load(), 1);
  21878. EXPECT_TRUE(proxy_saw_c_url.load());
  21879. }
  21880. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  21881. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  21882. // request reconnects to the correct endpoint.
  21883. std::atomic<int> proxy_hits{0};
  21884. std::atomic<int> target_hits{0};
  21885. no_proxy_test::ScopedServer proxy_mock, target;
  21886. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21887. proxy_hits++;
  21888. res.set_content("via-proxy", "text/plain");
  21889. });
  21890. target.svr().Get(".*", [&](const Request &, Response &res) {
  21891. target_hits++;
  21892. res.set_content("direct", "text/plain");
  21893. });
  21894. proxy_mock.listen();
  21895. target.listen();
  21896. Client cli("public.example", target.port());
  21897. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21898. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21899. cli.set_keep_alive(true);
  21900. auto res1 = cli.Get("/a");
  21901. ASSERT_TRUE(res1);
  21902. EXPECT_EQ("via-proxy", res1->body);
  21903. EXPECT_EQ(1, proxy_hits.load());
  21904. EXPECT_EQ(0, target_hits.load());
  21905. cli.set_no_proxy({"public.example"});
  21906. auto res2 = cli.Get("/b");
  21907. ASSERT_TRUE(res2);
  21908. EXPECT_EQ("direct", res2->body);
  21909. EXPECT_EQ(1, proxy_hits.load());
  21910. EXPECT_EQ(1, target_hits.load());
  21911. }
  21912. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  21913. namespace proxy_tunnel_test {
  21914. // SSLServer counterpart to no_proxy_test::ScopedServer.
  21915. class ScopedSSLServer {
  21916. public:
  21917. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  21918. port_ = svr_.bind_to_any_port("127.0.0.1");
  21919. }
  21920. ~ScopedSSLServer() {
  21921. svr_.stop();
  21922. if (th_.joinable()) { th_.join(); }
  21923. }
  21924. SSLServer &svr() { return svr_; }
  21925. int port() const { return port_; }
  21926. void listen() {
  21927. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21928. svr_.wait_until_ready();
  21929. }
  21930. private:
  21931. SSLServer svr_;
  21932. std::thread th_;
  21933. int port_ = 0;
  21934. };
  21935. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  21936. class ScopedConnectProxy {
  21937. public:
  21938. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  21939. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  21940. if (listen_fd_ < 0) { return; }
  21941. int yes = 1;
  21942. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  21943. sockaddr_in a{};
  21944. a.sin_family = AF_INET;
  21945. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21946. a.sin_port = 0;
  21947. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  21948. return;
  21949. }
  21950. socklen_t alen = sizeof(a);
  21951. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  21952. 0) {
  21953. return;
  21954. }
  21955. port_ = ntohs(a.sin_port);
  21956. if (::listen(listen_fd_, 1) != 0) { return; }
  21957. th_ = std::thread([this] { run(); });
  21958. }
  21959. ~ScopedConnectProxy() {
  21960. stop_ = true;
  21961. if (listen_fd_ >= 0) {
  21962. ::shutdown(listen_fd_, SHUT_RDWR);
  21963. ::close(listen_fd_);
  21964. }
  21965. if (th_.joinable()) { th_.join(); }
  21966. }
  21967. int port() const { return port_; }
  21968. int connect_hits() const { return connect_hits_.load(); }
  21969. // Head of the last CONNECT request, as the proxy saw it on the wire.
  21970. std::string connect_request() const {
  21971. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21972. return connect_request_;
  21973. }
  21974. private:
  21975. void run() {
  21976. while (!stop_.load()) {
  21977. fd_set rfds;
  21978. FD_ZERO(&rfds);
  21979. FD_SET(listen_fd_, &rfds);
  21980. timeval tv{0, 100 * 1000};
  21981. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  21982. if (sel <= 0) { continue; }
  21983. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  21984. if (client_fd < 0) { continue; }
  21985. std::string req;
  21986. char buf[2048];
  21987. while (req.find("\r\n\r\n") == std::string::npos) {
  21988. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  21989. if (n <= 0) { break; }
  21990. req.append(buf, static_cast<size_t>(n));
  21991. }
  21992. if (req.compare(0, 7, "CONNECT") != 0) {
  21993. ::close(client_fd);
  21994. continue;
  21995. }
  21996. connect_hits_++;
  21997. {
  21998. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21999. connect_request_ = req;
  22000. }
  22001. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22002. ::send(client_fd, ok, std::strlen(ok), 0);
  22003. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22004. sockaddr_in o{};
  22005. o.sin_family = AF_INET;
  22006. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22007. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22008. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22009. 0) {
  22010. ::close(client_fd);
  22011. ::close(origin_fd);
  22012. continue;
  22013. }
  22014. auto forward = [](int from, int to) {
  22015. char b[8192];
  22016. for (;;) {
  22017. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22018. if (n <= 0) { break; }
  22019. ssize_t off = 0;
  22020. while (off < n) {
  22021. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22022. if (s <= 0) {
  22023. off = n;
  22024. break;
  22025. }
  22026. off += s;
  22027. }
  22028. }
  22029. ::shutdown(to, SHUT_WR);
  22030. };
  22031. std::thread t1([&] { forward(client_fd, origin_fd); });
  22032. std::thread t2([&] { forward(origin_fd, client_fd); });
  22033. t1.join();
  22034. t2.join();
  22035. ::close(client_fd);
  22036. ::close(origin_fd);
  22037. }
  22038. }
  22039. int forward_port_ = -1;
  22040. int listen_fd_ = -1;
  22041. int port_ = 0;
  22042. std::thread th_;
  22043. std::atomic<bool> stop_{false};
  22044. std::atomic<int> connect_hits_{0};
  22045. mutable std::mutex connect_request_mutex_;
  22046. std::string connect_request_;
  22047. };
  22048. // Sends one request through the CONNECT proxy to the TLS origin with a
  22049. // credential configured for each hop, and checks that each credential reaches
  22050. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22051. // origin's (every header in origin_headers) on the tunnelled request.
  22052. void CredentialsStayWithTheirHop(
  22053. const std::function<void(SSLClient &)> &set_credentials,
  22054. const std::string &scheme,
  22055. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22056. std::atomic<int> origin_hits{0};
  22057. std::atomic<bool> origin_saw_proxy_authz{false};
  22058. std::atomic<bool> origin_saw_headers{false};
  22059. ScopedSSLServer origin;
  22060. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22061. origin_hits++;
  22062. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22063. origin_saw_headers =
  22064. std::all_of(origin_headers.begin(), origin_headers.end(),
  22065. [&](const std::string &h) { return req.has_header(h); });
  22066. res.set_content("ok", "text/plain");
  22067. });
  22068. origin.listen();
  22069. ScopedConnectProxy proxy(origin.port());
  22070. ASSERT_NE(0, proxy.port());
  22071. // Pinned to 127.0.0.1 for the same reason as the test below.
  22072. SSLClient cli("127.0.0.1", origin.port());
  22073. cli.enable_server_certificate_verification(false);
  22074. cli.set_proxy("127.0.0.1", proxy.port());
  22075. set_credentials(cli);
  22076. auto res = cli.Get("/x");
  22077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22078. EXPECT_EQ(StatusCode::OK_200, res->status);
  22079. EXPECT_EQ(1, origin_hits.load());
  22080. EXPECT_EQ(1, proxy.connect_hits());
  22081. EXPECT_TRUE(origin_saw_headers.load());
  22082. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22083. << "Proxy-Authorization must not be sent inside the tunnel";
  22084. auto connect_req = proxy.connect_request();
  22085. EXPECT_NE(std::string::npos,
  22086. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22087. for (const auto &h : origin_headers) {
  22088. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22089. << h << " must not be sent to the proxy on CONNECT";
  22090. }
  22091. }
  22092. } // namespace proxy_tunnel_test
  22093. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22094. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22095. [](SSLClient &cli) {
  22096. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22097. cli.set_basic_auth("origin-user", "origin-pass");
  22098. },
  22099. "Basic");
  22100. }
  22101. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22102. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22103. [](SSLClient &cli) {
  22104. cli.set_proxy_bearer_token_auth("proxy-token");
  22105. cli.set_bearer_token_auth("origin-token");
  22106. },
  22107. "Bearer");
  22108. }
  22109. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22110. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22111. [](SSLClient &cli) {
  22112. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22113. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22114. {"Cookie", "sid=origin-session"},
  22115. {"X-Api-Key", "origin-key"}});
  22116. },
  22117. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22118. }
  22119. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22120. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22121. // retry; otherwise proxy creds would be sent to the origin.
  22122. std::atomic<int> origin_hits{0};
  22123. std::atomic<bool> origin_saw_proxy_authz{false};
  22124. proxy_tunnel_test::ScopedSSLServer origin;
  22125. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22126. origin_hits++;
  22127. if (req.has_header("Proxy-Authorization")) {
  22128. origin_saw_proxy_authz = true;
  22129. }
  22130. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22131. res.set_header("Proxy-Authenticate",
  22132. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22133. "algorithm=MD5");
  22134. });
  22135. origin.listen();
  22136. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22137. ASSERT_NE(0, proxy.port());
  22138. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22139. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22140. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22141. // and answer with its own status, making this test flaky.
  22142. SSLClient cli("127.0.0.1", origin.port());
  22143. cli.enable_server_certificate_verification(false);
  22144. cli.set_proxy("127.0.0.1", proxy.port());
  22145. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22146. auto res = cli.Get("/x");
  22147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22148. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22149. EXPECT_EQ(1, origin_hits.load());
  22150. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22151. EXPECT_EQ(1, proxy.connect_hits());
  22152. }
  22153. #endif