test.cc 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711
  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_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. } // namespace tls
  71. } // namespace httplib
  72. #endif
  73. using namespace std;
  74. using namespace httplib;
  75. const char *HOST = "localhost";
  76. static int get_base_port() {
  77. const char *shard = getenv("GTEST_SHARD_INDEX");
  78. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  79. }
  80. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  81. // New standalone tests MUST use svr.bind_to_any_port() instead.
  82. const int PORT = get_base_port();
  83. const string LONG_QUERY_VALUE = string(25000, '@');
  84. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  85. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  86. const string TOO_LONG_QUERY_URL =
  87. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  88. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  89. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  90. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  91. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  92. return file.name == key;
  93. });
  94. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  95. return *it;
  96. #else
  97. if (it != items.end()) { return *it; }
  98. throw std::runtime_error("invalid multipart form data name error");
  99. #endif
  100. }
  101. static void read_file(const std::string &path, std::string &out) {
  102. std::ifstream fs(path, std::ios_base::binary);
  103. if (!fs) {
  104. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  105. return;
  106. #else
  107. throw std::runtime_error("File not found: " + path);
  108. #endif
  109. }
  110. fs.seekg(0, std::ios_base::end);
  111. auto size = fs.tellg();
  112. fs.seekg(0);
  113. out.resize(static_cast<size_t>(size));
  114. fs.read(&out[0], static_cast<std::streamsize>(size));
  115. }
  116. class UnixSocketTest : public ::testing::Test {
  117. protected:
  118. void TearDown() override { std::remove(pathname_.c_str()); }
  119. void client_GET(const std::string &addr) {
  120. httplib::Client cli{addr};
  121. cli.set_address_family(AF_UNIX);
  122. ASSERT_TRUE(cli.is_valid());
  123. const auto &result = cli.Get(pattern_);
  124. ASSERT_TRUE(result) << "error: " << result.error();
  125. const auto &resp = result.value();
  126. EXPECT_EQ(resp.status, StatusCode::OK_200);
  127. EXPECT_EQ(resp.body, content_);
  128. }
  129. static std::string make_sock_path() {
  130. const char *shard = getenv("GTEST_SHARD_INDEX");
  131. return shard ? std::string("./httplib-server-") + shard + ".sock"
  132. : "./httplib-server.sock";
  133. }
  134. const std::string pathname_{make_sock_path()};
  135. const std::string pattern_{"/hi"};
  136. const std::string content_{"Hello World!"};
  137. };
  138. TEST_F(UnixSocketTest, pathname) {
  139. httplib::Server svr;
  140. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  141. res.set_content(content_, "text/plain");
  142. });
  143. std::thread t{[&] {
  144. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  145. }};
  146. auto se = detail::scope_exit([&] {
  147. svr.stop();
  148. t.join();
  149. ASSERT_FALSE(svr.is_running());
  150. });
  151. svr.wait_until_ready();
  152. ASSERT_TRUE(svr.is_running());
  153. client_GET(pathname_);
  154. // ".//x.sock", which is not taken for a URL
  155. client_GET("./" + pathname_.substr(1));
  156. }
  157. #if defined(__linux__) || \
  158. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  159. TEST_F(UnixSocketTest, PeerPid) {
  160. httplib::Server svr;
  161. std::string remote_port_val;
  162. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  163. res.set_content(content_, "text/plain");
  164. remote_port_val = std::to_string(req.remote_port);
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  178. }
  179. #endif
  180. #ifdef __linux__
  181. TEST_F(UnixSocketTest, abstract) {
  182. constexpr char svr_path[]{"\x00httplib-server.sock"};
  183. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  184. httplib::Server svr;
  185. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  186. res.set_content(content_, "text/plain");
  187. });
  188. std::thread t{[&] {
  189. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  190. }};
  191. auto se = detail::scope_exit([&] {
  192. svr.stop();
  193. t.join();
  194. ASSERT_FALSE(svr.is_running());
  195. });
  196. svr.wait_until_ready();
  197. ASSERT_TRUE(svr.is_running());
  198. client_GET(abstract_addr);
  199. }
  200. #endif
  201. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  202. httplib::Server svr;
  203. std::string received_host_header;
  204. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  205. // Capture the Host header sent by the client
  206. auto host_iter = req.headers.find("Host");
  207. if (host_iter != req.headers.end()) {
  208. received_host_header = host_iter->second;
  209. }
  210. res.set_content(content_, "text/plain");
  211. });
  212. std::thread t{[&] {
  213. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  214. }};
  215. auto se = detail::scope_exit([&] {
  216. svr.stop();
  217. t.join();
  218. ASSERT_FALSE(svr.is_running());
  219. });
  220. svr.wait_until_ready();
  221. ASSERT_TRUE(svr.is_running());
  222. // Test that Host header is automatically set to "localhost" for Unix socket
  223. // connections
  224. httplib::Client cli{pathname_};
  225. cli.set_address_family(AF_UNIX);
  226. ASSERT_TRUE(cli.is_valid());
  227. const auto &result = cli.Get(pattern_);
  228. ASSERT_TRUE(result) << "error: " << result.error();
  229. const auto &resp = result.value();
  230. EXPECT_EQ(resp.status, StatusCode::OK_200);
  231. EXPECT_EQ(resp.body, content_);
  232. // Verify that Host header was automatically set to "localhost"
  233. EXPECT_EQ(received_host_header, "localhost");
  234. }
  235. #ifndef _WIN32
  236. TEST(SocketStream, wait_writable_UNIX) {
  237. int fds[2];
  238. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  239. const auto asSocketStream = [&](socket_t fd,
  240. std::function<bool(Stream &)> func) {
  241. return detail::process_client_socket(
  242. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  243. };
  244. asSocketStream(fds[0], [&](Stream &s0) {
  245. EXPECT_EQ(s0.socket(), fds[0]);
  246. EXPECT_TRUE(s0.wait_writable());
  247. EXPECT_TRUE(s0.is_peer_alive());
  248. EXPECT_EQ(0, close(fds[1]));
  249. EXPECT_FALSE(s0.is_peer_alive());
  250. return true;
  251. });
  252. EXPECT_EQ(0, close(fds[0]));
  253. }
  254. TEST(SocketStream, wait_writable_INET) {
  255. sockaddr_in addr;
  256. memset(&addr, 0, sizeof(addr));
  257. addr.sin_family = AF_INET;
  258. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  259. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  260. int disconnected_svr_sock = -1;
  261. std::thread svr{[&] {
  262. const int s = socket(AF_INET, SOCK_STREAM, 0);
  263. ASSERT_LE(0, s);
  264. // PORT + 1 is shared with the SSL redirect tests and with
  265. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  266. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  267. // because that happens on a worker thread the ASSERT does not stop the
  268. // test: it runs on and fails at the disconnected_svr_sock check instead.
  269. default_socket_options(s);
  270. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  271. ASSERT_EQ(0, listen(s, 1));
  272. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  276. std::thread cli{[&] {
  277. const int s = socket(AF_INET, SOCK_STREAM, 0);
  278. ASSERT_LE(0, s);
  279. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  280. ASSERT_EQ(0, close(s));
  281. }};
  282. cli.join();
  283. svr.join();
  284. ASSERT_NE(disconnected_svr_sock, -1);
  285. const auto asSocketStream = [&](socket_t fd,
  286. std::function<bool(Stream &)> func) {
  287. return detail::process_client_socket(
  288. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  289. };
  290. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  291. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  292. // wait_writable() returns true because select_write() only checks if the
  293. // send buffer has space. Peer disconnection is detected later by send().
  294. EXPECT_TRUE(ss.wait_writable());
  295. return true;
  296. });
  297. ASSERT_EQ(0, close(disconnected_svr_sock));
  298. }
  299. #endif // #ifndef _WIN32
  300. TEST(SetSocketOptTest, TcpNoDelay) {
  301. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  302. ASSERT_NE(sock, INVALID_SOCKET);
  303. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  304. int val = 0;
  305. socklen_t len = sizeof(val);
  306. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  307. reinterpret_cast<char *>(&val), &len));
  308. EXPECT_NE(val, 0);
  309. detail::close_socket(sock);
  310. }
  311. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  312. // accept() reports failures through WSAGetLastError() on Windows and through
  313. // errno everywhere else. Asking the wrong one is what made the accept loop
  314. // treat every recoverable failure as fatal on Windows.
  315. struct Classification {
  316. bool resource;
  317. bool transient;
  318. };
  319. auto classify = [](int err) {
  320. #ifdef _WIN32
  321. WSASetLastError(err);
  322. #else
  323. errno = err;
  324. #endif
  325. // Read both before asserting: an assertion may clobber the error slot.
  326. Classification c;
  327. c.resource = detail::is_accept_resource_error();
  328. c.transient = detail::is_accept_transient_error();
  329. return c;
  330. };
  331. #ifdef _WIN32
  332. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  333. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  334. WSAECONNRESET, WSAECONNABORTED};
  335. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  336. #else
  337. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  338. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  339. ECONNABORTED};
  340. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  341. #endif
  342. for (auto err : resource_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.resource) << "error " << err;
  345. EXPECT_FALSE(c.transient) << "error " << err;
  346. }
  347. for (auto err : transient_errors) {
  348. const auto c = classify(err);
  349. EXPECT_TRUE(c.transient) << "error " << err;
  350. EXPECT_FALSE(c.resource) << "error " << err;
  351. }
  352. for (auto err : fatal_errors) {
  353. const auto c = classify(err);
  354. EXPECT_FALSE(c.resource) << "error " << err;
  355. EXPECT_FALSE(c.transient) << "error " << err;
  356. }
  357. #ifdef _WIN32
  358. WSASetLastError(0);
  359. #else
  360. errno = 0;
  361. #endif
  362. }
  363. TEST(ClientTest, MoveConstructible) {
  364. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  365. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  366. }
  367. TEST(ClientTest, MoveAssignable) {
  368. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  369. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  370. }
  371. #ifdef _WIN32
  372. TEST(StartupTest, WSAStartup) {
  373. WSADATA wsaData;
  374. int ret = WSAStartup(0x0002, &wsaData);
  375. ASSERT_EQ(0, ret);
  376. }
  377. #endif
  378. TEST(DecodePathTest, PercentCharacter) {
  379. EXPECT_EQ(
  380. decode_path_component(
  381. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  382. U8("descrip=Gastos áéíóúñÑ 6"));
  383. }
  384. TEST(DecodePathTest, PercentCharacterNUL) {
  385. string expected;
  386. expected.push_back('x');
  387. expected.push_back('\0');
  388. expected.push_back('x');
  389. EXPECT_EQ(decode_path_component("x%00x"), expected);
  390. }
  391. TEST(DecodePathTest, UnicodeEncoding) {
  392. // %u0041 = 'A' (1-byte UTF-8)
  393. EXPECT_EQ("A", decode_path_component("%u0041"));
  394. // %u00E9 = 'é' (2-byte UTF-8)
  395. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  396. // %u3042 = 'あ' (3-byte UTF-8)
  397. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  398. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  399. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  400. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  401. // neighbours)
  402. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  403. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  404. }
  405. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  406. // A sign or whitespace inside the two-character escape window must not be
  407. // accepted as a valid percent-encoding; the sequence is passed through
  408. // literally, matching decode_uri_component / decode_path_component.
  409. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  410. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  411. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  412. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  413. // Well-formed escapes still decode.
  414. EXPECT_EQ("-", decode_query_component("%2D", false));
  415. EXPECT_EQ("A", decode_query_component("%41", false));
  416. }
  417. TEST(SanitizeFilenameTest, VariousPatterns) {
  418. // Path traversal
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  420. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  421. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  422. // Normal and edge cases
  423. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  424. EXPECT_EQ("filename.txt",
  425. httplib::sanitize_filename("/path/to/filename.txt"));
  426. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  427. EXPECT_EQ("", httplib::sanitize_filename(".."));
  428. EXPECT_EQ("", httplib::sanitize_filename(""));
  429. // Null bytes stripped
  430. EXPECT_EQ("safe.txt",
  431. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  432. // Whitespace-only rejected
  433. EXPECT_EQ("", httplib::sanitize_filename(" "));
  434. }
  435. // Forward declaration (see the base64_encode note below): split builds move the
  436. // definition into httplib.cc, so re-declaring it here lets the test link.
  437. namespace httplib {
  438. namespace detail {
  439. bool is_chunked_transfer_encoding(const Headers &headers);
  440. } // namespace detail
  441. } // namespace httplib
  442. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  443. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  444. auto make = [](std::initializer_list<const char *> lines) {
  445. Headers h;
  446. for (auto te : lines) {
  447. if (te) { h.emplace("Transfer-Encoding", te); }
  448. }
  449. return h;
  450. };
  451. // Sole coding, matched case-insensitively.
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  455. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  458. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  459. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  464. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  465. // were received, into one list. Headers preserves that order, so the answer
  466. // is decided by the last coding of the last line and the order the lines
  467. // arrived in is significant.
  468. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  470. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  471. // The split can fall anywhere in the list.
  472. EXPECT_TRUE(
  473. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  474. EXPECT_FALSE(
  475. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  476. // A trailing line naming no coding leaves the list ending in nothing, so it
  477. // must not inherit the chunked from the line before it.
  478. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  479. }
  480. // Forward declarations (see the base64_encode note below).
  481. namespace httplib {
  482. namespace detail {
  483. bool parse_status_line(const char *line, std::string &version, int &status,
  484. std::string &reason);
  485. std::string file_extension(const std::string &path);
  486. std::string
  487. find_content_type(const std::string &path,
  488. const std::map<std::string, std::string> &user_data,
  489. const std::string &default_content_type);
  490. bool can_compress_content_type(const std::string &content_type);
  491. bool is_prohibited_header_name(const std::string &name);
  492. bool is_valid_path(const std::string &path);
  493. #ifdef CPPHTTPLIB_SSL_ENABLED
  494. bool match_hostname(const std::string &pattern, const std::string &hostname);
  495. #endif
  496. } // namespace detail
  497. } // namespace httplib
  498. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  499. struct {
  500. const char *line;
  501. const char *version;
  502. int status;
  503. const char *reason;
  504. } cases[] = {
  505. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  506. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  507. // The reason phrase may be empty, or left out along with its space.
  508. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  509. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  510. };
  511. for (const auto &c : cases) {
  512. std::string version;
  513. int status = 0;
  514. std::string reason = "unset";
  515. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  516. << c.line;
  517. EXPECT_EQ(c.version, version);
  518. EXPECT_EQ(c.status, status);
  519. EXPECT_EQ(c.reason, reason);
  520. }
  521. }
  522. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  523. const char *lines[] = {
  524. "HTTP/2 200 OK\r\n",
  525. "HTTP/1.2 200 OK\r\n",
  526. "HTTP/1.1 20 OK\r\n",
  527. "HTTP/1.1 2000 OK\r\n",
  528. "HTTP/1.1 2x0 OK\r\n",
  529. "HTTP/1.1 200 OK\r\n",
  530. "HTTP/1.1 200OK\r\n",
  531. "HTTP/1.1 200 O\rK\r\n",
  532. "HTTP/1.1 200 OK",
  533. "HTTP/1.1 200 OK\r\nX",
  534. "",
  535. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  536. "HTTP/1.1 200 OK\n",
  537. #endif
  538. };
  539. for (auto line : lines) {
  540. std::string version;
  541. int status = 0;
  542. std::string reason;
  543. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  544. << line;
  545. }
  546. }
  547. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  548. // Long enough to overflow the stack when matched with std::regex.
  549. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  550. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  551. std::string version;
  552. int status = 0;
  553. std::string reason;
  554. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  555. EXPECT_EQ(200, status);
  556. EXPECT_EQ(long_reason, reason);
  557. }
  558. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  559. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  560. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  561. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  562. EXPECT_EQ("", detail::file_extension("noext"));
  563. EXPECT_EQ("", detail::file_extension("a."));
  564. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  565. EXPECT_EQ("", detail::file_extension("a.b-c"));
  566. // Long enough to overflow the stack when matched with std::regex.
  567. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  568. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  569. }
  570. #ifdef CPPHTTPLIB_SSL_ENABLED
  571. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  572. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  573. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  574. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  575. // A wildcard needs two labels after it, in the leftmost label only
  576. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  577. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  578. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  579. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  580. EXPECT_FALSE(
  581. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  582. // No name may have an empty label
  583. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  584. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  585. }
  586. #endif
  587. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  588. detail::case_ignore::hash hash;
  589. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  590. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  591. // Long enough to overflow the stack if hashed one call per character.
  592. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  593. }
  594. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  595. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  596. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  597. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  598. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  599. // Same 26-bit hash as html, svg and js.
  600. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  601. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  602. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  603. }
  604. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  605. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  606. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  607. }
  608. }
  609. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  610. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  611. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  612. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  613. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  614. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  615. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  616. // Same 26-bit hash as application/json.
  617. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  618. }
  619. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  620. Request req;
  621. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  622. EXPECT_TRUE(req.is_multipart_form_data());
  623. std::string boundary;
  624. EXPECT_TRUE(detail::parse_multipart_boundary(
  625. req.get_header_value("Content-Type"), boundary));
  626. EXPECT_EQ("x", boundary);
  627. }
  628. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  629. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  630. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  631. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  632. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  633. // Same 26-bit hash as REMOTE_ADDR.
  634. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  635. }
  636. // Forward declaration: in split builds split.py strips `inline` and moves the
  637. // definition into httplib.cc, so detail::base64_encode is not visible from the
  638. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  639. // in both header-only and split builds.
  640. namespace httplib {
  641. namespace detail {
  642. std::string base64_encode(const std::string &in);
  643. } // namespace detail
  644. } // namespace httplib
  645. TEST(Base64EncodeTest, KnownAnswers) {
  646. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  647. // where the accumulator's top bit is already set before the next shift.
  648. EXPECT_EQ("", detail::base64_encode(""));
  649. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  650. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  651. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  652. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  653. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  654. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  655. // High bytes keep the top bit set across several rounds.
  656. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  657. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  658. }
  659. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  660. string unescapedCharacters = "-_.!~*'()";
  661. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  662. }
  663. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  664. string reservedCharacters = ";,/?:@&=+$";
  665. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  666. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  667. }
  668. TEST(ClientQueryOrder, PreserveOrder) {
  669. // This test reproduces Issue #2259: client may reorder query parameters
  670. // when sending a GET request. The expected behavior is that the client
  671. // preserves the original query string order when the caller supplied it
  672. // as part of the path.
  673. Server svr;
  674. svr.Get("/", [&](const Request &req, Response &res) {
  675. // Echo back the raw target so the test can assert ordering
  676. res.set_content(req.target, "text/plain");
  677. });
  678. std::thread t{[&] { svr.listen(HOST, PORT); }};
  679. auto se = detail::scope_exit([&] {
  680. svr.stop();
  681. t.join();
  682. ASSERT_FALSE(svr.is_running());
  683. });
  684. svr.wait_until_ready();
  685. Client cli(HOST, PORT);
  686. ASSERT_TRUE(cli.is_valid());
  687. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  688. auto res = cli.Get(original);
  689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  690. // Expect the echoed target to exactly match the original path (order
  691. // preserved)
  692. EXPECT_EQ(res->body, original);
  693. }
  694. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  695. string chineseCharacters = U8("中国語");
  696. string russianCharacters = U8("дом");
  697. string brazilianCharacters = U8("óculos");
  698. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  699. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  700. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  701. "%D0%B4%D0%BE%D0%BC");
  702. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  703. }
  704. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  705. string unescapedCharacters = "-_.!~*'()";
  706. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  707. }
  708. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  709. string reservedCharacters = ";,/?:@&=+$";
  710. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  711. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  712. }
  713. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  714. string chineseCharacters = U8("中国語");
  715. string russianCharacters = U8("дом");
  716. string brazilianCharacters = U8("óculos");
  717. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  718. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  719. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  720. "%D0%B4%D0%BE%D0%BC");
  721. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  722. }
  723. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  724. // Issue #2082 use case: encoding path component with ampersand
  725. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  726. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  727. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  728. }
  729. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  730. string unescapedCharacters = "-_.!~*'()";
  731. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  732. }
  733. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  734. string reservedCharacters = ";,/?:@&=+$#";
  735. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  736. }
  737. TEST(EncodeUriTest, TestUTF8Characters) {
  738. string chineseCharacters = U8("中国語");
  739. string russianCharacters = U8("дом");
  740. string brazilianCharacters = U8("óculos");
  741. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  742. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  743. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  744. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  745. }
  746. TEST(EncodeUriTest, TestCompleteUri) {
  747. string uri =
  748. "https://example.com/path/to/resource?query=value&param=test#fragment";
  749. EXPECT_EQ(
  750. httplib::encode_uri(uri),
  751. "https://example.com/path/to/resource?query=value&param=test#fragment");
  752. }
  753. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  754. string uri =
  755. "https://example.com/path with spaces/file name.html?q=hello world";
  756. EXPECT_EQ(httplib::encode_uri(uri),
  757. "https://example.com/path%20with%20spaces/"
  758. "file%20name.html?q=hello%20world");
  759. }
  760. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  761. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  762. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  763. }
  764. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  765. string unescapedCharacters = "-_.!~*'()";
  766. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  767. }
  768. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  769. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  770. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  771. string encodedBrazilian = "%C3%B3culos";
  772. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  773. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  774. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  775. }
  776. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  777. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  778. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  779. "Piri Tommy Villiers - on & on");
  780. }
  781. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  782. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  783. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  784. }
  785. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  786. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  787. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  788. }
  789. TEST(DecodeUriTest, TestUTF8Characters) {
  790. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  791. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  792. string encodedBrazilian = "%C3%B3culos";
  793. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  794. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  795. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  796. }
  797. TEST(DecodeUriTest, TestCompleteUri) {
  798. string encodedUri = "https://example.com/path%20with%20spaces/"
  799. "file%20name.html?q=hello%20world";
  800. EXPECT_EQ(
  801. httplib::decode_uri(encodedUri),
  802. "https://example.com/path with spaces/file name.html?q=hello world");
  803. }
  804. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  805. string original =
  806. "https://example.com/path with spaces/file name.html?q=hello world";
  807. string encoded = httplib::encode_uri(original);
  808. string decoded = httplib::decode_uri(encoded);
  809. EXPECT_EQ(decoded, original);
  810. }
  811. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  812. // decode_uri is the inverse of encode_uri: an escaped reserved character
  813. // stays encoded so it is not promoted into a real delimiter, while
  814. // non-reserved escapes still decode (like JS decodeURI).
  815. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  816. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  817. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  818. "%3F%3A%40%26%3D%2B%24%2C%3B");
  819. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  820. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  821. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  822. "http://example.com/a%2Fb");
  823. // decode_uri_component still decodes the reserved character.
  824. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  825. }
  826. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  827. string original = "Piri Tommy Villiers - on & on";
  828. string encoded = httplib::encode_uri_component(original);
  829. string decoded = httplib::decode_uri_component(encoded);
  830. EXPECT_EQ(decoded, original);
  831. }
  832. TEST(TrimTests, TrimStringTests) {
  833. EXPECT_EQ("abc", detail::trim_copy("abc"));
  834. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  835. EXPECT_TRUE(detail::trim_copy("").empty());
  836. }
  837. TEST(AsciiTest, LocaleIndependentClassification) {
  838. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  839. // which consult the global C locale: std::isalnum(0xC5) can return true
  840. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  841. // helpers must classify every byte by the ASCII grammar alone.
  842. for (int i = 0; i < 256; i++) {
  843. auto c = static_cast<char>(i);
  844. auto is_digit = i >= '0' && i <= '9';
  845. auto is_upper = i >= 'A' && i <= 'Z';
  846. auto is_lower = i >= 'a' && i <= 'z';
  847. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  848. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  849. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  850. << "byte " << i;
  851. }
  852. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  853. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  854. // Non-ASCII bytes must be percent-encoded, never passed through as
  855. // alphanumeric.
  856. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  857. }
  858. TEST(FromCharsTest, Double) {
  859. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  860. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  861. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  862. auto parse = [](const std::string &s, double &v) {
  863. return detail::from_chars(s.data(), s.data() + s.size(), v);
  864. };
  865. double v = -1.0;
  866. // Representative quality values.
  867. EXPECT_EQ(parse("0", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.0);
  869. EXPECT_EQ(parse("1", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 1.0);
  871. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.8);
  873. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 0.001);
  875. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 1.0);
  877. // A missing integer or fractional part is tolerated.
  878. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  879. EXPECT_DOUBLE_EQ(v, 0.5);
  880. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 5.0);
  882. // Values outside [0, 1] still parse; the caller range-checks them.
  883. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  884. EXPECT_DOUBLE_EQ(v, 123.456);
  885. // Stops at the first byte that is not part of the number and reports where.
  886. std::string trailing = "0.9, text/html";
  887. auto r = parse(trailing, v);
  888. EXPECT_EQ(r.ec, std::errc{});
  889. EXPECT_DOUBLE_EQ(v, 0.9);
  890. EXPECT_EQ(*r.ptr, ',');
  891. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  892. // outright, and an 'e'/'E' simply ends the number.
  893. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  895. std::string exp_input = "1.5e3";
  896. r = parse(exp_input, v);
  897. EXPECT_EQ(r.ec, std::errc{});
  898. EXPECT_DOUBLE_EQ(v, 1.5);
  899. EXPECT_EQ(*r.ptr, 'e');
  900. // Invalid inputs.
  901. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  902. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  903. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  904. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  905. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  906. // Pathological but well-formed inputs must stay bounded (no overflow, no
  907. // out-of-bounds table access) and stay within [0, 1] for the caller.
  908. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  909. std::errc{});
  910. EXPECT_DOUBLE_EQ(v, 0.0);
  911. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  912. std::errc{});
  913. EXPECT_GE(v, 0.0);
  914. EXPECT_LE(v, 1.0);
  915. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  916. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  917. }
  918. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  919. // Simple case without quality values
  920. std::vector<std::string> result1;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html,application/json,text/plain", result1));
  923. EXPECT_EQ(result1.size(), 3U);
  924. EXPECT_EQ(result1[0], "text/html");
  925. EXPECT_EQ(result1[1], "application/json");
  926. EXPECT_EQ(result1[2], "text/plain");
  927. // With quality values
  928. std::vector<std::string> result2;
  929. EXPECT_TRUE(detail::parse_accept_header(
  930. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  931. EXPECT_EQ(result2.size(), 3U);
  932. EXPECT_EQ(result2[0], "application/json"); // highest q value
  933. EXPECT_EQ(result2[1], "text/html");
  934. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  935. }
  936. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  937. // Mixed with and without quality values
  938. std::vector<std::string> result;
  939. EXPECT_TRUE(detail::parse_accept_header(
  940. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  941. EXPECT_EQ(result.size(), 3U);
  942. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  943. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  944. EXPECT_EQ(result[2], "application/json"); // q=0.5
  945. }
  946. TEST(ParseAcceptHeaderTest, EdgeCases) {
  947. // Empty header
  948. std::vector<std::string> empty_result;
  949. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  950. EXPECT_TRUE(empty_result.empty());
  951. // Single type
  952. std::vector<std::string> single_result;
  953. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  954. EXPECT_EQ(single_result.size(), 1U);
  955. EXPECT_EQ(single_result[0], "application/json");
  956. // Wildcard types
  957. std::vector<std::string> wildcard_result;
  958. EXPECT_TRUE(detail::parse_accept_header(
  959. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  960. EXPECT_EQ(wildcard_result.size(), 3U);
  961. EXPECT_EQ(wildcard_result[0], "application/json");
  962. EXPECT_EQ(wildcard_result[1], "text/*");
  963. EXPECT_EQ(wildcard_result[2], "*/*");
  964. }
  965. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  966. // Common browser Accept header
  967. std::vector<std::string> browser_result;
  968. EXPECT_TRUE(
  969. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  970. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  971. browser_result));
  972. EXPECT_EQ(browser_result.size(), 6U);
  973. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  974. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  975. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  976. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  977. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  978. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  979. // API client header
  980. std::vector<std::string> api_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  983. api_result));
  984. EXPECT_EQ(api_result.size(), 3U);
  985. EXPECT_EQ(api_result[0], "application/json");
  986. EXPECT_EQ(api_result[1], "application/xml");
  987. EXPECT_EQ(api_result[2], "text/plain");
  988. }
  989. TEST(ParseAcceptHeaderTest, SpecialCases) {
  990. // Quality value with 3 decimal places
  991. std::vector<std::string> decimal_result;
  992. EXPECT_TRUE(detail::parse_accept_header(
  993. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  994. EXPECT_EQ(decimal_result.size(), 2U);
  995. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  996. EXPECT_EQ(decimal_result[1], "text/html");
  997. // Zero quality (should still be included but with lowest priority)
  998. std::vector<std::string> zero_q_result;
  999. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1000. zero_q_result));
  1001. EXPECT_EQ(zero_q_result.size(), 2U);
  1002. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1003. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1004. // No spaces around commas
  1005. std::vector<std::string> no_space_result;
  1006. EXPECT_TRUE(detail::parse_accept_header(
  1007. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1008. no_space_result));
  1009. EXPECT_EQ(no_space_result.size(), 3U);
  1010. EXPECT_EQ(no_space_result[0], "text/html");
  1011. EXPECT_EQ(no_space_result[1], "application/json");
  1012. EXPECT_EQ(no_space_result[2], "text/plain");
  1013. }
  1014. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1015. // Quality values always use '.' as the decimal separator, so parsing must
  1016. // not depend on the process locale. An embedding application may have
  1017. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1018. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1019. std::string saved = cur ? cur : "C";
  1020. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1021. "fr_FR.UTF-8"};
  1022. bool switched = false;
  1023. for (const auto loc : comma_locales) {
  1024. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1025. std::localeconv()->decimal_point[0] == ',') {
  1026. switched = true;
  1027. break;
  1028. }
  1029. }
  1030. if (!switched) {
  1031. std::setlocale(LC_NUMERIC, saved.c_str());
  1032. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1033. }
  1034. // The higher-weighted type appears later in the list, so a correct parse
  1035. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1036. // sensitive parse reads both weights as 0 and leaves the original order.
  1037. std::vector<std::string> result;
  1038. EXPECT_TRUE(detail::parse_accept_header(
  1039. "application/json;q=0.1,text/html;q=0.9", result));
  1040. ASSERT_EQ(result.size(), 2U);
  1041. EXPECT_EQ(result[0], "text/html");
  1042. EXPECT_EQ(result[1], "application/json");
  1043. std::setlocale(LC_NUMERIC, saved.c_str());
  1044. }
  1045. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1046. std::vector<std::string> result;
  1047. // Invalid quality value (> 1.0)
  1048. EXPECT_FALSE(
  1049. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1050. // Invalid quality value (< 0.0)
  1051. EXPECT_FALSE(
  1052. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1053. // Invalid quality value (not a number)
  1054. EXPECT_FALSE(detail::parse_accept_header(
  1055. "text/html;q=invalid,application/json", result));
  1056. // A valid numeric prefix does not make the entire quality value valid.
  1057. EXPECT_FALSE(detail::parse_accept_header(
  1058. "text/html;q=0.5junk,application/json", result));
  1059. // Empty quality value
  1060. EXPECT_FALSE(
  1061. detail::parse_accept_header("text/html;q=,application/json", result));
  1062. // Invalid media type format (no slash and not wildcard)
  1063. EXPECT_FALSE(
  1064. detail::parse_accept_header("invalidtype,application/json", result));
  1065. // Valid cases should still work
  1066. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1067. EXPECT_EQ(result.size(), 1U);
  1068. EXPECT_EQ(result[0], "*/*");
  1069. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1070. EXPECT_EQ(result.size(), 1U);
  1071. EXPECT_EQ(result[0], "*");
  1072. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1073. EXPECT_EQ(result.size(), 1U);
  1074. EXPECT_EQ(result[0], "text/*");
  1075. }
  1076. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1077. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1078. // and must not be answered with 400 Bad Request.
  1079. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1080. struct {
  1081. const char *value;
  1082. std::vector<std::string> expected;
  1083. } cases[] = {
  1084. {",application/json", {"application/json"}},
  1085. {"text/html,", {"text/html"}},
  1086. {"text/html,,*/*", {"text/html", "*/*"}},
  1087. // An empty element may be spelled with whitespace in it
  1088. {"text/html, , application/json", {"text/html", "application/json"}},
  1089. // Nothing but empty elements is an empty list, which means the same
  1090. // thing as no Accept header at all
  1091. {",,,", {}},
  1092. // Quality values still apply across ignored empty elements
  1093. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1094. };
  1095. for (const auto &c : cases) {
  1096. std::vector<std::string> result;
  1097. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1098. << "value: " << c.value;
  1099. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1100. }
  1101. // An invalid entry is still rejected when empty elements surround it
  1102. std::vector<std::string> result;
  1103. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1104. }
  1105. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1106. // or ';' inside one does not end the list element or the parameter. Section
  1107. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1108. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1109. struct {
  1110. const char *value;
  1111. std::vector<std::string> expected;
  1112. } cases[] = {
  1113. {"text/html;profile=\"a,b\",application/json",
  1114. {"text/html", "application/json"}},
  1115. // A "q=" inside a quoted value is not the weight
  1116. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1117. {"text/html", "application/json"}},
  1118. // The weight after a quoted value still applies
  1119. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1120. {"application/json", "text/html"}},
  1121. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1122. {"application/json", "text/html"}},
  1123. {"text/html;profile=\"a\\\"b\",application/json",
  1124. {"text/html", "application/json"}},
  1125. // An escaped backslash does not escape the '"' after it
  1126. {"text/html;profile=\"a\\\\\",application/json",
  1127. {"text/html", "application/json"}},
  1128. };
  1129. for (const auto &c : cases) {
  1130. std::vector<std::string> result;
  1131. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1132. << "value: " << c.value;
  1133. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1134. }
  1135. }
  1136. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1137. Server svr;
  1138. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1139. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1140. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1141. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1142. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1143. res.set_content("ok", "text/plain");
  1144. });
  1145. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1146. EXPECT_TRUE(false);
  1147. res.set_content("bad request", "text/plain");
  1148. });
  1149. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1150. auto se = detail::scope_exit([&] {
  1151. svr.stop();
  1152. listen_thread.join();
  1153. ASSERT_FALSE(svr.is_running());
  1154. });
  1155. svr.wait_until_ready();
  1156. Client cli("localhost", PORT);
  1157. {
  1158. auto res = cli.Get(
  1159. "/accept_ok",
  1160. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1162. EXPECT_EQ(StatusCode::OK_200, res->status);
  1163. }
  1164. {
  1165. auto res = cli.Get("/accept_bad_request",
  1166. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1168. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1169. }
  1170. }
  1171. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1172. Server svr;
  1173. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1174. res.set_content("ok", "text/plain");
  1175. });
  1176. std::atomic<int> start_count{0};
  1177. std::atomic<bool> running_when_called{false};
  1178. svr.set_start_handler([&]() {
  1179. running_when_called = svr.is_running();
  1180. start_count++;
  1181. });
  1182. auto port = svr.bind_to_any_port(HOST);
  1183. std::thread t([&]() { svr.listen_after_bind(); });
  1184. auto se = detail::scope_exit([&] {
  1185. svr.stop();
  1186. t.join();
  1187. ASSERT_FALSE(svr.is_running());
  1188. });
  1189. svr.wait_until_ready();
  1190. // A successful request proves the accept loop is running, which the start
  1191. // handler precedes; so by now the handler must have run exactly once.
  1192. Client cli(HOST, port);
  1193. cli.set_connection_timeout(std::chrono::seconds(5));
  1194. auto res = cli.Get("/");
  1195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1196. EXPECT_EQ(StatusCode::OK_200, res->status);
  1197. EXPECT_EQ(1, start_count.load());
  1198. EXPECT_TRUE(running_when_called.load());
  1199. }
  1200. TEST(DivideTest, DivideStringTests) {
  1201. auto divide = [](const std::string &str, char d) {
  1202. std::string lhs;
  1203. std::string rhs;
  1204. detail::divide(str, d,
  1205. [&](const char *lhs_data, std::size_t lhs_size,
  1206. const char *rhs_data, std::size_t rhs_size) {
  1207. lhs.assign(lhs_data, lhs_size);
  1208. rhs.assign(rhs_data, rhs_size);
  1209. });
  1210. return std::make_pair(std::move(lhs), std::move(rhs));
  1211. };
  1212. {
  1213. const auto res = divide("", '=');
  1214. EXPECT_EQ(res.first, "");
  1215. EXPECT_EQ(res.second, "");
  1216. }
  1217. {
  1218. const auto res = divide("=", '=');
  1219. EXPECT_EQ(res.first, "");
  1220. EXPECT_EQ(res.second, "");
  1221. }
  1222. {
  1223. const auto res = divide(" ", '=');
  1224. EXPECT_EQ(res.first, " ");
  1225. EXPECT_EQ(res.second, "");
  1226. }
  1227. {
  1228. const auto res = divide("a", '=');
  1229. EXPECT_EQ(res.first, "a");
  1230. EXPECT_EQ(res.second, "");
  1231. }
  1232. {
  1233. const auto res = divide("a=", '=');
  1234. EXPECT_EQ(res.first, "a");
  1235. EXPECT_EQ(res.second, "");
  1236. }
  1237. {
  1238. const auto res = divide("=b", '=');
  1239. EXPECT_EQ(res.first, "");
  1240. EXPECT_EQ(res.second, "b");
  1241. }
  1242. {
  1243. const auto res = divide("a=b", '=');
  1244. EXPECT_EQ(res.first, "a");
  1245. EXPECT_EQ(res.second, "b");
  1246. }
  1247. {
  1248. const auto res = divide("a=b=", '=');
  1249. EXPECT_EQ(res.first, "a");
  1250. EXPECT_EQ(res.second, "b=");
  1251. }
  1252. {
  1253. const auto res = divide("a=b=c", '=');
  1254. EXPECT_EQ(res.first, "a");
  1255. EXPECT_EQ(res.second, "b=c");
  1256. }
  1257. }
  1258. TEST(SplitTest, ParseQueryString) {
  1259. string s = "key1=val1&key2=val2&key3=val3";
  1260. Params dic;
  1261. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1262. [&](const char *b, const char *e) {
  1263. string key, val;
  1264. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1265. if (key.empty()) {
  1266. key.assign(b2, e2);
  1267. } else {
  1268. val.assign(b2, e2);
  1269. }
  1270. });
  1271. dic.emplace(key, val);
  1272. });
  1273. EXPECT_EQ("val1", dic.find("key1")->second);
  1274. EXPECT_EQ("val2", dic.find("key2")->second);
  1275. EXPECT_EQ("val3", dic.find("key3")->second);
  1276. }
  1277. TEST(SplitTest, ParseInvalidQueryTests) {
  1278. {
  1279. string s = " ";
  1280. Params dict;
  1281. detail::parse_query_text(s, dict);
  1282. EXPECT_TRUE(dict.empty());
  1283. }
  1284. {
  1285. string s = " = =";
  1286. Params dict;
  1287. detail::parse_query_text(s, dict);
  1288. EXPECT_TRUE(dict.empty());
  1289. }
  1290. }
  1291. TEST(ParseQueryTest, ParseQueryString) {
  1292. {
  1293. std::string s = "key1=val1&key2=val2&key3=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("val1", dic.find("key1")->second);
  1297. EXPECT_EQ("val2", dic.find("key2")->second);
  1298. EXPECT_EQ("val3", dic.find("key3")->second);
  1299. }
  1300. {
  1301. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1302. Params dic;
  1303. detail::parse_query_text(s, dic);
  1304. EXPECT_EQ("", dic.find("key1")->second);
  1305. EXPECT_EQ("val1", dic.find("key2")->second);
  1306. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1307. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1308. }
  1309. }
  1310. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1311. Params dic;
  1312. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1313. dic.emplace("key1", "val1");
  1314. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1315. dic.emplace("key2", "val2");
  1316. dic.emplace("key3", "val3");
  1317. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1318. }
  1319. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1320. Params params;
  1321. params.emplace("a", "1");
  1322. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1323. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1324. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1325. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1326. // Long enough to overflow the stack when matched with std::regex.
  1327. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1328. EXPECT_EQ("/p?" + long_query + "&a=1",
  1329. append_query_params("/p?" + long_query, params));
  1330. }
  1331. // Joins every entry of a Headers or Params into "key=value " so a whole
  1332. // traversal can be compared in one assertion. Both are instantiations of the
  1333. // same insertion-ordered container, so one helper serves both.
  1334. template <typename Map> static std::string entries_to_string(const Map &m) {
  1335. std::string s;
  1336. for (const auto &entry : m) {
  1337. s += entry.first + "=" + entry.second + " ";
  1338. }
  1339. return s;
  1340. }
  1341. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1342. // Params used to be a std::multimap, which sorted by name and handed the
  1343. // caller's query back alphabetised. A client signing its query string could
  1344. // not reproduce the order it asked for.
  1345. Params dic;
  1346. dic.emplace("zulu", "1");
  1347. dic.emplace("alpha", "2");
  1348. dic.emplace("mike", "3");
  1349. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1350. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1351. }
  1352. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1353. Params dic;
  1354. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1355. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1356. }
  1357. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1358. Request req;
  1359. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1360. req.params);
  1361. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1362. EXPECT_EQ("first", req.get_param_value("tag"));
  1363. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1364. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1365. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1366. EXPECT_EQ("", req.get_param_value("tag", 3));
  1367. }
  1368. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1369. // Params shares its container with Headers, which matches field names
  1370. // case-insensitively. Parameter names must not pick that up.
  1371. Params dic;
  1372. dic.emplace("Key", "upper");
  1373. dic.emplace("key", "lower");
  1374. EXPECT_EQ(2U, dic.size());
  1375. EXPECT_EQ(1U, dic.count("Key"));
  1376. EXPECT_EQ(1U, dic.count("key"));
  1377. EXPECT_EQ("upper", dic.find("Key")->second);
  1378. EXPECT_EQ("lower", dic.find("key")->second);
  1379. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1380. }
  1381. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1382. Server svr;
  1383. std::string order;
  1384. svr.Get("/order", [&](const Request &req, Response &res) {
  1385. order = entries_to_string(req.params);
  1386. res.set_content("ok", "text/plain");
  1387. });
  1388. auto port = svr.bind_to_any_port(HOST);
  1389. thread t = thread([&] { svr.listen_after_bind(); });
  1390. auto se = detail::scope_exit([&] {
  1391. svr.stop();
  1392. t.join();
  1393. ASSERT_FALSE(svr.is_running());
  1394. });
  1395. svr.wait_until_ready();
  1396. Client cli(HOST, port);
  1397. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1398. ASSERT_TRUE(res);
  1399. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1400. }
  1401. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1402. Server svr;
  1403. std::string field_order, file_order;
  1404. svr.Post("/order", [&](const Request &req, Response &res) {
  1405. for (const auto &field : req.form.fields) {
  1406. field_order += field.first + "=" + field.second.content + " ";
  1407. }
  1408. for (const auto &file : req.form.files) {
  1409. file_order += file.first + "=" + file.second.filename + " ";
  1410. }
  1411. res.set_content("ok", "text/plain");
  1412. });
  1413. auto port = svr.bind_to_any_port(HOST);
  1414. thread t = thread([&] { svr.listen_after_bind(); });
  1415. auto se = detail::scope_exit([&] {
  1416. svr.stop();
  1417. t.join();
  1418. ASSERT_FALSE(svr.is_running());
  1419. });
  1420. svr.wait_until_ready();
  1421. UploadFormDataItems items = {
  1422. {"zulu", "1", "", ""},
  1423. {"alpha", "2", "", ""},
  1424. {"mike", "3", "", ""},
  1425. {"zebra", "z", "z.txt", "text/plain"},
  1426. {"apple", "a", "a.txt", "text/plain"},
  1427. };
  1428. Client cli(HOST, port);
  1429. auto res = cli.Post("/order", items);
  1430. ASSERT_TRUE(res);
  1431. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1432. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1433. }
  1434. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1435. Server svr;
  1436. std::vector<std::string> values;
  1437. std::string first, second, out_of_range, order;
  1438. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1439. values = req.form.get_fields("tag");
  1440. first = req.form.get_field("tag", 0);
  1441. second = req.form.get_field("tag", 1);
  1442. out_of_range = req.form.get_field("tag", 2);
  1443. for (const auto &field : req.form.fields) {
  1444. order += field.first + "=" + field.second.content + " ";
  1445. }
  1446. res.set_content("ok", "text/plain");
  1447. });
  1448. auto port = svr.bind_to_any_port(HOST);
  1449. thread t = thread([&] { svr.listen_after_bind(); });
  1450. auto se = detail::scope_exit([&] {
  1451. svr.stop();
  1452. t.join();
  1453. ASSERT_FALSE(svr.is_running());
  1454. });
  1455. svr.wait_until_ready();
  1456. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1457. // not adjacent in the container.
  1458. UploadFormDataItems items = {
  1459. {"tag", "first", "", ""},
  1460. {"other", "x", "", ""},
  1461. {"tag", "second", "", ""},
  1462. };
  1463. Client cli(HOST, port);
  1464. auto res = cli.Post("/repeated", items);
  1465. ASSERT_TRUE(res);
  1466. ASSERT_EQ(2U, values.size());
  1467. EXPECT_EQ("first", values[0]);
  1468. EXPECT_EQ("second", values[1]);
  1469. EXPECT_EQ("first", first);
  1470. EXPECT_EQ("second", second);
  1471. // std::multimap already kept entries sharing a name in insertion order, so
  1472. // everything above passes without this change too. The whole traversal is
  1473. // what tells the two apart: sorting by name would hoist "other" to the front
  1474. // and the two "tag" parts would end up adjacent.
  1475. EXPECT_EQ("tag=first other=x tag=second ", order);
  1476. // Advancing past the last entry of a name used to run off the container;
  1477. // the container's saturating increment makes it return the default instead.
  1478. EXPECT_EQ("", out_of_range);
  1479. }
  1480. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1481. Server svr;
  1482. std::string file_names;
  1483. svr.Post("/upload", [&](const Request &req, Response &res) {
  1484. for (const auto &file : req.form.files) {
  1485. file_names += file.first + "|" + file.second.filename + " ";
  1486. }
  1487. res.set_content("ok", "text/plain");
  1488. });
  1489. auto port = svr.bind_to_any_port(HOST);
  1490. thread t = thread([&] { svr.listen_after_bind(); });
  1491. auto se = detail::scope_exit([&] {
  1492. svr.stop();
  1493. t.join();
  1494. ASSERT_FALSE(svr.is_running());
  1495. });
  1496. svr.wait_until_ready();
  1497. // A trailing backslash would otherwise escape the closing quote.
  1498. UploadFormDataItems items = {
  1499. {"dir\\", "x", "a.txt", "text/plain"},
  1500. {"b", "y", "a\\\\b.txt", "text/plain"},
  1501. };
  1502. Client cli(HOST, port);
  1503. auto res = cli.Post("/upload", items);
  1504. ASSERT_TRUE(res);
  1505. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1506. }
  1507. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1508. // Server::read_content() keeps a FormFields::iterator alive across the
  1509. // content callbacks that fill the part it points at. The container is
  1510. // vector-backed, so a later emplace can reallocate and invalidate an older
  1511. // iterator; 64 parts grow the vector through seven reallocations, which
  1512. // checks that every part's content still lands in its own entry.
  1513. const size_t part_count = 64;
  1514. // One formula for both the parts sent and the values expected back, so the
  1515. // two cannot drift apart.
  1516. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1517. auto content_of = [](size_t i) {
  1518. return std::string(64, static_cast<char>('a' + (i % 26)));
  1519. };
  1520. Server svr;
  1521. std::vector<std::pair<std::string, std::string>> received;
  1522. svr.Post("/many", [&](const Request &req, Response &res) {
  1523. for (const auto &field : req.form.fields) {
  1524. received.emplace_back(field.first, field.second.content);
  1525. }
  1526. res.set_content("ok", "text/plain");
  1527. });
  1528. auto port = svr.bind_to_any_port(HOST);
  1529. thread t = thread([&] { svr.listen_after_bind(); });
  1530. auto se = detail::scope_exit([&] {
  1531. svr.stop();
  1532. t.join();
  1533. ASSERT_FALSE(svr.is_running());
  1534. });
  1535. svr.wait_until_ready();
  1536. UploadFormDataItems items;
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. items.push_back({name_of(i), content_of(i), "", ""});
  1539. }
  1540. Client cli(HOST, port);
  1541. auto res = cli.Post("/many", items);
  1542. ASSERT_TRUE(res);
  1543. ASSERT_EQ(part_count, received.size());
  1544. for (size_t i = 0; i < part_count; i++) {
  1545. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1546. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1547. }
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1550. string content_type = "multipart/form-data; boundary=something";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "something");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1557. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1572. string content_type =
  1573. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1574. string boundary;
  1575. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1580. const string boundary(70, 'a');
  1581. string content_type = "multipart/form-data; boundary=" + boundary;
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_TRUE(ret);
  1585. EXPECT_EQ(parsed, boundary);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1588. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1589. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1590. string parsed;
  1591. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1592. EXPECT_FALSE(ret);
  1593. }
  1594. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1595. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1596. // is 72 characters on the wire and still valid.
  1597. const string boundary(70, 'a');
  1598. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1599. string parsed;
  1600. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1601. EXPECT_EQ(parsed, boundary);
  1602. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1603. parsed.clear();
  1604. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1605. }
  1606. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1607. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1608. // The parameter parser must not treat that '=' as the key/value separator.
  1609. string content_type =
  1610. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1611. "charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1617. // A ';' inside the quoted-string is part of the value, not a parameter
  1618. // separator, so it must not truncate the boundary.
  1619. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1620. string parsed;
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1622. EXPECT_EQ(parsed, "a;b");
  1623. }
  1624. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1625. string parsed;
  1626. EXPECT_TRUE(detail::parse_multipart_boundary(
  1627. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1628. EXPECT_EQ("a\\b", parsed);
  1629. EXPECT_TRUE(detail::parse_multipart_boundary(
  1630. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1631. EXPECT_EQ("a\"b", parsed);
  1632. }
  1633. TEST(ParseDispositionParamsTest, QuotedValues) {
  1634. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1635. // ';' and '=' are ordinary characters inside one.
  1636. struct {
  1637. const char *value;
  1638. std::vector<std::pair<const char *, const char *>> expected;
  1639. } cases[] = {
  1640. {"name=\"file1\"; filename=\"a.txt\"",
  1641. {{"name", "file1"}, {"filename", "a.txt"}}},
  1642. // Whitespace around '=' and ';' is still trimmed
  1643. {"name=\"file2\" ;filename = \"a.html\"",
  1644. {{"name", "file2"}, {"filename", "a.html"}}},
  1645. // '=' inside the value used to leave only the text after the last one
  1646. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1647. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1648. {"name=\"x=y\"", {{"name", "x=y"}}},
  1649. // ';' inside the value used to truncate the pair and leave a bogus one
  1650. {"name=\"file3\"; filename=\"a;b.txt\"",
  1651. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1652. // An unquoted value keeps working, and so does filename*
  1653. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1654. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1655. // A parameter with no key is dropped rather than turned into one whose
  1656. // key is the value
  1657. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1658. // An escaped quote does not end the value
  1659. {"name=\"a\\\"; filename=evil.php\"",
  1660. {{"name", "a\"; filename=evil.php"}}},
  1661. // Other backslashes, as in a Windows path, are kept
  1662. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1663. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1664. };
  1665. for (const auto &c : cases) {
  1666. Params params;
  1667. detail::parse_disposition_params(c.value, params);
  1668. for (const auto &kv : c.expected) {
  1669. auto it = params.find(kv.first);
  1670. ASSERT_NE(it, params.end())
  1671. << "value: " << c.value << ", key: " << kv.first;
  1672. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1673. }
  1674. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1675. }
  1676. }
  1677. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1678. Server svr;
  1679. std::string filename;
  1680. std::string content;
  1681. svr.Post("/upload", [&](const Request &req, Response &) {
  1682. const auto &file = req.form.get_file("file");
  1683. filename = file.filename;
  1684. content = file.content;
  1685. });
  1686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. thread.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. std::string body = "--B\r\n"
  1694. "Content-Disposition: form-data; name=\"file\"; "
  1695. "filename=\"a.txt\"\r\n"
  1696. "Content-Type: text/plain\r\n"
  1697. "\r\n"
  1698. "hello\r\n"
  1699. "--B--\r\n";
  1700. Client cli(HOST, PORT);
  1701. auto res = cli.Post(
  1702. "/upload",
  1703. [&](size_t offset, DataSink &sink) {
  1704. if (offset < body.size()) {
  1705. sink.write(&body[offset], 1);
  1706. } else {
  1707. sink.done();
  1708. }
  1709. return true;
  1710. },
  1711. "multipart/form-data; boundary=B");
  1712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1713. EXPECT_EQ(StatusCode::OK_200, res->status);
  1714. EXPECT_EQ("a.txt", filename);
  1715. EXPECT_EQ("hello", content);
  1716. }
  1717. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1718. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1719. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1720. Server svr;
  1721. std::string field_value, file_name, file_filename;
  1722. bool has_field = false, has_file = false;
  1723. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1724. has_field = req.form.has_field("x=y");
  1725. field_value = req.form.get_field("x=y");
  1726. has_file = req.form.has_file("file1");
  1727. const auto &file = req.form.get_file("file1");
  1728. file_name = file.name;
  1729. file_filename = file.filename;
  1730. res.set_content("ok", "text/plain");
  1731. });
  1732. auto port = svr.bind_to_any_port(HOST);
  1733. thread t = thread([&] { svr.listen_after_bind(); });
  1734. auto se = detail::scope_exit([&] {
  1735. svr.stop();
  1736. t.join();
  1737. ASSERT_FALSE(svr.is_running());
  1738. });
  1739. svr.wait_until_ready();
  1740. UploadFormDataItems items = {
  1741. {"x=y", "field-value", "", ""},
  1742. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1743. };
  1744. Client cli(HOST, port);
  1745. auto res = cli.Post("/quoted", items);
  1746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1747. ASSERT_EQ(StatusCode::OK_200, res->status);
  1748. EXPECT_TRUE(has_field);
  1749. EXPECT_EQ("field-value", field_value);
  1750. EXPECT_TRUE(has_file);
  1751. EXPECT_EQ("file1", file_name);
  1752. EXPECT_EQ("a;b=report.pdf", file_filename);
  1753. }
  1754. TEST(GetHeaderValueTest, DefaultValue) {
  1755. Headers headers = {{"Dummy", "Dummy"}};
  1756. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1757. EXPECT_STREQ("text/plain", val);
  1758. }
  1759. TEST(GetHeaderValueTest, DefaultValueInt) {
  1760. Headers headers = {{"Dummy", "Dummy"}};
  1761. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1762. EXPECT_EQ(100ull, val);
  1763. }
  1764. TEST(GetHeaderValueTest, RegularValue) {
  1765. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1766. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1767. EXPECT_STREQ("text/html", val);
  1768. }
  1769. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1770. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1771. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1772. EXPECT_STREQ("text/html", val);
  1773. }
  1774. TEST(GetHeaderValueTest, SetContent) {
  1775. Response res;
  1776. res.set_content("html", "text/html");
  1777. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1778. res.set_content("text", "text/plain");
  1779. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1780. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1781. }
  1782. TEST(GetHeaderValueTest, RegularValueInt) {
  1783. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1784. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1785. EXPECT_EQ(100ull, val);
  1786. }
  1787. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1788. Headers headers = {{"Content-Length", "x"}};
  1789. auto is_invalid_value = false;
  1790. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1791. is_invalid_value);
  1792. EXPECT_EQ(0ull, val);
  1793. EXPECT_TRUE(is_invalid_value);
  1794. }
  1795. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1796. // An all-digit value that overflows size_t must be reported as invalid, not
  1797. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1798. // a large length to a small one on 32-bit builds, leaving the framing length
  1799. // wrong while is_invalid_value stayed false.
  1800. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1801. auto is_invalid_value = false;
  1802. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1803. is_invalid_value);
  1804. EXPECT_TRUE(is_invalid_value);
  1805. // A well-formed length is unaffected.
  1806. Headers ok = {{"Content-Length", "1234"}};
  1807. is_invalid_value = false;
  1808. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1809. is_invalid_value);
  1810. EXPECT_EQ(1234ull, val);
  1811. EXPECT_FALSE(is_invalid_value);
  1812. }
  1813. TEST(GetHeaderValueTest, Range) {
  1814. {
  1815. Headers headers = {make_range_header({{1, -1}})};
  1816. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1817. EXPECT_STREQ("bytes=1-", val);
  1818. }
  1819. {
  1820. Headers headers = {make_range_header({{-1, 1}})};
  1821. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1822. EXPECT_STREQ("bytes=-1", val);
  1823. }
  1824. {
  1825. Headers headers = {make_range_header({{1, 10}})};
  1826. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1827. EXPECT_STREQ("bytes=1-10", val);
  1828. }
  1829. {
  1830. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1831. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1832. EXPECT_STREQ("bytes=1-10, 100-", val);
  1833. }
  1834. {
  1835. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1836. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1837. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1838. }
  1839. {
  1840. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1841. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1842. EXPECT_STREQ("bytes=0-0, -1", val);
  1843. }
  1844. }
  1845. TEST(BearerTokenAuthTest, SchemeValidation) {
  1846. // A value shorter than "Bearer " must not throw from the fixed-length
  1847. // substr, and a non-Bearer scheme must not be reported as a token.
  1848. struct {
  1849. const char *value;
  1850. const char *expected;
  1851. } cases[] = {
  1852. {"x", ""},
  1853. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1854. {"Bearer abc123", "abc123"},
  1855. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1856. };
  1857. for (const auto &c : cases) {
  1858. Request req;
  1859. req.set_header("Authorization", c.value);
  1860. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1861. }
  1862. }
  1863. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1864. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1865. // to depend on the standard library (libstdc++ handed back duplicates in
  1866. // reverse insertion order, libc++ in insertion order).
  1867. Request req;
  1868. req.set_header("Accept-Encoding", "gzip");
  1869. req.set_header("Accept-Encoding", "deflate");
  1870. req.set_header("Accept-Encoding", "br");
  1871. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1872. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1873. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1874. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1875. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1876. }
  1877. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-Test", "only");
  1880. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1881. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1882. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1883. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1884. }
  1885. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1886. Request req;
  1887. req.set_header("X-First", "1");
  1888. req.set_header("X-Test", "2");
  1889. req.params.emplace("first", "1");
  1890. req.params.emplace("test", "2");
  1891. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1892. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1893. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1894. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1895. // The second one is negative when read as a signed value
  1896. const auto max_id = (std::numeric_limits<size_t>::max)();
  1897. for (auto id : {max_id / 2, max_id}) {
  1898. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1899. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1900. EXPECT_EQ("", req.get_param_value("test", id));
  1901. EXPECT_EQ("", req.form.get_field("test", id));
  1902. EXPECT_EQ("", req.form.get_file("test", id).content);
  1903. }
  1904. }
  1905. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1906. Headers headers;
  1907. headers.emplace("Host", "example.com");
  1908. headers.emplace("Accept-Encoding", "gzip");
  1909. headers.emplace("User-Agent", "test");
  1910. headers.emplace("Accept-Encoding", "deflate");
  1911. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1912. "Accept-Encoding=deflate ",
  1913. entries_to_string(headers));
  1914. }
  1915. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1916. Headers headers = {{"Content-Type", "text/html"},
  1917. {"CONTENT-TYPE", "text/xml"}};
  1918. EXPECT_EQ(2U, headers.count("content-type"));
  1919. auto it = headers.find("content-type");
  1920. ASSERT_TRUE(it != headers.end());
  1921. EXPECT_EQ("text/html", it->second);
  1922. }
  1923. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1924. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1925. // drop only those fields and leave everything positioned between them.
  1926. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1927. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1928. auto rng = headers.equal_range("a");
  1929. headers.erase(rng.first, rng.second);
  1930. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1933. Headers headers = {
  1934. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1935. EXPECT_EQ(3U, headers.erase("A"));
  1936. EXPECT_EQ(0U, headers.count("A"));
  1937. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1938. }
  1939. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1940. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1941. headers.emplace_front("Host", "example.com");
  1942. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1943. entries_to_string(headers));
  1944. }
  1945. TEST(ParseHeaderValueTest, Range) {
  1946. {
  1947. Ranges ranges;
  1948. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1949. EXPECT_TRUE(ret);
  1950. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1951. }
  1952. {
  1953. Ranges ranges;
  1954. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1955. EXPECT_TRUE(ret);
  1956. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1957. }
  1958. {
  1959. Ranges ranges;
  1960. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1961. EXPECT_TRUE(ret);
  1962. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1963. }
  1964. {
  1965. Ranges ranges;
  1966. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1967. EXPECT_FALSE(ret);
  1968. }
  1969. {
  1970. Ranges ranges;
  1971. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. auto ret =
  1978. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1979. EXPECT_TRUE(ret);
  1980. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1981. }
  1982. {
  1983. Ranges ranges;
  1984. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1990. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1997. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1998. EXPECT_FALSE(
  1999. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2000. EXPECT_TRUE(ranges.empty());
  2001. }
  2002. {
  2003. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2004. // remainder of the representation, so it stays accepted.
  2005. Ranges ranges;
  2006. auto ret =
  2007. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2008. EXPECT_TRUE(ret);
  2009. ASSERT_EQ(1u, ranges.size());
  2010. EXPECT_EQ(0, ranges[0].first);
  2011. EXPECT_EQ(-1, ranges[0].second);
  2012. }
  2013. // RFC 9110 14.1: range unit names are case-insensitive.
  2014. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2015. Ranges ranges;
  2016. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2017. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2018. }
  2019. }
  2020. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2021. Request req;
  2022. req.set_header("Accept-Encoding", "gzip");
  2023. Response res;
  2024. res.set_header("Content-Type", "text/plain");
  2025. auto ret = detail::encoding_type(req, res);
  2026. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2027. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2028. #else
  2029. EXPECT_TRUE(ret == detail::EncodingType::None);
  2030. #endif
  2031. }
  2032. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2033. Request req;
  2034. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2035. Response res;
  2036. res.set_header("Content-Type", "text/plain");
  2037. auto ret = detail::encoding_type(req, res);
  2038. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2039. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2040. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2041. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2042. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2043. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2044. #else
  2045. EXPECT_TRUE(ret == detail::EncodingType::None);
  2046. #endif
  2047. }
  2048. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2049. Request req;
  2050. req.set_header("Accept-Encoding",
  2051. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2052. Response res;
  2053. res.set_header("Content-Type", "text/plain");
  2054. auto ret = detail::encoding_type(req, res);
  2055. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2056. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2057. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2058. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2059. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2060. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2061. #else
  2062. EXPECT_TRUE(ret == detail::EncodingType::None);
  2063. #endif
  2064. }
  2065. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2066. // All supported encodings rejected with q=0 should return None
  2067. Request req;
  2068. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2069. Response res;
  2070. res.set_header("Content-Type", "text/plain");
  2071. auto ret = detail::encoding_type(req, res);
  2072. EXPECT_TRUE(ret == detail::EncodingType::None);
  2073. }
  2074. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2075. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2076. Request req;
  2077. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2078. Response res;
  2079. res.set_header("Content-Type", "text/plain");
  2080. auto ret = detail::encoding_type(req, res);
  2081. EXPECT_TRUE(ret == detail::EncodingType::None);
  2082. }
  2083. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2089. }
  2090. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2091. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2092. Request req;
  2093. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2094. Response res;
  2095. res.set_header("Content-Type", "text/plain");
  2096. auto ret = detail::encoding_type(req, res);
  2097. EXPECT_TRUE(ret == detail::EncodingType::None);
  2098. }
  2099. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2100. // RFC 7231: Accept-Encoding values are case-insensitive
  2101. Request req;
  2102. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2103. Response res;
  2104. res.set_header("Content-Type", "text/plain");
  2105. auto ret = detail::encoding_type(req, res);
  2106. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2107. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2108. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2109. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2110. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2111. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2112. #else
  2113. EXPECT_TRUE(ret == detail::EncodingType::None);
  2114. #endif
  2115. }
  2116. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2117. // q value should determine priority, not hardcoded order
  2118. Request req;
  2119. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2120. Response res;
  2121. res.set_header("Content-Type", "text/plain");
  2122. auto ret = detail::encoding_type(req, res);
  2123. // gzip has highest q=1.0, so it should be selected even though
  2124. // br and zstd are also supported
  2125. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2126. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2127. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2128. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2129. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2130. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2131. #else
  2132. EXPECT_TRUE(ret == detail::EncodingType::None);
  2133. #endif
  2134. }
  2135. TEST(BufferStreamTest, read) {
  2136. detail::BufferStream strm1;
  2137. Stream &strm = strm1;
  2138. EXPECT_EQ(5, strm.write("hello"));
  2139. char buf[512];
  2140. EXPECT_EQ(2, strm.read(buf, 2));
  2141. EXPECT_EQ('h', buf[0]);
  2142. EXPECT_EQ('e', buf[1]);
  2143. EXPECT_EQ(2, strm.read(buf, 2));
  2144. EXPECT_EQ('l', buf[0]);
  2145. EXPECT_EQ('l', buf[1]);
  2146. EXPECT_EQ(1, strm.read(buf, 1));
  2147. EXPECT_EQ('o', buf[0]);
  2148. EXPECT_EQ(0, strm.read(buf, 1));
  2149. }
  2150. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2151. auto host = "www.httpwatch.com";
  2152. auto ip = hosted_at(host);
  2153. EXPECT_EQ("23.96.13.243", ip);
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(1u, addrs.size());
  2157. }
  2158. #if 0 // It depends on each test environment...
  2159. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2160. auto host = "www.youtube.com";
  2161. std::vector<std::string> addrs;
  2162. hosted_at(host, addrs);
  2163. EXPECT_EQ(20u, addrs.size());
  2164. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2165. EXPECT_TRUE(it != addrs.end());
  2166. }
  2167. #endif
  2168. class ChunkedEncodingTest : public ::testing::Test {
  2169. protected:
  2170. ChunkedEncodingTest()
  2171. : cli_(HOST, PORT)
  2172. #ifdef CPPHTTPLIB_SSL_ENABLED
  2173. ,
  2174. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2175. #endif
  2176. {
  2177. cli_.set_connection_timeout(2);
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. cli_.enable_server_certificate_verification(false);
  2180. #endif
  2181. }
  2182. virtual void SetUp() {
  2183. read_file("./image.jpg", image_data_);
  2184. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2185. res.set_content("Hello World!", "text/plain");
  2186. });
  2187. svr_.Get(
  2188. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2189. res.set_chunked_content_provider(
  2190. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2191. size_t remaining = image_data_.size() - offset;
  2192. if (remaining == 0) {
  2193. sink.done();
  2194. } else {
  2195. constexpr size_t CHUNK_SIZE = 1024;
  2196. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2197. sink.write(&image_data_[offset], send_size);
  2198. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2199. }
  2200. return true;
  2201. });
  2202. });
  2203. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2204. svr_.wait_until_ready();
  2205. }
  2206. virtual void TearDown() {
  2207. svr_.stop();
  2208. if (!request_threads_.empty()) {
  2209. std::this_thread::sleep_for(std::chrono::seconds(1));
  2210. for (auto &t : request_threads_) {
  2211. t.join();
  2212. }
  2213. }
  2214. t_.join();
  2215. }
  2216. #ifdef CPPHTTPLIB_SSL_ENABLED
  2217. SSLClient cli_;
  2218. SSLServer svr_;
  2219. #else
  2220. Client cli_;
  2221. Server svr_;
  2222. #endif
  2223. thread t_;
  2224. std::vector<thread> request_threads_;
  2225. std::string image_data_;
  2226. };
  2227. TEST_F(ChunkedEncodingTest, NormalGet) {
  2228. auto res = cli_.Get("/chunked");
  2229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2230. std::string out;
  2231. read_file("./image.jpg", out);
  2232. EXPECT_EQ(StatusCode::OK_200, res->status);
  2233. EXPECT_EQ(out, res->body);
  2234. }
  2235. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2236. std::string body;
  2237. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2238. body.append(data, data_length);
  2239. return true;
  2240. });
  2241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2242. std::string out;
  2243. read_file("./image.jpg", out);
  2244. EXPECT_EQ(StatusCode::OK_200, res->status);
  2245. EXPECT_EQ(out, body);
  2246. }
  2247. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2248. std::string body;
  2249. auto res = cli_.Get(
  2250. "/chunked",
  2251. [&](const Response &response) {
  2252. EXPECT_EQ(StatusCode::OK_200, response.status);
  2253. return true;
  2254. },
  2255. [&](const char *data, size_t data_length) {
  2256. body.append(data, data_length);
  2257. return true;
  2258. });
  2259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2260. std::string out;
  2261. read_file("./image.jpg", out);
  2262. EXPECT_EQ(StatusCode::OK_200, res->status);
  2263. EXPECT_EQ(out, body);
  2264. }
  2265. TEST(RangeTest, FromHTTPBin_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/range/32"};
  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(5);
  2276. {
  2277. auto res = cli.Get(path);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::OK_200, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, -1}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. {
  2290. Headers headers = {make_range_header({{1, 10}})};
  2291. auto res = cli.Get(path, headers);
  2292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2293. EXPECT_EQ("bcdefghijk", res->body);
  2294. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2295. }
  2296. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2297. // entire resource, while the original httpbin returned 200. Both are
  2298. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2299. {
  2300. Headers headers = {make_range_header({{0, 31}})};
  2301. auto res = cli.Get(path, headers);
  2302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2304. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2305. res->status == StatusCode::PartialContent_206);
  2306. }
  2307. {
  2308. Headers headers = {make_range_header({{0, -1}})};
  2309. auto res = cli.Get(path, headers);
  2310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2311. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2312. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2313. res->status == StatusCode::PartialContent_206);
  2314. }
  2315. // go-httpbin returns 206 with clamped range for over-range requests,
  2316. // while the original httpbin returned 416. Both behaviors are observed
  2317. // in real servers, so we only verify the request succeeds.
  2318. {
  2319. Headers headers = {make_range_header({{0, 32}})};
  2320. auto res = cli.Get(path, headers);
  2321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2322. }
  2323. }
  2324. TEST(RangeTest, IgnoredForPost) {
  2325. Server svr;
  2326. svr.Post("/", [](const Request &, Response &res) {
  2327. res.set_content("abcdefg", "text/plain");
  2328. });
  2329. auto port = svr.bind_to_any_port(HOST);
  2330. ASSERT_GT(port, 0);
  2331. thread t = thread([&] { svr.listen_after_bind(); });
  2332. auto se = detail::scope_exit([&] {
  2333. svr.stop();
  2334. t.join();
  2335. ASSERT_FALSE(svr.is_running());
  2336. });
  2337. svr.wait_until_ready();
  2338. Client cli(HOST, port);
  2339. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2340. auto res = cli.Post("/", Headers{{"Range", range}});
  2341. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2342. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2343. EXPECT_EQ("abcdefg", res->body) << range;
  2344. }
  2345. }
  2346. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2347. auto host = "unresolvableaddress.local";
  2348. auto path = std::string{"/"};
  2349. #ifdef CPPHTTPLIB_SSL_ENABLED
  2350. auto port = 443;
  2351. SSLClient cli(host, port);
  2352. #else
  2353. auto port = 80;
  2354. Client cli(host, port);
  2355. #endif
  2356. cli.set_connection_timeout(1);
  2357. {
  2358. auto res = cli.Get(path);
  2359. ASSERT_FALSE(res);
  2360. }
  2361. std::this_thread::sleep_for(std::chrono::seconds(8));
  2362. }
  2363. #if defined(__linux__) && defined(__GLIBC__) && \
  2364. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2365. // Forward declaration: in split builds split.py strips `inline` and moves the
  2366. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2367. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2368. // against the symbol in both header-only and split builds.
  2369. namespace httplib {
  2370. namespace detail {
  2371. int getaddrinfo_with_timeout(const char *node, const char *service,
  2372. const struct addrinfo *hints,
  2373. struct addrinfo **res, time_t timeout_sec);
  2374. } // namespace detail
  2375. } // namespace httplib
  2376. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2377. //
  2378. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2379. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2380. // gai_suspend() call hits the connection timeout the function calls
  2381. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2382. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2383. // still alive and still references the now-destroyed stack frame.
  2384. //
  2385. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2386. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2387. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2388. // and runs them in a container.
  2389. namespace {
  2390. bool should_run_issue_2431_tests() {
  2391. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2392. return v && *v && std::string(v) != "0";
  2393. }
  2394. std::string unique_unresolvable_host(int n) {
  2395. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2396. // glibc still asks the configured nameserver — which is exactly the path
  2397. // we want to exercise. A unique label per call avoids the resolver cache.
  2398. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2399. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2400. std::to_string(n) + ".invalid";
  2401. }
  2402. } // namespace
  2403. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2404. if (!should_run_issue_2431_tests()) {
  2405. GTEST_SKIP()
  2406. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2407. }
  2408. for (int i = 0; i < 8; ++i) {
  2409. struct addrinfo hints;
  2410. memset(&hints, 0, sizeof(hints));
  2411. hints.ai_family = AF_UNSPEC;
  2412. hints.ai_socktype = SOCK_STREAM;
  2413. auto host = unique_unresolvable_host(i);
  2414. struct addrinfo *result = nullptr;
  2415. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2416. &result, /*timeout_sec=*/1);
  2417. if (rc == 0 && result) { freeaddrinfo(result); }
  2418. }
  2419. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2420. // stack region they still believe holds their gaicb.
  2421. std::this_thread::sleep_for(std::chrono::seconds(3));
  2422. }
  2423. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2424. if (!should_run_issue_2431_tests()) {
  2425. GTEST_SKIP()
  2426. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2427. }
  2428. std::atomic<bool> stop{false};
  2429. std::vector<std::thread> threads;
  2430. for (int t = 0; t < 8; ++t) {
  2431. threads.emplace_back([t, &stop] {
  2432. int i = 0;
  2433. while (!stop.load(std::memory_order_relaxed)) {
  2434. struct addrinfo hints;
  2435. memset(&hints, 0, sizeof(hints));
  2436. hints.ai_family = AF_UNSPEC;
  2437. hints.ai_socktype = SOCK_STREAM;
  2438. auto host = unique_unresolvable_host(t * 100000 + i++);
  2439. struct addrinfo *result = nullptr;
  2440. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2441. &result, /*timeout_sec=*/1);
  2442. if (rc == 0 && result) { freeaddrinfo(result); }
  2443. }
  2444. });
  2445. }
  2446. std::this_thread::sleep_for(std::chrono::seconds(8));
  2447. stop.store(true, std::memory_order_relaxed);
  2448. for (auto &th : threads) {
  2449. th.join();
  2450. }
  2451. std::this_thread::sleep_for(std::chrono::seconds(3));
  2452. }
  2453. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2454. if (!should_run_issue_2431_tests()) {
  2455. GTEST_SKIP()
  2456. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2457. }
  2458. std::atomic<bool> stop{false};
  2459. std::vector<std::thread> threads;
  2460. for (int t = 0; t < 8; ++t) {
  2461. threads.emplace_back([t, &stop] {
  2462. int i = 0;
  2463. while (!stop.load(std::memory_order_relaxed)) {
  2464. auto host = unique_unresolvable_host(t * 100000 + i++);
  2465. Client cli(host, 80);
  2466. cli.set_connection_timeout(1, 0);
  2467. cli.set_read_timeout(1, 0);
  2468. cli.set_write_timeout(1, 0);
  2469. (void)cli.Get("/");
  2470. }
  2471. });
  2472. }
  2473. std::this_thread::sleep_for(std::chrono::seconds(8));
  2474. stop.store(true, std::memory_order_relaxed);
  2475. for (auto &th : threads) {
  2476. th.join();
  2477. }
  2478. std::this_thread::sleep_for(std::chrono::seconds(3));
  2479. }
  2480. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2481. TEST(ConnectionErrorTest, InvalidHost) {
  2482. auto host = "-abcde.com";
  2483. #ifdef CPPHTTPLIB_SSL_ENABLED
  2484. auto port = 443;
  2485. SSLClient cli(host, port);
  2486. #else
  2487. auto port = 80;
  2488. Client cli(host, port);
  2489. #endif
  2490. cli.set_connection_timeout(std::chrono::seconds(2));
  2491. auto res = cli.Get("/");
  2492. ASSERT_TRUE(!res);
  2493. EXPECT_EQ(Error::Connection, res.error());
  2494. }
  2495. TEST(ConnectionErrorTest, InvalidHost2) {
  2496. auto host = "httpcan.org/";
  2497. #ifdef CPPHTTPLIB_SSL_ENABLED
  2498. SSLClient cli(host);
  2499. #else
  2500. Client cli(host);
  2501. #endif
  2502. cli.set_connection_timeout(std::chrono::seconds(2));
  2503. auto res = cli.Get("/");
  2504. ASSERT_TRUE(!res);
  2505. EXPECT_EQ(Error::Connection, res.error());
  2506. }
  2507. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2508. auto host = "httpcan.org/";
  2509. #ifdef CPPHTTPLIB_SSL_ENABLED
  2510. SSLClient cli(host);
  2511. #else
  2512. Client cli(host);
  2513. #endif
  2514. cli.set_connection_timeout(std::chrono::seconds(2));
  2515. auto res = cli.Get("/");
  2516. ASSERT_TRUE(!res);
  2517. stringstream s;
  2518. s << "error code: " << res.error();
  2519. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2520. }
  2521. TEST(ConnectionErrorTest, InvalidPort) {
  2522. auto host = "localhost";
  2523. auto port = 44380;
  2524. #ifdef CPPHTTPLIB_SSL_ENABLED
  2525. SSLClient cli(host, port);
  2526. #else
  2527. Client cli(host, port);
  2528. #endif
  2529. cli.set_connection_timeout(std::chrono::seconds(2));
  2530. auto res = cli.Get("/");
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_TRUE(Error::Connection == res.error() ||
  2533. Error::ConnectionTimeout == res.error());
  2534. }
  2535. TEST(ConnectionErrorTest, Timeout_Online) {
  2536. auto host = "google.com";
  2537. #ifdef CPPHTTPLIB_SSL_ENABLED
  2538. auto port = 44380;
  2539. SSLClient cli(host, port);
  2540. #else
  2541. auto port = 8080;
  2542. Client cli(host, port);
  2543. #endif
  2544. cli.set_connection_timeout(std::chrono::seconds(2));
  2545. // only probe one address type so that the error reason
  2546. // correlates to the timed-out IPv4, not the unsupported
  2547. // IPv6 connection attempt
  2548. cli.set_address_family(AF_INET);
  2549. auto res = cli.Get("/");
  2550. ASSERT_TRUE(!res);
  2551. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2552. }
  2553. TEST(CancelTest, NoCancel_Online) {
  2554. auto host = "httpbingo.org";
  2555. auto path = std::string{"/range/32"};
  2556. #ifdef CPPHTTPLIB_SSL_ENABLED
  2557. auto port = 443;
  2558. SSLClient cli(host, port);
  2559. #else
  2560. auto port = 80;
  2561. Client cli(host, port);
  2562. #endif
  2563. cli.set_connection_timeout(std::chrono::seconds(5));
  2564. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2566. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2567. EXPECT_EQ(StatusCode::OK_200, res->status);
  2568. }
  2569. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2570. // Use /bytes with a large payload so that the DownloadProgress callback
  2571. // (which only fires for Content-Length responses) is invoked before the
  2572. // entire body is received, giving cancellation a chance to fire.
  2573. auto host = "httpbingo.org";
  2574. auto path = std::string{"/bytes/524288"};
  2575. #ifdef CPPHTTPLIB_SSL_ENABLED
  2576. auto port = 443;
  2577. SSLClient cli(host, port);
  2578. #else
  2579. auto port = 80;
  2580. Client cli(host, port);
  2581. #endif
  2582. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2583. cli.set_connection_timeout(std::chrono::seconds(5));
  2584. ASSERT_TRUE(!res);
  2585. EXPECT_EQ(Error::Canceled, res.error());
  2586. }
  2587. TEST(CancelTest, WithCancelLargePayload_Online) {
  2588. auto host = "httpbingo.org";
  2589. auto path = std::string{"/bytes/524288"};
  2590. #ifdef CPPHTTPLIB_SSL_ENABLED
  2591. auto port = 443;
  2592. SSLClient cli(host, port);
  2593. #else
  2594. auto port = 80;
  2595. Client cli(host, port);
  2596. #endif
  2597. cli.set_connection_timeout(std::chrono::seconds(5));
  2598. uint32_t count = 0;
  2599. auto res =
  2600. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2601. ASSERT_TRUE(!res);
  2602. EXPECT_EQ(Error::Canceled, res.error());
  2603. }
  2604. TEST(CancelTest, NoCancelPost) {
  2605. Server svr;
  2606. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2607. res.set_content("Hello World!", "text/plain");
  2608. });
  2609. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2610. auto se = detail::scope_exit([&] {
  2611. svr.stop();
  2612. thread.join();
  2613. ASSERT_FALSE(svr.is_running());
  2614. });
  2615. svr.wait_until_ready();
  2616. Client cli(HOST, PORT);
  2617. cli.set_connection_timeout(std::chrono::seconds(5));
  2618. auto res =
  2619. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2620. "application/json", [](uint64_t, uint64_t) { return true; });
  2621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2622. EXPECT_EQ("Hello World!", res->body);
  2623. EXPECT_EQ(StatusCode::OK_200, res->status);
  2624. }
  2625. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2626. Server svr;
  2627. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2628. res.set_content("Hello World!", "text/plain");
  2629. });
  2630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2631. auto se = detail::scope_exit([&] {
  2632. svr.stop();
  2633. thread.join();
  2634. ASSERT_FALSE(svr.is_running());
  2635. });
  2636. svr.wait_until_ready();
  2637. Client cli(HOST, PORT);
  2638. cli.set_connection_timeout(std::chrono::seconds(5));
  2639. auto res =
  2640. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2641. "application/json", [](uint64_t, uint64_t) { return false; });
  2642. ASSERT_TRUE(!res);
  2643. EXPECT_EQ(Error::Canceled, res.error());
  2644. }
  2645. TEST(CancelTest, WithCancelLargePayloadPost) {
  2646. Server svr;
  2647. svr.set_payload_max_length(200 * 1024 * 1024);
  2648. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2649. res.set_content(LARGE_DATA, "text/plain");
  2650. });
  2651. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2652. auto se = detail::scope_exit([&] {
  2653. svr.stop();
  2654. thread.join();
  2655. ASSERT_FALSE(svr.is_running());
  2656. });
  2657. svr.wait_until_ready();
  2658. Client cli(HOST, PORT);
  2659. cli.set_payload_max_length(200 * 1024 * 1024);
  2660. cli.set_connection_timeout(std::chrono::seconds(5));
  2661. auto res =
  2662. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2663. "application/json", [](uint64_t, uint64_t) { return false; });
  2664. ASSERT_TRUE(!res);
  2665. EXPECT_EQ(Error::Canceled, res.error());
  2666. }
  2667. TEST(CancelTest, NoCancelPut) {
  2668. Server svr;
  2669. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2670. res.set_content("Hello World!", "text/plain");
  2671. });
  2672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2673. auto se = detail::scope_exit([&] {
  2674. svr.stop();
  2675. thread.join();
  2676. ASSERT_FALSE(svr.is_running());
  2677. });
  2678. svr.wait_until_ready();
  2679. Client cli(HOST, PORT);
  2680. cli.set_connection_timeout(std::chrono::seconds(5));
  2681. auto res =
  2682. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2683. "application/json", [](uint64_t, uint64_t) { return true; });
  2684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2685. EXPECT_EQ("Hello World!", res->body);
  2686. EXPECT_EQ(StatusCode::OK_200, res->status);
  2687. }
  2688. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2689. Server svr;
  2690. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2691. res.set_content("Hello World!", "text/plain");
  2692. });
  2693. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. thread.join();
  2697. ASSERT_FALSE(svr.is_running());
  2698. });
  2699. svr.wait_until_ready();
  2700. Client cli(HOST, PORT);
  2701. cli.set_connection_timeout(std::chrono::seconds(5));
  2702. auto res =
  2703. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2704. "application/json", [](uint64_t, uint64_t) { return false; });
  2705. ASSERT_TRUE(!res);
  2706. EXPECT_EQ(Error::Canceled, res.error());
  2707. }
  2708. TEST(CancelTest, WithCancelLargePayloadPut) {
  2709. Server svr;
  2710. svr.set_payload_max_length(200 * 1024 * 1024);
  2711. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2712. res.set_content(LARGE_DATA, "text/plain");
  2713. });
  2714. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2715. auto se = detail::scope_exit([&] {
  2716. svr.stop();
  2717. thread.join();
  2718. ASSERT_FALSE(svr.is_running());
  2719. });
  2720. svr.wait_until_ready();
  2721. Client cli(HOST, PORT);
  2722. cli.set_payload_max_length(200 * 1024 * 1024);
  2723. cli.set_connection_timeout(std::chrono::seconds(5));
  2724. auto res =
  2725. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2726. "application/json", [](uint64_t, uint64_t) { return false; });
  2727. ASSERT_TRUE(!res);
  2728. EXPECT_EQ(Error::Canceled, res.error());
  2729. }
  2730. TEST(CancelTest, NoCancelPatch) {
  2731. Server svr;
  2732. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2733. res.set_content("Hello World!", "text/plain");
  2734. });
  2735. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2736. auto se = detail::scope_exit([&] {
  2737. svr.stop();
  2738. thread.join();
  2739. ASSERT_FALSE(svr.is_running());
  2740. });
  2741. svr.wait_until_ready();
  2742. Client cli(HOST, PORT);
  2743. cli.set_connection_timeout(std::chrono::seconds(5));
  2744. auto res =
  2745. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2746. "application/json", [](uint64_t, uint64_t) { return true; });
  2747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2748. EXPECT_EQ("Hello World!", res->body);
  2749. EXPECT_EQ(StatusCode::OK_200, res->status);
  2750. }
  2751. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2752. Server svr;
  2753. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2754. res.set_content("Hello World!", "text/plain");
  2755. });
  2756. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2757. auto se = detail::scope_exit([&] {
  2758. svr.stop();
  2759. thread.join();
  2760. ASSERT_FALSE(svr.is_running());
  2761. });
  2762. svr.wait_until_ready();
  2763. Client cli(HOST, PORT);
  2764. cli.set_connection_timeout(std::chrono::seconds(5));
  2765. auto res =
  2766. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2767. "application/json", [](uint64_t, uint64_t) { return false; });
  2768. ASSERT_TRUE(!res);
  2769. EXPECT_EQ(Error::Canceled, res.error());
  2770. }
  2771. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2772. Server svr;
  2773. svr.set_payload_max_length(200 * 1024 * 1024);
  2774. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2775. res.set_content(LARGE_DATA, "text/plain");
  2776. });
  2777. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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_payload_max_length(200 * 1024 * 1024);
  2786. cli.set_connection_timeout(std::chrono::seconds(5));
  2787. auto res =
  2788. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2789. "application/json", [](uint64_t, uint64_t) { return false; });
  2790. ASSERT_TRUE(!res);
  2791. EXPECT_EQ(Error::Canceled, res.error());
  2792. }
  2793. TEST(CancelTest, NoCancelDelete) {
  2794. Server svr;
  2795. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2796. res.set_content("Hello World!", "text/plain");
  2797. });
  2798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2799. auto se = detail::scope_exit([&] {
  2800. svr.stop();
  2801. thread.join();
  2802. ASSERT_FALSE(svr.is_running());
  2803. });
  2804. svr.wait_until_ready();
  2805. Client cli(HOST, PORT);
  2806. cli.set_connection_timeout(std::chrono::seconds(5));
  2807. auto res =
  2808. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2809. "application/json", [](uint64_t, uint64_t) { return true; });
  2810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2811. EXPECT_EQ("Hello World!", res->body);
  2812. EXPECT_EQ(StatusCode::OK_200, res->status);
  2813. }
  2814. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2815. Server svr;
  2816. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2817. res.set_content("Hello World!", "text/plain");
  2818. });
  2819. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2820. auto se = detail::scope_exit([&] {
  2821. svr.stop();
  2822. thread.join();
  2823. ASSERT_FALSE(svr.is_running());
  2824. });
  2825. svr.wait_until_ready();
  2826. Client cli(HOST, PORT);
  2827. cli.set_connection_timeout(std::chrono::seconds(5));
  2828. auto res =
  2829. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2830. "application/json", [](uint64_t, uint64_t) { return false; });
  2831. ASSERT_TRUE(!res);
  2832. EXPECT_EQ(Error::Canceled, res.error());
  2833. }
  2834. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2835. Server svr;
  2836. svr.set_payload_max_length(200 * 1024 * 1024);
  2837. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2838. res.set_content(LARGE_DATA, "text/plain");
  2839. });
  2840. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2841. auto se = detail::scope_exit([&] {
  2842. svr.stop();
  2843. thread.join();
  2844. ASSERT_FALSE(svr.is_running());
  2845. });
  2846. svr.wait_until_ready();
  2847. Client cli(HOST, PORT);
  2848. cli.set_payload_max_length(200 * 1024 * 1024);
  2849. cli.set_connection_timeout(std::chrono::seconds(5));
  2850. auto res =
  2851. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2852. "application/json", [](uint64_t, uint64_t) { return false; });
  2853. ASSERT_TRUE(!res);
  2854. EXPECT_EQ(Error::Canceled, res.error());
  2855. }
  2856. static std::string remove_whitespace(const std::string &input) {
  2857. std::string output;
  2858. output.reserve(input.size());
  2859. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2860. [](unsigned char c) { return !std::isspace(c); });
  2861. return output;
  2862. }
  2863. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2864. auto host = "httpbingo.org";
  2865. auto path = std::string{"/basic-auth/hello/world"};
  2866. #ifdef CPPHTTPLIB_SSL_ENABLED
  2867. auto port = 443;
  2868. SSLClient cli(host, port);
  2869. #else
  2870. auto port = 80;
  2871. Client cli(host, port);
  2872. #endif
  2873. {
  2874. auto res = cli.Get(path);
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2877. }
  2878. {
  2879. auto res = cli.Get(
  2880. path, Headers{make_basic_authentication_header("hello", "world")});
  2881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2882. auto body = remove_whitespace(res->body);
  2883. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2884. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2885. EXPECT_EQ(StatusCode::OK_200, res->status);
  2886. }
  2887. {
  2888. cli.set_basic_auth("hello", "world");
  2889. auto res = cli.Get(path);
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. auto body = remove_whitespace(res->body);
  2892. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2893. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2894. EXPECT_EQ(StatusCode::OK_200, res->status);
  2895. }
  2896. {
  2897. cli.set_basic_auth("hello", "bad");
  2898. auto res = cli.Get(path);
  2899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2900. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2901. }
  2902. {
  2903. cli.set_basic_auth("bad", "world");
  2904. auto res = cli.Get(path);
  2905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2906. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2907. }
  2908. }
  2909. #ifdef CPPHTTPLIB_SSL_ENABLED
  2910. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2911. auto host = "httpbingo.org";
  2912. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2913. auto paths = std::vector<std::string>{
  2914. "/digest-auth/auth/hello/world/MD5",
  2915. "/digest-auth/auth/hello/world/SHA-256",
  2916. };
  2917. auto port = 443;
  2918. SSLClient cli(host, port);
  2919. {
  2920. auto res = cli.Get(unauth_path);
  2921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2922. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2923. }
  2924. {
  2925. cli.set_digest_auth("hello", "world");
  2926. for (const auto &path : paths) {
  2927. auto res = cli.Get(path.c_str());
  2928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2929. auto body = remove_whitespace(res->body);
  2930. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2931. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2932. EXPECT_EQ(StatusCode::OK_200, res->status);
  2933. }
  2934. cli.set_digest_auth("hello", "bad");
  2935. for (const auto &path : paths) {
  2936. auto res = cli.Get(path.c_str());
  2937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2938. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2939. }
  2940. }
  2941. }
  2942. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2943. // comma-separated list of challenges, and each challenge may itself carry a
  2944. // comma-separated auth-param list, so a server can legally offer Basic
  2945. // before Digest, either as two field lines or packed into one. Runs one 401
  2946. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2947. // value() joins them in receipt order) and checks that the retry carries a
  2948. // well-formed Digest Authorization header naming expected_realm.
  2949. static void
  2950. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2951. const std::string &expected_realm) {
  2952. std::atomic<int> hits{0};
  2953. Server svr;
  2954. svr.Get("/x", [&](const Request &req, Response &res) {
  2955. if (++hits == 1) {
  2956. res.status = StatusCode::Unauthorized_401;
  2957. for (const auto &challenge : challenges) {
  2958. res.set_header("WWW-Authenticate", challenge);
  2959. }
  2960. } else {
  2961. auto authorization = req.get_header_value("Authorization");
  2962. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2963. EXPECT_NE(std::string::npos,
  2964. authorization.find("realm=\"" + expected_realm + "\""));
  2965. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2966. res.set_content("ok", "text/plain");
  2967. }
  2968. });
  2969. auto port = svr.bind_to_any_port(HOST);
  2970. std::thread t([&]() { svr.listen_after_bind(); });
  2971. auto se = detail::scope_exit([&] {
  2972. svr.stop();
  2973. t.join();
  2974. });
  2975. svr.wait_until_ready();
  2976. Client cli(HOST, port);
  2977. cli.set_digest_auth("hello", "world");
  2978. auto res = cli.Get("/x");
  2979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2980. EXPECT_EQ(2, hits.load());
  2981. }
  2982. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2983. static const char *kDigestChallenge =
  2984. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2985. "algorithm=MD5";
  2986. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2987. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2988. "testrealm");
  2989. }
  2990. // Same challenge list with the schemes in the opposite order, to make sure
  2991. // the fix above didn't just special-case "Basic first".
  2992. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2993. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2994. "testrealm");
  2995. }
  2996. // A comma inside a quoted auth-param value must not be mistaken for the
  2997. // separator between two challenges (or two auth-params).
  2998. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2999. run_digest_challenge_list_test(
  3000. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3001. "algorithm=MD5"},
  3002. "test,realm");
  3003. }
  3004. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3005. // the params and leaves out the fragment.
  3006. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3007. Server svr;
  3008. std::string uri, target;
  3009. svr.Get("/a b", [&](const Request &req, Response &res) {
  3010. auto auth = req.get_header_value("Authorization");
  3011. if (auth.empty()) {
  3012. res.status = StatusCode::Unauthorized_401;
  3013. res.set_header("WWW-Authenticate",
  3014. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3015. return;
  3016. }
  3017. auto b = auth.find("uri=\"") + 5;
  3018. uri = auth.substr(b, auth.find('"', b) - b);
  3019. target = req.target;
  3020. });
  3021. auto port = svr.bind_to_any_port(HOST);
  3022. std::thread t([&]() { svr.listen_after_bind(); });
  3023. auto se = detail::scope_exit([&] {
  3024. svr.stop();
  3025. t.join();
  3026. });
  3027. svr.wait_until_ready();
  3028. Client cli(HOST, port);
  3029. cli.set_digest_auth("hello", "world");
  3030. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3032. EXPECT_EQ("/a%20b?x=1", target);
  3033. EXPECT_EQ(target, uri);
  3034. }
  3035. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3036. // make_digest_authentication_header() dereferences both unconditionally, so
  3037. // a server sending a challenge missing either one must not be treated as
  3038. // usable -- doing so used to crash the client with std::out_of_range.
  3039. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3040. Server svr;
  3041. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3042. res.status = StatusCode::Unauthorized_401;
  3043. res.set_header("WWW-Authenticate", challenge);
  3044. });
  3045. auto port = svr.bind_to_any_port(HOST);
  3046. std::thread t([&]() { svr.listen_after_bind(); });
  3047. auto se = detail::scope_exit([&] {
  3048. svr.stop();
  3049. t.join();
  3050. });
  3051. svr.wait_until_ready();
  3052. Client cli(HOST, port);
  3053. cli.set_digest_auth("hello", "world");
  3054. auto res = cli.Get("/x");
  3055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3056. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3057. }
  3058. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3059. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3060. }
  3061. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3062. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3063. }
  3064. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3065. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3066. }
  3067. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3068. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3069. // when storing the values, so the header builder has to re-escape them (and
  3070. // keep algorithm a bare token); otherwise the value breaks out of its
  3071. // quoted-string and injects extra auth-params into the client's Authorization.
  3072. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3073. std::atomic<int> hits{0};
  3074. std::string authorization;
  3075. Server svr;
  3076. svr.Get("/x", [&](const Request &req, Response &res) {
  3077. if (++hits == 1) {
  3078. res.status = StatusCode::Unauthorized_401;
  3079. // On the wire the quotes embedded in the values are backslash-escaped.
  3080. res.set_header("WWW-Authenticate",
  3081. "Digest realm=\"testrealm\", "
  3082. "nonce=\"n\\\"; injected=\\\"x\", "
  3083. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3084. } else {
  3085. authorization = req.get_header_value("Authorization");
  3086. res.set_content("ok", "text/plain");
  3087. }
  3088. });
  3089. auto port = svr.bind_to_any_port(HOST);
  3090. std::thread t([&]() { svr.listen_after_bind(); });
  3091. auto se = detail::scope_exit([&] {
  3092. svr.stop();
  3093. t.join();
  3094. });
  3095. svr.wait_until_ready();
  3096. Client cli(HOST, port);
  3097. cli.set_digest_auth("hello", "world");
  3098. auto res = cli.Get("/x");
  3099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3100. EXPECT_EQ(2, hits.load());
  3101. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3102. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3103. // inside its quoted-string rather than starting an "injected" auth-param.
  3104. EXPECT_NE(std::string::npos,
  3105. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3106. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3107. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3108. }
  3109. #endif
  3110. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3111. auto host = "google.com";
  3112. auto another_host = "example.com";
  3113. auto wrong_ip = "0.0.0.0";
  3114. #ifdef CPPHTTPLIB_SSL_ENABLED
  3115. SSLClient cli(host);
  3116. #else
  3117. Client cli(host);
  3118. #endif
  3119. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3120. auto res = cli.Get("/");
  3121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3122. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3123. }
  3124. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3125. auto host = "google.com";
  3126. auto wrong_ip = "0.0.0.0";
  3127. #ifdef CPPHTTPLIB_SSL_ENABLED
  3128. SSLClient cli(host);
  3129. #else
  3130. Client cli(host);
  3131. #endif
  3132. cli.set_hostname_addr_map({{host, wrong_ip}});
  3133. auto res = cli.Get("/");
  3134. ASSERT_TRUE(!res);
  3135. EXPECT_EQ(Error::Connection, res.error());
  3136. }
  3137. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3138. // A mapped value that is not an IP literal must be resolved. "localhost"
  3139. // resolves from the hosts file, so this test needs no external DNS.
  3140. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3141. auto host = "target.invalid";
  3142. Server svr;
  3143. std::string received_host;
  3144. svr.Get("/hi", [&](const Request &req, Response &res) {
  3145. received_host = req.get_header_value("Host");
  3146. res.set_content("Hello World!", "text/plain");
  3147. });
  3148. auto port = svr.bind_to_any_port(HOST);
  3149. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3150. auto se = detail::scope_exit([&] {
  3151. svr.stop();
  3152. thread.join();
  3153. ASSERT_FALSE(svr.is_running());
  3154. });
  3155. svr.wait_until_ready();
  3156. Client cli(host, port);
  3157. cli.set_hostname_addr_map({{host, HOST}});
  3158. auto res = cli.Get("/hi");
  3159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3160. EXPECT_EQ(StatusCode::OK_200, res->status);
  3161. // The mapping only redirects the connection; the identity stays host_.
  3162. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3163. }
  3164. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3165. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3166. auto host = "target.invalid";
  3167. Server svr;
  3168. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3169. res.set_content("Hello World!", "text/plain");
  3170. });
  3171. auto port = svr.bind_to_any_port("127.0.0.1");
  3172. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3173. auto se = detail::scope_exit([&] {
  3174. svr.stop();
  3175. thread.join();
  3176. ASSERT_FALSE(svr.is_running());
  3177. });
  3178. svr.wait_until_ready();
  3179. Client cli(host, port);
  3180. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3181. auto res = cli.Get("/hi");
  3182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3183. EXPECT_EQ(StatusCode::OK_200, res->status);
  3184. }
  3185. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3186. // An empty mapped value must leave host_ as the connection target. Without
  3187. // that guard the empty value would become the host argument, getaddrinfo
  3188. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3189. // loopback - silently connecting somewhere the caller never asked for.
  3190. // The server listens on loopback, so such a fallback would succeed and is
  3191. // therefore observable as a failure of this test.
  3192. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3193. Server svr;
  3194. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3195. res.set_content("Hello World!", "text/plain");
  3196. });
  3197. auto port = svr.bind_to_any_port(HOST);
  3198. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3199. auto se = detail::scope_exit([&] {
  3200. svr.stop();
  3201. thread.join();
  3202. ASSERT_FALSE(svr.is_running());
  3203. });
  3204. svr.wait_until_ready();
  3205. Client cli(blackhole, port);
  3206. cli.set_hostname_addr_map({{blackhole, ""}});
  3207. cli.set_connection_timeout(1);
  3208. auto res = cli.Get("/hi");
  3209. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3210. }
  3211. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3212. auto host = "httpbingo.org";
  3213. auto path = std::string{"/absolute-redirect/3"};
  3214. #ifdef CPPHTTPLIB_SSL_ENABLED
  3215. SSLClient cli(host);
  3216. #else
  3217. Client cli(host);
  3218. #endif
  3219. cli.set_follow_location(true);
  3220. auto res = cli.Get(path);
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::OK_200, res->status);
  3223. }
  3224. TEST(RedirectTest, Redirect_Online) {
  3225. auto host = "httpbingo.org";
  3226. auto path = std::string{"/redirect/3"};
  3227. #ifdef CPPHTTPLIB_SSL_ENABLED
  3228. SSLClient cli(host);
  3229. #else
  3230. Client cli(host);
  3231. #endif
  3232. cli.set_follow_location(true);
  3233. auto res = cli.Get(path);
  3234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3235. EXPECT_EQ(StatusCode::OK_200, res->status);
  3236. }
  3237. TEST(RelativeRedirectTest, Redirect_Online) {
  3238. auto host = "httpbingo.org";
  3239. auto path = std::string{"/relative-redirect/3"};
  3240. #ifdef CPPHTTPLIB_SSL_ENABLED
  3241. SSLClient cli(host);
  3242. #else
  3243. Client cli(host);
  3244. #endif
  3245. cli.set_follow_location(true);
  3246. auto res = cli.Get(path);
  3247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3248. EXPECT_EQ(StatusCode::OK_200, res->status);
  3249. }
  3250. TEST(TooManyRedirectTest, Redirect_Online) {
  3251. auto host = "httpbingo.org";
  3252. auto path = std::string{"/redirect/21"};
  3253. #ifdef CPPHTTPLIB_SSL_ENABLED
  3254. SSLClient cli(host);
  3255. #else
  3256. Client cli(host);
  3257. #endif
  3258. cli.set_follow_location(true);
  3259. auto res = cli.Get(path);
  3260. ASSERT_TRUE(!res);
  3261. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3262. }
  3263. #ifdef CPPHTTPLIB_SSL_ENABLED
  3264. TEST(YahooRedirectTest, Redirect_Online) {
  3265. Client cli("yahoo.com");
  3266. auto res = cli.Get("/");
  3267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3268. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3269. cli.set_follow_location(true);
  3270. res = cli.Get("/");
  3271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3272. EXPECT_EQ(StatusCode::OK_200, res->status);
  3273. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3274. }
  3275. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3276. #define REDIR_HOST "httpbingo.org"
  3277. #define REDIR_PATH "/redirect-to"
  3278. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3279. SSLClient cli(REDIR_HOST);
  3280. cli.set_follow_location(true);
  3281. auto res =
  3282. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3284. EXPECT_EQ(StatusCode::OK_200, res->status);
  3285. }
  3286. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3287. SSLClient cli(REDIR_HOST);
  3288. cli.set_follow_location(true);
  3289. Params params;
  3290. params.emplace("url", "http://example.com");
  3291. params.emplace("status_code", "302");
  3292. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3294. EXPECT_EQ(StatusCode::OK_200, res->status);
  3295. }
  3296. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3297. SSLClient cli(REDIR_HOST);
  3298. cli.set_follow_location(true);
  3299. Params params;
  3300. params.emplace("url", "http://example.com");
  3301. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. EXPECT_EQ(StatusCode::OK_200, res->status);
  3304. }
  3305. TEST(UrlWithSpace, Redirect_Online) {
  3306. SSLClient cli("edge.forgecdn.net");
  3307. cli.set_follow_location(true);
  3308. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3310. EXPECT_EQ(StatusCode::OK_200, res->status);
  3311. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3312. }
  3313. #endif
  3314. #if !defined(_WIN32) && !defined(_WIN64)
  3315. TEST(ReceiveSignals, Signal) {
  3316. auto setupSignalHandlers = []() {
  3317. struct sigaction act;
  3318. sigemptyset(&act.sa_mask);
  3319. act.sa_flags = SA_SIGINFO;
  3320. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3321. switch (sig) {
  3322. case SIGINT:
  3323. default: break;
  3324. }
  3325. };
  3326. ::sigaction(SIGINT, &act, nullptr);
  3327. };
  3328. Server svr;
  3329. int port = 0;
  3330. auto thread = std::thread([&]() {
  3331. setupSignalHandlers();
  3332. port = svr.bind_to_any_port(HOST);
  3333. svr.listen_after_bind();
  3334. });
  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. ASSERT_TRUE(svr.is_running());
  3342. pthread_kill(thread.native_handle(), SIGINT);
  3343. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3344. ASSERT_TRUE(svr.is_running());
  3345. }
  3346. #endif
  3347. TEST(RedirectToDifferentPort, Redirect) {
  3348. Server svr1;
  3349. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3350. res.set_content("Hello World!", "text/plain");
  3351. });
  3352. int svr1_port = 0;
  3353. auto thread1 = std::thread([&]() {
  3354. svr1_port = svr1.bind_to_any_port(HOST);
  3355. svr1.listen_after_bind();
  3356. });
  3357. Server svr2;
  3358. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3359. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3360. });
  3361. int svr2_port = 0;
  3362. auto thread2 = std::thread([&]() {
  3363. svr2_port = svr2.bind_to_any_port(HOST);
  3364. svr2.listen_after_bind();
  3365. });
  3366. auto se = detail::scope_exit([&] {
  3367. svr2.stop();
  3368. thread2.join();
  3369. svr1.stop();
  3370. thread1.join();
  3371. ASSERT_FALSE(svr2.is_running());
  3372. ASSERT_FALSE(svr1.is_running());
  3373. });
  3374. svr1.wait_until_ready();
  3375. svr2.wait_until_ready();
  3376. Client cli("localhost", svr2_port);
  3377. cli.set_follow_location(true);
  3378. auto res = cli.Get("/2");
  3379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3380. EXPECT_EQ(StatusCode::OK_200, res->status);
  3381. EXPECT_EQ("Hello World!", res->body);
  3382. }
  3383. // GET /redir on one server redirects to /target on another port, so the
  3384. // client follows it with a new client.
  3385. static Result
  3386. GetThroughRedirectToDifferentPort(Server::Handler target,
  3387. const std::function<void(Client &)> &setup,
  3388. const Headers &headers = Headers()) {
  3389. Server target_svr;
  3390. target_svr.Get("/target", target);
  3391. int target_port = 0;
  3392. auto target_thread = std::thread([&]() {
  3393. target_port = target_svr.bind_to_any_port(HOST);
  3394. target_svr.listen_after_bind();
  3395. });
  3396. Server origin_svr;
  3397. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3398. res.set_redirect(
  3399. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3400. });
  3401. int origin_port = 0;
  3402. auto origin_thread = std::thread([&]() {
  3403. origin_port = origin_svr.bind_to_any_port(HOST);
  3404. origin_svr.listen_after_bind();
  3405. });
  3406. auto se = detail::scope_exit([&] {
  3407. origin_svr.stop();
  3408. origin_thread.join();
  3409. target_svr.stop();
  3410. target_thread.join();
  3411. });
  3412. target_svr.wait_until_ready();
  3413. origin_svr.wait_until_ready();
  3414. Client cli("localhost", origin_port);
  3415. cli.set_follow_location(true);
  3416. setup(cli);
  3417. return cli.Get("/redir", headers);
  3418. }
  3419. static void
  3420. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3421. std::string captured_authorization;
  3422. auto result = GetThroughRedirectToDifferentPort(
  3423. [&](const Request &req, Response &res) {
  3424. captured_authorization = req.get_header_value("Authorization");
  3425. res.set_content("OK", "text/plain");
  3426. },
  3427. set_auth);
  3428. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3429. EXPECT_EQ(StatusCode::OK_200, result->status);
  3430. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3431. EXPECT_TRUE(captured_authorization.empty());
  3432. }
  3433. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3434. TestDoNotForwardCredentialsOnRedirect(
  3435. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3436. }
  3437. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3438. TestDoNotForwardCredentialsOnRedirect(
  3439. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3440. }
  3441. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3442. std::string captured_cookie;
  3443. auto result = GetThroughRedirectToDifferentPort(
  3444. [&](const Request &req, Response &res) {
  3445. captured_cookie = req.get_header_value("Cookie");
  3446. res.set_content("OK", "text/plain");
  3447. },
  3448. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3449. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3450. EXPECT_EQ(StatusCode::OK_200, result->status);
  3451. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3452. EXPECT_TRUE(captured_cookie.empty());
  3453. }
  3454. TEST(RedirectToSamePort, ForwardCookie) {
  3455. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3456. // header so that ordinary session flows keep working.
  3457. Server svr;
  3458. std::string captured_cookie;
  3459. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3460. res.set_redirect("/target", 302);
  3461. });
  3462. svr.Get("/target", [&](const Request &req, Response &res) {
  3463. captured_cookie = req.get_header_value("Cookie");
  3464. res.set_content("OK", "text/plain");
  3465. });
  3466. auto port = svr.bind_to_any_port(HOST);
  3467. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3468. auto se = detail::scope_exit([&] {
  3469. svr.stop();
  3470. thread.join();
  3471. ASSERT_FALSE(svr.is_running());
  3472. });
  3473. svr.wait_until_ready();
  3474. Client cli(HOST, port);
  3475. cli.set_follow_location(true);
  3476. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3477. auto res = cli.Get("/redir", headers);
  3478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3479. EXPECT_EQ(StatusCode::OK_200, res->status);
  3480. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3481. }
  3482. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3483. std::string authorization;
  3484. std::string trace_id;
  3485. auto result = GetThroughRedirectToDifferentPort(
  3486. [&](const Request &req, Response &res) {
  3487. authorization = req.get_header_value("Authorization");
  3488. trace_id = req.get_header_value("X-Trace-Id");
  3489. res.set_content("OK", "text/plain");
  3490. },
  3491. [](Client &cli) {
  3492. cli.set_default_headers(
  3493. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3494. });
  3495. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3496. EXPECT_EQ(StatusCode::OK_200, result->status);
  3497. // Like a header given with the request, a default one goes along unless it
  3498. // carries credentials (RFC 9110 15.4).
  3499. EXPECT_TRUE(authorization.empty());
  3500. EXPECT_EQ("42", trace_id);
  3501. }
  3502. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3503. auto result = GetThroughRedirectToDifferentPort(
  3504. [](const Request &, Response &res) {
  3505. res.set_content(std::string(2048, 'x'), "text/plain");
  3506. },
  3507. [](Client &cli) { cli.set_payload_max_length(1024); });
  3508. EXPECT_FALSE(result);
  3509. }
  3510. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3511. auto result = GetThroughRedirectToDifferentPort(
  3512. [](const Request &req, Response &res) {
  3513. // Answer after a second, or once the client gives up.
  3514. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3515. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3516. }
  3517. res.set_content("late", "text/plain");
  3518. },
  3519. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3520. ASSERT_FALSE(result);
  3521. EXPECT_EQ(Error::Read, result.error());
  3522. }
  3523. #ifdef CPPHTTPLIB_SSL_ENABLED
  3524. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3525. auto result = GetThroughRedirectToDifferentPort(
  3526. [](const Request &, Response &res) {
  3527. res.status = StatusCode::Unauthorized_401;
  3528. res.set_header("WWW-Authenticate",
  3529. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3530. },
  3531. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3532. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3533. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3534. }
  3535. #endif
  3536. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3537. Server svr;
  3538. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3539. // Port number that overflows int — should not crash
  3540. res.set_redirect("http://localhost:99999999999999999999/target");
  3541. });
  3542. auto port = svr.bind_to_any_port(HOST);
  3543. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3544. auto se = detail::scope_exit([&] {
  3545. svr.stop();
  3546. thread.join();
  3547. ASSERT_FALSE(svr.is_running());
  3548. });
  3549. svr.wait_until_ready();
  3550. Client cli(HOST, port);
  3551. cli.set_follow_location(true);
  3552. auto res = cli.Get("/redir");
  3553. // Should fail gracefully, not crash (no valid response due to bad port)
  3554. EXPECT_FALSE(res);
  3555. }
  3556. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3557. Server svr;
  3558. auto port = svr.bind_to_any_port(HOST);
  3559. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3560. // The server's own port followed by junk must not be followed
  3561. res.set_redirect("http://" + std::string(HOST) + ":" +
  3562. std::to_string(port) + "junk/target");
  3563. });
  3564. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3565. res.set_content("target", "text/plain");
  3566. });
  3567. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3568. auto se = detail::scope_exit([&] {
  3569. svr.stop();
  3570. thread.join();
  3571. ASSERT_FALSE(svr.is_running());
  3572. });
  3573. svr.wait_until_ready();
  3574. Client cli(HOST, port);
  3575. cli.set_follow_location(true);
  3576. auto res = cli.Get("/redir");
  3577. EXPECT_FALSE(res);
  3578. }
  3579. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3580. Server svr;
  3581. std::atomic<bool> followed{false};
  3582. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3583. res.status = StatusCode::NotModified_304;
  3584. res.set_header("Location", "/target");
  3585. });
  3586. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3587. res.status = StatusCode::UseProxy_305;
  3588. res.set_header("Location", "/target");
  3589. });
  3590. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3591. followed = true;
  3592. res.set_content("target", "text/plain");
  3593. });
  3594. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3595. auto se = detail::scope_exit([&] {
  3596. svr.stop();
  3597. th.join();
  3598. ASSERT_FALSE(svr.is_running());
  3599. });
  3600. svr.wait_until_ready();
  3601. Client cli("localhost", PORT);
  3602. cli.set_follow_location(true);
  3603. auto res = cli.Get("/304");
  3604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3605. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3606. res = cli.Get("/305");
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3609. EXPECT_FALSE(followed);
  3610. }
  3611. TEST(RedirectFromPageWithContent, Redirect) {
  3612. Server svr;
  3613. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3614. res.set_content("___", "text/plain");
  3615. res.set_redirect("/2");
  3616. });
  3617. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3618. res.set_content("Hello World!", "text/plain");
  3619. });
  3620. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3621. auto se = detail::scope_exit([&] {
  3622. svr.stop();
  3623. th.join();
  3624. ASSERT_FALSE(svr.is_running());
  3625. });
  3626. svr.wait_until_ready();
  3627. {
  3628. Client cli("localhost", PORT);
  3629. cli.set_follow_location(true);
  3630. std::string body;
  3631. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3632. body.append(data, data_length);
  3633. return true;
  3634. });
  3635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3636. EXPECT_EQ(StatusCode::OK_200, res->status);
  3637. EXPECT_EQ("Hello World!", body);
  3638. }
  3639. {
  3640. Client cli("localhost", PORT);
  3641. std::string body;
  3642. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3643. body.append(data, data_length);
  3644. return true;
  3645. });
  3646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3647. EXPECT_EQ(StatusCode::Found_302, res->status);
  3648. EXPECT_EQ("___", body);
  3649. }
  3650. }
  3651. // A server can close the connection after a request with "Connection: close"
  3652. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3653. // redirected request must go out on a new connection.
  3654. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3655. #ifndef _WIN32
  3656. signal(SIGPIPE, SIG_IGN);
  3657. #endif
  3658. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3659. default_socket_options(srv);
  3660. sockaddr_in addr{};
  3661. addr.sin_family = AF_INET;
  3662. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3663. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3664. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3665. ASSERT_EQ(0, ::listen(srv, 2));
  3666. auto send_text = [](socket_t sock, const std::string &text) {
  3667. ::send(sock,
  3668. #ifdef _WIN32
  3669. static_cast<const char *>(text.c_str()),
  3670. static_cast<int>(text.size()),
  3671. #else
  3672. text.c_str(), text.size(),
  3673. #endif
  3674. 0);
  3675. };
  3676. auto reused = false;
  3677. auto server_thread = std::thread([&] {
  3678. char buf[4096];
  3679. auto first = ::accept(srv, nullptr, nullptr);
  3680. if (first == INVALID_SOCKET) { return; }
  3681. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3682. ::recv(first, buf, sizeof(buf), 0);
  3683. send_text(
  3684. first,
  3685. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3686. auto next = first;
  3687. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3688. reused = true;
  3689. } else {
  3690. detail::close_socket(first);
  3691. next = ::accept(srv, nullptr, nullptr);
  3692. if (next == INVALID_SOCKET) { return; }
  3693. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3694. ::recv(next, buf, sizeof(buf), 0);
  3695. }
  3696. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3697. "Connection: close\r\n\r\nok");
  3698. detail::close_socket(next);
  3699. });
  3700. Client cli("127.0.0.1", PORT + 2);
  3701. cli.set_follow_location(true);
  3702. cli.set_read_timeout(5, 0);
  3703. auto res = cli.Get("/1");
  3704. server_thread.join();
  3705. detail::close_socket(srv);
  3706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3707. EXPECT_EQ(StatusCode::OK_200, res->status);
  3708. EXPECT_EQ("ok", res->body);
  3709. EXPECT_FALSE(reused);
  3710. }
  3711. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3712. Server svr;
  3713. auto port_str = std::to_string(PORT);
  3714. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3715. auto expected_host = "[::1]:" + port_str;
  3716. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3717. res.set_content("___", "text/plain");
  3718. // res.set_redirect("/2");
  3719. res.set_redirect(redirect_url);
  3720. });
  3721. svr.Get("/2", [&](const Request &req, Response &res) {
  3722. auto host_header = req.headers.find("Host");
  3723. ASSERT_TRUE(host_header != req.headers.end());
  3724. EXPECT_EQ(expected_host, host_header->second);
  3725. res.set_content("Hello World!", "text/plain");
  3726. });
  3727. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3728. auto se = detail::scope_exit([&] {
  3729. svr.stop();
  3730. th.join();
  3731. ASSERT_FALSE(svr.is_running());
  3732. });
  3733. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3734. // actually starts anything, so the condition !svr.is_running() will
  3735. // always remain true, and the loop never stops.
  3736. // This basically counts how many milliseconds have passed since the
  3737. // call to svr.listen(), and if after 5 seconds nothing started yet
  3738. // aborts the test.
  3739. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3740. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3741. ASSERT_LT(milliseconds, 5000U);
  3742. }
  3743. {
  3744. Client cli("::1", PORT);
  3745. cli.set_follow_location(true);
  3746. std::string body;
  3747. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3748. body.append(data, data_length);
  3749. return true;
  3750. });
  3751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3752. EXPECT_EQ(StatusCode::OK_200, res->status);
  3753. EXPECT_EQ("Hello World!", body);
  3754. }
  3755. {
  3756. Client cli("::1", PORT);
  3757. std::string body;
  3758. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3759. body.append(data, data_length);
  3760. return true;
  3761. });
  3762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3763. EXPECT_EQ(StatusCode::Found_302, res->status);
  3764. EXPECT_EQ("___", body);
  3765. }
  3766. }
  3767. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3768. Server svr;
  3769. svr.Get("/foo", [](const Request &req, Response &res) {
  3770. auto a = req.params.find("a");
  3771. if (a != req.params.end()) {
  3772. res.set_content((*a).second, "text/plain");
  3773. res.status = StatusCode::OK_200;
  3774. } else {
  3775. res.status = StatusCode::BadRequest_400;
  3776. }
  3777. });
  3778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3779. auto se = detail::scope_exit([&] {
  3780. svr.stop();
  3781. thread.join();
  3782. ASSERT_FALSE(svr.is_running());
  3783. });
  3784. svr.wait_until_ready();
  3785. {
  3786. Client cli(HOST, PORT);
  3787. cli.set_path_encode(false);
  3788. auto res = cli.Get("/foo?a=explicitly+encoded");
  3789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3790. EXPECT_EQ(StatusCode::OK_200, res->status);
  3791. // This expects it back with a space, as the `+` won't have been
  3792. // url-encoded, and server-side the params get decoded turning `+`
  3793. // into spaces.
  3794. EXPECT_EQ("explicitly encoded", res->body);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3798. // When path encoding is disabled the client must transmit the supplied
  3799. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3800. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3801. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3802. // than a space (0x20). Assert on the raw wire target to catch this.
  3803. Server svr;
  3804. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3805. svr.Get("/foo", [&](const Request &req, Response &res) {
  3806. EXPECT_EQ(expected_target, req.target);
  3807. res.status = StatusCode::OK_200;
  3808. });
  3809. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. Client cli(HOST, PORT);
  3818. cli.set_path_encode(false);
  3819. auto res = cli.Get(expected_target.c_str());
  3820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3821. EXPECT_EQ(StatusCode::OK_200, res->status);
  3822. }
  3823. }
  3824. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3825. // `open_stream()` used to skip the path encoding that the buffered send
  3826. // path applies, so the same `path` produced different bytes in the request
  3827. // line depending on which API was used. Assert the two agree.
  3828. Server svr;
  3829. std::string target;
  3830. svr.Get(".*", [&](const Request &req, Response &res) {
  3831. target = req.target;
  3832. res.status = StatusCode::OK_200;
  3833. });
  3834. auto port = svr.bind_to_any_port(HOST);
  3835. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3836. auto se = detail::scope_exit([&] {
  3837. svr.stop();
  3838. thread.join();
  3839. ASSERT_FALSE(svr.is_running());
  3840. });
  3841. svr.wait_until_ready();
  3842. struct {
  3843. const char *path;
  3844. const char *expected;
  3845. } cases[] = {
  3846. {"/a b?x=1", "/a%20b?x=1"},
  3847. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3848. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3849. };
  3850. for (const auto &c : cases) {
  3851. Client cli(HOST, port);
  3852. target.clear();
  3853. auto res = cli.Get(c.path);
  3854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3855. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3856. auto buffered_target = target;
  3857. target.clear();
  3858. auto handle = cli.open_stream("GET", c.path);
  3859. EXPECT_TRUE(handle.is_valid())
  3860. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3861. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3862. }
  3863. }
  3864. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3865. // The `set_path_encode(false)` contract — transmit the supplied target
  3866. // verbatim — must hold for the streaming API too.
  3867. Server svr;
  3868. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3869. std::string target;
  3870. svr.Get("/foo", [&](const Request &req, Response &res) {
  3871. target = req.target;
  3872. res.status = StatusCode::OK_200;
  3873. });
  3874. auto port = svr.bind_to_any_port(HOST);
  3875. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3876. auto se = detail::scope_exit([&] {
  3877. svr.stop();
  3878. thread.join();
  3879. ASSERT_FALSE(svr.is_running());
  3880. });
  3881. svr.wait_until_ready();
  3882. {
  3883. Client cli(HOST, port);
  3884. cli.set_path_encode(false);
  3885. auto handle = cli.open_stream("GET", expected_target);
  3886. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3887. EXPECT_EQ(expected_target, target);
  3888. }
  3889. }
  3890. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3891. // With path encoding enabled a CR/LF in the target is percent-encoded
  3892. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3893. // write_request_line still backstops `set_path_encode(false)`, which is
  3894. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3895. Server svr;
  3896. // Captured before routing: the decoded path contains a newline, which a
  3897. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3898. std::string target;
  3899. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3900. target = req.target;
  3901. res.status = StatusCode::OK_200;
  3902. return Server::HandlerResponse::Handled;
  3903. });
  3904. auto port = svr.bind_to_any_port(HOST);
  3905. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3906. auto se = detail::scope_exit([&] {
  3907. svr.stop();
  3908. thread.join();
  3909. ASSERT_FALSE(svr.is_running());
  3910. });
  3911. svr.wait_until_ready();
  3912. {
  3913. Client cli(HOST, port);
  3914. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3915. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3916. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3917. }
  3918. }
  3919. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3920. // Every control character is percent-encoded, not just CR/LF, so the target
  3921. // passes the request-target check in write_request_line.
  3922. Server svr;
  3923. std::string target;
  3924. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3925. target = req.target;
  3926. res.status = StatusCode::OK_200;
  3927. return Server::HandlerResponse::Handled;
  3928. });
  3929. auto port = svr.bind_to_any_port(HOST);
  3930. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3931. auto se = detail::scope_exit([&] {
  3932. svr.stop();
  3933. thread.join();
  3934. ASSERT_FALSE(svr.is_running());
  3935. });
  3936. svr.wait_until_ready();
  3937. {
  3938. Client cli(HOST, port);
  3939. auto res = cli.Get("/a\tb\x1b\x7f");
  3940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3941. EXPECT_EQ("/a%09b%1B%7F", target);
  3942. }
  3943. }
  3944. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3945. // Nothing may reach the wire: a raw CR/LF target would split the request
  3946. // line and inject headers.
  3947. Server svr;
  3948. // Pre-routing so that "not called" means nothing reached the server at all,
  3949. // rather than merely failing to match a handler pattern.
  3950. auto handler_called = false;
  3951. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3952. handler_called = true;
  3953. res.status = StatusCode::OK_200;
  3954. return Server::HandlerResponse::Handled;
  3955. });
  3956. auto port = svr.bind_to_any_port(HOST);
  3957. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3958. auto se = detail::scope_exit([&] {
  3959. svr.stop();
  3960. thread.join();
  3961. ASSERT_FALSE(svr.is_running());
  3962. });
  3963. svr.wait_until_ready();
  3964. {
  3965. Client cli(HOST, port);
  3966. cli.set_path_encode(false);
  3967. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3968. EXPECT_FALSE(handle.is_valid());
  3969. EXPECT_EQ(Error::Write, handle.error);
  3970. EXPECT_FALSE(handler_called);
  3971. }
  3972. }
  3973. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3974. // Which of the two branches runs is decided by whether the query component
  3975. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3976. // an empty query and must still fall back to building one from
  3977. // `req.params`, while a non-empty query must win over `req.params`.
  3978. Server svr;
  3979. std::string target;
  3980. svr.Get("/foo", [&](const Request &req, Response &res) {
  3981. target = req.target;
  3982. res.status = StatusCode::OK_200;
  3983. });
  3984. auto port = svr.bind_to_any_port(HOST);
  3985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3986. auto se = detail::scope_exit([&] {
  3987. svr.stop();
  3988. thread.join();
  3989. ASSERT_FALSE(svr.is_running());
  3990. });
  3991. svr.wait_until_ready();
  3992. {
  3993. // Trailing `?` -> empty query component -> `req.params` is used.
  3994. Client cli(HOST, port);
  3995. Request req;
  3996. req.method = "GET";
  3997. req.path = "/foo?";
  3998. req.params.emplace("a", "1");
  3999. target.clear();
  4000. auto res = cli.send(req);
  4001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4002. EXPECT_EQ("/foo?a=1", target);
  4003. }
  4004. {
  4005. // Non-empty query in `req.path` -> `req.params` is not appended.
  4006. Client cli(HOST, port);
  4007. Request req;
  4008. req.method = "GET";
  4009. req.path = "/foo?b=2";
  4010. req.params.emplace("a", "1");
  4011. target.clear();
  4012. auto res = cli.send(req);
  4013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4014. EXPECT_EQ("/foo?b=2", target);
  4015. }
  4016. }
  4017. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4018. Server svr;
  4019. svr.Get("/", [](const Request &req, Response &) {
  4020. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4021. });
  4022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4023. auto se = detail::scope_exit([&] {
  4024. svr.stop();
  4025. thread.join();
  4026. ASSERT_FALSE(svr.is_running());
  4027. });
  4028. svr.wait_until_ready();
  4029. {
  4030. Client cli(HOST, PORT);
  4031. cli.set_path_encode(false);
  4032. auto res = cli.Get("/?something=%0A");
  4033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4034. EXPECT_EQ(StatusCode::OK_200, res->status);
  4035. }
  4036. }
  4037. TEST(BindServerTest, BindDualStack) {
  4038. Server svr;
  4039. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4040. res.set_content("Hello World!", "text/plain");
  4041. });
  4042. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4043. auto se = detail::scope_exit([&] {
  4044. svr.stop();
  4045. thread.join();
  4046. ASSERT_FALSE(svr.is_running());
  4047. });
  4048. svr.wait_until_ready();
  4049. {
  4050. Client cli("127.0.0.1", PORT);
  4051. auto res = cli.Get("/1");
  4052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4053. EXPECT_EQ(StatusCode::OK_200, res->status);
  4054. EXPECT_EQ("Hello World!", res->body);
  4055. }
  4056. {
  4057. Client cli("::1", PORT);
  4058. auto res = cli.Get("/1");
  4059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4060. EXPECT_EQ(StatusCode::OK_200, res->status);
  4061. EXPECT_EQ("Hello World!", res->body);
  4062. }
  4063. }
  4064. TEST(BindServerTest, BindAndListenSeparately) {
  4065. Server svr;
  4066. int port = svr.bind_to_any_port("0.0.0.0");
  4067. ASSERT_TRUE(svr.is_valid());
  4068. ASSERT_TRUE(port > 0);
  4069. svr.stop();
  4070. }
  4071. // Reports whether anything is still listening on a loopback port. A plain
  4072. // connect() is used instead of a Client request because a socket left bound by
  4073. // mistake accepts the connection into its backlog and never answers, which
  4074. // would hang the test instead of failing it.
  4075. static bool is_loopback_port_accepting(int port) {
  4076. sockaddr_in addr{};
  4077. addr.sin_family = AF_INET;
  4078. addr.sin_port = htons(static_cast<uint16_t>(port));
  4079. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4080. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4081. EXPECT_NE(sock, INVALID_SOCKET);
  4082. if (sock == INVALID_SOCKET) { return false; }
  4083. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4084. static_cast<socklen_t>(sizeof(addr)));
  4085. detail::close_socket(sock);
  4086. return ret == 0;
  4087. }
  4088. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4089. Server svr;
  4090. auto port = svr.bind_to_any_port("127.0.0.1");
  4091. ASSERT_TRUE(port > 0);
  4092. svr.stop();
  4093. // bind_to_any_port() already called listen(2), so until stop() closed the
  4094. // descriptor the port kept accepting connections into the backlog. ASSERT
  4095. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4096. // below blocks forever in the accept loop.
  4097. ASSERT_FALSE(is_loopback_port_accepting(port));
  4098. // Nothing is left to accept on, so listen_after_bind() must report failure
  4099. // instead of returning success without ever serving.
  4100. EXPECT_FALSE(svr.listen_after_bind());
  4101. // The failed listen marks the server decommissioned, so a waiter returns
  4102. // instead of spinning forever.
  4103. svr.wait_until_ready();
  4104. }
  4105. #ifdef CPPHTTPLIB_SSL_ENABLED
  4106. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4107. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4108. CLIENT_CA_CERT_DIR);
  4109. int port = svr.bind_to_any_port("0.0.0.0");
  4110. ASSERT_TRUE(svr.is_valid());
  4111. ASSERT_TRUE(port > 0);
  4112. svr.stop();
  4113. }
  4114. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4115. // or a rejected CustomRoute() registration would not stop the server binding.
  4116. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4118. CLIENT_CA_CERT_DIR);
  4119. ASSERT_TRUE(svr.is_valid());
  4120. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4121. EXPECT_FALSE(svr.is_valid());
  4122. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4123. }
  4124. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4125. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4126. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4127. int port = svr.bind_to_any_port("0.0.0.0");
  4128. ASSERT_TRUE(svr.is_valid());
  4129. ASSERT_TRUE(port > 0);
  4130. svr.stop();
  4131. }
  4132. TEST(BindServerTest, UpdateCertsPem) {
  4133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4134. int port = svr.bind_to_any_port("0.0.0.0");
  4135. ASSERT_TRUE(svr.is_valid());
  4136. ASSERT_TRUE(port > 0);
  4137. // Read PEM files
  4138. std::string cert_pem, key_pem, ca_pem;
  4139. read_file(SERVER_CERT_FILE, cert_pem);
  4140. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4141. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4142. // Update server certificates using PEM API
  4143. ASSERT_TRUE(
  4144. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4145. ASSERT_TRUE(svr.is_valid());
  4146. svr.stop();
  4147. }
  4148. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4149. // Start server with client CA (enables client auth)
  4150. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4151. ASSERT_TRUE(svr.is_valid());
  4152. bool handler_called = false;
  4153. svr.Get("/test", [&](const Request &req, Response &res) {
  4154. handler_called = true;
  4155. // Verify client certificate is present
  4156. auto cert = req.peer_cert();
  4157. EXPECT_TRUE(static_cast<bool>(cert));
  4158. res.set_content("ok", "text/plain");
  4159. });
  4160. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4161. auto se = detail::scope_exit([&] {
  4162. svr.stop();
  4163. t.join();
  4164. ASSERT_FALSE(svr.is_running());
  4165. });
  4166. svr.wait_until_ready();
  4167. // Read PEM files
  4168. std::string cert_pem, key_pem, ca_pem;
  4169. read_file(SERVER_CERT_FILE, cert_pem);
  4170. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4171. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4172. // Update server certificates and client CA using PEM API while server running
  4173. ASSERT_TRUE(
  4174. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4175. // Connect with client certificate
  4176. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4177. cli.enable_server_certificate_verification(false);
  4178. cli.set_connection_timeout(30);
  4179. auto res = cli.Get("/test");
  4180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4181. ASSERT_EQ(StatusCode::OK_200, res->status);
  4182. ASSERT_TRUE(handler_called);
  4183. EXPECT_EQ("ok", res->body);
  4184. }
  4185. // Puts a CA that did not sign the client's certificate in the old one's place.
  4186. static bool replace_client_ca(SSLServer &svr) {
  4187. std::string cert_pem, key_pem, ca_pem;
  4188. read_file(SERVER_CERT_FILE, cert_pem);
  4189. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4190. read_file(SERVER_CERT2_FILE, ca_pem);
  4191. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4192. ca_pem.c_str());
  4193. }
  4194. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4196. ASSERT_TRUE(svr.is_valid());
  4197. svr.Get("/test", [](const Request &, Response &res) {
  4198. res.set_content("ok", "text/plain");
  4199. });
  4200. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4201. auto se = detail::scope_exit([&] {
  4202. svr.stop();
  4203. t.join();
  4204. ASSERT_FALSE(svr.is_running());
  4205. });
  4206. svr.wait_until_ready();
  4207. auto get = [] {
  4208. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4209. cli.enable_server_certificate_verification(false);
  4210. return cli.Get("/test");
  4211. };
  4212. ASSERT_TRUE(get());
  4213. ASSERT_TRUE(replace_client_ca(svr));
  4214. EXPECT_FALSE(get());
  4215. }
  4216. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4217. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4219. ASSERT_TRUE(svr.is_valid());
  4220. tls::set_verify_callback(svr.tls_context(),
  4221. [](const tls::VerifyContext &) -> bool {
  4222. throw std::runtime_error("verify");
  4223. });
  4224. svr.Get("/test", [](const Request &, Response &res) {
  4225. res.set_content("ok", "text/plain");
  4226. });
  4227. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4228. auto se = detail::scope_exit([&] {
  4229. svr.stop();
  4230. t.join();
  4231. ASSERT_FALSE(svr.is_running());
  4232. });
  4233. svr.wait_until_ready();
  4234. auto get = [] {
  4235. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4236. cli.enable_server_certificate_verification(false);
  4237. return cli.Get("/test");
  4238. };
  4239. EXPECT_FALSE(get());
  4240. // The handshake is over, so an update does not wait for it.
  4241. std::string cert_pem, key_pem;
  4242. read_file(SERVER_CERT_FILE, cert_pem);
  4243. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4244. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4245. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4246. return v.preverify_ok;
  4247. });
  4248. auto res = get();
  4249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4250. EXPECT_EQ("ok", res->body);
  4251. }
  4252. #endif
  4253. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4254. // Sends each request over a new connection with a client certificate,
  4255. // resuming the session of the one before when there is one.
  4256. class ResumingClient {
  4257. public:
  4258. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4259. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4260. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4261. SSL_FILETYPE_PEM);
  4262. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4263. // callback, not through SSL_get1_session().
  4264. SSL_CTX_set_app_data(ctx_, this);
  4265. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4266. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4267. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4268. auto self = static_cast<ResumingClient *>(
  4269. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4270. SSL_SESSION_free(self->session_);
  4271. self->session_ = session;
  4272. return 1; // Keeps the reference
  4273. });
  4274. }
  4275. ~ResumingClient() {
  4276. SSL_SESSION_free(session_);
  4277. SSL_CTX_free(ctx_);
  4278. }
  4279. // Tells whether the request was answered.
  4280. bool get() {
  4281. auto error = Error::Success;
  4282. auto sock = detail::create_client_socket(
  4283. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4284. /*connection_timeout_sec=*/5, 0,
  4285. /*read_timeout_sec=*/5, 0,
  4286. /*write_timeout_sec=*/5, 0, std::string(), error);
  4287. if (sock == INVALID_SOCKET) { return false; }
  4288. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4289. auto ssl = SSL_new(ctx_);
  4290. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4291. SSL_set_fd(ssl, static_cast<int>(sock));
  4292. if (session_) { SSL_set_session(ssl, session_); }
  4293. if (SSL_connect(ssl) != 1) { return false; }
  4294. reused_ = SSL_session_reused(ssl) == 1;
  4295. // Reading the response also takes in a TLS 1.3 session ticket.
  4296. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4297. "Connection: close\r\n\r\n";
  4298. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4299. std::string res;
  4300. char buf[256];
  4301. int n;
  4302. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4303. res.append(buf, static_cast<size_t>(n));
  4304. }
  4305. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4306. SSL_shutdown(ssl);
  4307. return res.find("200 OK") != std::string::npos;
  4308. }
  4309. // Whether the last connection resumed a session
  4310. bool reused() const { return reused_; }
  4311. private:
  4312. SSL_CTX *ctx_;
  4313. SSL_SESSION *session_ = nullptr;
  4314. bool reused_ = false;
  4315. };
  4316. // A client that resumes its session gets through, but not once the client CA
  4317. // has changed, as a resumed session does not show the certificate again.
  4318. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4320. ASSERT_TRUE(svr.is_valid());
  4321. svr.Get("/test", [](const Request &, Response &res) {
  4322. res.set_content("ok", "text/plain");
  4323. });
  4324. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4325. auto se = detail::scope_exit([&] {
  4326. svr.stop();
  4327. t.join();
  4328. ASSERT_FALSE(svr.is_running());
  4329. });
  4330. svr.wait_until_ready();
  4331. ResumingClient cli;
  4332. ASSERT_TRUE(cli.get());
  4333. ASSERT_TRUE(cli.get());
  4334. EXPECT_TRUE(cli.reused());
  4335. ASSERT_TRUE(replace_client_ca(svr));
  4336. EXPECT_FALSE(cli.get());
  4337. }
  4338. // A resumed session does not show the certificate again, so the server does
  4339. // not resume one with a verify callback to run on it.
  4340. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4342. ASSERT_TRUE(svr.is_valid());
  4343. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4344. return v.preverify_ok;
  4345. });
  4346. svr.Get("/test", [](const Request &, Response &res) {
  4347. res.set_content("ok", "text/plain");
  4348. });
  4349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4350. auto se = detail::scope_exit([&] {
  4351. svr.stop();
  4352. t.join();
  4353. ASSERT_FALSE(svr.is_running());
  4354. });
  4355. svr.wait_until_ready();
  4356. ResumingClient cli;
  4357. ASSERT_TRUE(cli.get());
  4358. ASSERT_TRUE(cli.get());
  4359. EXPECT_FALSE(cli.reused());
  4360. }
  4361. #endif
  4362. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4363. // wolfSSL shares its session cache between contexts, so a resumed session
  4364. // could carry a client certificate checked against another server's CA, or
  4365. // against a client CA since replaced.
  4366. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4367. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4368. ASSERT_TRUE(svr.is_valid());
  4369. // Trusts a CA that did not sign the client's certificate.
  4370. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4371. ASSERT_TRUE(other.is_valid());
  4372. for (auto s : {&svr, &other}) {
  4373. s->Get("/test", [](const Request &, Response &res) {
  4374. res.set_content("ok", "text/plain");
  4375. });
  4376. }
  4377. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4378. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4379. auto se = detail::scope_exit([&] {
  4380. other.stop();
  4381. svr.stop();
  4382. t2.join();
  4383. t.join();
  4384. });
  4385. svr.wait_until_ready();
  4386. other.wait_until_ready();
  4387. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4388. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4389. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4390. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4391. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4392. ASSERT_EQ(WOLFSSL_SUCCESS,
  4393. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4394. WOLFSSL_FILETYPE_PEM));
  4395. WOLFSSL_SESSION *session = nullptr;
  4396. auto session_se = detail::scope_exit([&] {
  4397. if (session) { wolfSSL_SESSION_free(session); }
  4398. });
  4399. // A request over a new connection, resuming `session` when there is one and
  4400. // keeping the connection's own in its place. Tells whether it was answered.
  4401. auto get = [&](int port) {
  4402. auto error = Error::Success;
  4403. auto sock = detail::create_client_socket(
  4404. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4405. /*connection_timeout_sec=*/5, 0,
  4406. /*read_timeout_sec=*/5, 0,
  4407. /*write_timeout_sec=*/5, 0, std::string(), error);
  4408. if (sock == INVALID_SOCKET) { return false; }
  4409. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4410. auto ssl = wolfSSL_new(ctx);
  4411. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4412. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4413. if (session) { wolfSSL_set_session(ssl, session); }
  4414. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4415. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4416. "Connection: close\r\n\r\n";
  4417. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4418. std::string res;
  4419. char buf[256];
  4420. int n;
  4421. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4422. res.append(buf, static_cast<size_t>(n));
  4423. }
  4424. wolfSSL_shutdown(ssl);
  4425. if (session) { wolfSSL_SESSION_free(session); }
  4426. session = wolfSSL_get1_session(ssl);
  4427. return res.find("200 OK") != std::string::npos;
  4428. };
  4429. ASSERT_TRUE(get(PORT));
  4430. EXPECT_FALSE(get(PORT + 1));
  4431. ASSERT_TRUE(get(PORT));
  4432. ASSERT_TRUE(replace_client_ca(svr));
  4433. EXPECT_FALSE(get(PORT));
  4434. }
  4435. #endif
  4436. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4437. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4438. ASSERT_TRUE(svr.is_valid());
  4439. svr.Get("/test", [](const Request &, Response &res) {
  4440. res.set_content("ok", "text/plain");
  4441. });
  4442. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4443. auto se = detail::scope_exit([&] {
  4444. svr.stop();
  4445. t.join();
  4446. ASSERT_FALSE(svr.is_running());
  4447. });
  4448. svr.wait_until_ready();
  4449. // A connection that sends no ClientHello keeps its handshake in progress,
  4450. // once the server has had a moment to start it.
  4451. auto error = Error::Success;
  4452. auto sock = detail::create_client_socket(
  4453. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4454. /*connection_timeout_sec=*/5, 0,
  4455. /*read_timeout_sec=*/5, 0,
  4456. /*write_timeout_sec=*/5, 0, std::string(), error);
  4457. ASSERT_NE(INVALID_SOCKET, sock);
  4458. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4459. std::string cert_pem, key_pem;
  4460. read_file(SERVER_CERT_FILE, cert_pem);
  4461. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4462. auto update = std::async(std::launch::async, [&]() {
  4463. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4464. });
  4465. EXPECT_EQ(std::future_status::timeout,
  4466. update.wait_for(std::chrono::milliseconds(200)));
  4467. detail::close_socket(sock);
  4468. EXPECT_TRUE(update.get());
  4469. SSLClient cli(HOST, PORT);
  4470. cli.enable_server_certificate_verification(false);
  4471. auto res = cli.Get("/test");
  4472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4473. EXPECT_EQ(StatusCode::OK_200, res->status);
  4474. }
  4475. #endif
  4476. TEST(ErrorHandlerTest, ContentLength) {
  4477. Server svr;
  4478. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4479. res.status = StatusCode::OK_200;
  4480. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4481. "text/html"); // <= Content-Length still 13
  4482. });
  4483. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4484. res.set_content("Hello World!\n", "text/plain");
  4485. res.status = 524;
  4486. });
  4487. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4488. auto se = detail::scope_exit([&] {
  4489. svr.stop();
  4490. thread.join();
  4491. ASSERT_FALSE(svr.is_running());
  4492. });
  4493. svr.wait_until_ready();
  4494. {
  4495. Client cli(HOST, PORT);
  4496. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4498. EXPECT_EQ(StatusCode::OK_200, res->status);
  4499. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4500. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4501. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4502. }
  4503. }
  4504. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4505. TEST(ExceptionTest, WithoutExceptionHandler) {
  4506. Server svr;
  4507. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4508. throw std::runtime_error("exception...");
  4509. });
  4510. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4511. throw std::runtime_error("exception\r\n...");
  4512. });
  4513. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4514. auto se = detail::scope_exit([&] {
  4515. svr.stop();
  4516. listen_thread.join();
  4517. ASSERT_FALSE(svr.is_running());
  4518. });
  4519. svr.wait_until_ready();
  4520. Client cli("localhost", PORT);
  4521. {
  4522. auto res = cli.Get("/exception");
  4523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4524. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4525. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4526. }
  4527. {
  4528. auto res = cli.Get("/unknown");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4531. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4532. }
  4533. }
  4534. TEST(ExceptionTest, WithExceptionHandler) {
  4535. Server svr;
  4536. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4537. std::exception_ptr ep) {
  4538. EXPECT_FALSE(ep == nullptr);
  4539. try {
  4540. std::rethrow_exception(ep);
  4541. } catch (std::exception &e) {
  4542. EXPECT_EQ("abc", std::string(e.what()));
  4543. } catch (...) {}
  4544. res.status = StatusCode::InternalServerError_500;
  4545. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4546. "text/html"); // <= Content-Length still 13 at this point
  4547. });
  4548. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4549. res.set_content("Hello World!\n", "text/plain");
  4550. throw std::runtime_error("abc");
  4551. });
  4552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4553. auto se = detail::scope_exit([&] {
  4554. svr.stop();
  4555. thread.join();
  4556. ASSERT_FALSE(svr.is_running());
  4557. });
  4558. svr.wait_until_ready();
  4559. for (size_t i = 0; i < 10; i++) {
  4560. Client cli(HOST, PORT);
  4561. for (size_t j = 0; j < 100; j++) {
  4562. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4564. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4565. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4566. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4567. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4568. }
  4569. cli.set_keep_alive(true);
  4570. for (size_t j = 0; j < 100; j++) {
  4571. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4573. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4574. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4575. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4576. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4577. }
  4578. }
  4579. }
  4580. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4581. Server svr;
  4582. svr.set_exception_handler(
  4583. [](const Request &, Response &res, std::exception_ptr) {
  4584. res.set_content("oops", "text/plain");
  4585. });
  4586. svr.Get("/throw", [](const Request &, Response &) {
  4587. throw std::runtime_error("throw");
  4588. });
  4589. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4590. res.status = StatusCode::Created_201;
  4591. throw std::runtime_error("created-then-throw");
  4592. });
  4593. auto port = svr.bind_to_any_port(HOST);
  4594. ASSERT_GT(port, 0);
  4595. thread t = thread([&] { svr.listen_after_bind(); });
  4596. auto se = detail::scope_exit([&] {
  4597. svr.stop();
  4598. t.join();
  4599. ASSERT_FALSE(svr.is_running());
  4600. });
  4601. svr.wait_until_ready();
  4602. Client cli(HOST, port);
  4603. for (auto path : {"/throw", "/created-then-throw"}) {
  4604. auto res = cli.Get(path);
  4605. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4606. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4607. }
  4608. }
  4609. TEST(ExceptionTest, AndErrorHandler) {
  4610. Server svr;
  4611. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4612. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4613. });
  4614. svr.set_exception_handler(
  4615. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4616. EXPECT_FALSE(ep == nullptr);
  4617. try {
  4618. std::rethrow_exception(ep);
  4619. } catch (std::exception &e) {
  4620. res.set_content(e.what(), "text/html");
  4621. } catch (...) {}
  4622. res.status = StatusCode::InternalServerError_500;
  4623. });
  4624. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4625. throw std::runtime_error("EXCEPTION");
  4626. });
  4627. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4628. res.set_content("ERROR", "text/html");
  4629. res.status = StatusCode::InternalServerError_500;
  4630. });
  4631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4632. auto se = detail::scope_exit([&] {
  4633. svr.stop();
  4634. thread.join();
  4635. ASSERT_FALSE(svr.is_running());
  4636. });
  4637. svr.wait_until_ready();
  4638. Client cli(HOST, PORT);
  4639. {
  4640. auto res = cli.Get("/exception");
  4641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4642. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4643. EXPECT_EQ("EXCEPTION", res->body);
  4644. }
  4645. {
  4646. auto res = cli.Get("/error");
  4647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4648. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4649. EXPECT_EQ("ERROR", res->body);
  4650. }
  4651. {
  4652. auto res = cli.Get("/invalid");
  4653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4655. EXPECT_EQ("NOT_FOUND", res->body);
  4656. }
  4657. }
  4658. #endif
  4659. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4660. // An exception from a user callback outside process_request()'s try/catch
  4661. // used to unwind into the task queue - which does not catch - and terminate
  4662. // the process. Each test below runs the server on a single worker thread: a
  4663. // guard that catches the exception but still loses the thread would otherwise
  4664. // be hidden by a spare worker serving the follow-up request. Note that a
  4665. // regression here aborts the whole test binary rather than failing one test.
  4666. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4667. Server svr;
  4668. svr.new_task_queue = [] { return new ThreadPool(1); };
  4669. std::atomic<int> reported{0};
  4670. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4671. if (err == Error::UserCallbackException) { reported++; }
  4672. });
  4673. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4674. res.set_content_provider(
  4675. 1024, "text/plain",
  4676. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4677. sink.write("hello", 5);
  4678. throw std::runtime_error("from the content provider");
  4679. });
  4680. });
  4681. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4682. res.set_content("ok", "text/plain");
  4683. });
  4684. auto port = svr.bind_to_any_port(HOST);
  4685. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4686. auto se = detail::scope_exit([&] {
  4687. svr.stop();
  4688. listen_thread.join();
  4689. ASSERT_FALSE(svr.is_running());
  4690. });
  4691. svr.wait_until_ready();
  4692. {
  4693. Client cli(HOST, port);
  4694. cli.set_read_timeout(5, 0);
  4695. EXPECT_FALSE(cli.Get("/throw"));
  4696. }
  4697. EXPECT_TRUE(svr.is_running());
  4698. EXPECT_EQ(1, reported.load());
  4699. // A request on a fresh connection is still served.
  4700. {
  4701. Client cli(HOST, port);
  4702. auto res = cli.Get("/ok");
  4703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. EXPECT_EQ("ok", res->body);
  4706. }
  4707. }
  4708. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4709. Server svr;
  4710. svr.new_task_queue = [] { return new ThreadPool(1); };
  4711. std::atomic<bool> should_throw{true};
  4712. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4713. res.set_content("hi", "text/plain");
  4714. });
  4715. svr.set_post_routing_handler(
  4716. [&](const Request & /*req*/, Response & /*res*/) {
  4717. if (should_throw) {
  4718. throw std::runtime_error("from the post-routing handler");
  4719. }
  4720. });
  4721. auto port = svr.bind_to_any_port(HOST);
  4722. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4723. auto se = detail::scope_exit([&] {
  4724. svr.stop();
  4725. listen_thread.join();
  4726. ASSERT_FALSE(svr.is_running());
  4727. });
  4728. svr.wait_until_ready();
  4729. {
  4730. Client cli(HOST, port);
  4731. cli.set_read_timeout(5, 0);
  4732. EXPECT_FALSE(cli.Get("/hi"));
  4733. }
  4734. EXPECT_TRUE(svr.is_running());
  4735. should_throw = false;
  4736. {
  4737. Client cli(HOST, port);
  4738. auto res = cli.Get("/hi");
  4739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4740. EXPECT_EQ(StatusCode::OK_200, res->status);
  4741. EXPECT_EQ("hi", res->body);
  4742. }
  4743. }
  4744. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4745. // The guard reports the caught exception through the error logger, which is
  4746. // a user callback too. A logger that throws has to be contained as well, or
  4747. // the process would terminate from inside the catch.
  4748. Server svr;
  4749. svr.new_task_queue = [] { return new ThreadPool(1); };
  4750. std::atomic<int> reported{0};
  4751. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4752. if (err == Error::UserCallbackException) {
  4753. reported++;
  4754. throw std::runtime_error("from the error logger");
  4755. }
  4756. });
  4757. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4758. res.set_content_provider(
  4759. 1024, "text/plain",
  4760. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4761. sink.write("hello", 5);
  4762. throw std::runtime_error("from the content provider");
  4763. });
  4764. });
  4765. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4766. res.set_content("ok", "text/plain");
  4767. });
  4768. auto port = svr.bind_to_any_port(HOST);
  4769. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4770. auto se = detail::scope_exit([&] {
  4771. svr.stop();
  4772. listen_thread.join();
  4773. ASSERT_FALSE(svr.is_running());
  4774. });
  4775. svr.wait_until_ready();
  4776. {
  4777. Client cli(HOST, port);
  4778. cli.set_read_timeout(5, 0);
  4779. EXPECT_FALSE(cli.Get("/throw"));
  4780. }
  4781. EXPECT_TRUE(svr.is_running());
  4782. EXPECT_EQ(1, reported.load());
  4783. {
  4784. Client cli(HOST, port);
  4785. auto res = cli.Get("/ok");
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. EXPECT_EQ(StatusCode::OK_200, res->status);
  4788. EXPECT_EQ("ok", res->body);
  4789. }
  4790. }
  4791. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4792. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4793. // so the exception unwinds through the ws::WebSocket object on its way to
  4794. // the guard. None of the HTTP cases above cross that.
  4795. Server svr;
  4796. svr.new_task_queue = [] { return new ThreadPool(1); };
  4797. std::atomic<int> reported{0};
  4798. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4799. if (err == Error::UserCallbackException) { reported++; }
  4800. });
  4801. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4802. throw std::runtime_error("from the WebSocket handler");
  4803. });
  4804. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4805. res.set_content("ok", "text/plain");
  4806. });
  4807. auto port = svr.bind_to_any_port(HOST);
  4808. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4809. auto se = detail::scope_exit([&] {
  4810. svr.stop();
  4811. listen_thread.join();
  4812. ASSERT_FALSE(svr.is_running());
  4813. });
  4814. svr.wait_until_ready();
  4815. {
  4816. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4817. "/ws");
  4818. auto res = client.connect();
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. // The server dropped the connection instead of dying.
  4821. std::string msg;
  4822. EXPECT_FALSE(client.read(msg));
  4823. client.close();
  4824. }
  4825. EXPECT_TRUE(svr.is_running());
  4826. EXPECT_EQ(1, reported.load());
  4827. {
  4828. Client cli(HOST, port);
  4829. auto res = cli.Get("/ok");
  4830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4831. EXPECT_EQ(StatusCode::OK_200, res->status);
  4832. EXPECT_EQ("ok", res->body);
  4833. }
  4834. }
  4835. #ifdef CPPHTTPLIB_SSL_ENABLED
  4836. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4837. // SSLServer::process_and_close_socket() is a separate overload with its own
  4838. // guard, so it is exercised on its own.
  4839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4840. ASSERT_TRUE(svr.is_valid());
  4841. svr.new_task_queue = [] { return new ThreadPool(1); };
  4842. std::atomic<int> reported{0};
  4843. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4844. if (err == Error::UserCallbackException) { reported++; }
  4845. });
  4846. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4847. res.set_content_provider(
  4848. 1024, "text/plain",
  4849. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4850. sink.write("hello", 5);
  4851. throw std::runtime_error("from the content provider");
  4852. });
  4853. });
  4854. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4855. res.set_content("ok", "text/plain");
  4856. });
  4857. auto port = svr.bind_to_any_port(HOST);
  4858. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4859. auto se = detail::scope_exit([&] {
  4860. svr.stop();
  4861. listen_thread.join();
  4862. ASSERT_FALSE(svr.is_running());
  4863. });
  4864. svr.wait_until_ready();
  4865. {
  4866. SSLClient cli(HOST, port);
  4867. cli.enable_server_certificate_verification(false);
  4868. cli.set_read_timeout(5, 0);
  4869. EXPECT_FALSE(cli.Get("/throw"));
  4870. }
  4871. EXPECT_TRUE(svr.is_running());
  4872. EXPECT_EQ(1, reported.load());
  4873. {
  4874. SSLClient cli(HOST, port);
  4875. cli.enable_server_certificate_verification(false);
  4876. auto res = cli.Get("/ok");
  4877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4878. EXPECT_EQ(StatusCode::OK_200, res->status);
  4879. EXPECT_EQ("ok", res->body);
  4880. }
  4881. }
  4882. #endif
  4883. #endif
  4884. TEST(NoContentTest, ContentLength) {
  4885. Server svr;
  4886. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4887. res.status = StatusCode::NoContent_204;
  4888. });
  4889. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4890. auto se = detail::scope_exit([&] {
  4891. svr.stop();
  4892. thread.join();
  4893. ASSERT_FALSE(svr.is_running());
  4894. });
  4895. svr.wait_until_ready();
  4896. {
  4897. Client cli(HOST, PORT);
  4898. auto res = cli.Get("/hi");
  4899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4900. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4901. // RFC 9110 8.6: none in a 204 response
  4902. EXPECT_FALSE(res->has_header("Content-Length"));
  4903. }
  4904. }
  4905. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4906. Server svr;
  4907. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4908. res.set_header("Content-Length", "5");
  4909. res.set_content("hello world", "text/plain");
  4910. });
  4911. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4912. // A body that reads as the last chunk, were it taken as chunked
  4913. res.set_header("Transfer-Encoding", "chunked");
  4914. res.set_content("0\r\n\r\n", "text/plain");
  4915. });
  4916. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4917. res.set_header("Content-Length", "2");
  4918. res.set_content_provider(5, "text/plain",
  4919. [](size_t offset, size_t length, DataSink &sink) {
  4920. sink.write(&"hello"[offset], length);
  4921. return true;
  4922. });
  4923. });
  4924. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4925. res.set_header("Content-Length", "1234");
  4926. });
  4927. thread t = thread([&] { svr.listen(HOST, PORT); });
  4928. auto se = detail::scope_exit([&] {
  4929. svr.stop();
  4930. t.join();
  4931. ASSERT_FALSE(svr.is_running());
  4932. });
  4933. svr.wait_until_ready();
  4934. Client cli(HOST, PORT);
  4935. cli.set_read_timeout(1, 0);
  4936. auto expect_body = [&](const Result &res, const std::string &body) {
  4937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4938. EXPECT_EQ(body, res->body);
  4939. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4940. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4941. };
  4942. Headers identity{{"Accept-Encoding", ""}};
  4943. expect_body(cli.Get("/body", identity), "hello world");
  4944. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4945. expect_body(cli.Get("/body",
  4946. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4947. "he");
  4948. expect_body(cli.Get("/provider", identity), "hello");
  4949. expect_body(cli.Get("/empty", identity), "");
  4950. // A HEAD response may give the length of the body a GET would get.
  4951. auto res = cli.Head("/empty");
  4952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4953. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4954. }
  4955. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4956. Server svr;
  4957. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4958. res.set_content("short", "text/plain");
  4959. });
  4960. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4961. res.body += " with a footer";
  4962. res.set_header("Transfer-Encoding", "chunked");
  4963. });
  4964. thread t = thread([&] { svr.listen(HOST, PORT); });
  4965. auto se = detail::scope_exit([&] {
  4966. svr.stop();
  4967. t.join();
  4968. ASSERT_FALSE(svr.is_running());
  4969. });
  4970. svr.wait_until_ready();
  4971. Client cli(HOST, PORT);
  4972. cli.set_read_timeout(1, 0);
  4973. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. EXPECT_EQ("short with a footer", res->body);
  4976. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4977. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4978. }
  4979. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4980. Server svr;
  4981. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4982. res.set_header("Content-Length", "3");
  4983. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4984. sink.write("abc", 3);
  4985. sink.done();
  4986. return true;
  4987. });
  4988. });
  4989. thread t = thread([&] { svr.listen(HOST, PORT); });
  4990. auto se = detail::scope_exit([&] {
  4991. svr.stop();
  4992. t.join();
  4993. ASSERT_FALSE(svr.is_running());
  4994. });
  4995. svr.wait_until_ready();
  4996. Client cli(HOST, PORT);
  4997. cli.set_keep_alive(true);
  4998. auto res = cli.Get("/");
  4999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5000. EXPECT_EQ("abc", res->body);
  5001. EXPECT_FALSE(res->has_header("Content-Length"));
  5002. EXPECT_EQ("close", res->get_header_value("Connection"));
  5003. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5004. // No body to delimit
  5005. auto head = cli.Head("/");
  5006. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5007. EXPECT_FALSE(head->has_header("Connection"));
  5008. }
  5009. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5010. #ifdef CPPHTTPLIB_SSL_ENABLED
  5011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5012. ASSERT_TRUE(svr.is_valid());
  5013. #else
  5014. Server svr;
  5015. #endif
  5016. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5017. if (req.path == "/routing_handler") {
  5018. res.set_header("PRE_ROUTING", "on");
  5019. res.set_content("Routing Handler", "text/plain");
  5020. return httplib::Server::HandlerResponse::Handled;
  5021. }
  5022. return httplib::Server::HandlerResponse::Unhandled;
  5023. });
  5024. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5025. res.set_content("Error", "text/html");
  5026. });
  5027. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5028. if (req.path == "/routing_handler") {
  5029. res.set_header("POST_ROUTING", "on");
  5030. }
  5031. });
  5032. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5033. res.set_content("Hello World!\n", "text/plain");
  5034. });
  5035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5036. auto se = detail::scope_exit([&] {
  5037. svr.stop();
  5038. thread.join();
  5039. ASSERT_FALSE(svr.is_running());
  5040. });
  5041. svr.wait_until_ready();
  5042. {
  5043. #ifdef CPPHTTPLIB_SSL_ENABLED
  5044. SSLClient cli(HOST, PORT);
  5045. cli.enable_server_certificate_verification(false);
  5046. #else
  5047. Client cli(HOST, PORT);
  5048. #endif
  5049. auto res = cli.Get("/routing_handler");
  5050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5051. EXPECT_EQ(StatusCode::OK_200, res->status);
  5052. EXPECT_EQ("Routing Handler", res->body);
  5053. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5054. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5055. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5056. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5057. }
  5058. {
  5059. #ifdef CPPHTTPLIB_SSL_ENABLED
  5060. SSLClient cli(HOST, PORT);
  5061. cli.enable_server_certificate_verification(false);
  5062. #else
  5063. Client cli(HOST, PORT);
  5064. #endif
  5065. auto res = cli.Get("/hi");
  5066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5067. EXPECT_EQ(StatusCode::OK_200, res->status);
  5068. EXPECT_EQ("Hello World!\n", res->body);
  5069. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5070. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5071. }
  5072. {
  5073. #ifdef CPPHTTPLIB_SSL_ENABLED
  5074. SSLClient cli(HOST, PORT);
  5075. cli.enable_server_certificate_verification(false);
  5076. #else
  5077. Client cli(HOST, PORT);
  5078. #endif
  5079. auto res = cli.Get("/aaa");
  5080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5081. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5082. EXPECT_EQ("Error", res->body);
  5083. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5084. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5085. }
  5086. }
  5087. TEST(RequestHandlerTest, PreRequestHandler) {
  5088. auto route_path = "/user/:user";
  5089. Server svr;
  5090. svr.Get("/hi", [](const Request &, Response &res) {
  5091. res.set_content("hi", "text/plain");
  5092. });
  5093. svr.Get(route_path, [](const Request &req, Response &res) {
  5094. res.set_content(req.path_params.at("user"), "text/plain");
  5095. });
  5096. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5097. if (req.matched_route == route_path) {
  5098. auto user = req.path_params.at("user");
  5099. if (user != "john") {
  5100. res.status = StatusCode::Forbidden_403;
  5101. res.set_content("error", "text/html");
  5102. return Server::HandlerResponse::Handled;
  5103. }
  5104. }
  5105. return Server::HandlerResponse::Unhandled;
  5106. });
  5107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5108. auto se = detail::scope_exit([&] {
  5109. svr.stop();
  5110. thread.join();
  5111. ASSERT_FALSE(svr.is_running());
  5112. });
  5113. svr.wait_until_ready();
  5114. Client cli(HOST, PORT);
  5115. {
  5116. auto res = cli.Get("/hi");
  5117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5118. EXPECT_EQ(StatusCode::OK_200, res->status);
  5119. EXPECT_EQ("hi", res->body);
  5120. }
  5121. {
  5122. auto res = cli.Get("/user/john");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::OK_200, res->status);
  5125. EXPECT_EQ("john", res->body);
  5126. }
  5127. {
  5128. auto res = cli.Get("/user/invalid-user");
  5129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5130. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5131. EXPECT_EQ("error", res->body);
  5132. }
  5133. }
  5134. // The pre-request handler must run before the request body is read, so a
  5135. // rejected request never forces the server to buffer a (potentially large)
  5136. // body. Here the posted body is larger than the payload limit: if the body
  5137. // were read first the server would answer 413, but because the pre-request
  5138. // handler runs first it answers 403 and the body is never read.
  5139. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5140. Server svr;
  5141. svr.set_payload_max_length(8);
  5142. auto handler_ran = false;
  5143. svr.Post("/reject", [&](const Request &req, Response &res) {
  5144. handler_ran = true;
  5145. res.set_content(req.body, "text/plain");
  5146. });
  5147. svr.Post("/accept", [](const Request &req, Response &res) {
  5148. res.set_content(req.body, "text/plain");
  5149. });
  5150. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5151. if (req.matched_route == "/reject") {
  5152. res.status = StatusCode::Forbidden_403;
  5153. res.set_content("denied", "text/plain");
  5154. return Server::HandlerResponse::Handled;
  5155. }
  5156. return Server::HandlerResponse::Unhandled;
  5157. });
  5158. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5159. auto se = detail::scope_exit([&] {
  5160. svr.stop();
  5161. thread.join();
  5162. ASSERT_FALSE(svr.is_running());
  5163. });
  5164. svr.wait_until_ready();
  5165. Client cli(HOST, PORT);
  5166. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5167. // rejects with 403 before the body is read, so 413 is never reached.
  5168. {
  5169. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5171. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5172. EXPECT_EQ("denied", res->body);
  5173. EXPECT_FALSE(handler_ran);
  5174. }
  5175. // An approved route still reads the body and enforces the payload limit.
  5176. {
  5177. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5179. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5180. }
  5181. }
  5182. TEST(UserDataTest, BasicOperations) {
  5183. httplib::UserData ud;
  5184. // Initially empty
  5185. EXPECT_FALSE(ud.has("key"));
  5186. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5187. // set and get
  5188. ud.set("key", 42);
  5189. EXPECT_TRUE(ud.has("key"));
  5190. auto *p = ud.get<int>("key");
  5191. ASSERT_NE(nullptr, p);
  5192. EXPECT_EQ(42, *p);
  5193. // Type mismatch → nullptr
  5194. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5195. // Overwrite with different type
  5196. ud.set("key", std::string("hello"));
  5197. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5198. auto *s = ud.get<std::string>("key");
  5199. ASSERT_NE(nullptr, s);
  5200. EXPECT_EQ("hello", *s);
  5201. // erase
  5202. ud.erase("key");
  5203. EXPECT_FALSE(ud.has("key"));
  5204. // clear
  5205. ud.set("a", 1);
  5206. ud.set("b", 2);
  5207. ud.clear();
  5208. EXPECT_FALSE(ud.has("a"));
  5209. EXPECT_FALSE(ud.has("b"));
  5210. }
  5211. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5212. struct AuthCtx {
  5213. std::string user_id;
  5214. };
  5215. Server svr;
  5216. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5217. res.user_data.set("auth", AuthCtx{"alice"});
  5218. return Server::HandlerResponse::Unhandled;
  5219. });
  5220. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5221. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5222. ASSERT_NE(nullptr, ctx);
  5223. res.set_content("Hello " + ctx->user_id, "text/plain");
  5224. });
  5225. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5226. auto se = detail::scope_exit([&] {
  5227. svr.stop();
  5228. thread.join();
  5229. ASSERT_FALSE(svr.is_running());
  5230. });
  5231. svr.wait_until_ready();
  5232. Client cli(HOST, PORT);
  5233. auto res = cli.Get("/me");
  5234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5235. EXPECT_EQ(StatusCode::OK_200, res->status);
  5236. EXPECT_EQ("Hello alice", res->body);
  5237. }
  5238. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5239. struct RoleCtx {
  5240. std::string role;
  5241. };
  5242. Server svr;
  5243. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5244. res.user_data.set("role", RoleCtx{"admin"});
  5245. return Server::HandlerResponse::Unhandled;
  5246. });
  5247. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5248. auto *ctx = res.user_data.get<RoleCtx>("role");
  5249. ASSERT_NE(nullptr, ctx);
  5250. res.set_content(ctx->role, "text/plain");
  5251. });
  5252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5253. auto se = detail::scope_exit([&] {
  5254. svr.stop();
  5255. thread.join();
  5256. ASSERT_FALSE(svr.is_running());
  5257. });
  5258. svr.wait_until_ready();
  5259. Client cli(HOST, PORT);
  5260. auto res = cli.Get("/role");
  5261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5262. EXPECT_EQ(StatusCode::OK_200, res->status);
  5263. EXPECT_EQ("admin", res->body);
  5264. }
  5265. TEST(InvalidFormatTest, StatusCode) {
  5266. Server svr;
  5267. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5268. res.set_content("Hello World!\n", "text/plain");
  5269. res.status = 9999; // Status should be a three-digit code...
  5270. });
  5271. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5272. auto se = detail::scope_exit([&] {
  5273. svr.stop();
  5274. thread.join();
  5275. ASSERT_FALSE(svr.is_running());
  5276. });
  5277. svr.wait_until_ready();
  5278. {
  5279. Client cli(HOST, PORT);
  5280. auto res = cli.Get("/hi");
  5281. ASSERT_FALSE(res);
  5282. }
  5283. }
  5284. TEST(URLFragmentTest, WithFragment) {
  5285. Server svr;
  5286. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5287. EXPECT_TRUE(req.target == "/hi");
  5288. });
  5289. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5290. auto se = detail::scope_exit([&] {
  5291. svr.stop();
  5292. thread.join();
  5293. ASSERT_FALSE(svr.is_running());
  5294. });
  5295. svr.wait_until_ready();
  5296. {
  5297. Client cli(HOST, PORT);
  5298. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5299. EXPECT_TRUE(res);
  5300. EXPECT_EQ(StatusCode::OK_200, res->status);
  5301. res = cli.Get("/hi%23key1=val1=key2=val2");
  5302. EXPECT_TRUE(res);
  5303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5304. }
  5305. }
  5306. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5307. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5308. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5309. Server svr;
  5310. std::vector<std::string> targets;
  5311. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5312. targets.push_back(req.target);
  5313. });
  5314. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5315. auto se = detail::scope_exit([&] {
  5316. svr.stop();
  5317. thread.join();
  5318. ASSERT_FALSE(svr.is_running());
  5319. });
  5320. svr.wait_until_ready();
  5321. Client cli(HOST, PORT);
  5322. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5323. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5324. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5325. // A '?' after the '#' belongs to the fragment, not to the query.
  5326. Request req;
  5327. req.method = "GET";
  5328. req.path = "/hi#f?x=1";
  5329. req.params.emplace("a", "1");
  5330. Response res;
  5331. auto error = Error::Success;
  5332. EXPECT_TRUE(cli.send(req, res, error));
  5333. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5334. "/hi?a=1"}),
  5335. targets);
  5336. }
  5337. TEST(HeaderWriter, SetHeaderWriter) {
  5338. Server svr;
  5339. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5340. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5341. return detail::write_headers(strm, hdrs);
  5342. });
  5343. svr.Get("/hi", [](const Request &req, Response &res) {
  5344. auto it = req.headers.find("CustomClientHeader");
  5345. EXPECT_TRUE(it != req.headers.end());
  5346. EXPECT_EQ(it->second, "CustomClientValue");
  5347. res.set_content("Hello World!\n", "text/plain");
  5348. });
  5349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5350. auto se = detail::scope_exit([&] {
  5351. svr.stop();
  5352. thread.join();
  5353. ASSERT_FALSE(svr.is_running());
  5354. });
  5355. svr.wait_until_ready();
  5356. {
  5357. Client cli(HOST, PORT);
  5358. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5359. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5360. return detail::write_headers(strm, hdrs);
  5361. });
  5362. auto res = cli.Get("/hi");
  5363. EXPECT_TRUE(res);
  5364. EXPECT_EQ(StatusCode::OK_200, res->status);
  5365. auto it = res->headers.find("CustomServerHeader");
  5366. EXPECT_TRUE(it != res->headers.end());
  5367. EXPECT_EQ(it->second, "CustomServerValue");
  5368. }
  5369. }
  5370. class ServerTest : public ::testing::Test {
  5371. protected:
  5372. ServerTest()
  5373. : cli_(HOST, PORT)
  5374. #ifdef CPPHTTPLIB_SSL_ENABLED
  5375. ,
  5376. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5377. #endif
  5378. {
  5379. #ifdef CPPHTTPLIB_SSL_ENABLED
  5380. cli_.enable_server_certificate_verification(false);
  5381. #endif
  5382. // Allow LARGE_DATA (100MB) responses
  5383. cli_.set_payload_max_length(200 * 1024 * 1024);
  5384. }
  5385. virtual void SetUp() {
  5386. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5387. svr_.set_payload_max_length(200 * 1024 * 1024);
  5388. svr_.set_mount_point("/", "./www");
  5389. svr_.set_mount_point("/mount", "./www2");
  5390. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5391. svr_.Get("/hi",
  5392. [&](const Request & /*req*/, Response &res) {
  5393. res.set_content("Hello World!", "text/plain");
  5394. })
  5395. .Get("/file_content",
  5396. [&](const Request & /*req*/, Response &res) {
  5397. res.set_file_content("./www/dir/test.html");
  5398. })
  5399. .Get("/file_content_with_content_type",
  5400. [&](const Request & /*req*/, Response &res) {
  5401. res.set_file_content("./www/file", "text/plain");
  5402. })
  5403. .Get("/invalid_file_content",
  5404. [&](const Request & /*req*/, Response &res) {
  5405. res.set_file_content("./www/dir/invalid_file_path");
  5406. })
  5407. .Get("/http_response_splitting",
  5408. [&](const Request & /*req*/, Response &res) {
  5409. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5410. EXPECT_EQ(0U, res.headers.size());
  5411. EXPECT_FALSE(res.has_header("a"));
  5412. res.set_header("a", "1\nSet-Cookie: a=1");
  5413. EXPECT_EQ(0U, res.headers.size());
  5414. EXPECT_FALSE(res.has_header("a"));
  5415. res.set_header("a", "1\rSet-Cookie: a=1");
  5416. EXPECT_EQ(0U, res.headers.size());
  5417. EXPECT_FALSE(res.has_header("a"));
  5418. res.set_header("a\r\nb", "0");
  5419. EXPECT_EQ(0U, res.headers.size());
  5420. EXPECT_FALSE(res.has_header("a"));
  5421. res.set_header("a\rb", "0");
  5422. EXPECT_EQ(0U, res.headers.size());
  5423. EXPECT_FALSE(res.has_header("a"));
  5424. res.set_header("a\nb", "0");
  5425. EXPECT_EQ(0U, res.headers.size());
  5426. EXPECT_FALSE(res.has_header("a"));
  5427. res.set_redirect("1\r\nSet-Cookie: a=1");
  5428. EXPECT_EQ(0U, res.headers.size());
  5429. EXPECT_FALSE(res.has_header("Location"));
  5430. })
  5431. .Get("/slow",
  5432. [&](const Request & /*req*/, Response &res) {
  5433. std::this_thread::sleep_for(std::chrono::seconds(4));
  5434. res.set_content("slow", "text/plain");
  5435. })
  5436. #if 0
  5437. .Post("/slowpost",
  5438. [&](const Request & /*req*/, Response &res) {
  5439. std::this_thread::sleep_for(std::chrono::seconds(2));
  5440. res.set_content("slow", "text/plain");
  5441. })
  5442. #endif
  5443. .Get("/remote_addr",
  5444. [&](const Request &req, Response &res) {
  5445. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5446. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5447. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5448. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5449. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5450. #endif
  5451. res.set_content(req.remote_addr, "text/plain");
  5452. })
  5453. .Get("/local_addr",
  5454. [&](const Request &req, Response &res) {
  5455. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5456. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5457. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5458. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5459. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5460. #endif
  5461. auto local_addr = req.local_addr;
  5462. auto local_port = std::to_string(req.local_port);
  5463. res.set_content(local_addr.append(":").append(local_port),
  5464. "text/plain");
  5465. })
  5466. .Get("/endwith%",
  5467. [&](const Request & /*req*/, Response &res) {
  5468. res.set_content("Hello World!", "text/plain");
  5469. })
  5470. .Get("/a\\+\\+b",
  5471. [&](const Request &req, Response &res) {
  5472. ASSERT_TRUE(req.has_param("a +b"));
  5473. auto val = req.get_param_value("a +b");
  5474. res.set_content(val, "text/plain");
  5475. })
  5476. .Get("/", [&](const Request & /*req*/,
  5477. Response &res) { res.set_redirect("/hi"); })
  5478. .Post("/1",
  5479. [](const Request & /*req*/, Response &res) {
  5480. res.set_redirect("/2", StatusCode::SeeOther_303);
  5481. })
  5482. .Get("/2",
  5483. [](const Request & /*req*/, Response &res) {
  5484. res.set_content("redirected.", "text/plain");
  5485. res.status = StatusCode::OK_200;
  5486. })
  5487. .Post("/person",
  5488. [&](const Request &req, Response &res) {
  5489. if (req.has_param("name") && req.has_param("note")) {
  5490. persons_[req.get_param_value("name")] =
  5491. req.get_param_value("note");
  5492. } else {
  5493. res.status = StatusCode::BadRequest_400;
  5494. }
  5495. })
  5496. .Put("/person",
  5497. [&](const Request &req, Response &res) {
  5498. if (req.has_param("name") && req.has_param("note")) {
  5499. persons_[req.get_param_value("name")] =
  5500. req.get_param_value("note");
  5501. } else {
  5502. res.status = StatusCode::BadRequest_400;
  5503. }
  5504. })
  5505. .Get("/person/(.*)",
  5506. [&](const Request &req, Response &res) {
  5507. string name = req.matches[1];
  5508. if (persons_.find(name) != persons_.end()) {
  5509. auto note = persons_[name];
  5510. res.set_content(note, "text/plain");
  5511. } else {
  5512. res.status = StatusCode::NotFound_404;
  5513. }
  5514. })
  5515. .Delete("/person",
  5516. [&](const Request &req, Response &res) {
  5517. if (req.has_param("name")) {
  5518. string name = req.get_param_value("name");
  5519. if (persons_.find(name) != persons_.end()) {
  5520. persons_.erase(name);
  5521. res.set_content("DELETED", "text/plain");
  5522. } else {
  5523. res.status = StatusCode::NotFound_404;
  5524. }
  5525. } else {
  5526. res.status = StatusCode::BadRequest_400;
  5527. }
  5528. })
  5529. .Post("/x-www-form-urlencoded-json",
  5530. [&](const Request &req, Response &res) {
  5531. auto json = req.get_param_value("json");
  5532. ASSERT_EQ(JSON_DATA, json);
  5533. res.set_content(json, "appliation/json");
  5534. res.status = StatusCode::OK_200;
  5535. })
  5536. .Get("/streamed-chunked",
  5537. [&](const Request & /*req*/, Response &res) {
  5538. res.set_chunked_content_provider(
  5539. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5540. sink.os << "123";
  5541. sink.os << "456";
  5542. sink.os << "789";
  5543. sink.done();
  5544. return true;
  5545. });
  5546. })
  5547. .Get("/streamed-chunked-with-prohibited-trailer",
  5548. [&](const Request & /*req*/, Response &res) {
  5549. auto i = new int(0);
  5550. // Declare both a prohibited trailer (Content-Length) and an
  5551. // allowed one
  5552. res.set_header("Trailer", "Content-Length, X-Allowed");
  5553. res.set_chunked_content_provider(
  5554. "text/plain",
  5555. [i](size_t /*offset*/, DataSink &sink) {
  5556. switch (*i) {
  5557. case 0: sink.os << "123"; break;
  5558. case 1: sink.os << "456"; break;
  5559. case 2: sink.os << "789"; break;
  5560. case 3: {
  5561. sink.done_with_trailer(
  5562. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5563. } break;
  5564. }
  5565. (*i)++;
  5566. return true;
  5567. },
  5568. [i](bool success) {
  5569. EXPECT_TRUE(success);
  5570. delete i;
  5571. });
  5572. })
  5573. .Get("/streamed-chunked2",
  5574. [&](const Request & /*req*/, Response &res) {
  5575. auto i = new int(0);
  5576. res.set_chunked_content_provider(
  5577. "text/plain",
  5578. [i](size_t /*offset*/, DataSink &sink) {
  5579. switch (*i) {
  5580. case 0: sink.os << "123"; break;
  5581. case 1: sink.os << "456"; break;
  5582. case 2: sink.os << "789"; break;
  5583. case 3: sink.done(); break;
  5584. }
  5585. (*i)++;
  5586. return true;
  5587. },
  5588. [i](bool success) {
  5589. EXPECT_TRUE(success);
  5590. delete i;
  5591. });
  5592. })
  5593. .Get("/streamed-chunked-with-trailer",
  5594. [&](const Request & /*req*/, Response &res) {
  5595. auto i = new int(0);
  5596. res.set_header("Trailer", "Dummy1, Dummy2");
  5597. res.set_chunked_content_provider(
  5598. "text/plain",
  5599. [i](size_t /*offset*/, DataSink &sink) {
  5600. switch (*i) {
  5601. case 0: sink.os << "123"; break;
  5602. case 1: sink.os << "456"; break;
  5603. case 2: sink.os << "789"; break;
  5604. case 3: {
  5605. sink.done_with_trailer(
  5606. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5607. } break;
  5608. }
  5609. (*i)++;
  5610. return true;
  5611. },
  5612. [i](bool success) {
  5613. EXPECT_TRUE(success);
  5614. delete i;
  5615. });
  5616. })
  5617. .Get("/streamed",
  5618. [&](const Request & /*req*/, Response &res) {
  5619. res.set_content_provider(
  5620. 6, "text/plain",
  5621. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5622. sink.os << (offset < 3 ? "a" : "b");
  5623. return true;
  5624. });
  5625. })
  5626. .Get("/streamed-without-length",
  5627. [&](const Request & /*req*/, Response &res) {
  5628. auto data = new std::string("abcdefg");
  5629. res.set_content_provider(
  5630. "text/plain",
  5631. [data](size_t offset, DataSink &sink) {
  5632. if (offset < data->size()) {
  5633. sink.os << data->substr(offset);
  5634. }
  5635. sink.done();
  5636. return true;
  5637. },
  5638. [data](bool success) {
  5639. EXPECT_TRUE(success);
  5640. delete data;
  5641. });
  5642. })
  5643. .Get("/streamed-with-range",
  5644. [&](const Request &req, Response &res) {
  5645. auto data = new std::string("abcdefg");
  5646. // An explicit status keeps the server from picking the 206 it
  5647. // would otherwise choose for a ranged request, so the response
  5648. // is not a partial representation.
  5649. auto status = req.get_param_value("status");
  5650. if (status == "200") {
  5651. res.status = StatusCode::OK_200;
  5652. } else if (status == "403") {
  5653. res.status = StatusCode::Forbidden_403;
  5654. }
  5655. res.set_content_provider(
  5656. data->size(), "text/plain",
  5657. [data](size_t offset, size_t length, DataSink &sink) {
  5658. size_t DATA_CHUNK_SIZE = 4;
  5659. const auto &d = *data;
  5660. auto out_len =
  5661. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5662. auto ret =
  5663. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5664. EXPECT_TRUE(ret);
  5665. return true;
  5666. },
  5667. [data, &req](bool success) {
  5668. EXPECT_EQ(success, !req.has_param("error"));
  5669. delete data;
  5670. });
  5671. })
  5672. .Get("/streamed-cancel",
  5673. [&](const Request & /*req*/, Response &res) {
  5674. res.set_content_provider(
  5675. size_t(-1), "text/plain",
  5676. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5677. sink.os << "data_chunk";
  5678. return true;
  5679. });
  5680. })
  5681. .Get("/regex-with-delimiter",
  5682. [&](const Request &req, Response & /*res*/) {
  5683. ASSERT_TRUE(req.has_param("key"));
  5684. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5685. })
  5686. .Get("/with-range",
  5687. [&](const Request & /*req*/, Response &res) {
  5688. res.set_content("abcdefg", "text/plain");
  5689. })
  5690. .Get("/test-start-time",
  5691. [&](const Request &req, Response & /*res*/) {
  5692. EXPECT_NE(req.start_time_,
  5693. std::chrono::steady_clock::time_point::min());
  5694. })
  5695. .Get("/with-range-customized-response",
  5696. [&](const Request & /*req*/, Response &res) {
  5697. res.status = StatusCode::BadRequest_400;
  5698. res.set_content(JSON_DATA, "application/json");
  5699. })
  5700. .Post("/chunked",
  5701. [&](const Request &req, Response & /*res*/) {
  5702. EXPECT_EQ(req.body, "dechunked post body");
  5703. })
  5704. .Post("/large-chunked",
  5705. [&](const Request &req, Response & /*res*/) {
  5706. std::string expected(6 * 30 * 1024u, 'a');
  5707. EXPECT_EQ(req.body, expected);
  5708. })
  5709. .Post("/multipart",
  5710. [&](const Request &req, Response & /*res*/) {
  5711. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5712. req.form.get_field_count("text2") +
  5713. req.form.get_field_count("file3") +
  5714. req.form.get_field_count("file4"));
  5715. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5716. req.form.get_file_count("file2"));
  5717. ASSERT_TRUE(!req.form.has_file("???"));
  5718. ASSERT_TRUE(!req.form.has_field("???"));
  5719. ASSERT_TRUE(req.body.empty());
  5720. {
  5721. const auto &text = req.form.get_field("text1");
  5722. EXPECT_EQ("text default", text);
  5723. }
  5724. {
  5725. const auto &text = req.form.get_field("text2");
  5726. EXPECT_EQ("aωb", text);
  5727. }
  5728. {
  5729. const auto &file = req.form.get_file("file1");
  5730. EXPECT_EQ("hello.txt", file.filename);
  5731. EXPECT_EQ("text/plain", file.content_type);
  5732. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5733. }
  5734. {
  5735. const auto &file = req.form.get_file("file2");
  5736. EXPECT_EQ("world.json", file.filename);
  5737. EXPECT_EQ("application/json", file.content_type);
  5738. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5739. }
  5740. {
  5741. const auto &text = req.form.get_field("file3");
  5742. EXPECT_EQ(0u, text.size());
  5743. }
  5744. {
  5745. const auto &text = req.form.get_field("file4");
  5746. EXPECT_EQ(0u, text.size());
  5747. }
  5748. })
  5749. .Post("/multipart/multi_file_values",
  5750. [&](const Request &req, Response & /*res*/) {
  5751. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5752. req.form.get_field_count("multi_text1"));
  5753. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5754. ASSERT_TRUE(!req.form.has_file("???"));
  5755. ASSERT_TRUE(!req.form.has_field("???"));
  5756. ASSERT_TRUE(req.body.empty());
  5757. {
  5758. const auto &text = req.form.get_field("text");
  5759. EXPECT_EQ("default text", text);
  5760. }
  5761. {
  5762. const auto &text1_values = req.form.get_fields("multi_text1");
  5763. EXPECT_EQ(2u, text1_values.size());
  5764. EXPECT_EQ("aaaaa", text1_values[0]);
  5765. EXPECT_EQ("bbbbb", text1_values[1]);
  5766. }
  5767. {
  5768. const auto &file1_values = req.form.get_files("multi_file1");
  5769. EXPECT_EQ(2u, file1_values.size());
  5770. auto file1 = file1_values[0];
  5771. EXPECT_EQ(file1.filename, "hello.txt");
  5772. EXPECT_EQ(file1.content_type, "text/plain");
  5773. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5774. auto file2 = file1_values[1];
  5775. EXPECT_EQ(file2.filename, "world.json");
  5776. EXPECT_EQ(file2.content_type, "application/json");
  5777. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5778. }
  5779. })
  5780. .Post("/empty",
  5781. [&](const Request &req, Response &res) {
  5782. EXPECT_EQ(req.body, "");
  5783. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5784. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5785. res.set_content("empty", "text/plain");
  5786. })
  5787. .Post("/empty-no-content-type",
  5788. [&](const Request &req, Response &res) {
  5789. EXPECT_EQ(req.body, "");
  5790. EXPECT_FALSE(req.has_header("Content-Type"));
  5791. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5792. res.set_content("empty-no-content-type", "text/plain");
  5793. })
  5794. .Post("/path-only",
  5795. [&](const Request &req, Response &res) {
  5796. EXPECT_EQ(req.body, "");
  5797. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5798. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5799. res.set_content("path-only", "text/plain");
  5800. })
  5801. .Post("/path-headers-only",
  5802. [&](const Request &req, Response &res) {
  5803. EXPECT_EQ(req.body, "");
  5804. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5805. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5806. EXPECT_EQ("world", req.get_header_value("hello"));
  5807. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5808. res.set_content("path-headers-only", "text/plain");
  5809. })
  5810. .Post("/post-large",
  5811. [&](const Request &req, Response &res) {
  5812. EXPECT_EQ(req.body, LARGE_DATA);
  5813. res.set_content(req.body, "text/plain");
  5814. })
  5815. .Post("/post-loopback",
  5816. [&](const Request &, Response &res,
  5817. ContentReader const &content_reader) {
  5818. std::string body;
  5819. content_reader([&](const char *data, size_t data_length) {
  5820. body.append(data, data_length);
  5821. return true;
  5822. });
  5823. res.set_content(body, "text/plain");
  5824. })
  5825. .Put("/put-loopback",
  5826. [&](const Request &, Response &res,
  5827. ContentReader const &content_reader) {
  5828. std::string body;
  5829. content_reader([&](const char *data, size_t data_length) {
  5830. body.append(data, data_length);
  5831. return true;
  5832. });
  5833. res.set_content(body, "text/plain");
  5834. })
  5835. .Patch("/patch-loopback",
  5836. [&](const Request &, Response &res,
  5837. ContentReader const &content_reader) {
  5838. std::string body;
  5839. content_reader([&](const char *data, size_t data_length) {
  5840. body.append(data, data_length);
  5841. return true;
  5842. });
  5843. res.set_content(body, "text/plain");
  5844. })
  5845. .Put("/empty-no-content-type",
  5846. [&](const Request &req, Response &res) {
  5847. EXPECT_EQ(req.body, "");
  5848. EXPECT_FALSE(req.has_header("Content-Type"));
  5849. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5850. res.set_content("empty-no-content-type", "text/plain");
  5851. })
  5852. .Put("/put",
  5853. [&](const Request &req, Response &res) {
  5854. EXPECT_EQ(req.body, "PUT");
  5855. res.set_content(req.body, "text/plain");
  5856. })
  5857. .Put("/put-large",
  5858. [&](const Request &req, Response &res) {
  5859. EXPECT_EQ(req.body, LARGE_DATA);
  5860. res.set_content(req.body, "text/plain");
  5861. })
  5862. .Patch("/patch",
  5863. [&](const Request &req, Response &res) {
  5864. EXPECT_EQ(req.body, "PATCH");
  5865. res.set_content(req.body, "text/plain");
  5866. })
  5867. .Delete("/delete",
  5868. [&](const Request & /*req*/, Response &res) {
  5869. res.set_content("DELETE", "text/plain");
  5870. })
  5871. .Delete("/delete-body",
  5872. [&](const Request &req, Response &res) {
  5873. EXPECT_EQ(req.body, "content");
  5874. res.set_content(req.body, "text/plain");
  5875. })
  5876. .Options(R"(\*)",
  5877. [&](const Request & /*req*/, Response &res) {
  5878. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5879. })
  5880. .CustomRoute("PROPFIND", "/dav/:id",
  5881. [&](const Request &req, Response &res) {
  5882. res.set_header("x-body-size",
  5883. std::to_string(req.body.size()));
  5884. res.set_header("x-matched-route", req.matched_route);
  5885. res.set_header("x-dav-id", req.path_params.at("id"));
  5886. res.status = StatusCode::MultiStatus_207;
  5887. res.set_content(req.body, "application/xml");
  5888. })
  5889. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5890. [&](const Request &req, Response &res) {
  5891. res.set_header("x-dav-match", req.matches[1]);
  5892. res.status = StatusCode::MultiStatus_207;
  5893. })
  5894. .CustomRoute("MKCOL", "/dav-mkcol",
  5895. [&](const Request &req, Response &res) {
  5896. EXPECT_TRUE(req.body.empty());
  5897. res.status = StatusCode::Created_201;
  5898. })
  5899. .CustomRoute(
  5900. "REPORT", "/dav-report",
  5901. [&](const Request & /*req*/, Response &res,
  5902. const ContentReader &content_reader) {
  5903. std::string body;
  5904. content_reader([&](const char *data, size_t data_length) {
  5905. body.append(data, data_length);
  5906. return true;
  5907. });
  5908. res.set_header("x-body-size", std::to_string(body.size()));
  5909. res.status = StatusCode::MultiStatus_207;
  5910. res.set_content(body, "application/xml");
  5911. })
  5912. .Get("/request-target",
  5913. [&](const Request &req, Response & /*res*/) {
  5914. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5915. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5916. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5917. })
  5918. .Get("/long-query-value",
  5919. [&](const Request &req, Response & /*res*/) {
  5920. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5921. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5922. })
  5923. .Get("/too-long-query-value",
  5924. [&](const Request &req, Response & /*res*/) {
  5925. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5926. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5927. })
  5928. .Get("/array-param",
  5929. [&](const Request &req, Response & /*res*/) {
  5930. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5931. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5932. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5933. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5934. })
  5935. .Get("/array-param-values",
  5936. [&](const Request &req, Response & /*res*/) {
  5937. auto values = req.get_param_values("array");
  5938. EXPECT_EQ(3u, values.size());
  5939. EXPECT_EQ("value1", values[0]);
  5940. EXPECT_EQ("value2", values[1]);
  5941. EXPECT_EQ("value3", values[2]);
  5942. auto empty = req.get_param_values("nonexistent");
  5943. EXPECT_TRUE(empty.empty());
  5944. })
  5945. .Post("/validate-no-multiple-headers",
  5946. [&](const Request &req, Response & /*res*/) {
  5947. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5948. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5949. })
  5950. .Post("/content_receiver",
  5951. [&](const Request &req, Response &res,
  5952. const ContentReader &content_reader) {
  5953. if (req.is_multipart_form_data()) {
  5954. std::vector<FormData> items;
  5955. content_reader(
  5956. [&](const FormData &file) {
  5957. items.push_back(file);
  5958. return true;
  5959. },
  5960. [&](const char *data, size_t data_length) {
  5961. items.back().content.append(data, data_length);
  5962. return true;
  5963. });
  5964. EXPECT_EQ(5u, items.size());
  5965. {
  5966. const auto &file = get_file_value(items, "text1");
  5967. EXPECT_TRUE(file.filename.empty());
  5968. EXPECT_EQ("text default", file.content);
  5969. }
  5970. {
  5971. const auto &file = get_file_value(items, "text2");
  5972. EXPECT_TRUE(file.filename.empty());
  5973. EXPECT_EQ("aωb", file.content);
  5974. }
  5975. {
  5976. const auto &file = get_file_value(items, "file1");
  5977. EXPECT_EQ("hello.txt", file.filename);
  5978. EXPECT_EQ("text/plain", file.content_type);
  5979. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5980. }
  5981. {
  5982. const auto &file = get_file_value(items, "file2");
  5983. EXPECT_EQ("world.json", file.filename);
  5984. EXPECT_EQ("application/json", file.content_type);
  5985. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5986. }
  5987. {
  5988. const auto &file = get_file_value(items, "file3");
  5989. EXPECT_TRUE(file.filename.empty());
  5990. EXPECT_EQ("application/octet-stream", file.content_type);
  5991. EXPECT_EQ(0u, file.content.size());
  5992. }
  5993. } else {
  5994. std::string body;
  5995. content_reader([&](const char *data, size_t data_length) {
  5996. EXPECT_EQ(7U, data_length);
  5997. body.append(data, data_length);
  5998. return true;
  5999. });
  6000. EXPECT_EQ(body, "content");
  6001. res.set_content(body, "text/plain");
  6002. }
  6003. })
  6004. .Put("/content_receiver",
  6005. [&](const Request & /*req*/, Response &res,
  6006. const ContentReader &content_reader) {
  6007. std::string body;
  6008. content_reader([&](const char *data, size_t data_length) {
  6009. body.append(data, data_length);
  6010. return true;
  6011. });
  6012. EXPECT_EQ(body, "content");
  6013. res.set_content(body, "text/plain");
  6014. })
  6015. .Patch("/content_receiver",
  6016. [&](const Request & /*req*/, Response &res,
  6017. const ContentReader &content_reader) {
  6018. std::string body;
  6019. content_reader([&](const char *data, size_t data_length) {
  6020. body.append(data, data_length);
  6021. return true;
  6022. });
  6023. EXPECT_EQ(body, "content");
  6024. res.set_content(body, "text/plain");
  6025. })
  6026. .Post("/query-string-and-body",
  6027. [&](const Request &req, Response & /*res*/) {
  6028. ASSERT_TRUE(req.has_param("key"));
  6029. EXPECT_EQ(req.get_param_value("key"), "value");
  6030. EXPECT_EQ(req.body, "content");
  6031. })
  6032. .Get("/last-request",
  6033. [&](const Request &req, Response & /*res*/) {
  6034. EXPECT_EQ("close", req.get_header_value("Connection"));
  6035. })
  6036. .Get(R"(/redirect/(\d+))",
  6037. [&](const Request &req, Response &res) {
  6038. auto num = std::stoi(req.matches[1]) + 1;
  6039. std::string url = "/redirect/" + std::to_string(num);
  6040. res.set_redirect(url);
  6041. })
  6042. .Post("/binary",
  6043. [&](const Request &req, Response &res) {
  6044. EXPECT_EQ(4U, req.body.size());
  6045. EXPECT_EQ("application/octet-stream",
  6046. req.get_header_value("Content-Type"));
  6047. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6048. res.set_content(req.body, "application/octet-stream");
  6049. })
  6050. .Put("/binary",
  6051. [&](const Request &req, Response &res) {
  6052. EXPECT_EQ(4U, req.body.size());
  6053. EXPECT_EQ("application/octet-stream",
  6054. req.get_header_value("Content-Type"));
  6055. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6056. res.set_content(req.body, "application/octet-stream");
  6057. })
  6058. .Patch("/binary",
  6059. [&](const Request &req, Response &res) {
  6060. EXPECT_EQ(4U, req.body.size());
  6061. EXPECT_EQ("application/octet-stream",
  6062. req.get_header_value("Content-Type"));
  6063. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6064. res.set_content(req.body, "application/octet-stream");
  6065. })
  6066. .Delete("/binary",
  6067. [&](const Request &req, Response &res) {
  6068. EXPECT_EQ(4U, req.body.size());
  6069. EXPECT_EQ("application/octet-stream",
  6070. req.get_header_value("Content-Type"));
  6071. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6072. res.set_content(req.body, "application/octet-stream");
  6073. })
  6074. .Get("/issue1772",
  6075. [&](const Request & /*req*/, Response &res) {
  6076. res.status = 401;
  6077. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6078. })
  6079. .Delete("/issue609",
  6080. [](const httplib::Request &, httplib::Response &res,
  6081. const httplib::ContentReader &) {
  6082. res.set_content("ok", "text/plain");
  6083. })
  6084. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6085. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6086. .Get("/compress",
  6087. [&](const Request & /*req*/, Response &res) {
  6088. res.set_content(
  6089. "12345678901234567890123456789012345678901234567890123456789"
  6090. "01234567890123456789012345678901234567890",
  6091. "text/plain");
  6092. })
  6093. .Get("/compress-with-charset",
  6094. [&](const Request & /*req*/, Response &res) {
  6095. res.set_content(
  6096. "12345678901234567890123456789012345678901234567890123456789"
  6097. "01234567890123456789012345678901234567890",
  6098. "application/json; charset=utf-8");
  6099. })
  6100. .Get("/nocompress",
  6101. [&](const Request & /*req*/, Response &res) {
  6102. res.set_content(
  6103. "12345678901234567890123456789012345678901234567890123456789"
  6104. "01234567890123456789012345678901234567890",
  6105. "application/octet-stream");
  6106. })
  6107. .Post("/compress-multipart",
  6108. [&](const Request &req, Response & /*res*/) {
  6109. EXPECT_EQ(2u, req.form.fields.size());
  6110. ASSERT_TRUE(!req.form.has_field("???"));
  6111. {
  6112. const auto &text = req.form.get_field("key1");
  6113. EXPECT_EQ("test", text);
  6114. }
  6115. {
  6116. const auto &text = req.form.get_field("key2");
  6117. EXPECT_EQ("--abcdefg123", text);
  6118. }
  6119. })
  6120. #endif
  6121. ;
  6122. persons_["john"] = "programmer";
  6123. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6124. svr_.wait_until_ready();
  6125. }
  6126. virtual void TearDown() {
  6127. svr_.stop();
  6128. if (!request_threads_.empty()) {
  6129. std::this_thread::sleep_for(std::chrono::seconds(1));
  6130. for (auto &t : request_threads_) {
  6131. t.join();
  6132. }
  6133. }
  6134. t_.join();
  6135. }
  6136. map<string, string> persons_;
  6137. #ifdef CPPHTTPLIB_SSL_ENABLED
  6138. SSLClient cli_;
  6139. SSLServer svr_;
  6140. #else
  6141. Client cli_;
  6142. Server svr_;
  6143. #endif
  6144. thread t_;
  6145. std::vector<thread> request_threads_;
  6146. };
  6147. TEST_F(ServerTest, GetMethod200) {
  6148. auto res = cli_.Get("/hi");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. EXPECT_EQ("HTTP/1.1", res->version);
  6151. EXPECT_EQ(StatusCode::OK_200, res->status);
  6152. EXPECT_EQ("OK", res->reason);
  6153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6154. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6155. EXPECT_EQ("Hello World!", res->body);
  6156. }
  6157. TEST_F(ServerTest, GetEmptyFile) {
  6158. auto res = cli_.Get("/empty_file");
  6159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6160. EXPECT_EQ(StatusCode::OK_200, res->status);
  6161. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6162. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6163. EXPECT_EQ("", res->body);
  6164. }
  6165. TEST_F(ServerTest, GetFileContent) {
  6166. auto res = cli_.Get("/file_content");
  6167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6168. EXPECT_EQ(StatusCode::OK_200, res->status);
  6169. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6170. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6171. EXPECT_EQ("test.html", res->body);
  6172. }
  6173. TEST_F(ServerTest, GetFileContentWithRange) {
  6174. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6177. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6178. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6179. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6180. EXPECT_EQ("est", res->body);
  6181. }
  6182. TEST_F(ServerTest, GetFileContentWithContentType) {
  6183. auto res = cli_.Get("/file_content_with_content_type");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. EXPECT_EQ(StatusCode::OK_200, res->status);
  6186. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6187. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6188. EXPECT_EQ("file\n", res->body);
  6189. }
  6190. TEST_F(ServerTest, GetInvalidFileContent) {
  6191. auto res = cli_.Get("/invalid_file_content");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6194. }
  6195. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6196. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. EXPECT_EQ("HTTP/1.1", res->version);
  6199. EXPECT_EQ(StatusCode::OK_200, res->status);
  6200. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6201. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6202. EXPECT_EQ("Hello World!", res->body);
  6203. }
  6204. TEST_F(ServerTest, GetMethod302) {
  6205. auto res = cli_.Get("/");
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. EXPECT_EQ(StatusCode::Found_302, res->status);
  6208. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6209. }
  6210. TEST_F(ServerTest, GetMethod302Redirect) {
  6211. cli_.set_follow_location(true);
  6212. auto res = cli_.Get("/");
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. EXPECT_EQ("Hello World!", res->body);
  6216. EXPECT_EQ("/hi", res->location);
  6217. }
  6218. TEST_F(ServerTest, GetMethod404) {
  6219. auto res = cli_.Get("/invalid");
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6222. }
  6223. TEST_F(ServerTest, HeadMethod200) {
  6224. auto res = cli_.Head("/hi");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6228. EXPECT_TRUE(res->body.empty());
  6229. }
  6230. TEST_F(ServerTest, HeadMethod200Static) {
  6231. auto res = cli_.Head("/mount/dir/index.html");
  6232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6233. EXPECT_EQ(StatusCode::OK_200, res->status);
  6234. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6235. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6236. EXPECT_TRUE(res->body.empty());
  6237. }
  6238. TEST_F(ServerTest, HeadMethod404) {
  6239. auto res = cli_.Head("/invalid");
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6242. EXPECT_TRUE(res->body.empty());
  6243. }
  6244. TEST_F(ServerTest, GetMethodPersonJohn) {
  6245. auto res = cli_.Get("/person/john");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. EXPECT_EQ(StatusCode::OK_200, res->status);
  6248. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6249. EXPECT_EQ("programmer", res->body);
  6250. }
  6251. TEST_F(ServerTest, PostMethod1) {
  6252. auto res = cli_.Get("/person/john1");
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6255. res = cli_.Post("/person", "name=john1&note=coder",
  6256. "application/x-www-form-urlencoded");
  6257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6258. ASSERT_EQ(StatusCode::OK_200, res->status);
  6259. res = cli_.Get("/person/john1");
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. ASSERT_EQ(StatusCode::OK_200, res->status);
  6262. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6263. ASSERT_EQ("coder", res->body);
  6264. }
  6265. TEST_F(ServerTest, PostMethod2) {
  6266. auto res = cli_.Get("/person/john2");
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6269. Params params;
  6270. params.emplace("name", "john2");
  6271. params.emplace("note", "coder");
  6272. res = cli_.Post("/person", params);
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. ASSERT_EQ(StatusCode::OK_200, res->status);
  6275. res = cli_.Get("/person/john2");
  6276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6277. ASSERT_EQ(StatusCode::OK_200, res->status);
  6278. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6279. ASSERT_EQ("coder", res->body);
  6280. }
  6281. TEST_F(ServerTest, PutMethod3) {
  6282. auto res = cli_.Get("/person/john3");
  6283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6284. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6285. Params params;
  6286. params.emplace("name", "john3");
  6287. params.emplace("note", "coder");
  6288. res = cli_.Put("/person", params);
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. ASSERT_EQ(StatusCode::OK_200, res->status);
  6291. res = cli_.Get("/person/john3");
  6292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6293. ASSERT_EQ(StatusCode::OK_200, res->status);
  6294. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6295. ASSERT_EQ("coder", res->body);
  6296. }
  6297. TEST_F(ServerTest, DeleteMethod1) {
  6298. auto res = cli_.Get("/person/john4");
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6301. Params params;
  6302. params.emplace("name", "john4");
  6303. params.emplace("note", "coder");
  6304. res = cli_.Post("/person", params);
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. ASSERT_EQ(StatusCode::OK_200, res->status);
  6307. res = cli_.Get("/person/john4");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. ASSERT_EQ(StatusCode::OK_200, res->status);
  6310. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6311. ASSERT_EQ("coder", res->body);
  6312. Params delete_params;
  6313. delete_params.emplace("name", "john4");
  6314. res = cli_.Delete("/person", delete_params);
  6315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6316. ASSERT_EQ(StatusCode::OK_200, res->status);
  6317. ASSERT_EQ("DELETED", res->body);
  6318. res = cli_.Get("/person/john4");
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6321. }
  6322. TEST_F(ServerTest, DeleteMethod2) {
  6323. auto res = cli_.Get("/person/john5");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6326. Params params;
  6327. params.emplace("name", "john5");
  6328. params.emplace("note", "developer");
  6329. res = cli_.Post("/person", params);
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. ASSERT_EQ(StatusCode::OK_200, res->status);
  6332. res = cli_.Get("/person/john5");
  6333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6334. ASSERT_EQ(StatusCode::OK_200, res->status);
  6335. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6336. ASSERT_EQ("developer", res->body);
  6337. Params delete_params;
  6338. delete_params.emplace("name", "john5");
  6339. Headers headers;
  6340. headers.emplace("Custom-Header", "test-value");
  6341. res = cli_.Delete("/person", headers, delete_params);
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. ASSERT_EQ(StatusCode::OK_200, res->status);
  6344. ASSERT_EQ("DELETED", res->body);
  6345. res = cli_.Get("/person/john5");
  6346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6347. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6348. }
  6349. TEST_F(ServerTest, DeleteMethod3) {
  6350. auto res = cli_.Get("/person/john6");
  6351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6352. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6353. Params params;
  6354. params.emplace("name", "john6");
  6355. params.emplace("note", "tester");
  6356. res = cli_.Post("/person", params);
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. ASSERT_EQ(StatusCode::OK_200, res->status);
  6359. res = cli_.Get("/person/john6");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. ASSERT_EQ(StatusCode::OK_200, res->status);
  6362. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6363. ASSERT_EQ("tester", res->body);
  6364. Params delete_params;
  6365. delete_params.emplace("name", "john6");
  6366. Headers headers;
  6367. headers.emplace("Custom-Header", "test-value");
  6368. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. ASSERT_EQ(StatusCode::OK_200, res->status);
  6371. ASSERT_EQ("DELETED", res->body);
  6372. res = cli_.Get("/person/john6");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6375. }
  6376. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6377. Params params;
  6378. params.emplace("json", JSON_DATA);
  6379. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. ASSERT_EQ(StatusCode::OK_200, res->status);
  6382. ASSERT_EQ(JSON_DATA, res->body);
  6383. }
  6384. TEST_F(ServerTest, PostEmptyContent) {
  6385. auto res = cli_.Post("/empty", "", "text/plain");
  6386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6387. ASSERT_EQ(StatusCode::OK_200, res->status);
  6388. ASSERT_EQ("empty", res->body);
  6389. }
  6390. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6391. auto res = cli_.Post("/empty-no-content-type");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. ASSERT_EQ(StatusCode::OK_200, res->status);
  6394. ASSERT_EQ("empty-no-content-type", res->body);
  6395. }
  6396. TEST_F(ServerTest, PostPathOnly) {
  6397. auto res = cli_.Post("/path-only");
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. ASSERT_EQ(StatusCode::OK_200, res->status);
  6400. ASSERT_EQ("path-only", res->body);
  6401. }
  6402. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6403. auto res = cli_.Post("/path-headers-only",
  6404. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6406. ASSERT_EQ(StatusCode::OK_200, res->status);
  6407. ASSERT_EQ("path-headers-only", res->body);
  6408. }
  6409. TEST_F(ServerTest, PostLarge) {
  6410. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. ASSERT_EQ(StatusCode::OK_200, res->status);
  6413. EXPECT_EQ(LARGE_DATA, res->body);
  6414. }
  6415. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6416. auto res = cli_.Put("/empty-no-content-type");
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. ASSERT_EQ(StatusCode::OK_200, res->status);
  6419. ASSERT_EQ("empty-no-content-type", res->body);
  6420. }
  6421. TEST_F(ServerTest, GetMethodDir) {
  6422. auto res = cli_.Get("/dir/");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. EXPECT_EQ(StatusCode::OK_200, res->status);
  6425. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6426. auto body = R"(<html>
  6427. <head>
  6428. </head>
  6429. <body>
  6430. <a href="/dir/test.html">Test</a>
  6431. <a href="/hi">hi</a>
  6432. </body>
  6433. </html>
  6434. )";
  6435. EXPECT_EQ(body, res->body);
  6436. }
  6437. TEST_F(ServerTest, GetMethodDirTest) {
  6438. auto res = cli_.Get("/dir/test.html");
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::OK_200, res->status);
  6441. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6442. EXPECT_EQ("test.html", res->body);
  6443. }
  6444. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6445. auto res = cli_.Get("/dir/../dir/test.html");
  6446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6448. }
  6449. TEST_F(ServerTest, GetMethodInvalidPath) {
  6450. auto res = cli_.Get("/dir/../test.html");
  6451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6452. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6453. }
  6454. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6455. auto res = cli_.Get("/../www/dir/test.html");
  6456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6457. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6458. }
  6459. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6460. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6463. }
  6464. TEST_F(ServerTest, GetMethodDirMountTest) {
  6465. auto res = cli_.Get("/mount/dir/test.html");
  6466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6467. EXPECT_EQ(StatusCode::OK_200, res->status);
  6468. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6469. EXPECT_EQ("test.html", res->body);
  6470. }
  6471. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6472. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6474. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6475. }
  6476. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6477. auto res = cli_.Get("/mount/dir/../test.html");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6480. }
  6481. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6482. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6485. }
  6486. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6487. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6490. }
  6491. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6492. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6495. }
  6496. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6497. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6500. }
  6501. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6502. auto res = cli_.Get("/mount/dir");
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6505. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6506. }
  6507. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6508. auto res = cli_.Get("//dir");
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6511. EXPECT_FALSE(res->has_header("Location"));
  6512. }
  6513. TEST_F(ServerTest, PostMethod303) {
  6514. auto res = cli_.Post("/1", "body", "text/plain");
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6517. EXPECT_EQ("/2", res->get_header_value("Location"));
  6518. }
  6519. TEST_F(ServerTest, PostMethod303Redirect) {
  6520. cli_.set_follow_location(true);
  6521. auto res = cli_.Post("/1", "body", "text/plain");
  6522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6523. EXPECT_EQ(StatusCode::OK_200, res->status);
  6524. EXPECT_EQ("redirected.", res->body);
  6525. EXPECT_EQ("/2", res->location);
  6526. }
  6527. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6528. auto res = cli_.Get("/dir/test.abcde");
  6529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6530. EXPECT_EQ(StatusCode::OK_200, res->status);
  6531. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6532. EXPECT_EQ("abcde", res->body);
  6533. }
  6534. TEST_F(ServerTest, StaticFileRange) {
  6535. auto res =
  6536. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6538. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6539. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6540. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6541. EXPECT_EQ(true, res->has_header("Content-Range"));
  6542. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6543. EXPECT_EQ(std::string("cd"), res->body);
  6544. }
  6545. TEST_F(ServerTest, StaticFileRanges) {
  6546. auto res = cli_.Get("/dir/test.abcde",
  6547. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6549. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6550. EXPECT_TRUE(
  6551. res->get_header_value("Content-Type")
  6552. .find(
  6553. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6554. 0);
  6555. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6556. }
  6557. TEST_F(ServerTest, StaticFileRangeHead) {
  6558. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6560. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6561. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6562. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6563. EXPECT_EQ(true, res->has_header("Content-Range"));
  6564. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6565. }
  6566. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6567. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6571. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6572. EXPECT_EQ(true, res->has_header("Content-Range"));
  6573. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6574. res->get_header_value("Content-Range"));
  6575. EXPECT_EQ("LAST\n", res->body);
  6576. }
  6577. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6578. auto res =
  6579. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6581. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6583. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6584. EXPECT_EQ(true, res->has_header("Content-Range"));
  6585. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6586. }
  6587. TEST_F(ServerTest, StaticFileBigFile) {
  6588. auto res = cli_.Get("/dir/1MB.txt");
  6589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6590. EXPECT_EQ(StatusCode::OK_200, res->status);
  6591. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6592. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6593. }
  6594. TEST_F(ServerTest, InvalidBaseDirMount) {
  6595. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6596. }
  6597. TEST_F(ServerTest, Binary) {
  6598. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6599. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6600. "application/octet-stream");
  6601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6602. ASSERT_EQ(StatusCode::OK_200, res->status);
  6603. ASSERT_EQ(4U, res->body.size());
  6604. res = cli_.Put("/binary", binary.data(), binary.size(),
  6605. "application/octet-stream");
  6606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6607. ASSERT_EQ(StatusCode::OK_200, res->status);
  6608. ASSERT_EQ(4U, res->body.size());
  6609. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6610. "application/octet-stream");
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. ASSERT_EQ(StatusCode::OK_200, res->status);
  6613. ASSERT_EQ(4U, res->body.size());
  6614. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6615. "application/octet-stream");
  6616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6617. ASSERT_EQ(StatusCode::OK_200, res->status);
  6618. ASSERT_EQ(4U, res->body.size());
  6619. }
  6620. TEST_F(ServerTest, BinaryString) {
  6621. auto binary = std::string("\x00\x01\x02\x03", 4);
  6622. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6624. ASSERT_EQ(StatusCode::OK_200, res->status);
  6625. ASSERT_EQ(4U, res->body.size());
  6626. res = cli_.Put("/binary", binary, "application/octet-stream");
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. ASSERT_EQ(StatusCode::OK_200, res->status);
  6629. ASSERT_EQ(4U, res->body.size());
  6630. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. ASSERT_EQ(StatusCode::OK_200, res->status);
  6633. ASSERT_EQ(4U, res->body.size());
  6634. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6636. ASSERT_EQ(StatusCode::OK_200, res->status);
  6637. ASSERT_EQ(4U, res->body.size());
  6638. }
  6639. TEST_F(ServerTest, EmptyRequest) {
  6640. auto res = cli_.Get("");
  6641. ASSERT_TRUE(!res);
  6642. EXPECT_EQ(Error::Connection, res.error());
  6643. }
  6644. TEST_F(ServerTest, LongRequest) {
  6645. std::string request;
  6646. for (size_t i = 0; i < 545; i++) {
  6647. request += "/TooLongRequest";
  6648. }
  6649. request += "OK";
  6650. auto res = cli_.Get(request.c_str());
  6651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6653. }
  6654. TEST_F(ServerTest, TooLongRequest) {
  6655. std::string request;
  6656. for (size_t i = 0; i < 546; i++) {
  6657. request += "/TooLongRequest";
  6658. }
  6659. request += "_NG";
  6660. auto start = std::chrono::high_resolution_clock::now();
  6661. cli_.set_keep_alive(true);
  6662. auto res = cli_.Get(request.c_str());
  6663. auto end = std::chrono::high_resolution_clock::now();
  6664. auto elapsed =
  6665. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6666. .count();
  6667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6668. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6669. EXPECT_LE(elapsed, 1000);
  6670. EXPECT_EQ("close", res->get_header_value("Connection"));
  6671. EXPECT_FALSE(cli_.is_socket_open());
  6672. }
  6673. TEST_F(ServerTest, AlmostTooLongRequest) {
  6674. // test for #2046 - URI length check shouldn't include other content on req
  6675. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6676. // leading /, space, HTTP/1.1)
  6677. std::string request =
  6678. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6679. auto res = cli_.Get(request.c_str());
  6680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6681. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6682. }
  6683. TEST_F(ServerTest, LongHeader) {
  6684. Request req;
  6685. req.method = "GET";
  6686. req.path = "/hi";
  6687. std::string host_and_port;
  6688. host_and_port += HOST;
  6689. host_and_port += ":";
  6690. host_and_port += std::to_string(PORT);
  6691. req.headers.emplace("Host", host_and_port.c_str());
  6692. req.headers.emplace("Accept", "*/*");
  6693. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6694. req.headers.emplace(
  6695. "Header-Name",
  6696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6724. "@@@@@@@@@@@@@@@@");
  6725. auto res = std::make_shared<Response>();
  6726. auto error = Error::Success;
  6727. auto ret = cli_.send(req, *res, error);
  6728. ASSERT_TRUE(ret);
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. }
  6731. TEST_F(ServerTest, LongQueryValue) {
  6732. auto start = std::chrono::high_resolution_clock::now();
  6733. cli_.set_keep_alive(true);
  6734. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6735. auto end = std::chrono::high_resolution_clock::now();
  6736. auto elapsed =
  6737. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6738. .count();
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6741. EXPECT_LE(elapsed, 1000);
  6742. EXPECT_EQ("close", res->get_header_value("Connection"));
  6743. EXPECT_FALSE(cli_.is_socket_open());
  6744. }
  6745. TEST_F(ServerTest, TooLongQueryValue) {
  6746. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6747. ASSERT_FALSE(res);
  6748. EXPECT_EQ(Error::Read, res.error());
  6749. }
  6750. TEST_F(ServerTest, TooLongHeader) {
  6751. Request req;
  6752. req.method = "GET";
  6753. req.path = "/hi";
  6754. std::string host_and_port;
  6755. host_and_port += HOST;
  6756. host_and_port += ":";
  6757. host_and_port += std::to_string(PORT);
  6758. req.headers.emplace("Host", host_and_port.c_str());
  6759. req.headers.emplace("Accept", "*/*");
  6760. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6761. req.headers.emplace(
  6762. "Header-Name",
  6763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6791. "@@@@@@@@@@@@@@@@@");
  6792. auto res = std::make_shared<Response>();
  6793. auto error = Error::Success;
  6794. auto ret = cli_.send(req, *res, error);
  6795. ASSERT_TRUE(ret);
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. }
  6798. TEST_F(ServerTest, HeaderCountAtLimit) {
  6799. // Test with headers just under the 100 limit
  6800. httplib::Headers headers;
  6801. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6802. // This should keep us just under the 100 header limit
  6803. for (int i = 0; i < 95; i++) {
  6804. std::string name = "X-Test-Header-" + std::to_string(i);
  6805. std::string value = "value" + std::to_string(i);
  6806. headers.emplace(name, value);
  6807. }
  6808. // This should work fine as we're under the limit
  6809. auto res = cli_.Get("/hi", headers);
  6810. EXPECT_TRUE(res);
  6811. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6812. }
  6813. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6814. // Test with many headers to exceed the 100 limit
  6815. httplib::Headers headers;
  6816. // Add 150 headers to definitely exceed the 100 limit
  6817. for (int i = 0; i < 150; i++) {
  6818. std::string name = "X-Test-Header-" + std::to_string(i);
  6819. std::string value = "value" + std::to_string(i);
  6820. headers.emplace(name, value);
  6821. }
  6822. // This should fail due to exceeding header count limit
  6823. cli_.set_keep_alive(true);
  6824. auto res = cli_.Get("/hi", headers);
  6825. // The server should respond with 400 Bad Request
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6828. EXPECT_EQ("close", res->get_header_value("Connection"));
  6829. EXPECT_FALSE(cli_.is_socket_open());
  6830. }
  6831. TEST_F(ServerTest, PercentEncoding) {
  6832. auto res = cli_.Get("/e%6edwith%");
  6833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6834. EXPECT_EQ(StatusCode::OK_200, res->status);
  6835. }
  6836. TEST_F(ServerTest, PercentEncodingUnicode) {
  6837. auto res = cli_.Get("/e%u006edwith%");
  6838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6839. EXPECT_EQ(StatusCode::OK_200, res->status);
  6840. }
  6841. TEST_F(ServerTest, InvalidPercentEncoding) {
  6842. auto res = cli_.Get("/%endwith%");
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6845. }
  6846. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6847. auto res = cli_.Get("/%uendwith%");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6850. }
  6851. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6852. auto res = cli_.Get("/hello?aaa=bbb%");
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6855. }
  6856. TEST_F(ServerTest, PlusSignEncoding) {
  6857. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6859. EXPECT_EQ(StatusCode::OK_200, res->status);
  6860. EXPECT_EQ("a +b", res->body);
  6861. }
  6862. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6863. // This test simulates a potential DoS attack using many headers
  6864. // to verify our security fix prevents memory exhaustion
  6865. httplib::Headers attack_headers;
  6866. // Attempt to add many headers like an attacker would (200 headers to far
  6867. // exceed limit)
  6868. for (int i = 0; i < 200; i++) {
  6869. std::string name = "X-Attack-Header-" + std::to_string(i);
  6870. std::string value = "attack_payload_" + std::to_string(i);
  6871. attack_headers.emplace(name, value);
  6872. }
  6873. // Try to POST with excessive headers
  6874. cli_.set_keep_alive(true);
  6875. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6876. // Should either fail or return 400 Bad Request due to security limit
  6877. if (res) {
  6878. // If we get a response, it should be 400 Bad Request
  6879. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6880. EXPECT_EQ("close", res->get_header_value("Connection"));
  6881. }
  6882. EXPECT_FALSE(cli_.is_socket_open());
  6883. }
  6884. TEST_F(ServerTest, MultipartFormData) {
  6885. UploadFormDataItems items = {
  6886. {"text1", "text default", "", ""},
  6887. {"text2", "aωb", "", ""},
  6888. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6889. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6890. {"file3", "", "", "application/octet-stream"},
  6891. {"file4", "", "", " application/json tmp-string "}};
  6892. auto res = cli_.Post("/multipart", items);
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::OK_200, res->status);
  6895. }
  6896. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6897. UploadFormDataItems items = {
  6898. {"text", "default text", "", ""},
  6899. {"multi_text1", "aaaaa", "", ""},
  6900. {"multi_text1", "bbbbb", "", ""},
  6901. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6902. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6903. "application/json"},
  6904. };
  6905. auto res = cli_.Post("/multipart/multi_file_values", items);
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::OK_200, res->status);
  6908. }
  6909. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6910. auto res = cli_.Get("/hi");
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::OK_200, res->status);
  6913. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6914. EXPECT_EQ("Hello World!", res->body);
  6915. }
  6916. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6917. Request req;
  6918. req.method = "POST";
  6919. req.path = "/chunked";
  6920. std::string host_and_port;
  6921. host_and_port += HOST;
  6922. host_and_port += ":";
  6923. host_and_port += std::to_string(PORT);
  6924. req.headers.emplace("Host", host_and_port.c_str());
  6925. req.headers.emplace("Accept", "*/*");
  6926. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6927. req.headers.emplace("Content-Type", "text/plain");
  6928. req.headers.emplace("Content-Length", "0");
  6929. req.headers.emplace(
  6930. "Transfer-Encoding",
  6931. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6932. // Client does not chunk, so make a chunked body manually.
  6933. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6934. auto res = std::make_shared<Response>();
  6935. auto error = Error::Success;
  6936. auto ret = cli_.send(req, *res, error);
  6937. ASSERT_TRUE(ret);
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. }
  6940. template <typename ClientT>
  6941. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6942. int expected_status) {
  6943. Request req;
  6944. req.method = "POST";
  6945. req.path = "/chunked";
  6946. std::string host_and_port;
  6947. host_and_port += HOST;
  6948. host_and_port += ":";
  6949. host_and_port += std::to_string(PORT);
  6950. req.headers.emplace("Host", host_and_port.c_str());
  6951. req.headers.emplace("Content-Length", "0");
  6952. req.headers.emplace("Transfer-Encoding", "chunked");
  6953. req.body = body;
  6954. auto res = std::make_shared<Response>();
  6955. auto error = Error::Success;
  6956. ASSERT_TRUE(cli.send(req, *res, error));
  6957. EXPECT_EQ(expected_status, res->status);
  6958. }
  6959. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6960. // rather than treat them as valid lengths.
  6961. template <typename ClientT>
  6962. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6963. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6964. }
  6965. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6966. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6967. }
  6968. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6969. expect_chunked_body_rejected(
  6970. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6971. }
  6972. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6973. // chunk-size line carries no CR, LF or other control character ahead of its
  6974. // terminator. Such a line must be refused rather than read as extension text.
  6975. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6976. expect_chunked_body_rejected(
  6977. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6978. }
  6979. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6980. expect_chunked_body_rejected(
  6981. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6982. }
  6983. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6984. expect_chunked_body_rejected(
  6985. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6986. }
  6987. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6988. // The literal stays split: a hex escape consumes every hex digit that
  6989. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6990. expect_chunked_body_rejected(
  6991. cli_, "4;a\x01"
  6992. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6993. }
  6994. // The bytes around chunk data are no payload, so they cannot ride on the
  6995. // payload limit
  6996. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6997. // Small enough that the whole request is sent before the server turns it
  6998. // down, yet past the limit by the last chunks
  6999. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7000. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7001. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7002. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7003. SCOPED_TRACE(size_line.substr(0, 2));
  7004. std::string body;
  7005. for (auto c : std::string("dechunked post body")) {
  7006. body += size_line + "\r\n" + c + "\r\n";
  7007. }
  7008. body += "0\r\n\r\n";
  7009. expect_chunked_body_rejected(cli_, body.c_str());
  7010. }
  7011. }
  7012. TEST_F(ServerTest, AcceptsChunkExtension) {
  7013. expect_chunked_body_status(cli_,
  7014. "4;name=value\r\ndech\r\n"
  7015. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7016. "0;last\r\n\r\n",
  7017. StatusCode::OK_200);
  7018. }
  7019. TEST_F(ServerTest, GetStreamed2) {
  7020. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7022. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7023. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7024. EXPECT_EQ(true, res->has_header("Content-Range"));
  7025. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7026. EXPECT_EQ(std::string("ab"), res->body);
  7027. }
  7028. TEST_F(ServerTest, GetStreamed) {
  7029. auto res = cli_.Get("/streamed");
  7030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7031. EXPECT_EQ(StatusCode::OK_200, res->status);
  7032. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7033. EXPECT_EQ(std::string("aaabbb"), res->body);
  7034. }
  7035. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7036. auto res = cli_.Get("/streamed-without-length",
  7037. Headers{make_range_header({{0, -1}})});
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::OK_200, res->status);
  7040. EXPECT_EQ(false, res->has_header("Content-Length"));
  7041. EXPECT_EQ(false, res->has_header("Content-Range"));
  7042. EXPECT_EQ(std::string("abcdefg"), res->body);
  7043. }
  7044. TEST_F(ServerTest, GetStreamedWithRange1) {
  7045. auto res =
  7046. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7049. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7050. EXPECT_EQ(true, res->has_header("Content-Range"));
  7051. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7052. EXPECT_EQ(std::string("def"), res->body);
  7053. }
  7054. TEST_F(ServerTest, GetStreamedWithRange2) {
  7055. auto res =
  7056. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7059. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7060. EXPECT_EQ(true, res->has_header("Content-Range"));
  7061. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7062. EXPECT_EQ(std::string("bcdefg"), res->body);
  7063. }
  7064. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7065. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7067. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7068. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7069. EXPECT_EQ(true, res->has_header("Content-Range"));
  7070. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7071. EXPECT_EQ(std::string("efg"), res->body);
  7072. }
  7073. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7074. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7075. // the entire representation.
  7076. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7077. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7079. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7080. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7081. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7082. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7083. }
  7084. }
  7085. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7086. auto res =
  7087. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7089. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7090. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7091. EXPECT_EQ(false, res->has_header("Content-Range"));
  7092. EXPECT_EQ(0U, res->body.size());
  7093. }
  7094. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7095. // Only a 206 is served as a partial representation. Under any other status
  7096. // `apply_ranges()` reported the full content length, so the body must match
  7097. // that header, and the content provider must never be asked for an offset
  7098. // outside the representation.
  7099. auto check = [&](int status, const char *range) {
  7100. auto path =
  7101. std::string("/streamed-with-range?status=") + std::to_string(status);
  7102. auto ctx = path + " Range: " + range;
  7103. auto res = cli_.Get(path, Headers{{"Range", range}});
  7104. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7105. EXPECT_EQ(status, res->status) << ctx;
  7106. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7108. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7109. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7110. };
  7111. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7112. check(403, "bytes=3-5");
  7113. // The offset is far past the representation.
  7114. check(403, "bytes=100000-100200");
  7115. // `first_pos` is still -1 here, and the bounds asserts in
  7116. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7117. check(403, "bytes=-3");
  7118. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7119. // multipart branch would have written one that is empty.
  7120. check(403, "bytes=1-2, 4-5");
  7121. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7122. // covers the whole representation.
  7123. check(200, "bytes=3-5");
  7124. check(200, "bytes=1-2, 4-5");
  7125. }
  7126. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7127. auto res =
  7128. cli_.Get("/streamed-with-range",
  7129. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7130. "92233720368547758079223372036854775807"}});
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7133. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7134. EXPECT_EQ(false, res->has_header("Content-Range"));
  7135. EXPECT_EQ(0U, res->body.size());
  7136. }
  7137. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7138. auto res = cli_.Get(
  7139. "/with-range",
  7140. Headers{{"Range",
  7141. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7142. {"Accept-Encoding", ""}});
  7143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7144. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7145. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7146. EXPECT_EQ(true, res->has_header("Content-Range"));
  7147. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7148. EXPECT_EQ(std::string("abcdefg"), res->body);
  7149. }
  7150. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7151. auto res = cli_.Get("/with-range", Headers{
  7152. {"Range", "bytes=0-"},
  7153. {"Accept-Encoding", ""},
  7154. });
  7155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7157. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7158. EXPECT_EQ(true, res->has_header("Content-Range"));
  7159. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7160. EXPECT_EQ(std::string("abcdefg"), res->body);
  7161. }
  7162. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7163. auto res = cli_.Get("/streamed-with-range",
  7164. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7167. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7168. EXPECT_EQ(false, res->has_header("Content-Range"));
  7169. EXPECT_EQ(267U, res->body.size());
  7170. // Check that both range contents are present
  7171. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7172. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7173. // Check that Content-Range headers are present for both ranges
  7174. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7175. std::string::npos);
  7176. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7177. std::string::npos);
  7178. }
  7179. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7180. Ranges ranges;
  7181. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7182. ranges.emplace_back(0, -1);
  7183. }
  7184. auto res = cli_.Get("/streamed-with-range?error",
  7185. Headers{{make_range_header(ranges)}});
  7186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7187. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7188. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7189. EXPECT_EQ(false, res->has_header("Content-Range"));
  7190. EXPECT_EQ(0U, res->body.size());
  7191. }
  7192. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7193. auto res = cli_.Get("/streamed-with-range",
  7194. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7197. EXPECT_EQ(5U, res->body.size());
  7198. // Check that overlapping ranges are coalesced into a single range
  7199. EXPECT_EQ("bcdef", res->body);
  7200. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7201. // Should be single range, not multipart
  7202. EXPECT_TRUE(res->has_header("Content-Range"));
  7203. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7204. }
  7205. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7206. auto res = cli_.Get("/streamed-with-range",
  7207. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7210. EXPECT_EQ(268U, res->body.size());
  7211. // Check that both range contents are present
  7212. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7213. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7214. // Check that Content-Range headers are present for both ranges
  7215. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7216. std::string::npos);
  7217. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7218. std::string::npos);
  7219. }
  7220. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7221. auto res = cli_.Get("/streamed-with-range",
  7222. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7224. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7225. EXPECT_EQ(269U, res->body.size());
  7226. // Check that both duplicate range contents are present
  7227. size_t first_abc = res->body.find("abc\r\n");
  7228. EXPECT_TRUE(first_abc != std::string::npos);
  7229. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7230. EXPECT_TRUE(second_abc != std::string::npos);
  7231. // Check that Content-Range headers are present for both ranges
  7232. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7233. EXPECT_TRUE(first_range != std::string::npos);
  7234. size_t second_range =
  7235. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7236. EXPECT_TRUE(second_range != std::string::npos);
  7237. }
  7238. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7239. auto res =
  7240. cli_.Get("/streamed-with-range?error",
  7241. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7243. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7244. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7245. EXPECT_EQ(false, res->has_header("Content-Range"));
  7246. EXPECT_EQ(0U, res->body.size());
  7247. }
  7248. TEST_F(ServerTest, GetStreamedEndless) {
  7249. uint64_t offset = 0;
  7250. auto res = cli_.Get("/streamed-cancel",
  7251. [&](const char * /*data*/, uint64_t data_length) {
  7252. if (offset < 100) {
  7253. offset += data_length;
  7254. return true;
  7255. }
  7256. return false;
  7257. });
  7258. ASSERT_TRUE(!res);
  7259. EXPECT_EQ(Error::Canceled, res.error());
  7260. }
  7261. TEST_F(ServerTest, ClientStop) {
  7262. std::atomic_size_t count{4};
  7263. std::vector<std::thread> threads;
  7264. for (auto i = count.load(); i != 0; --i) {
  7265. threads.emplace_back([&]() {
  7266. auto res = cli_.Get("/streamed-cancel",
  7267. [&](const char *, uint64_t) { return true; });
  7268. --count;
  7269. ASSERT_TRUE(!res);
  7270. EXPECT_TRUE(res.error() == Error::Canceled ||
  7271. res.error() == Error::Read || res.error() == Error::Write);
  7272. });
  7273. }
  7274. std::this_thread::sleep_for(std::chrono::seconds(2));
  7275. while (count != 0) {
  7276. cli_.stop();
  7277. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7278. }
  7279. for (auto &t : threads) {
  7280. t.join();
  7281. }
  7282. }
  7283. TEST_F(ServerTest, GetWithRange1) {
  7284. auto res = cli_.Get("/with-range", Headers{
  7285. make_range_header({{3, 5}}),
  7286. {"Accept-Encoding", ""},
  7287. });
  7288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7289. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7290. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7291. EXPECT_EQ(true, res->has_header("Content-Range"));
  7292. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7293. EXPECT_EQ(std::string("def"), res->body);
  7294. }
  7295. TEST_F(ServerTest, GetWithRange2) {
  7296. auto res = cli_.Get("/with-range", Headers{
  7297. make_range_header({{1, -1}}),
  7298. {"Accept-Encoding", ""},
  7299. });
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7302. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7303. EXPECT_EQ(true, res->has_header("Content-Range"));
  7304. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7305. EXPECT_EQ(std::string("bcdefg"), res->body);
  7306. }
  7307. TEST_F(ServerTest, GetWithRange3) {
  7308. auto res = cli_.Get("/with-range", Headers{
  7309. make_range_header({{0, 0}}),
  7310. {"Accept-Encoding", ""},
  7311. });
  7312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7313. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7314. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7315. EXPECT_EQ(true, res->has_header("Content-Range"));
  7316. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7317. EXPECT_EQ(std::string("a"), res->body);
  7318. }
  7319. TEST_F(ServerTest, GetWithRange4) {
  7320. auto res = cli_.Get("/with-range", Headers{
  7321. make_range_header({{-1, 2}}),
  7322. {"Accept-Encoding", ""},
  7323. });
  7324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7325. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7326. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7327. EXPECT_EQ(true, res->has_header("Content-Range"));
  7328. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7329. EXPECT_EQ(std::string("fg"), res->body);
  7330. }
  7331. TEST_F(ServerTest, GetWithRange5) {
  7332. auto res = cli_.Get("/with-range", Headers{
  7333. make_range_header({{0, 5}}),
  7334. {"Accept-Encoding", ""},
  7335. });
  7336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7337. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7338. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7339. EXPECT_EQ(true, res->has_header("Content-Range"));
  7340. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7341. EXPECT_EQ(std::string("abcdef"), res->body);
  7342. }
  7343. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7344. auto res =
  7345. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7347. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7348. }
  7349. TEST_F(ServerTest, GetWithRangeMultipart) {
  7350. auto res =
  7351. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7353. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7354. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7355. EXPECT_EQ(false, res->has_header("Content-Range"));
  7356. EXPECT_EQ(267U, res->body.size());
  7357. }
  7358. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7359. auto res = cli_.Get("/with-range",
  7360. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7362. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7363. }
  7364. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7365. auto res = cli_.Get("/with-range-customized-response",
  7366. Headers{{make_range_header({{1, 2}})}});
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7369. EXPECT_EQ(true, res->has_header("Content-Length"));
  7370. EXPECT_EQ(false, res->has_header("Content-Range"));
  7371. EXPECT_EQ(JSON_DATA, res->body);
  7372. }
  7373. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7374. auto res = cli_.Get("/with-range-customized-response",
  7375. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7377. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7378. EXPECT_EQ(true, res->has_header("Content-Length"));
  7379. EXPECT_EQ(false, res->has_header("Content-Range"));
  7380. EXPECT_EQ(JSON_DATA, res->body);
  7381. }
  7382. TEST_F(ServerTest, Issue1772) {
  7383. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7385. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7386. }
  7387. TEST_F(ServerTest, Issue609) {
  7388. auto res = cli_.Delete("/issue609");
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. EXPECT_EQ(std::string("ok"), res->body);
  7392. }
  7393. TEST_F(ServerTest, GetStreamedChunked) {
  7394. auto res = cli_.Get("/streamed-chunked");
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::OK_200, res->status);
  7397. EXPECT_EQ(std::string("123456789"), res->body);
  7398. }
  7399. TEST_F(ServerTest, GetStreamedChunked2) {
  7400. auto res = cli_.Get("/streamed-chunked2");
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::OK_200, res->status);
  7403. EXPECT_EQ(std::string("123456789"), res->body);
  7404. }
  7405. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7406. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::OK_200, res->status);
  7409. EXPECT_EQ(std::string("123456789"), res->body);
  7410. EXPECT_TRUE(res->has_header("Trailer"));
  7411. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7412. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7413. // Trailers are now stored separately from headers (security fix)
  7414. EXPECT_EQ(2U, res->trailers.size());
  7415. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7416. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7417. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7418. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7419. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7420. // Verify trailers are NOT in headers (security verification)
  7421. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7422. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7423. }
  7424. TEST_F(ServerTest, LargeChunkedPost) {
  7425. Request req;
  7426. req.method = "POST";
  7427. req.path = "/large-chunked";
  7428. std::string host_and_port;
  7429. host_and_port += HOST;
  7430. host_and_port += ":";
  7431. host_and_port += std::to_string(PORT);
  7432. req.headers.emplace("Host", host_and_port.c_str());
  7433. req.headers.emplace("Accept", "*/*");
  7434. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7435. req.headers.emplace("Content-Type", "text/plain");
  7436. req.headers.emplace("Content-Length", "0");
  7437. req.headers.emplace("Transfer-Encoding", "chunked");
  7438. std::string long_string(30 * 1024u, 'a');
  7439. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7440. // Attempt to make a large enough post to exceed OS buffers, to test that
  7441. // the server handles short reads if the full chunk data isn't available.
  7442. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7443. auto res = std::make_shared<Response>();
  7444. auto error = Error::Success;
  7445. auto ret = cli_.send(req, *res, error);
  7446. ASSERT_TRUE(ret);
  7447. EXPECT_EQ(StatusCode::OK_200, res->status);
  7448. }
  7449. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7450. auto res = cli_.Get("/remote_addr");
  7451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7452. EXPECT_EQ(StatusCode::OK_200, res->status);
  7453. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7454. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7455. }
  7456. TEST_F(ServerTest, GetMethodLocalAddr) {
  7457. auto res = cli_.Get("/local_addr");
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::OK_200, res->status);
  7460. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7461. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7462. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7463. }
  7464. TEST_F(ServerTest, HTTPResponseSplitting) {
  7465. auto res = cli_.Get("/http_response_splitting");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. }
  7469. TEST_F(ServerTest, SlowRequest) {
  7470. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7471. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7472. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7473. }
  7474. #if 0
  7475. TEST_F(ServerTest, SlowPost) {
  7476. char buffer[64 * 1024];
  7477. memset(buffer, 0x42, sizeof(buffer));
  7478. auto res = cli_.Post(
  7479. "/slowpost", 64 * 1024 * 1024,
  7480. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7481. auto ret = sink.write(buffer, sizeof(buffer));
  7482. EXPECT_TRUE(ret);
  7483. return true;
  7484. },
  7485. "text/plain");
  7486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7487. EXPECT_EQ(StatusCode::OK_200, res->status);
  7488. }
  7489. TEST_F(ServerTest, SlowPostFail) {
  7490. char buffer[64 * 1024];
  7491. memset(buffer, 0x42, sizeof(buffer));
  7492. cli_.set_write_timeout(std::chrono::seconds(0));
  7493. auto res = cli_.Post(
  7494. "/slowpost", 64 * 1024 * 1024,
  7495. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7496. sink.write(buffer, sizeof(buffer));
  7497. return true;
  7498. },
  7499. "text/plain");
  7500. ASSERT_TRUE(!res);
  7501. EXPECT_EQ(Error::Write, res.error());
  7502. }
  7503. #endif
  7504. TEST_F(ServerTest, Put) {
  7505. auto res = cli_.Put("/put", "PUT", "text/plain");
  7506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7507. EXPECT_EQ(StatusCode::OK_200, res->status);
  7508. EXPECT_EQ("PUT", res->body);
  7509. }
  7510. TEST_F(ServerTest, PutWithContentProvider) {
  7511. auto res = cli_.Put(
  7512. "/put", 3,
  7513. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7514. sink.os << "PUT";
  7515. return true;
  7516. },
  7517. "text/plain");
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. EXPECT_EQ("PUT", res->body);
  7521. }
  7522. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7523. auto res = cli_.Post(
  7524. "/post", 42,
  7525. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7526. return false;
  7527. },
  7528. "text/plain");
  7529. ASSERT_TRUE(!res);
  7530. EXPECT_EQ(Error::Canceled, res.error());
  7531. }
  7532. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7533. auto res = cli_.Put(
  7534. "/put",
  7535. [](size_t /*offset*/, DataSink &sink) {
  7536. sink.os << "PUT";
  7537. sink.done();
  7538. return true;
  7539. },
  7540. "text/plain");
  7541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7542. EXPECT_EQ(StatusCode::OK_200, res->status);
  7543. EXPECT_EQ("PUT", res->body);
  7544. }
  7545. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7546. auto res = cli_.Post(
  7547. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7548. "text/plain");
  7549. ASSERT_TRUE(!res);
  7550. EXPECT_EQ(Error::Canceled, res.error());
  7551. }
  7552. TEST_F(ServerTest, PostLoopBack) {
  7553. std::string body;
  7554. auto res = cli_.Post(
  7555. "/post-loopback", 9,
  7556. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7557. EXPECT_EQ(9u, length);
  7558. sink.write("123", 3);
  7559. sink.write("456", 3);
  7560. sink.write("789", 3);
  7561. return true;
  7562. },
  7563. "text/plain",
  7564. [&body](const char *data, size_t data_length) {
  7565. body.append(data, data_length);
  7566. return true;
  7567. });
  7568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7569. EXPECT_EQ(StatusCode::OK_200, res->status);
  7570. EXPECT_EQ("123456789", body);
  7571. }
  7572. TEST_F(ServerTest, PutLoopBack) {
  7573. std::string body;
  7574. auto res = cli_.Put(
  7575. "/put-loopback", 9,
  7576. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7577. EXPECT_EQ(9u, length);
  7578. sink.write("123", 3);
  7579. sink.write("456", 3);
  7580. sink.write("789", 3);
  7581. return true;
  7582. },
  7583. "text/plain",
  7584. [&body](const char *data, size_t data_length) {
  7585. body.append(data, data_length);
  7586. return true;
  7587. });
  7588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7589. EXPECT_EQ(StatusCode::OK_200, res->status);
  7590. EXPECT_EQ("123456789", body);
  7591. }
  7592. TEST_F(ServerTest, PatchLoopBack) {
  7593. std::string body;
  7594. auto res = cli_.Patch(
  7595. "/patch-loopback", 9,
  7596. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7597. EXPECT_EQ(9u, length);
  7598. sink.write("123", 3);
  7599. sink.write("456", 3);
  7600. sink.write("789", 3);
  7601. return true;
  7602. },
  7603. "text/plain",
  7604. [&body](const char *data, size_t data_length) {
  7605. body.append(data, data_length);
  7606. return true;
  7607. });
  7608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7609. EXPECT_EQ(StatusCode::OK_200, res->status);
  7610. EXPECT_EQ("123456789", body);
  7611. }
  7612. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7613. std::string body;
  7614. auto res = cli_.Post(
  7615. "/post-loopback",
  7616. [](size_t /*offset*/, DataSink &sink) {
  7617. sink.write("123", 3);
  7618. sink.write("456", 3);
  7619. sink.write("789", 3);
  7620. sink.done();
  7621. return true;
  7622. },
  7623. "text/plain",
  7624. [&body](const char *data, size_t data_length) {
  7625. body.append(data, data_length);
  7626. return true;
  7627. });
  7628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7629. EXPECT_EQ(StatusCode::OK_200, res->status);
  7630. EXPECT_EQ("123456789", body);
  7631. }
  7632. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7633. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7634. cli_.set_compress(true);
  7635. auto res = cli_.Put(
  7636. "/put", 3,
  7637. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7638. sink.os << "PUT";
  7639. return true;
  7640. },
  7641. "text/plain");
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(StatusCode::OK_200, res->status);
  7644. EXPECT_EQ("PUT", res->body);
  7645. }
  7646. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7647. cli_.set_compress(true);
  7648. auto res = cli_.Post(
  7649. "/post", 42,
  7650. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7651. return false;
  7652. },
  7653. "text/plain");
  7654. ASSERT_TRUE(!res);
  7655. EXPECT_EQ(Error::Canceled, res.error());
  7656. }
  7657. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7658. cli_.set_compress(true);
  7659. auto res = cli_.Put(
  7660. "/put",
  7661. [](size_t /*offset*/, DataSink &sink) {
  7662. sink.os << "PUT";
  7663. sink.done();
  7664. return true;
  7665. },
  7666. "text/plain");
  7667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7668. EXPECT_EQ(StatusCode::OK_200, res->status);
  7669. EXPECT_EQ("PUT", res->body);
  7670. }
  7671. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7672. cli_.set_compress(true);
  7673. auto res = cli_.Post(
  7674. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7675. "text/plain");
  7676. ASSERT_TRUE(!res);
  7677. EXPECT_EQ(Error::Canceled, res.error());
  7678. }
  7679. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7680. cli_.set_compress(true);
  7681. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7683. EXPECT_EQ(StatusCode::OK_200, res->status);
  7684. EXPECT_EQ(LARGE_DATA, res->body);
  7685. }
  7686. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7687. #ifdef CPPHTTPLIB_SSL_ENABLED
  7688. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7689. Client cli(s.c_str());
  7690. cli.enable_server_certificate_verification(false);
  7691. #else
  7692. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7693. Client cli(s.c_str());
  7694. #endif
  7695. cli.set_compress(true);
  7696. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7698. EXPECT_EQ(StatusCode::OK_200, res->status);
  7699. EXPECT_EQ(LARGE_DATA, res->body);
  7700. // The compressed size should be less than a 10th of the original. May vary
  7701. // depending on the zlib library.
  7702. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7703. static_cast<uint64_t>(10 * 1024 * 1024));
  7704. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7705. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7706. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7707. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7708. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7709. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7710. #endif
  7711. }
  7712. TEST_F(ServerTest, PutContentWithDeflate) {
  7713. cli_.set_compress(false);
  7714. Headers headers;
  7715. headers.emplace("Content-Encoding", "deflate");
  7716. // PUT in deflate format:
  7717. auto res = cli_.Put("/put", headers,
  7718. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7720. EXPECT_EQ(StatusCode::OK_200, res->status);
  7721. EXPECT_EQ("PUT", res->body);
  7722. }
  7723. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7724. Headers headers;
  7725. headers.emplace("Accept-Encoding", "gzip, deflate");
  7726. auto res = cli_.Get("/streamed-chunked", headers);
  7727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7728. EXPECT_EQ(StatusCode::OK_200, res->status);
  7729. EXPECT_EQ(std::string("123456789"), res->body);
  7730. }
  7731. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7732. Headers headers;
  7733. headers.emplace("Accept-Encoding", "gzip, deflate");
  7734. auto res = cli_.Get("/streamed-chunked2", headers);
  7735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7736. EXPECT_EQ(StatusCode::OK_200, res->status);
  7737. EXPECT_EQ(std::string("123456789"), res->body);
  7738. }
  7739. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7740. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. }
  7744. TEST(GzipDecompressor, ChunkedDecompression) {
  7745. std::string data;
  7746. for (size_t i = 0; i < 32 * 1024; ++i) {
  7747. data.push_back(static_cast<char>('a' + i % 26));
  7748. }
  7749. std::string compressed_data;
  7750. {
  7751. httplib::detail::gzip_compressor compressor;
  7752. bool result = compressor.compress(
  7753. data.data(), data.size(),
  7754. /*last=*/true,
  7755. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7756. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7757. compressed_data_size);
  7758. return true;
  7759. });
  7760. ASSERT_TRUE(result);
  7761. }
  7762. std::string decompressed_data;
  7763. {
  7764. httplib::detail::gzip_decompressor decompressor;
  7765. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7766. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7767. size_t chunk_size = 130;
  7768. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7769. chunk_begin += chunk_size) {
  7770. size_t current_chunk_size =
  7771. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7772. bool result = decompressor.decompress(
  7773. compressed_data.data() + chunk_begin, current_chunk_size,
  7774. [&](const char *decompressed_data_chunk,
  7775. size_t decompressed_data_chunk_size) {
  7776. decompressed_data.insert(decompressed_data.size(),
  7777. decompressed_data_chunk,
  7778. decompressed_data_chunk_size);
  7779. return true;
  7780. });
  7781. ASSERT_TRUE(result);
  7782. }
  7783. }
  7784. ASSERT_EQ(data, decompressed_data);
  7785. }
  7786. TEST(GzipDecompressor, DeflateDecompression) {
  7787. std::string original_text = "Raw deflate without gzip";
  7788. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7789. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7790. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7791. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7792. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7793. std::string decompressed_data;
  7794. {
  7795. httplib::detail::gzip_decompressor decompressor;
  7796. bool result = decompressor.decompress(
  7797. compressed_data.data(), compressed_data.size(),
  7798. [&](const char *decompressed_data_chunk,
  7799. size_t decompressed_data_chunk_size) {
  7800. decompressed_data.insert(decompressed_data.size(),
  7801. decompressed_data_chunk,
  7802. decompressed_data_chunk_size);
  7803. return true;
  7804. });
  7805. ASSERT_TRUE(result);
  7806. }
  7807. ASSERT_EQ(original_text, decompressed_data);
  7808. }
  7809. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7810. std::string original_text = "Raw deflate without gzip";
  7811. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7812. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7813. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7814. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7815. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7816. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7817. std::string decompressed_data;
  7818. {
  7819. httplib::detail::gzip_decompressor decompressor;
  7820. bool result = decompressor.decompress(
  7821. compressed_data.data(), compressed_data.size(),
  7822. [&](const char *decompressed_data_chunk,
  7823. size_t decompressed_data_chunk_size) {
  7824. decompressed_data.insert(decompressed_data.size(),
  7825. decompressed_data_chunk,
  7826. decompressed_data_chunk_size);
  7827. return true;
  7828. });
  7829. ASSERT_TRUE(result);
  7830. }
  7831. ASSERT_EQ(original_text, decompressed_data);
  7832. }
  7833. #endif
  7834. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7835. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7836. Headers headers;
  7837. headers.emplace("Accept-Encoding", "br");
  7838. auto res = cli_.Get("/streamed-chunked", headers);
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::OK_200, res->status);
  7841. EXPECT_EQ(std::string("123456789"), res->body);
  7842. }
  7843. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7844. Headers headers;
  7845. headers.emplace("Accept-Encoding", "br");
  7846. auto res = cli_.Get("/streamed-chunked2", headers);
  7847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7848. EXPECT_EQ(StatusCode::OK_200, res->status);
  7849. EXPECT_EQ(std::string("123456789"), res->body);
  7850. }
  7851. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7852. cli_.set_compress(true);
  7853. auto res = cli_.Put(
  7854. "/put", 3,
  7855. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7856. sink.os << "PUT";
  7857. return true;
  7858. },
  7859. "text/plain");
  7860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7861. EXPECT_EQ(StatusCode::OK_200, res->status);
  7862. EXPECT_EQ("PUT", res->body);
  7863. }
  7864. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7865. cli_.set_compress(true);
  7866. auto res = cli_.Put(
  7867. "/put",
  7868. [](size_t /*offset*/, DataSink &sink) {
  7869. sink.os << "PUT";
  7870. sink.done();
  7871. return true;
  7872. },
  7873. "text/plain");
  7874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7875. EXPECT_EQ(StatusCode::OK_200, res->status);
  7876. EXPECT_EQ("PUT", res->body);
  7877. }
  7878. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7879. cli_.set_compress(true);
  7880. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7882. EXPECT_EQ(StatusCode::OK_200, res->status);
  7883. EXPECT_EQ(LARGE_DATA, res->body);
  7884. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7885. }
  7886. #endif
  7887. TEST_F(ServerTest, Patch) {
  7888. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7890. EXPECT_EQ(StatusCode::OK_200, res->status);
  7891. EXPECT_EQ("PATCH", res->body);
  7892. }
  7893. TEST_F(ServerTest, Delete) {
  7894. auto res = cli_.Delete("/delete");
  7895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7896. EXPECT_EQ(StatusCode::OK_200, res->status);
  7897. EXPECT_EQ("DELETE", res->body);
  7898. }
  7899. TEST_F(ServerTest, DeleteContentReceiver) {
  7900. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ(StatusCode::OK_200, res->status);
  7903. EXPECT_EQ("content", res->body);
  7904. }
  7905. TEST_F(ServerTest, Options) {
  7906. auto res = cli_.Options("*");
  7907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7908. EXPECT_EQ(StatusCode::OK_200, res->status);
  7909. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7910. EXPECT_TRUE(res->body.empty());
  7911. }
  7912. TEST_F(ServerTest, URL) {
  7913. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7915. EXPECT_EQ(StatusCode::OK_200, res->status);
  7916. }
  7917. TEST_F(ServerTest, ArrayParam) {
  7918. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_EQ(StatusCode::OK_200, res->status);
  7921. }
  7922. TEST_F(ServerTest, ArrayParamValues) {
  7923. auto res =
  7924. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7926. EXPECT_EQ(StatusCode::OK_200, res->status);
  7927. }
  7928. TEST_F(ServerTest, NoMultipleHeaders) {
  7929. Headers headers = {{"Content-Length", "5"}};
  7930. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7931. "text/plain");
  7932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. TEST_F(ServerTest, PostContentReceiver) {
  7936. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7938. ASSERT_EQ(StatusCode::OK_200, res->status);
  7939. ASSERT_EQ("content", res->body);
  7940. }
  7941. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7942. UploadFormDataItems items = {
  7943. {"text1", "text default", "", ""},
  7944. {"text2", "aωb", "", ""},
  7945. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7946. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7947. {"file3", "", "", "application/octet-stream"},
  7948. };
  7949. auto res = cli_.Post("/content_receiver", items);
  7950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7951. EXPECT_EQ(StatusCode::OK_200, res->status);
  7952. }
  7953. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7954. UploadFormDataItems items = {
  7955. {"text1", "text default", "", ""},
  7956. {"text2", "aωb", "", ""},
  7957. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7958. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7959. {"file3", "", "", "application/octet-stream"},
  7960. };
  7961. auto boundary = std::string("+++++");
  7962. std::string body;
  7963. for (const auto &item : items) {
  7964. body += "--" + boundary + "\r\n";
  7965. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7966. if (!item.filename.empty()) {
  7967. body += "; filename=\"" + item.filename + "\"";
  7968. }
  7969. body += "\r\n";
  7970. if (!item.content_type.empty()) {
  7971. body += "Content-Type: " + item.content_type + "\r\n";
  7972. }
  7973. body += "\r\n";
  7974. body += item.content + "\r\n";
  7975. }
  7976. body += "--" + boundary + "--\r\n";
  7977. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7978. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7980. EXPECT_EQ(StatusCode::OK_200, res->status);
  7981. }
  7982. TEST(MultipartFormDataTest, FieldEscaping) {
  7983. Server svr;
  7984. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7985. const ContentReader &content_reader) {
  7986. ASSERT_TRUE(req.is_multipart_form_data());
  7987. std::vector<FormData> received;
  7988. content_reader(
  7989. [&](const FormData &file) {
  7990. received.push_back(file);
  7991. return true;
  7992. },
  7993. [&](const char *data, size_t data_length) {
  7994. received.back().content.append(data, data_length);
  7995. return true;
  7996. });
  7997. // '"', CR and LF in names and filenames are escaped following the
  7998. // WHATWG HTML standard, so each part still parses as a single part
  7999. // with no injected headers. Content types get CR/LF escaped too,
  8000. // while '"' (legal there, e.g. quoted charset) is preserved.
  8001. ASSERT_EQ(4U, received.size());
  8002. EXPECT_EQ("na%22me", received[0].name);
  8003. EXPECT_EQ("quoted name", received[0].content);
  8004. EXPECT_EQ("file", received[1].name);
  8005. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8006. received[1].filename);
  8007. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8008. EXPECT_EQ("injected", received[1].content);
  8009. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8010. EXPECT_EQ("my%22file.txt", received[2].filename);
  8011. EXPECT_EQ("cr lf name", received[2].content);
  8012. EXPECT_EQ("typed", received[3].name);
  8013. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8014. received[3].content_type);
  8015. EXPECT_EQ("typed content", received[3].content);
  8016. });
  8017. auto port = svr.bind_to_any_port("localhost");
  8018. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8019. auto se = detail::scope_exit([&] {
  8020. svr.stop();
  8021. t.join();
  8022. ASSERT_FALSE(svr.is_running());
  8023. });
  8024. svr.wait_until_ready();
  8025. Client cli("localhost", port);
  8026. UploadFormDataItems items = {
  8027. {"na\"me", "quoted name", "", ""},
  8028. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8029. "application/octet-stream"},
  8030. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8031. {"typed", "typed content", "",
  8032. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8033. };
  8034. auto res = cli.Post("/post", items);
  8035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8036. EXPECT_EQ(StatusCode::OK_200, res->status);
  8037. }
  8038. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8039. const UploadFormDataItems items = {
  8040. {"name1", "Content 1", "", ""},
  8041. {"name2", "Content 2", "file2.txt", "text/plain"},
  8042. };
  8043. Server svr;
  8044. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8045. const ContentReader &content_reader) {
  8046. ASSERT_TRUE(req.is_multipart_form_data());
  8047. std::vector<FormData> received;
  8048. content_reader(
  8049. [&](const FormData &file) {
  8050. received.push_back(file);
  8051. return true;
  8052. },
  8053. [&](const char *data, size_t data_length) {
  8054. received.back().content.append(data, data_length);
  8055. return true;
  8056. });
  8057. ASSERT_EQ(2U, received.size());
  8058. EXPECT_EQ("name1", received[0].name);
  8059. EXPECT_EQ("Content 1", received[0].content);
  8060. EXPECT_EQ("name2", received[1].name);
  8061. EXPECT_EQ("Content 2", received[1].content);
  8062. EXPECT_EQ("file2.txt", received[1].filename);
  8063. EXPECT_EQ("text/plain", received[1].content_type);
  8064. });
  8065. auto port = svr.bind_to_any_port("localhost");
  8066. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8067. auto se = detail::scope_exit([&] {
  8068. svr.stop();
  8069. t.join();
  8070. ASSERT_FALSE(svr.is_running());
  8071. });
  8072. svr.wait_until_ready();
  8073. Client cli("localhost", port);
  8074. // Whole-body serialization with a generated boundary
  8075. {
  8076. MultipartFormDataWriter writer;
  8077. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8078. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8079. writer.content_type());
  8080. auto body = writer.serialize(items);
  8081. EXPECT_EQ(body.size(), writer.content_length(items));
  8082. auto res = cli.Post("/post", body, writer.content_type());
  8083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8084. EXPECT_EQ(StatusCode::OK_200, res->status);
  8085. }
  8086. // Per-part framing with a custom boundary via a content provider
  8087. {
  8088. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8089. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8090. MultipartFormDataWriter writer("custom-boundary_123");
  8091. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8092. std::string body;
  8093. for (const auto &item : items) {
  8094. body += writer.item_begin(item);
  8095. body += item.content;
  8096. body += MultipartFormDataWriter::item_end();
  8097. }
  8098. body += writer.finish();
  8099. EXPECT_EQ(body.size(), writer.content_length(items));
  8100. auto res = cli.Post(
  8101. "/post", body.size(),
  8102. [&](size_t offset, size_t length, DataSink &sink) {
  8103. sink.write(body.data() + offset, length);
  8104. return true;
  8105. },
  8106. writer.content_type());
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. }
  8110. }
  8111. TEST_F(ServerTest, PostContentReceiverGzip) {
  8112. cli_.set_compress(true);
  8113. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8115. ASSERT_EQ(StatusCode::OK_200, res->status);
  8116. ASSERT_EQ("content", res->body);
  8117. }
  8118. TEST_F(ServerTest, PutContentReceiver) {
  8119. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8121. ASSERT_EQ(StatusCode::OK_200, res->status);
  8122. ASSERT_EQ("content", res->body);
  8123. }
  8124. TEST_F(ServerTest, PatchContentReceiver) {
  8125. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. ASSERT_EQ(StatusCode::OK_200, res->status);
  8128. ASSERT_EQ("content", res->body);
  8129. }
  8130. template <typename ClientType>
  8131. void TestWithHeadersAndContentReceiver(
  8132. ClientType &cli,
  8133. std::function<Result(ClientType &, const std::string &, const Headers &,
  8134. const std::string &, const std::string &,
  8135. ContentReceiver, DownloadProgress)>
  8136. request_func) {
  8137. Headers headers;
  8138. headers.emplace("X-Custom-Header", "test-value");
  8139. std::string received_body;
  8140. auto res = request_func(
  8141. cli, "/content_receiver", headers, "content", "application/json",
  8142. [&](const char *data, size_t data_length) {
  8143. received_body.append(data, data_length);
  8144. return true;
  8145. },
  8146. nullptr);
  8147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8148. EXPECT_EQ(StatusCode::OK_200, res->status);
  8149. EXPECT_EQ("content", received_body);
  8150. }
  8151. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8152. #ifdef CPPHTTPLIB_SSL_ENABLED
  8153. using ClientT = SSLClient;
  8154. #else
  8155. using ClientT = Client;
  8156. #endif
  8157. TestWithHeadersAndContentReceiver<ClientT>(
  8158. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8159. const std::string &body, const std::string &content_type,
  8160. ContentReceiver receiver, DownloadProgress progress) {
  8161. return cli.Post(path, headers, body, content_type, receiver, progress);
  8162. });
  8163. }
  8164. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8165. #ifdef CPPHTTPLIB_SSL_ENABLED
  8166. using ClientT = SSLClient;
  8167. #else
  8168. using ClientT = Client;
  8169. #endif
  8170. TestWithHeadersAndContentReceiver<ClientT>(
  8171. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8172. const std::string &body, const std::string &content_type,
  8173. ContentReceiver receiver, DownloadProgress progress) {
  8174. return cli.Put(path, headers, body, content_type, receiver, progress);
  8175. });
  8176. }
  8177. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8178. #ifdef CPPHTTPLIB_SSL_ENABLED
  8179. using ClientT = SSLClient;
  8180. #else
  8181. using ClientT = Client;
  8182. #endif
  8183. TestWithHeadersAndContentReceiver<ClientT>(
  8184. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8185. const std::string &body, const std::string &content_type,
  8186. ContentReceiver receiver, DownloadProgress progress) {
  8187. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8188. });
  8189. }
  8190. template <typename ClientType>
  8191. void TestWithHeadersAndContentReceiverWithProgress(
  8192. ClientType &cli,
  8193. std::function<Result(ClientType &, const std::string &, const Headers &,
  8194. const std::string &, const std::string &,
  8195. ContentReceiver, DownloadProgress)>
  8196. request_func) {
  8197. Headers headers;
  8198. headers.emplace("X-Test-Header", "progress-test");
  8199. std::string received_body;
  8200. auto progress_called = false;
  8201. auto res = request_func(
  8202. cli, "/content_receiver", headers, "content", "text/plain",
  8203. [&](const char *data, size_t data_length) {
  8204. received_body.append(data, data_length);
  8205. return true;
  8206. },
  8207. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8208. progress_called = true;
  8209. return true;
  8210. });
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_EQ("content", received_body);
  8214. EXPECT_TRUE(progress_called);
  8215. }
  8216. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8217. #ifdef CPPHTTPLIB_SSL_ENABLED
  8218. using ClientT = SSLClient;
  8219. #else
  8220. using ClientT = Client;
  8221. #endif
  8222. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8223. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8224. const std::string &body, const std::string &content_type,
  8225. ContentReceiver receiver, DownloadProgress progress) {
  8226. return cli.Post(path, headers, body, content_type, receiver, progress);
  8227. });
  8228. }
  8229. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8230. #ifdef CPPHTTPLIB_SSL_ENABLED
  8231. using ClientT = SSLClient;
  8232. #else
  8233. using ClientT = Client;
  8234. #endif
  8235. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8236. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8237. const std::string &body, const std::string &content_type,
  8238. ContentReceiver receiver, DownloadProgress progress) {
  8239. return cli.Put(path, headers, body, content_type, receiver, progress);
  8240. });
  8241. }
  8242. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8243. #ifdef CPPHTTPLIB_SSL_ENABLED
  8244. using ClientT = SSLClient;
  8245. #else
  8246. using ClientT = Client;
  8247. #endif
  8248. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8249. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8250. const std::string &body, const std::string &content_type,
  8251. ContentReceiver receiver, DownloadProgress progress) {
  8252. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8253. });
  8254. }
  8255. template <typename ClientType>
  8256. void TestWithHeadersAndContentReceiverError(
  8257. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8258. const Headers &, const std::string &,
  8259. const std::string &, ContentReceiver)>
  8260. request_func) {
  8261. Headers headers;
  8262. headers.emplace("X-Error-Test", "true");
  8263. std::string received_body;
  8264. auto receiver_failed = false;
  8265. auto res =
  8266. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8267. [&](const char *data, size_t data_length) {
  8268. received_body.append(data, data_length);
  8269. receiver_failed = true;
  8270. return false;
  8271. });
  8272. ASSERT_FALSE(res);
  8273. EXPECT_TRUE(receiver_failed);
  8274. }
  8275. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8276. #ifdef CPPHTTPLIB_SSL_ENABLED
  8277. using ClientT = SSLClient;
  8278. #else
  8279. using ClientT = Client;
  8280. #endif
  8281. TestWithHeadersAndContentReceiverError<ClientT>(
  8282. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8283. const std::string &body, const std::string &content_type,
  8284. ContentReceiver receiver) {
  8285. return cli.Post(path, headers, body, content_type, receiver);
  8286. });
  8287. }
  8288. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8289. #ifdef CPPHTTPLIB_SSL_ENABLED
  8290. using ClientT = SSLClient;
  8291. #else
  8292. using ClientT = Client;
  8293. #endif
  8294. TestWithHeadersAndContentReceiverError<ClientT>(
  8295. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8296. const std::string &body, const std::string &content_type,
  8297. ContentReceiver receiver) {
  8298. return cli.Put(path, headers, body, content_type, receiver);
  8299. });
  8300. }
  8301. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8302. #ifdef CPPHTTPLIB_SSL_ENABLED
  8303. using ClientT = SSLClient;
  8304. #else
  8305. using ClientT = Client;
  8306. #endif
  8307. TestWithHeadersAndContentReceiverError<ClientT>(
  8308. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8309. const std::string &body, const std::string &content_type,
  8310. ContentReceiver receiver) {
  8311. return cli.Patch(path, headers, body, content_type, receiver);
  8312. });
  8313. }
  8314. TEST_F(ServerTest, PostQueryStringAndBody) {
  8315. auto res =
  8316. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8318. ASSERT_EQ(StatusCode::OK_200, res->status);
  8319. }
  8320. TEST_F(ServerTest, HTTP2Magic) {
  8321. Request req;
  8322. req.method = "PRI";
  8323. req.path = "*";
  8324. req.body = "SM";
  8325. auto res = std::make_shared<Response>();
  8326. auto error = Error::Success;
  8327. auto ret = cli_.send(req, *res, error);
  8328. ASSERT_TRUE(ret);
  8329. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8330. }
  8331. TEST_F(ServerTest, KeepAlive) {
  8332. auto res = cli_.Get("/hi");
  8333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8334. EXPECT_EQ(StatusCode::OK_200, res->status);
  8335. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8336. EXPECT_EQ("Hello World!", res->body);
  8337. res = cli_.Get("/hi");
  8338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8339. EXPECT_EQ(StatusCode::OK_200, res->status);
  8340. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8341. EXPECT_EQ("Hello World!", res->body);
  8342. res = cli_.Get("/hi");
  8343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8344. EXPECT_EQ(StatusCode::OK_200, res->status);
  8345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8346. EXPECT_EQ("Hello World!", res->body);
  8347. res = cli_.Get("/not-exist");
  8348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8350. res = cli_.Post("/empty", "", "text/plain");
  8351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8352. EXPECT_EQ(StatusCode::OK_200, res->status);
  8353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8354. EXPECT_EQ("empty", res->body);
  8355. EXPECT_EQ("close", res->get_header_value("Connection"));
  8356. res = cli_.Post(
  8357. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8358. "text/plain");
  8359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8360. EXPECT_EQ(StatusCode::OK_200, res->status);
  8361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8362. EXPECT_EQ("empty", res->body);
  8363. cli_.set_keep_alive(false);
  8364. res = cli_.Get("/last-request");
  8365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8366. EXPECT_EQ(StatusCode::OK_200, res->status);
  8367. EXPECT_EQ("close", res->get_header_value("Connection"));
  8368. }
  8369. TEST_F(ServerTest, TooManyRedirect) {
  8370. cli_.set_follow_location(true);
  8371. auto res = cli_.Get("/redirect/0");
  8372. ASSERT_TRUE(!res);
  8373. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8374. }
  8375. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8376. Request req;
  8377. req.method = "FOOBAR";
  8378. req.path = "/hi";
  8379. cli_.set_keep_alive(true);
  8380. auto res = cli_.send(req);
  8381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8382. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8383. EXPECT_EQ("close", res->get_header_value("Connection"));
  8384. EXPECT_FALSE(cli_.is_socket_open());
  8385. }
  8386. TEST_F(ServerTest, CustomRouteReadsBody) {
  8387. const std::string xml =
  8388. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8389. Request req;
  8390. req.method = "PROPFIND";
  8391. req.path = "/dav/dir";
  8392. req.set_header("Depth", "1");
  8393. req.body = xml;
  8394. auto res = cli_.send(req);
  8395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8396. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8397. EXPECT_EQ(xml, res->body);
  8398. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8399. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8400. }
  8401. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8402. Request req;
  8403. req.method = "PROPFIND";
  8404. req.path = "/dav/42";
  8405. auto res = cli_.send(req);
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8408. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8409. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8410. }
  8411. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8412. Request req;
  8413. req.method = "PROPFIND";
  8414. req.path = "/dav-re/123";
  8415. auto res = cli_.send(req);
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8418. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8419. }
  8420. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8421. Request req;
  8422. req.method = "MKCOL";
  8423. req.path = "/dav-mkcol";
  8424. auto res = cli_.send(req);
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ(StatusCode::Created_201, res->status);
  8427. }
  8428. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8429. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8430. Request req;
  8431. req.method = "REPORT";
  8432. req.path = "/dav-report";
  8433. req.body = xml;
  8434. auto res = cli_.send(req);
  8435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8436. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8437. EXPECT_EQ(xml, res->body);
  8438. }
  8439. // A content reader route must fire even when the request carries no body,
  8440. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8441. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8442. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8443. Request req;
  8444. req.method = "REPORT";
  8445. req.path = "/dav-report";
  8446. auto res = cli_.send(req);
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8449. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8450. }
  8451. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8452. Request req;
  8453. req.method = "PROPFIND";
  8454. req.path = "/not-dav";
  8455. auto res = cli_.send(req);
  8456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8457. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8458. }
  8459. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8460. Request req;
  8461. req.method = "UNLOCK";
  8462. req.path = "/dav/dir";
  8463. cli_.set_keep_alive(true);
  8464. auto res = cli_.send(req);
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8467. EXPECT_EQ("close", res->get_header_value("Connection"));
  8468. EXPECT_FALSE(cli_.is_socket_open());
  8469. }
  8470. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8471. // The mount point serves this path, but only for GET and HEAD.
  8472. auto get_res = cli_.Get("/dir/index.html");
  8473. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8474. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8475. Request req;
  8476. req.method = "PROPFIND";
  8477. req.path = "/dir/index.html";
  8478. auto res = cli_.send(req);
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8481. }
  8482. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8483. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8484. cli_.set_keep_alive(true);
  8485. for (auto i = 0; i < 2; i++) {
  8486. Request req;
  8487. req.method = "PROPFIND";
  8488. req.path = "/dav/dir";
  8489. req.body = xml;
  8490. auto res = cli_.send(req);
  8491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8492. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8493. EXPECT_EQ(xml, res->body);
  8494. EXPECT_TRUE(cli_.is_socket_open());
  8495. }
  8496. // A built-in method must still be served on the same connection.
  8497. cli_.set_keep_alive(false);
  8498. auto res = cli_.Get("/hi");
  8499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8500. EXPECT_EQ(StatusCode::OK_200, res->status);
  8501. EXPECT_EQ("close", res->get_header_value("Connection"));
  8502. }
  8503. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8504. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8505. Request req;
  8506. req.method = "PROPFIND";
  8507. req.path = "/dav/dir";
  8508. req.set_header("Expect", "100-continue");
  8509. req.body = xml;
  8510. auto res = cli_.send(req);
  8511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8512. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8513. EXPECT_EQ(xml, res->body);
  8514. }
  8515. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8516. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8517. TEST_F(ServerTest, Gzip) {
  8518. Headers headers;
  8519. headers.emplace("Accept-Encoding", "gzip, deflate");
  8520. auto res = cli_.Get("/compress", headers);
  8521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8522. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8523. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8524. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8525. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8526. "7890123456789012345678901234567890",
  8527. res->body);
  8528. EXPECT_EQ(StatusCode::OK_200, res->status);
  8529. }
  8530. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8531. Headers headers;
  8532. headers.emplace("Accept-Encoding", "gzip, deflate");
  8533. auto res = cli_.Get("/compress-with-charset", headers);
  8534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8535. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8536. EXPECT_EQ("application/json; charset=utf-8",
  8537. res->get_header_value("Content-Type"));
  8538. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8539. "7890123456789012345678901234567890",
  8540. res->body);
  8541. EXPECT_EQ(StatusCode::OK_200, res->status);
  8542. }
  8543. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8544. Headers headers;
  8545. headers.emplace("Accept-Encoding", "");
  8546. auto res = cli_.Get("/compress", headers);
  8547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8548. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8550. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8551. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8552. "7890123456789012345678901234567890",
  8553. res->body);
  8554. EXPECT_EQ(StatusCode::OK_200, res->status);
  8555. }
  8556. TEST_F(ServerTest, GzipWithContentReceiver) {
  8557. Headers headers;
  8558. headers.emplace("Accept-Encoding", "gzip, deflate");
  8559. std::string body;
  8560. auto res =
  8561. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8562. EXPECT_EQ(100U, data_length);
  8563. body.append(data, data_length);
  8564. return true;
  8565. });
  8566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8569. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8571. "7890123456789012345678901234567890",
  8572. body);
  8573. EXPECT_EQ(StatusCode::OK_200, res->status);
  8574. }
  8575. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8576. Headers headers;
  8577. headers.emplace("Accept-Encoding", "gzip, deflate");
  8578. cli_.set_decompress(false);
  8579. auto res = cli_.Get("/compress", headers);
  8580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8581. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8583. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8584. EXPECT_EQ(33U, res->body.size());
  8585. EXPECT_EQ(StatusCode::OK_200, res->status);
  8586. }
  8587. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8588. Headers headers;
  8589. headers.emplace("Accept-Encoding", "");
  8590. std::string body;
  8591. auto res =
  8592. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8593. EXPECT_EQ(100U, data_length);
  8594. body.append(data, data_length);
  8595. return true;
  8596. });
  8597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8598. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8599. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8600. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8601. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8602. "7890123456789012345678901234567890",
  8603. body);
  8604. EXPECT_EQ(StatusCode::OK_200, res->status);
  8605. }
  8606. TEST_F(ServerTest, NoGzip) {
  8607. Headers headers;
  8608. headers.emplace("Accept-Encoding", "gzip, deflate");
  8609. auto res = cli_.Get("/nocompress", headers);
  8610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8611. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8612. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8613. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8614. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8615. "7890123456789012345678901234567890",
  8616. res->body);
  8617. EXPECT_EQ(StatusCode::OK_200, res->status);
  8618. }
  8619. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8620. Headers headers;
  8621. headers.emplace("Accept-Encoding", "gzip, deflate");
  8622. std::string body;
  8623. auto res = cli_.Get("/nocompress", headers,
  8624. [&](const char *data, size_t data_length) {
  8625. EXPECT_EQ(100U, data_length);
  8626. body.append(data, data_length);
  8627. return true;
  8628. });
  8629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8630. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8631. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8634. "7890123456789012345678901234567890",
  8635. body);
  8636. EXPECT_EQ(StatusCode::OK_200, res->status);
  8637. }
  8638. TEST_F(ServerTest, MultipartFormDataGzip) {
  8639. UploadFormDataItems items = {
  8640. {"key1", "test", "", ""},
  8641. {"key2", "--abcdefg123", "", ""},
  8642. };
  8643. cli_.set_compress(true);
  8644. auto res = cli_.Post("/compress-multipart", items);
  8645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8646. EXPECT_EQ(StatusCode::OK_200, res->status);
  8647. }
  8648. #endif
  8649. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8650. // Static file compression is opt-in, so these run their own server rather than
  8651. // flipping it on for the shared ServerTest fixture, which would silently
  8652. // rewrite what every other static file test is asserting.
  8653. class StaticFileCompressionTest : public ::testing::Test {
  8654. protected:
  8655. void TearDown() override {
  8656. if (t_.joinable()) {
  8657. svr_.stop();
  8658. t_.join();
  8659. }
  8660. }
  8661. int start(const std::function<void(Server &)> &configure = nullptr) {
  8662. // Serves the same tree as a directory of build-time compressed assets
  8663. // would be served: the mount point names the coding the files are already
  8664. // stored in. Registered before "/" so it is the one that matches.
  8665. svr_.set_mount_point("/pre-encoded", "./www",
  8666. {{"Content-Encoding", "gzip"}});
  8667. svr_.set_mount_point("/", "./www");
  8668. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8669. res.set_file_content("./www/dir/index.html", "text/html");
  8670. });
  8671. svr_.Get("/pre-encoded-file-content",
  8672. [](const Request & /*req*/, Response &res) {
  8673. res.set_header("Content-Encoding", "gzip");
  8674. res.set_file_content("./www/dir/index.html", "text/html");
  8675. });
  8676. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8677. res.set_content_provider(
  8678. 6, "text/plain",
  8679. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8680. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8681. return true;
  8682. });
  8683. });
  8684. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8685. res.set_content_provider(
  8686. 1000, "text/plain",
  8687. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8688. if (offset < 100) {
  8689. std::string data(100, 'A');
  8690. sink.write(data.data(), data.size());
  8691. return true;
  8692. }
  8693. std::this_thread::sleep_for(std::chrono::seconds(2));
  8694. std::string data(900, 'B');
  8695. sink.write(data.data(), data.size());
  8696. return true;
  8697. });
  8698. });
  8699. if (configure) { configure(svr_); }
  8700. auto port = svr_.bind_to_any_port(HOST);
  8701. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8702. svr_.wait_until_ready();
  8703. return port;
  8704. }
  8705. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8706. // Every file under ./www except 1MB.txt is smaller than the default
  8707. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8708. // it out of the way.
  8709. static void enable_without_floor(Server &svr) {
  8710. svr.set_static_file_compression(true);
  8711. svr.set_static_file_compression_min_length(0);
  8712. }
  8713. Server svr_;
  8714. std::thread t_;
  8715. };
  8716. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8717. auto port = start();
  8718. Client cli(HOST, port);
  8719. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8721. EXPECT_EQ(StatusCode::OK_200, res->status);
  8722. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8723. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8724. EXPECT_EQ(1048576U, res->body.size());
  8725. }
  8726. TEST_F(StaticFileCompressionTest, MountPoint) {
  8727. auto port = start(enable);
  8728. Client cli(HOST, port);
  8729. cli.set_decompress(false);
  8730. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8732. EXPECT_EQ(StatusCode::OK_200, res->status);
  8733. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8734. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8735. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8736. // The response stays self-delimiting: a length, not a chunked body.
  8737. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8738. EXPECT_EQ(std::to_string(res->body.size()),
  8739. res->get_header_value("Content-Length"));
  8740. EXPECT_LT(res->body.size(), 1048576U);
  8741. EXPECT_FALSE(res->body.empty());
  8742. }
  8743. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8744. auto port = start(enable);
  8745. Client cli(HOST, port);
  8746. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8748. EXPECT_EQ(StatusCode::OK_200, res->status);
  8749. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8750. EXPECT_EQ(1048576U, res->body.size());
  8751. }
  8752. TEST_F(StaticFileCompressionTest, FileContent) {
  8753. auto port = start(enable_without_floor);
  8754. Client cli(HOST, port);
  8755. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8757. EXPECT_EQ(StatusCode::OK_200, res->status);
  8758. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8759. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8760. EXPECT_EQ(104U, res->body.size());
  8761. }
  8762. // A handler that serves an already-encoded file names the coding itself. The
  8763. // file-backed path decided its coding from Accept-Encoding and the content
  8764. // type alone, so it compressed the stored bytes a second time and appended a
  8765. // second Content-Encoding field line.
  8766. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8767. auto port = start(enable_without_floor);
  8768. Client cli(HOST, port);
  8769. cli.set_decompress(false);
  8770. auto res = cli.Get("/pre-encoded-file-content",
  8771. Headers{{"Accept-Encoding", "gzip"}});
  8772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8773. EXPECT_EQ(StatusCode::OK_200, res->status);
  8774. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8775. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8776. // Vary belongs to a coding the server chose, and it chose none here.
  8777. EXPECT_FALSE(res->has_header("Vary"));
  8778. // The file travels exactly as it is stored on disk.
  8779. EXPECT_EQ(104U, res->body.size());
  8780. }
  8781. // The 1MB file clears the default floor, so this one runs the configuration a
  8782. // deployment would actually have.
  8783. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8784. auto port = start(enable);
  8785. Client cli(HOST, port);
  8786. cli.set_decompress(false);
  8787. auto res =
  8788. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8790. EXPECT_EQ(StatusCode::OK_200, res->status);
  8791. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8792. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8793. EXPECT_FALSE(res->has_header("Vary"));
  8794. EXPECT_EQ(1048576U, res->body.size());
  8795. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8796. }
  8797. TEST_F(StaticFileCompressionTest, Head) {
  8798. auto port = start(enable);
  8799. Client cli(HOST, port);
  8800. cli.set_decompress(false);
  8801. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8802. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8803. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8805. EXPECT_EQ(StatusCode::OK_200, res->status);
  8806. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8807. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8808. // HEAD still reports the size a GET would return.
  8809. EXPECT_EQ(get->get_header_value("Content-Length"),
  8810. res->get_header_value("Content-Length"));
  8811. EXPECT_TRUE(res->body.empty());
  8812. }
  8813. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8814. auto port = start(enable);
  8815. Client cli(HOST, port);
  8816. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8817. {"Accept-Encoding", "gzip"}});
  8818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8819. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8820. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8821. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8822. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8823. EXPECT_EQ("cd", res->body);
  8824. }
  8825. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8826. auto port = start(enable);
  8827. Client cli(HOST, port);
  8828. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8830. EXPECT_EQ(StatusCode::OK_200, res->status);
  8831. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8832. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8833. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8834. }
  8835. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8836. auto port = start(enable);
  8837. Client cli(HOST, port);
  8838. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8840. EXPECT_EQ(StatusCode::OK_200, res->status);
  8841. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8842. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8843. EXPECT_TRUE(res->body.empty());
  8844. }
  8845. TEST_F(StaticFileCompressionTest, MinLength) {
  8846. auto port = start(enable);
  8847. Client cli(HOST, port);
  8848. // 104 bytes, well under the default floor. Compressing it would add the
  8849. // gzip header and trailer to a body that already fits in one packet.
  8850. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8852. EXPECT_EQ(StatusCode::OK_200, res->status);
  8853. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8854. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8855. }
  8856. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8857. auto port = start([](Server &svr) {
  8858. svr.set_static_file_compression(true);
  8859. svr.set_static_file_compression_min_length(1);
  8860. });
  8861. Client cli(HOST, port);
  8862. cli.set_decompress(false);
  8863. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8865. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8866. // A 9-byte file comes back larger than it went in, because gzip's header and
  8867. // trailer outweigh anything deflate can save. That is the end of the range
  8868. // the floor exists to keep out.
  8869. EXPECT_GT(res->body.size(), 9U);
  8870. }
  8871. TEST_F(StaticFileCompressionTest, MaxLength) {
  8872. auto port = start([](Server &svr) {
  8873. svr.set_static_file_compression(true);
  8874. svr.set_static_file_compression_min_length(0);
  8875. svr.set_static_file_compression_max_length(1024);
  8876. });
  8877. Client cli(HOST, port);
  8878. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8879. // defines `small` as a macro on Windows.
  8880. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8881. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8882. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8883. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8884. // Under it: compressed.
  8885. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8886. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8887. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8888. }
  8889. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8890. auto port = start(enable_without_floor);
  8891. Client cli(HOST, port);
  8892. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8893. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8894. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8895. auto identity_etag = identity->get_header_value("ETag");
  8896. ASSERT_FALSE(identity_etag.empty());
  8897. auto gzipped =
  8898. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8899. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8900. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8901. auto gzip_etag = gzipped->get_header_value("ETag");
  8902. ASSERT_FALSE(gzip_etag.empty());
  8903. // Two representations, two validators.
  8904. EXPECT_NE(identity_etag, gzip_etag);
  8905. // Each one revalidates against the request that would produce it...
  8906. auto fresh =
  8907. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8908. {"If-None-Match", gzip_etag}});
  8909. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8910. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8911. auto fresh_identity =
  8912. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8913. {"If-None-Match", identity_etag}});
  8914. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8915. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8916. // ...and not against the other representation.
  8917. auto crossed =
  8918. cli.Get("/dir/index.html",
  8919. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8920. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8921. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8922. }
  8923. // The opt-in covers responses the server reads off disk itself. A caller's own
  8924. // known-length provider keeps its Content-Length and, more importantly, keeps
  8925. // delivering incrementally: routing it through a compressor would hold every
  8926. // write back until zlib's window filled.
  8927. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8928. auto port = start(enable);
  8929. Client cli(HOST, port);
  8930. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8932. EXPECT_EQ(StatusCode::OK_200, res->status);
  8933. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8934. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8935. EXPECT_EQ("aaabbb", res->body);
  8936. }
  8937. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8938. auto port = start(enable);
  8939. Client cli(HOST, port);
  8940. cli.set_read_timeout(1, 0);
  8941. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8942. Headers{{"Accept-Encoding", "gzip"}});
  8943. ASSERT_TRUE(handle.is_valid());
  8944. // The provider writes 100 bytes and then stalls for longer than the read
  8945. // timeout. Those first bytes have to arrive anyway: run the response through
  8946. // a compressor and zlib holds them until its window fills, so the read would
  8947. // come back empty instead.
  8948. char buf[256];
  8949. auto n = handle.read(buf, sizeof(buf));
  8950. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8951. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8952. }
  8953. #endif
  8954. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8955. TEST_F(ServerTest, Brotli) {
  8956. Headers headers;
  8957. headers.emplace("Accept-Encoding", "br");
  8958. auto res = cli_.Get("/compress", headers);
  8959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8960. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8962. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8963. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8964. "7890123456789012345678901234567890",
  8965. res->body);
  8966. EXPECT_EQ(StatusCode::OK_200, res->status);
  8967. }
  8968. #endif
  8969. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8970. TEST_F(ServerTest, Zstd) {
  8971. Headers headers;
  8972. headers.emplace("Accept-Encoding", "zstd");
  8973. auto res = cli_.Get("/compress", headers);
  8974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8975. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8976. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8977. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8978. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8979. "7890123456789012345678901234567890",
  8980. res->body);
  8981. EXPECT_EQ(StatusCode::OK_200, res->status);
  8982. }
  8983. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8984. Headers headers;
  8985. headers.emplace("Accept-Encoding", "");
  8986. auto res = cli_.Get("/compress", headers);
  8987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8988. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8989. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8990. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8991. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8992. "7890123456789012345678901234567890",
  8993. res->body);
  8994. EXPECT_EQ(StatusCode::OK_200, res->status);
  8995. }
  8996. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8997. Headers headers;
  8998. headers.emplace("Accept-Encoding", "zstd");
  8999. std::string body;
  9000. auto res =
  9001. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9002. EXPECT_EQ(100U, data_length);
  9003. body.append(data, data_length);
  9004. return true;
  9005. });
  9006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9007. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9009. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9010. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9011. "7890123456789012345678901234567890",
  9012. body);
  9013. EXPECT_EQ(StatusCode::OK_200, res->status);
  9014. }
  9015. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9016. Headers headers;
  9017. headers.emplace("Accept-Encoding", "zstd");
  9018. cli_.set_decompress(false);
  9019. auto res = cli_.Get("/compress", headers);
  9020. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9021. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9022. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9023. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9025. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9027. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9028. EXPECT_EQ(StatusCode::OK_200, res->status);
  9029. ASSERT_EQ(26U, res->body.size());
  9030. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9031. 0);
  9032. }
  9033. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9034. Headers headers;
  9035. headers.emplace("Accept-Encoding", "");
  9036. std::string body;
  9037. auto res =
  9038. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9039. EXPECT_EQ(100U, data_length);
  9040. body.append(data, data_length);
  9041. return true;
  9042. });
  9043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9044. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9046. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9047. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9048. "7890123456789012345678901234567890",
  9049. body);
  9050. EXPECT_EQ(StatusCode::OK_200, res->status);
  9051. }
  9052. TEST_F(ServerTest, NoZstd) {
  9053. Headers headers;
  9054. headers.emplace("Accept-Encoding", "zstd");
  9055. auto res = cli_.Get("/nocompress", headers);
  9056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9057. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9058. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9059. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9060. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9061. "7890123456789012345678901234567890",
  9062. res->body);
  9063. EXPECT_EQ(StatusCode::OK_200, res->status);
  9064. }
  9065. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9066. Headers headers;
  9067. headers.emplace("Accept-Encoding", "zstd");
  9068. std::string body;
  9069. auto res = cli_.Get("/nocompress", headers,
  9070. [&](const char *data, size_t data_length) {
  9071. EXPECT_EQ(100U, data_length);
  9072. body.append(data, data_length);
  9073. return true;
  9074. });
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9077. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9078. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9080. "7890123456789012345678901234567890",
  9081. body);
  9082. EXPECT_EQ(StatusCode::OK_200, res->status);
  9083. }
  9084. // TODO: How to enable zstd ??
  9085. TEST_F(ServerTest, MultipartFormDataZstd) {
  9086. UploadFormDataItems items = {
  9087. {"key1", "test", "", ""},
  9088. {"key2", "--abcdefg123", "", ""},
  9089. };
  9090. Headers headers;
  9091. headers.emplace("Accept-Encoding", "zstd");
  9092. cli_.set_compress(true);
  9093. auto res = cli_.Post("/compress-multipart", headers, items);
  9094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9095. EXPECT_EQ(StatusCode::OK_200, res->status);
  9096. }
  9097. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9098. Headers headers;
  9099. headers.emplace("Accept-Encoding", "zstd");
  9100. cli_.set_compress(true);
  9101. auto res = cli_.Put(
  9102. "/put", headers, 3,
  9103. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9104. sink.os << "PUT";
  9105. return true;
  9106. },
  9107. "text/plain");
  9108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9109. EXPECT_EQ(StatusCode::OK_200, res->status);
  9110. EXPECT_EQ("PUT", res->body);
  9111. }
  9112. // Pre-compression logging tests
  9113. TEST_F(ServerTest, PreCompressionLogging) {
  9114. // Test data for compression (matches the actual /compress endpoint content)
  9115. const std::string test_content =
  9116. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9117. "3456789012345678901234567890";
  9118. // Variables to capture logging data
  9119. std::string pre_compression_body;
  9120. std::string pre_compression_content_type;
  9121. std::string pre_compression_content_encoding;
  9122. std::string post_compression_body;
  9123. std::string post_compression_content_type;
  9124. std::string post_compression_content_encoding;
  9125. // Set up pre-compression logger
  9126. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9127. const Response &res) {
  9128. pre_compression_body = res.body;
  9129. pre_compression_content_type = res.get_header_value("Content-Type");
  9130. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9131. });
  9132. // Set up post-compression logger
  9133. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9134. post_compression_body = res.body;
  9135. post_compression_content_type = res.get_header_value("Content-Type");
  9136. post_compression_content_encoding =
  9137. res.get_header_value("Content-Encoding");
  9138. });
  9139. // Test with gzip compression
  9140. Headers headers;
  9141. headers.emplace("Accept-Encoding", "gzip");
  9142. auto res = cli_.Get("/compress", headers);
  9143. // Verify response was compressed
  9144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9145. EXPECT_EQ(StatusCode::OK_200, res->status);
  9146. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9147. // Verify pre-compression logger captured uncompressed content
  9148. EXPECT_EQ(test_content, pre_compression_body);
  9149. EXPECT_EQ("text/plain", pre_compression_content_type);
  9150. EXPECT_TRUE(pre_compression_content_encoding
  9151. .empty()); // No encoding header before compression
  9152. // Verify post-compression logger captured compressed content
  9153. EXPECT_NE(test_content,
  9154. post_compression_body); // Should be different after compression
  9155. EXPECT_EQ("text/plain", post_compression_content_type);
  9156. EXPECT_EQ("gzip", post_compression_content_encoding);
  9157. // Verify compressed content is smaller
  9158. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9159. }
  9160. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9161. const std::string test_content =
  9162. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9163. "3456789012345678901234567890";
  9164. std::string pre_compression_body;
  9165. std::string post_compression_body;
  9166. svr_.set_pre_compression_logger(
  9167. [&](const Request & /*req*/, const Response &res) {
  9168. pre_compression_body = res.body;
  9169. });
  9170. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9171. post_compression_body = res.body;
  9172. });
  9173. Headers headers;
  9174. headers.emplace("Accept-Encoding", "br");
  9175. auto res = cli_.Get("/compress", headers);
  9176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9177. EXPECT_EQ(StatusCode::OK_200, res->status);
  9178. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9179. // Verify pre-compression content is uncompressed
  9180. EXPECT_EQ(test_content, pre_compression_body);
  9181. // Verify post-compression content is compressed
  9182. EXPECT_NE(test_content, post_compression_body);
  9183. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9184. }
  9185. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9186. const std::string test_content =
  9187. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9188. "3456789012345678901234567890";
  9189. std::string pre_compression_body;
  9190. std::string post_compression_body;
  9191. svr_.set_pre_compression_logger(
  9192. [&](const Request & /*req*/, const Response &res) {
  9193. pre_compression_body = res.body;
  9194. });
  9195. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9196. post_compression_body = res.body;
  9197. });
  9198. // Request without compression (use /nocompress endpoint)
  9199. Headers headers;
  9200. auto res = cli_.Get("/nocompress", headers);
  9201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9202. EXPECT_EQ(StatusCode::OK_200, res->status);
  9203. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9204. // Pre-compression logger should not be called when no compression is applied
  9205. EXPECT_TRUE(
  9206. pre_compression_body.empty()); // Pre-compression logger not called
  9207. EXPECT_EQ(
  9208. test_content,
  9209. post_compression_body); // Post-compression logger captures final content
  9210. }
  9211. TEST_F(ServerTest, LoggerSeesContentLength) {
  9212. size_t logged_content_length = 0;
  9213. std::string logged_content_length_header;
  9214. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9215. logged_content_length = res.content_length_;
  9216. logged_content_length_header = res.get_header_value("Content-Length");
  9217. });
  9218. auto res = cli_.Get("/nocompress");
  9219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9220. EXPECT_EQ(StatusCode::OK_200, res->status);
  9221. EXPECT_EQ(res->body.size(), logged_content_length);
  9222. EXPECT_EQ(std::to_string(logged_content_length),
  9223. logged_content_length_header);
  9224. }
  9225. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9226. const std::string test_content =
  9227. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9228. "3456789012345678901234567890";
  9229. std::string pre_compression_body;
  9230. bool pre_logger_called = false;
  9231. // Set only pre-compression logger
  9232. svr_.set_pre_compression_logger(
  9233. [&](const Request & /*req*/, const Response &res) {
  9234. pre_compression_body = res.body;
  9235. pre_logger_called = true;
  9236. });
  9237. Headers headers;
  9238. headers.emplace("Accept-Encoding", "gzip");
  9239. auto res = cli_.Get("/compress", headers);
  9240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9241. EXPECT_EQ(StatusCode::OK_200, res->status);
  9242. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9243. // Verify pre-compression logger was called
  9244. EXPECT_TRUE(pre_logger_called);
  9245. EXPECT_EQ(test_content, pre_compression_body);
  9246. }
  9247. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9248. {
  9249. // Test with Expect: 100-continue header - success case
  9250. // Server returns 100 Continue, client sends body, server returns 200 OK
  9251. Request req;
  9252. req.method = "POST";
  9253. req.path = "/post-large";
  9254. req.set_header("Expect", "100-continue");
  9255. req.body = LARGE_DATA;
  9256. Response res;
  9257. auto error = Error::Success;
  9258. cli_.set_keep_alive(true);
  9259. auto ret = cli_.send(req, res, error);
  9260. EXPECT_TRUE(ret);
  9261. EXPECT_EQ(StatusCode::OK_200, res.status);
  9262. EXPECT_EQ(LARGE_DATA, res.body);
  9263. }
  9264. {
  9265. // Test with Expect: 100-continue header - error case
  9266. // Client should not send the body when server returns an error
  9267. Request req;
  9268. req.method = "POST";
  9269. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9270. req.set_header("Expect", "100-continue");
  9271. req.body = LARGE_DATA;
  9272. Response res;
  9273. auto error = Error::Success;
  9274. auto start = std::chrono::high_resolution_clock::now();
  9275. cli_.set_keep_alive(true);
  9276. auto ret = cli_.send(req, res, error);
  9277. auto end = std::chrono::high_resolution_clock::now();
  9278. auto elapsed =
  9279. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9280. .count();
  9281. // With Expect: 100-continue, request completes successfully but with error
  9282. EXPECT_TRUE(ret);
  9283. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9284. EXPECT_EQ("close", res.get_header_value("Connection"));
  9285. EXPECT_FALSE(cli_.is_socket_open());
  9286. EXPECT_LE(elapsed, 2000);
  9287. }
  9288. {
  9289. // Send an extra GET request to ensure error recovery without hanging
  9290. Request req;
  9291. req.method = "GET";
  9292. req.path = "/hi";
  9293. auto start = std::chrono::high_resolution_clock::now();
  9294. auto res = cli_.send(req);
  9295. auto end = std::chrono::high_resolution_clock::now();
  9296. auto elapsed =
  9297. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9298. .count();
  9299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9300. EXPECT_EQ(StatusCode::OK_200, res->status);
  9301. EXPECT_EQ("Hello World!", res->body);
  9302. EXPECT_LE(elapsed, 500);
  9303. }
  9304. }
  9305. TEST(ZstdDecompressor, ChunkedDecompression) {
  9306. std::string data;
  9307. for (size_t i = 0; i < 32 * 1024; ++i) {
  9308. data.push_back(static_cast<char>('a' + i % 26));
  9309. }
  9310. std::string compressed_data;
  9311. {
  9312. httplib::detail::zstd_compressor compressor;
  9313. bool result = compressor.compress(
  9314. data.data(), data.size(),
  9315. /*last=*/true,
  9316. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9317. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9318. compressed_data_size);
  9319. return true;
  9320. });
  9321. ASSERT_TRUE(result);
  9322. }
  9323. std::string decompressed_data;
  9324. {
  9325. httplib::detail::zstd_decompressor decompressor;
  9326. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9327. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9328. size_t chunk_size = 130;
  9329. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9330. chunk_begin += chunk_size) {
  9331. size_t current_chunk_size =
  9332. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9333. bool result = decompressor.decompress(
  9334. compressed_data.data() + chunk_begin, current_chunk_size,
  9335. [&](const char *decompressed_data_chunk,
  9336. size_t decompressed_data_chunk_size) {
  9337. decompressed_data.insert(decompressed_data.size(),
  9338. decompressed_data_chunk,
  9339. decompressed_data_chunk_size);
  9340. return true;
  9341. });
  9342. ASSERT_TRUE(result);
  9343. }
  9344. }
  9345. ASSERT_EQ(data, decompressed_data);
  9346. }
  9347. TEST(ZstdDecompressor, Decompress) {
  9348. std::string original_text = "Compressed with ZSTD";
  9349. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9350. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9351. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9352. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9353. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9354. std::string decompressed_data;
  9355. {
  9356. httplib::detail::zstd_decompressor decompressor;
  9357. bool result = decompressor.decompress(
  9358. compressed_data.data(), compressed_data.size(),
  9359. [&](const char *decompressed_data_chunk,
  9360. size_t decompressed_data_chunk_size) {
  9361. decompressed_data.insert(decompressed_data.size(),
  9362. decompressed_data_chunk,
  9363. decompressed_data_chunk_size);
  9364. return true;
  9365. });
  9366. ASSERT_TRUE(result);
  9367. }
  9368. ASSERT_EQ(original_text, decompressed_data);
  9369. }
  9370. #endif
  9371. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9372. // separate chunks so that the server sees each part in its own read(). Used to
  9373. // place a read boundary at a specific offset of a request body.
  9374. static bool send_request_in_parts(time_t read_timeout_sec,
  9375. const std::vector<std::string> &parts,
  9376. std::string *resp = nullptr,
  9377. int port = PORT) {
  9378. auto error = Error::Success;
  9379. auto client_sock = detail::create_client_socket(
  9380. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9381. /*connection_timeout_sec=*/5, 0,
  9382. /*read_timeout_sec=*/5, 0,
  9383. /*write_timeout_sec=*/5, 0, std::string(), error);
  9384. if (client_sock == INVALID_SOCKET) { return false; }
  9385. auto ret = detail::process_client_socket(
  9386. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9387. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9388. for (size_t i = 0; i < parts.size(); i++) {
  9389. const auto &part = parts[i];
  9390. if (part.size() !=
  9391. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9392. return false;
  9393. }
  9394. if (i + 1 < parts.size()) {
  9395. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9396. }
  9397. }
  9398. char buf[512];
  9399. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9400. while (line_reader.getline()) {
  9401. if (resp) { *resp += line_reader.ptr(); }
  9402. }
  9403. return true;
  9404. });
  9405. detail::close_socket(client_sock);
  9406. return ret;
  9407. }
  9408. // Sends a raw request to a server listening at HOST:PORT.
  9409. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9410. std::string *resp = nullptr, int port = PORT) {
  9411. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9412. }
  9413. #ifdef CPPHTTPLIB_SSL_ENABLED
  9414. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9416. ASSERT_TRUE(svr.is_valid());
  9417. svr.set_read_timeout(1, 0);
  9418. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9419. auto se = detail::scope_exit([&] {
  9420. svr.stop();
  9421. t.join();
  9422. ASSERT_FALSE(svr.is_running());
  9423. });
  9424. svr.wait_until_ready();
  9425. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9426. // keeps each wait well within the read timeout. The server gives up a
  9427. // second in, so the bytes sent after that fail.
  9428. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9429. parts.resize(26, std::string(1, '\0'));
  9430. EXPECT_FALSE(send_request_in_parts(5, parts));
  9431. }
  9432. #endif
  9433. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9434. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9435. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9436. const std::vector<std::string> &parts,
  9437. std::string *resp = nullptr,
  9438. int port = PORT) {
  9439. auto error = Error::Success;
  9440. auto sock = detail::create_client_socket(
  9441. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9442. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9443. /*write_timeout_sec=*/5, 0, std::string(), error);
  9444. if (sock == INVALID_SOCKET) { return false; }
  9445. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9446. auto ctx = SSL_CTX_new(TLS_client_method());
  9447. auto ssl = SSL_new(ctx);
  9448. auto ssl_se = detail::scope_exit([&] {
  9449. SSL_free(ssl);
  9450. SSL_CTX_free(ctx);
  9451. });
  9452. SSL_set_fd(ssl, static_cast<int>(sock));
  9453. if (SSL_connect(ssl) != 1) { return false; }
  9454. for (size_t i = 0; i < parts.size(); i++) {
  9455. const auto &part = parts[i];
  9456. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9457. static_cast<int>(part.size())) {
  9458. return false;
  9459. }
  9460. if (i + 1 < parts.size()) {
  9461. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9462. }
  9463. }
  9464. char buf[512];
  9465. int n;
  9466. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9467. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9468. }
  9469. return true;
  9470. }
  9471. #endif
  9472. // The request line, then a header value a byte at a time.
  9473. static std::vector<std::string> slow_request_head_parts() {
  9474. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9475. parts.resize(26, "a");
  9476. parts.emplace_back("\r\n\r\n");
  9477. return parts;
  9478. }
  9479. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9480. // within the one-second read timeout. The server gives up a second in, before
  9481. // the head is complete.
  9482. static void
  9483. expect_slow_request_head_dropped(Server &svr,
  9484. const std::function<std::string()> &send) {
  9485. std::atomic<bool> handled(false);
  9486. svr.Get("/", [&](const Request &, Response &res) {
  9487. handled = true;
  9488. res.set_content("ok", "text/plain");
  9489. });
  9490. svr.set_read_timeout(1, 0);
  9491. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9492. auto se = detail::scope_exit([&] {
  9493. svr.stop();
  9494. t.join();
  9495. ASSERT_FALSE(svr.is_running());
  9496. });
  9497. svr.wait_until_ready();
  9498. auto resp = send();
  9499. EXPECT_FALSE(handled);
  9500. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9501. }
  9502. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9503. Server svr;
  9504. expect_slow_request_head_dropped(svr, [] {
  9505. std::string resp;
  9506. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9507. return resp;
  9508. });
  9509. }
  9510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9511. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9513. ASSERT_TRUE(svr.is_valid());
  9514. expect_slow_request_head_dropped(svr, [] {
  9515. std::string resp;
  9516. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9517. return resp;
  9518. });
  9519. }
  9520. #endif
  9521. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9522. Server svr;
  9523. std::string header_value;
  9524. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9525. header_value = req.get_header_value("foo");
  9526. res.set_content("ok", "text/plain");
  9527. });
  9528. thread t = thread([&] { svr.listen(HOST, PORT); });
  9529. auto se = detail::scope_exit([&] {
  9530. svr.stop();
  9531. t.join();
  9532. ASSERT_FALSE(svr.is_running());
  9533. });
  9534. svr.wait_until_ready();
  9535. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9536. // like characters are not treated the same - use vertical tab and escape.
  9537. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9538. "foo: \t \v bar \x1B\t \r\n"
  9539. "Connection: close\r\n"
  9540. "\r\n";
  9541. std::string res;
  9542. ASSERT_TRUE(send_request(5, req, &res));
  9543. EXPECT_EQ(header_value, "");
  9544. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9545. }
  9546. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9547. Server svr;
  9548. std::string received;
  9549. svr.Get("/order", [&](const Request &req, Response &res) {
  9550. received = entries_to_string(req.headers);
  9551. res.set_content("ok", "text/plain");
  9552. });
  9553. auto port = svr.bind_to_any_port(HOST);
  9554. thread t = thread([&] { svr.listen_after_bind(); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. t.join();
  9558. ASSERT_FALSE(svr.is_running());
  9559. });
  9560. svr.wait_until_ready();
  9561. const std::string req = "GET /order HTTP/1.1\r\n"
  9562. "Host: localhost\r\n"
  9563. "X-First: 1\r\n"
  9564. "X-Dup: a\r\n"
  9565. "X-Second: 2\r\n"
  9566. "X-Dup: b\r\n"
  9567. "Connection: close\r\n"
  9568. "\r\n";
  9569. std::string res;
  9570. ASSERT_TRUE(send_request(5, req, &res, port));
  9571. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9572. EXPECT_EQ(
  9573. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9574. received);
  9575. }
  9576. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9577. Server svr;
  9578. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9579. res.set_header("Set-Cookie", "first=1");
  9580. res.set_header("X-Between", "y");
  9581. res.set_header("Set-Cookie", "second=2");
  9582. res.set_content("ok", "text/plain");
  9583. });
  9584. auto port = svr.bind_to_any_port(HOST);
  9585. thread t = thread([&] { svr.listen_after_bind(); });
  9586. auto se = detail::scope_exit([&] {
  9587. svr.stop();
  9588. t.join();
  9589. ASSERT_FALSE(svr.is_running());
  9590. });
  9591. svr.wait_until_ready();
  9592. Client cli(HOST, port);
  9593. auto res = cli.Get("/cookies");
  9594. ASSERT_TRUE(res);
  9595. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9596. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9597. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9598. }
  9599. // A stream may send a byte at a time with a small extension on each chunk,
  9600. // however long it runs
  9601. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9602. Server svr;
  9603. svr.Post("/count", [](const Request &req, Response &res) {
  9604. res.set_content(std::to_string(req.body.size()), "text/plain");
  9605. });
  9606. auto port = svr.bind_to_any_port(HOST);
  9607. ASSERT_LT(0, port);
  9608. thread t = thread([&] { svr.listen_after_bind(); });
  9609. auto se = detail::scope_exit([&] {
  9610. svr.stop();
  9611. t.join();
  9612. ASSERT_FALSE(svr.is_running());
  9613. });
  9614. svr.wait_until_ready();
  9615. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9616. "\r\nTransfer-Encoding: chunked\r\n"
  9617. "Connection: close\r\n\r\n";
  9618. for (auto i = 0; i < 4096; i++) {
  9619. req += "1;a=b\r\nx\r\n";
  9620. }
  9621. req += "0\r\n\r\n";
  9622. std::string res;
  9623. ASSERT_TRUE(send_request(5, req, &res, port));
  9624. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9625. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9626. }
  9627. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9628. Server svr;
  9629. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9630. auto i = new int(0);
  9631. res.set_header("Trailer", "X-Safe, X-Reflected");
  9632. res.set_chunked_content_provider(
  9633. "text/plain",
  9634. [i](size_t /*offset*/, DataSink &sink) {
  9635. if (*i == 0) {
  9636. sink.os << "body";
  9637. } else {
  9638. Headers trailer;
  9639. // A valid trailer that must survive.
  9640. trailer.emplace("X-Safe", "safe");
  9641. // Attacker-controlled value carrying CR/LF (response splitting).
  9642. trailer.emplace("X-Reflected",
  9643. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9644. // Attacker-controlled name carrying CR/LF.
  9645. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9646. sink.done_with_trailer(trailer);
  9647. }
  9648. (*i)++;
  9649. return true;
  9650. },
  9651. [i](bool /*success*/) { delete i; });
  9652. });
  9653. thread t = thread([&] { svr.listen(HOST, PORT); });
  9654. auto se = detail::scope_exit([&] {
  9655. svr.stop();
  9656. t.join();
  9657. ASSERT_FALSE(svr.is_running());
  9658. });
  9659. svr.wait_until_ready();
  9660. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9661. "Host: " + HOST +
  9662. "\r\n"
  9663. "Connection: close\r\n"
  9664. "\r\n";
  9665. std::string res;
  9666. ASSERT_TRUE(send_request(5, req, &res));
  9667. // The injected fields must not appear anywhere in the raw response.
  9668. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9669. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9670. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9671. // Invalid trailers are dropped entirely, matching set_header().
  9672. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9673. // The valid trailer still passes through.
  9674. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9675. }
  9676. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9677. // A custom header writer gets only the fields the default one writes
  9678. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9679. std::string s;
  9680. for (const auto &h : hdrs) {
  9681. s += h.first + ": " + h.second + "\r\n";
  9682. }
  9683. s += "\r\n";
  9684. return strm.write(s.data(), s.size());
  9685. };
  9686. for (auto custom_writer : {false, true}) {
  9687. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9688. Server svr;
  9689. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9690. svr.set_post_routing_handler([](const Request &, Response &res) {
  9691. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9692. });
  9693. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9694. // res.headers is a public field an application can populate directly,
  9695. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9696. // A valid header that must survive.
  9697. res.headers.emplace("X-Safe", "safe");
  9698. // Attacker-controlled value carrying CR/LF (response splitting).
  9699. res.headers.emplace("X-Reflected",
  9700. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9701. // Attacker-controlled name carrying CR/LF.
  9702. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9703. res.set_content("body", "text/plain");
  9704. });
  9705. thread t = thread([&] { svr.listen(HOST, PORT); });
  9706. auto se = detail::scope_exit([&] {
  9707. svr.stop();
  9708. t.join();
  9709. ASSERT_FALSE(svr.is_running());
  9710. });
  9711. svr.wait_until_ready();
  9712. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9713. "Host: " + HOST +
  9714. "\r\n"
  9715. "Connection: close\r\n"
  9716. "\r\n";
  9717. std::string res;
  9718. ASSERT_TRUE(send_request(5, req, &res));
  9719. // The injected fields must not appear anywhere in the raw response.
  9720. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9721. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9722. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9723. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9724. // Invalid headers are dropped entirely, matching set_header().
  9725. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9726. // The valid header still passes through.
  9727. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9728. }
  9729. }
  9730. // Forward declaration: in split builds split.py strips `inline` and moves the
  9731. // definition into httplib.cc, so detail::write_request_line is not visible from
  9732. // the public httplib.h. Re-declaring it here lets the tests link against the
  9733. // symbol in both header-only and split builds.
  9734. namespace httplib {
  9735. namespace detail {
  9736. ssize_t write_request_line(Stream &strm, const std::string &method,
  9737. const std::string &path);
  9738. } // namespace detail
  9739. } // namespace httplib
  9740. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9741. // A well-formed target is written verbatim.
  9742. {
  9743. detail::BufferStream strm;
  9744. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9745. EXPECT_GT(n, 0);
  9746. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9747. }
  9748. // A target carrying CR/LF, SP or other control octets must be rejected
  9749. // before anything reaches the wire, otherwise it splits the request line and
  9750. // injects a header or a whole request.
  9751. const std::string evil_targets[] = {
  9752. "/a\r\nInjected: pwned",
  9753. "/a\rInjected",
  9754. "/a\nInjected",
  9755. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9756. "/a b",
  9757. "/a\tb",
  9758. "/a\x7f",
  9759. };
  9760. for (const auto &evil : evil_targets) {
  9761. detail::BufferStream strm;
  9762. auto n = detail::write_request_line(strm, "GET", evil);
  9763. EXPECT_LT(n, 0);
  9764. EXPECT_TRUE(strm.get_buffer().empty());
  9765. }
  9766. }
  9767. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9768. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9769. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9770. // target reaches write_request. The client must fail cleanly with
  9771. // Error::Write instead of putting a request-line-less, header-injecting
  9772. // request on the wire.
  9773. Server svr;
  9774. svr.Get("/a", [](const Request &, Response &res) {
  9775. res.set_content("ok", "text/plain");
  9776. });
  9777. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9778. auto se = detail::scope_exit([&] {
  9779. svr.stop();
  9780. thread.join();
  9781. ASSERT_FALSE(svr.is_running());
  9782. });
  9783. svr.wait_until_ready();
  9784. {
  9785. Client cli(HOST, PORT);
  9786. cli.set_path_encode(false);
  9787. // The request is rejected before anything is written, so the connection
  9788. // stays silent and the subsequent response read would otherwise block for
  9789. // the full default read timeout. Shorten it -- the assertion is on the
  9790. // error, not the timeout.
  9791. cli.set_read_timeout(1, 0);
  9792. auto res = cli.Get("/a\r\nInjected: pwned");
  9793. EXPECT_FALSE(res);
  9794. EXPECT_EQ(Error::Write, res.error());
  9795. }
  9796. }
  9797. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9798. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9799. // including extension methods.
  9800. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9801. for (const auto &method : good_methods) {
  9802. detail::BufferStream strm;
  9803. auto n = detail::write_request_line(strm, method, "/");
  9804. EXPECT_GT(n, 0);
  9805. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9806. }
  9807. // A method carrying CR/LF would split the request line and smuggle a whole
  9808. // request ahead of the real one. A space or an empty method corrupts the
  9809. // request line. All must be rejected before anything reaches the wire.
  9810. const std::string evil_methods[] = {
  9811. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9812. "GET\r\nInjected: pwned",
  9813. "GET\r",
  9814. "GET\n",
  9815. "GE T",
  9816. "",
  9817. };
  9818. for (const auto &evil : evil_methods) {
  9819. detail::BufferStream strm;
  9820. auto n = detail::write_request_line(strm, evil, "/");
  9821. EXPECT_LT(n, 0);
  9822. EXPECT_TRUE(strm.get_buffer().empty());
  9823. }
  9824. }
  9825. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9826. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9827. // through Client::send must fail with Error::Write and no request, neither
  9828. // the smuggled one nor the real one, may reach the server.
  9829. Server svr;
  9830. std::atomic<int> request_count(0);
  9831. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9832. request_count++;
  9833. res.status = StatusCode::OK_200;
  9834. return Server::HandlerResponse::Handled;
  9835. });
  9836. auto port = svr.bind_to_any_port(HOST);
  9837. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9838. auto se = detail::scope_exit([&] {
  9839. svr.stop();
  9840. thread.join();
  9841. ASSERT_FALSE(svr.is_running());
  9842. });
  9843. svr.wait_until_ready();
  9844. {
  9845. Client cli(HOST, port);
  9846. const std::string evil_methods[] = {
  9847. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9848. "GE T",
  9849. "",
  9850. };
  9851. for (const auto &evil : evil_methods) {
  9852. Request req;
  9853. req.method = evil;
  9854. req.path = "/";
  9855. auto res = cli.send(req);
  9856. EXPECT_FALSE(res);
  9857. EXPECT_EQ(Error::Write, res.error());
  9858. }
  9859. auto handle =
  9860. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9861. EXPECT_FALSE(handle.is_valid());
  9862. EXPECT_EQ(Error::Write, handle.error);
  9863. // A valid request on the same client still goes through.
  9864. auto res = cli.Get("/");
  9865. ASSERT_TRUE(res);
  9866. EXPECT_EQ(StatusCode::OK_200, res->status);
  9867. }
  9868. EXPECT_EQ(1, request_count.load());
  9869. }
  9870. // Sends a raw request and verifies that there isn't a crash or exception.
  9871. static void test_raw_request(const std::string &req,
  9872. std::string *out = nullptr) {
  9873. Server svr;
  9874. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9875. res.set_content("ok", "text/plain");
  9876. });
  9877. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9878. res.set_content("ok", "text/plain");
  9879. });
  9880. svr.Get("/header_field_value_check",
  9881. [&](const Request & /*req*/, Response &res) {
  9882. res.set_content("ok", "text/plain");
  9883. });
  9884. svr.CustomRoute("PROPFIND", "/dav",
  9885. [&](const Request & /*req*/, Response &res) {
  9886. res.status = StatusCode::MultiStatus_207;
  9887. });
  9888. // Server read timeout must be longer than the client read timeout for the
  9889. // bug to reproduce, probably to force the server to process a request
  9890. // without a trailing blank line.
  9891. const time_t client_read_timeout_sec = 1;
  9892. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9893. bool listen_thread_ok = false;
  9894. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9895. auto se = detail::scope_exit([&] {
  9896. svr.stop();
  9897. t.join();
  9898. ASSERT_FALSE(svr.is_running());
  9899. EXPECT_TRUE(listen_thread_ok);
  9900. });
  9901. svr.wait_until_ready();
  9902. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9903. }
  9904. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9905. // A certain header line causes an exception if the header property is parsed
  9906. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9907. test_raw_request(
  9908. "GET /hi HTTP/1.1\r\n"
  9909. " : "
  9910. " "
  9911. " ");
  9912. }
  9913. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9914. // A certain header line causes an exception if the header property *name* is
  9915. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9916. // greedy matcher and requires backtracking when there are a lot of ":"
  9917. // characters.
  9918. // This occurs with libc++ but not libstdc++.
  9919. test_raw_request(
  9920. "GET /hi HTTP/1.1\r\n"
  9921. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9922. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9923. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9924. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9925. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9926. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9927. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9928. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9929. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9930. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9931. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9932. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9933. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9934. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9935. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9936. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9937. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9938. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9939. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9940. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9941. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9942. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9943. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9944. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9945. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9946. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9947. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9948. "&&&%%%");
  9949. }
  9950. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9951. // Make sure this doesn't crash the server.
  9952. // In a previous version of the header line regex, the "\r" rendered the line
  9953. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9954. // a new position where the leading white space ended and the field value
  9955. // began.
  9956. // The crash occurs with libc++ but not libstdc++.
  9957. test_raw_request("GET /hi HTTP/1.1\r\n"
  9958. "a:" +
  9959. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9960. "\r\n"
  9961. "\r\n");
  9962. }
  9963. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9964. const char *rejected[] = {
  9965. // RFC 9112 §3: one SP between the parts, and nothing else
  9966. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9967. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9968. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9969. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9970. // A request-target has no fragment
  9971. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9972. // An HTTP/1.1 request needs a Host
  9973. "GET /hi HTTP/1.1\r\n\r\n",
  9974. };
  9975. for (auto request : rejected) {
  9976. std::string out;
  9977. test_raw_request(request, &out);
  9978. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9979. }
  9980. std::string out;
  9981. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9982. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9983. }
  9984. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9985. // RFC 9112 §6.1
  9986. const char *requests[] = {
  9987. "PUT /put_hi HTTP/1.1\r\n"
  9988. "Host: localhost\r\n"
  9989. "Content-Length: 0\r\n"
  9990. "Transfer-Encoding: chunked\r\n"
  9991. "\r\n"
  9992. "0\r\n\r\n",
  9993. "PUT /put_hi HTTP/1.0\r\n"
  9994. "Connection: keep-alive\r\n"
  9995. "Transfer-Encoding: chunked\r\n"
  9996. "\r\n"
  9997. "0\r\n\r\n",
  9998. };
  9999. for (auto request : requests) {
  10000. std::string out;
  10001. test_raw_request(request, &out);
  10002. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10003. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10004. }
  10005. }
  10006. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10007. std::string out;
  10008. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10009. "Content-Type: text/plain\r\n"
  10010. "Transfer-Encoding: chunked\r\n"
  10011. "\r\n"
  10012. "nothex\r\n",
  10013. &out);
  10014. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10015. }
  10016. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10017. std::string out;
  10018. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10019. "Content-Type: text/plain\r\n"
  10020. "Transfer-Encoding: chunked\r\n"
  10021. "\r\n"
  10022. "3\r\n"
  10023. "xyz\r\n"
  10024. "NaN\r\n",
  10025. &out);
  10026. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10027. }
  10028. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10029. std::string out;
  10030. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10031. "Content-Type: text/plain\r\n"
  10032. "Transfer-Encoding: chunked\r\n"
  10033. "\r\n"
  10034. // Length is too large for 64 bits.
  10035. "1ffffffffffffffff\r\n"
  10036. "xyz\r\n",
  10037. &out);
  10038. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10039. }
  10040. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10041. test_raw_request("GET /hi HTTP/1.1\r\n"
  10042. "Content-Type: text/plain\r\n\r");
  10043. }
  10044. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10045. std::string out;
  10046. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10047. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10048. }
  10049. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10050. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10051. std::string out;
  10052. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10053. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10054. }
  10055. }
  10056. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10057. std::string out;
  10058. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10059. "Host: localhost\r\n"
  10060. "Connection: close\r\n\r\n",
  10061. &out);
  10062. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10063. }
  10064. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10065. Server svr;
  10066. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10067. EXPECT_TRUE(!req.remote_addr.empty());
  10068. });
  10069. thread t = thread([&] { svr.listen(HOST, PORT); });
  10070. auto se = detail::scope_exit([&] {
  10071. svr.stop();
  10072. t.join();
  10073. ASSERT_FALSE(svr.is_running());
  10074. });
  10075. svr.wait_until_ready();
  10076. // Send an invalid request line to trigger Bad Request
  10077. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10078. std::string out;
  10079. ASSERT_TRUE(send_request(5, bad_req, &out));
  10080. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10081. }
  10082. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10083. // answered right away rather than blocking on a read that waits for EOF.
  10084. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10085. std::string out;
  10086. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10087. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10088. }
  10089. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10090. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10091. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10092. for (const auto *method : methods) {
  10093. Server svr;
  10094. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10095. EXPECT_FALSE(svr.is_valid()) << method;
  10096. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10097. }
  10098. }
  10099. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10100. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10101. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10102. for (const auto *method : methods) {
  10103. Server svr;
  10104. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10105. EXPECT_FALSE(svr.is_valid()) << method;
  10106. }
  10107. }
  10108. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10109. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10110. "COPY", "MOVE", "LOCK",
  10111. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10112. Server svr;
  10113. for (const auto *method : methods) {
  10114. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10115. }
  10116. EXPECT_TRUE(svr.is_valid());
  10117. }
  10118. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10119. Server svr;
  10120. svr.CustomRoute("POST", "/x",
  10121. [](const Request &, Response &, const ContentReader &) {});
  10122. EXPECT_FALSE(svr.is_valid());
  10123. }
  10124. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10125. Server svr;
  10126. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10127. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10128. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10129. EXPECT_FALSE(svr.is_valid());
  10130. }
  10131. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10132. Server svr;
  10133. auto captured = Error::Success;
  10134. svr.set_error_logger(
  10135. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10136. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10137. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10138. }
  10139. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10140. std::string out;
  10141. std::string request(
  10142. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10143. test_raw_request(request, &out);
  10144. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10145. }
  10146. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10147. std::string out;
  10148. std::string request(
  10149. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10150. test_raw_request(request, &out);
  10151. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10152. }
  10153. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10154. std::string out;
  10155. std::string request(
  10156. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10157. test_raw_request(request, &out);
  10158. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10159. }
  10160. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10161. std::string out;
  10162. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10163. "Host: localhost\r\n"
  10164. "Test: \r\n\r\n",
  10165. &out);
  10166. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10167. }
  10168. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10169. Server svr;
  10170. std::string x_custom;
  10171. std::string cookie;
  10172. std::string xff;
  10173. std::string x_unicode;
  10174. std::string x_iis;
  10175. svr.Get("/check", [&](const Request &req, Response &res) {
  10176. x_custom = req.get_header_value("X-Custom");
  10177. cookie = req.get_header_value("Cookie");
  10178. xff = req.get_header_value("X-Forwarded-For");
  10179. x_unicode = req.get_header_value("X-Unicode");
  10180. x_iis = req.get_header_value("X-IIS");
  10181. res.set_content("ok", "text/plain");
  10182. });
  10183. thread t = thread([&] { svr.listen(HOST, PORT); });
  10184. auto se = detail::scope_exit([&] {
  10185. svr.stop();
  10186. t.join();
  10187. ASSERT_FALSE(svr.is_running());
  10188. });
  10189. svr.wait_until_ready();
  10190. const std::string req = "GET /check HTTP/1.1\r\n"
  10191. "Host: localhost\r\n"
  10192. "X-Custom: a%0D%0AInjected: b\r\n"
  10193. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10194. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10195. "X-Unicode: %E3%81%82\r\n"
  10196. "X-IIS: %u00E9\r\n"
  10197. "Connection: close\r\n"
  10198. "\r\n";
  10199. std::string res;
  10200. ASSERT_TRUE(send_request(5, req, &res));
  10201. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10202. // Every value must be returned verbatim (wire form), with no decoding.
  10203. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10204. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10205. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10206. EXPECT_EQ("%E3%81%82", x_unicode);
  10207. EXPECT_EQ("%u00E9", x_iis);
  10208. }
  10209. // Applications that previously relied on automatic percent-decoding can
  10210. // reproduce the old behavior by explicitly calling decode_path_component()
  10211. // or, for RFC 3986 conformance, decode_uri_component().
  10212. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10213. Server svr;
  10214. std::string decoded;
  10215. svr.Get("/check", [&](const Request &req, Response &res) {
  10216. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10217. res.set_content("ok", "text/plain");
  10218. });
  10219. thread t = thread([&] { svr.listen(HOST, PORT); });
  10220. auto se = detail::scope_exit([&] {
  10221. svr.stop();
  10222. t.join();
  10223. ASSERT_FALSE(svr.is_running());
  10224. });
  10225. svr.wait_until_ready();
  10226. const std::string req = "GET /check HTTP/1.1\r\n"
  10227. "Host: localhost\r\n"
  10228. "X-Custom: hello%20world\r\n"
  10229. "Connection: close\r\n"
  10230. "\r\n";
  10231. std::string res;
  10232. ASSERT_TRUE(send_request(5, req, &res));
  10233. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10234. EXPECT_EQ("hello world", decoded);
  10235. }
  10236. // Regression test for #2033. Browsers send Referer values that include
  10237. // percent-encoded characters such as %0A inside the URL. Decoding the
  10238. // header value would either trip the post-decode CR/LF/NUL guard (the
  10239. // original bug, returning 400) or, after that guard was relaxed, silently
  10240. // store a literal LF — both unacceptable. The wire form must round-trip.
  10241. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10242. Server svr;
  10243. std::string referer;
  10244. svr.Get("/check", [&](const Request &req, Response &res) {
  10245. referer = req.get_header_value("Referer");
  10246. res.set_content("ok", "text/plain");
  10247. });
  10248. thread t = thread([&] { svr.listen(HOST, PORT); });
  10249. auto se = detail::scope_exit([&] {
  10250. svr.stop();
  10251. t.join();
  10252. ASSERT_FALSE(svr.is_running());
  10253. });
  10254. svr.wait_until_ready();
  10255. const std::string req = "GET /check HTTP/1.1\r\n"
  10256. "Host: localhost\r\n"
  10257. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10258. "Connection: close\r\n"
  10259. "\r\n";
  10260. std::string res;
  10261. ASSERT_TRUE(send_request(5, req, &res));
  10262. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10263. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10264. }
  10265. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10266. Server svr;
  10267. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10268. res.set_header("Cache-Control", "no-cache");
  10269. res.set_chunked_content_provider(
  10270. "text/event-stream", [](size_t offset, DataSink &sink) {
  10271. std::string s = "data:";
  10272. s += std::to_string(offset);
  10273. s += "\n\n";
  10274. auto ret = sink.write(s.data(), s.size());
  10275. EXPECT_TRUE(ret);
  10276. std::this_thread::sleep_for(std::chrono::seconds(1));
  10277. return true;
  10278. });
  10279. });
  10280. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10281. svr.wait_until_ready();
  10282. Client client(HOST, PORT);
  10283. const Headers headers = {{"Accept", "text/event-stream"}};
  10284. auto get_thread = std::thread([&client, &headers]() {
  10285. auto res = client.Get(
  10286. "/events", headers,
  10287. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10288. });
  10289. auto se = detail::scope_exit([&] {
  10290. svr.stop();
  10291. get_thread.join();
  10292. listen_thread.join();
  10293. ASSERT_FALSE(svr.is_running());
  10294. });
  10295. // Give GET time to get a few messages.
  10296. std::this_thread::sleep_for(std::chrono::seconds(2));
  10297. }
  10298. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10299. httplib::Server svr;
  10300. svr.Post("/hi",
  10301. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10302. res.status = StatusCode::OK_200;
  10303. });
  10304. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10305. svr.wait_until_ready();
  10306. Client cli(HOST, PORT);
  10307. auto res = cli.Post("/hi", "data", "text/plain");
  10308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10309. EXPECT_EQ(StatusCode::OK_200, res->status);
  10310. svr.stop();
  10311. thread.join();
  10312. ASSERT_FALSE(svr.is_running());
  10313. res = cli.Post("/hi", "data", "text/plain");
  10314. ASSERT_FALSE(res);
  10315. }
  10316. TEST(ServerStopTest, ListenFailure) {
  10317. Server svr;
  10318. auto t = thread([&]() {
  10319. auto ret = svr.listen("????", PORT);
  10320. EXPECT_FALSE(ret);
  10321. });
  10322. svr.wait_until_ready();
  10323. svr.stop();
  10324. t.join();
  10325. }
  10326. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10327. TEST(ServerStopTest, Decommision) {
  10328. Server svr;
  10329. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10330. for (int i = 0; i < 4; i++) {
  10331. auto is_even = !(i % 2);
  10332. std::thread t{[&] {
  10333. try {
  10334. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10335. if (is_even) {
  10336. throw std::runtime_error("Some thing that happens to go wrong.");
  10337. }
  10338. svr.listen(HOST, PORT);
  10339. } catch (...) { svr.decommission(); }
  10340. }};
  10341. svr.wait_until_ready();
  10342. // Server is up
  10343. {
  10344. Client cli(HOST, PORT);
  10345. auto res = cli.Get("/hi");
  10346. if (is_even) {
  10347. EXPECT_FALSE(res);
  10348. } else {
  10349. EXPECT_TRUE(res);
  10350. EXPECT_EQ("hi...", res->body);
  10351. }
  10352. }
  10353. svr.stop();
  10354. t.join();
  10355. // Server is down...
  10356. {
  10357. Client cli(HOST, PORT);
  10358. auto res = cli.Get("/hi");
  10359. EXPECT_FALSE(res);
  10360. }
  10361. }
  10362. }
  10363. #endif
  10364. // Helper function for string body upload progress tests
  10365. template <typename SetupHandler, typename ClientCall>
  10366. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10367. ClientCall &&client_call,
  10368. const string &body) {
  10369. Server svr;
  10370. setup_handler(svr);
  10371. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10372. auto se = detail::scope_exit([&] {
  10373. svr.stop();
  10374. t.join();
  10375. });
  10376. svr.wait_until_ready();
  10377. Client cli(HOST, PORT);
  10378. vector<uint64_t> progress_values;
  10379. bool progress_called = false;
  10380. auto res =
  10381. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10382. progress_values.push_back(current);
  10383. progress_called = true;
  10384. return true;
  10385. });
  10386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10387. EXPECT_EQ(200, res->status);
  10388. EXPECT_TRUE(progress_called);
  10389. }
  10390. TEST(UploadProgressTest, PostStringBodyBasic) {
  10391. TestStringBodyUploadProgress(
  10392. [](Server &svr) {
  10393. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10394. res.set_content("received", "text/plain");
  10395. });
  10396. },
  10397. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10398. return cli.Post("/test", body, "text/plain", progress_callback);
  10399. },
  10400. "test data for upload progress");
  10401. }
  10402. TEST(UploadProgressTest, PutStringBodyBasic) {
  10403. TestStringBodyUploadProgress(
  10404. [](Server &svr) {
  10405. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10406. res.set_content("put received", "text/plain");
  10407. });
  10408. },
  10409. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10410. return cli.Put("/test", body, "text/plain", progress_callback);
  10411. },
  10412. "put test data for upload progress");
  10413. }
  10414. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10415. TestStringBodyUploadProgress(
  10416. [](Server &svr) {
  10417. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10418. res.set_content("patch received", "text/plain");
  10419. });
  10420. },
  10421. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10422. return cli.Patch("/test", body, "text/plain", progress_callback);
  10423. },
  10424. "patch test data for upload progress");
  10425. }
  10426. // Helper function for content provider upload progress tests
  10427. template <typename SetupHandler, typename ClientCall>
  10428. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10429. ClientCall &&client_call) {
  10430. Server svr;
  10431. setup_handler(svr);
  10432. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10433. auto se = detail::scope_exit([&] {
  10434. svr.stop();
  10435. t.join();
  10436. });
  10437. svr.wait_until_ready();
  10438. Client cli(HOST, PORT);
  10439. vector<uint64_t> progress_values;
  10440. auto res =
  10441. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10442. progress_values.push_back(current);
  10443. return true;
  10444. });
  10445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10446. EXPECT_EQ(200, res->status);
  10447. EXPECT_FALSE(progress_values.empty());
  10448. }
  10449. TEST(UploadProgressTest, PostContentProviderProgress) {
  10450. TestContentProviderUploadProgress(
  10451. [](Server &svr) {
  10452. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10453. res.set_content("provider received", "text/plain");
  10454. });
  10455. },
  10456. [](Client &cli, UploadProgress progress_callback) {
  10457. return cli.Post(
  10458. "/test", 9,
  10459. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10460. sink.os << "test data";
  10461. return true;
  10462. },
  10463. "text/plain", progress_callback);
  10464. });
  10465. }
  10466. // Helper function for multipart upload progress tests
  10467. template <typename SetupHandler, typename ClientCall>
  10468. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10469. ClientCall &&client_call,
  10470. const string &endpoint) {
  10471. Server svr;
  10472. setup_handler(svr);
  10473. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10474. auto se = detail::scope_exit([&] {
  10475. svr.stop();
  10476. t.join();
  10477. });
  10478. svr.wait_until_ready();
  10479. Client cli(HOST, PORT);
  10480. vector<uint64_t> progress_values;
  10481. UploadFormDataItems items = {
  10482. {"field1", "value1", "", ""},
  10483. {"field2", "longer value for progress tracking test", "", ""},
  10484. {"file1", "file content data for upload progress", "test.txt",
  10485. "text/plain"}};
  10486. auto res = client_call(cli, endpoint, items,
  10487. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10488. progress_values.push_back(current);
  10489. return true;
  10490. });
  10491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10492. EXPECT_EQ(200, res->status);
  10493. EXPECT_FALSE(progress_values.empty());
  10494. }
  10495. TEST(UploadProgressTest, PostMultipartProgress) {
  10496. TestMultipartUploadProgress(
  10497. [](Server &svr) {
  10498. svr.Post("/multipart", [](const Request &req, Response &res) {
  10499. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10500. res.set_content("multipart received", "text/plain");
  10501. });
  10502. },
  10503. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10504. UploadProgress progress_callback) {
  10505. return cli.Post(endpoint, items, progress_callback);
  10506. },
  10507. "/multipart");
  10508. }
  10509. // Helper function for basic download progress tests
  10510. template <typename SetupHandler, typename ClientCall>
  10511. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10512. ClientCall &&client_call, const string &endpoint,
  10513. size_t expected_content_size) {
  10514. Server svr;
  10515. setup_handler(svr);
  10516. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10517. auto se = detail::scope_exit([&] {
  10518. svr.stop();
  10519. t.join();
  10520. });
  10521. svr.wait_until_ready();
  10522. Client cli(HOST, PORT);
  10523. vector<uint64_t> progress_values;
  10524. auto res = client_call(cli, endpoint,
  10525. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10526. progress_values.push_back(current);
  10527. return true;
  10528. });
  10529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10530. EXPECT_EQ(200, res->status);
  10531. EXPECT_FALSE(progress_values.empty());
  10532. EXPECT_EQ(expected_content_size, res->body.size());
  10533. }
  10534. TEST(DownloadProgressTest, GetBasic) {
  10535. TestBasicDownloadProgress(
  10536. [](Server &svr) {
  10537. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10538. string content(1000, 'D');
  10539. res.set_content(content, "text/plain");
  10540. });
  10541. },
  10542. [](Client &cli, const string &endpoint,
  10543. DownloadProgress progress_callback) {
  10544. return cli.Get(endpoint, progress_callback);
  10545. },
  10546. "/download", 1000u);
  10547. }
  10548. // Helper function for content receiver download progress tests
  10549. template <typename SetupHandler, typename ClientCall>
  10550. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10551. ClientCall &&client_call,
  10552. const string &endpoint,
  10553. size_t expected_content_size) {
  10554. Server svr;
  10555. setup_handler(svr);
  10556. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10557. auto se = detail::scope_exit([&] {
  10558. svr.stop();
  10559. t.join();
  10560. });
  10561. svr.wait_until_ready();
  10562. Client cli(HOST, PORT);
  10563. vector<uint64_t> progress_values;
  10564. string received_body;
  10565. auto res = client_call(
  10566. cli, endpoint,
  10567. [&](const char *data, size_t data_length) -> bool {
  10568. received_body.append(data, data_length);
  10569. return true;
  10570. },
  10571. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10572. progress_values.push_back(current);
  10573. return true;
  10574. });
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. EXPECT_EQ(200, res->status);
  10577. EXPECT_FALSE(progress_values.empty());
  10578. EXPECT_EQ(expected_content_size, received_body.size());
  10579. EXPECT_TRUE(res->body.empty());
  10580. }
  10581. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10582. TestContentReceiverDownloadProgress(
  10583. [](Server &svr) {
  10584. svr.Get("/download-receiver",
  10585. [](const Request & /*req*/, Response &res) {
  10586. string content(2000, 'R');
  10587. res.set_content(content, "text/plain");
  10588. });
  10589. },
  10590. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10591. DownloadProgress progress_callback) {
  10592. return cli.Get(endpoint, content_receiver, progress_callback);
  10593. },
  10594. "/download-receiver", 2000u);
  10595. }
  10596. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10597. // A provider reaching a pass with nothing to hand over - an empty buffer
  10598. // popped off a queue, say - must not be taken to mean the body is finished.
  10599. // It used to end the loop with the terminating chunk unwritten while the
  10600. // server still considered the response complete, so the peer waited for an
  10601. // end that never arrived.
  10602. Server svr;
  10603. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10604. auto step = std::make_shared<int>(0);
  10605. res.set_chunked_content_provider("text/plain",
  10606. [step](size_t /*offset*/, DataSink &sink) {
  10607. switch ((*step)++) {
  10608. case 0: sink.write("", 0); break;
  10609. case 1: sink.write("hello", 5); break;
  10610. default: sink.done(); break;
  10611. }
  10612. return true;
  10613. });
  10614. });
  10615. auto port = svr.bind_to_any_port(HOST);
  10616. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10617. auto listen_se = detail::scope_exit([&] {
  10618. svr.stop();
  10619. listen_thread.join();
  10620. ASSERT_FALSE(svr.is_running());
  10621. });
  10622. svr.wait_until_ready();
  10623. Client cli(HOST, port);
  10624. // Without the fix the body is never terminated, so bound the wait rather
  10625. // than letting the test hang on the default read timeout.
  10626. cli.set_read_timeout(5, 0);
  10627. auto res = cli.Get("/stream");
  10628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10629. EXPECT_EQ(StatusCode::OK_200, res->status);
  10630. EXPECT_EQ("hello", res->body);
  10631. }
  10632. TEST(StreamingTest, NoContentLengthStreaming) {
  10633. Server svr;
  10634. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10635. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10636. if (offset < 6) {
  10637. sink.os << (offset < 3 ? "a" : "b");
  10638. } else {
  10639. sink.done();
  10640. }
  10641. return true;
  10642. });
  10643. });
  10644. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10645. auto listen_se = detail::scope_exit([&] {
  10646. svr.stop();
  10647. listen_thread.join();
  10648. ASSERT_FALSE(svr.is_running());
  10649. });
  10650. svr.wait_until_ready();
  10651. Client client(HOST, PORT);
  10652. auto get_thread = std::thread([&client]() {
  10653. std::string s;
  10654. auto res =
  10655. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10656. s += std::string(data, len);
  10657. return true;
  10658. });
  10659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10660. EXPECT_EQ(StatusCode::OK_200, res->status);
  10661. EXPECT_EQ("aaabbb", s);
  10662. });
  10663. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10664. // Give GET time to get a few messages.
  10665. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10666. }
  10667. TEST(MountTest, Unmount) {
  10668. Server svr;
  10669. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10670. auto se = detail::scope_exit([&] {
  10671. svr.stop();
  10672. listen_thread.join();
  10673. ASSERT_FALSE(svr.is_running());
  10674. });
  10675. svr.wait_until_ready();
  10676. Client cli("localhost", PORT);
  10677. svr.set_mount_point("/mount2", "./www2");
  10678. auto res = cli.Get("/");
  10679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10681. res = cli.Get("/mount2/dir/test.html");
  10682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10683. EXPECT_EQ(StatusCode::OK_200, res->status);
  10684. svr.set_mount_point("/", "./www");
  10685. res = cli.Get("/dir/");
  10686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10687. EXPECT_EQ(StatusCode::OK_200, res->status);
  10688. svr.remove_mount_point("/");
  10689. res = cli.Get("/dir/");
  10690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10692. svr.remove_mount_point("/mount2");
  10693. res = cli.Get("/mount2/dir/test.html");
  10694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10696. }
  10697. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10698. Server svr;
  10699. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10700. svr.Get("/api/hello", [](const Request &, Response &res) {
  10701. res.set_content("api", "text/plain");
  10702. });
  10703. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10704. auto se = detail::scope_exit([&] {
  10705. svr.stop();
  10706. listen_thread.join();
  10707. ASSERT_FALSE(svr.is_running());
  10708. });
  10709. svr.wait_until_ready();
  10710. Client cli(HOST, PORT);
  10711. auto res = cli.Get("/dir/test.html");
  10712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10713. EXPECT_EQ(StatusCode::OK_200, res->status);
  10714. res = cli.Get("/api/hello");
  10715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10716. EXPECT_EQ(StatusCode::OK_200, res->status);
  10717. EXPECT_EQ("api", res->body);
  10718. }
  10719. TEST(MountTest, PathSegmentBoundary) {
  10720. Server svr;
  10721. svr.set_mount_point("/mount2", "./www2");
  10722. svr.set_mount_point("/", "./www");
  10723. auto port = svr.bind_to_any_port(HOST);
  10724. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10725. auto se = detail::scope_exit([&] {
  10726. svr.stop();
  10727. listen_thread.join();
  10728. ASSERT_FALSE(svr.is_running());
  10729. });
  10730. svr.wait_until_ready();
  10731. Client cli(HOST, port);
  10732. auto res = cli.Get("/mount2/dir/test.html");
  10733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10734. EXPECT_EQ(StatusCode::OK_200, res->status);
  10735. // "/mount2" must not match part-way through a path segment.
  10736. res = cli.Get("/mount2dir/test.html");
  10737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10738. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10739. // A mount point ending in '/' keeps matching every path below it.
  10740. res = cli.Get("/dir/test.html");
  10741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10742. EXPECT_EQ(StatusCode::OK_200, res->status);
  10743. }
  10744. TEST(MountTest, Redicect) {
  10745. Server svr;
  10746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10747. auto se = detail::scope_exit([&] {
  10748. svr.stop();
  10749. listen_thread.join();
  10750. ASSERT_FALSE(svr.is_running());
  10751. });
  10752. svr.set_mount_point("/", "./www");
  10753. svr.wait_until_ready();
  10754. Client cli("localhost", PORT);
  10755. auto res = cli.Get("/dir/");
  10756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10757. EXPECT_EQ(StatusCode::OK_200, res->status);
  10758. res = cli.Get("/dir");
  10759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10760. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10761. res = cli.Get("/file");
  10762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10763. EXPECT_EQ(StatusCode::OK_200, res->status);
  10764. res = cli.Get("/file/");
  10765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10766. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10767. cli.set_follow_location(true);
  10768. res = cli.Get("/dir");
  10769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10770. EXPECT_EQ(StatusCode::OK_200, res->status);
  10771. }
  10772. TEST(MountTest, MultibytesPathName) {
  10773. Server svr;
  10774. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10775. auto se = detail::scope_exit([&] {
  10776. svr.stop();
  10777. listen_thread.join();
  10778. ASSERT_FALSE(svr.is_running());
  10779. });
  10780. svr.set_mount_point("/", "./www");
  10781. svr.wait_until_ready();
  10782. Client cli("localhost", PORT);
  10783. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10785. EXPECT_EQ(StatusCode::OK_200, res->status);
  10786. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10787. }
  10788. // A mount point serves no path with an empty segment or one ending in '.' or
  10789. // a space, so a guard in the pre-routing handler sees the path of every file
  10790. // that is served
  10791. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10792. Server svr;
  10793. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10794. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10795. if (req.path == "/dir/test.html") {
  10796. res.status = StatusCode::Unauthorized_401;
  10797. return Server::HandlerResponse::Handled;
  10798. }
  10799. return Server::HandlerResponse::Unhandled;
  10800. });
  10801. auto port = svr.bind_to_any_port(HOST);
  10802. ASSERT_LT(0, port);
  10803. thread t = thread([&] { svr.listen_after_bind(); });
  10804. auto se = detail::scope_exit([&] {
  10805. svr.stop();
  10806. t.join();
  10807. ASSERT_FALSE(svr.is_running());
  10808. });
  10809. svr.wait_until_ready();
  10810. Client cli(HOST, port);
  10811. for (auto path :
  10812. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10813. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10814. "/dir/test.html.", "/dir/test.html%20"}) {
  10815. SCOPED_TRACE(path);
  10816. auto res = cli.Get(path);
  10817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10818. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10819. }
  10820. }
  10821. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10822. Server svr;
  10823. svr.set_mount_point("/", "./www");
  10824. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10825. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10826. auto port = svr.bind_to_any_port(HOST);
  10827. ASSERT_GT(port, 0);
  10828. thread t = thread([&] { svr.listen_after_bind(); });
  10829. auto se = detail::scope_exit([&] {
  10830. svr.stop();
  10831. t.join();
  10832. ASSERT_FALSE(svr.is_running());
  10833. });
  10834. svr.wait_until_ready();
  10835. Client cli(HOST, port);
  10836. auto res = cli.Get("/dir/test.abcde");
  10837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10838. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10839. res = cli.Get("/dir/test.html");
  10840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10841. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10842. }
  10843. #ifdef _WIN32
  10844. // Issue #2435: mmap::open() must succeed even when another handle holds
  10845. // the file open for writing (e.g. an active log file).
  10846. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10847. const char *path = "mmap_concurrent_writer_test.txt";
  10848. const char *content = "hello";
  10849. {
  10850. std::ofstream f(path, std::ios::binary);
  10851. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10852. }
  10853. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10854. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10855. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10856. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10857. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10858. detail::mmap m(path);
  10859. ASSERT_TRUE(m.is_open());
  10860. EXPECT_EQ(strlen(content), m.size());
  10861. char buf[8];
  10862. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10863. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10864. }
  10865. #endif
  10866. #ifndef _WIN32
  10867. // A directory or a device has no size to serve.
  10868. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10869. const char *path = "./mmap_not_regular_test_dir";
  10870. ASSERT_EQ(0, ::mkdir(path, 0755));
  10871. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10872. for (auto p : {path, "/dev/null"}) {
  10873. detail::mmap m(p);
  10874. EXPECT_FALSE(m.is_open()) << p;
  10875. EXPECT_EQ(0U, m.size()) << p;
  10876. }
  10877. Server svr;
  10878. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10879. res.set_file_content("/dev/null");
  10880. });
  10881. auto port = svr.bind_to_any_port(HOST);
  10882. thread t = thread([&] { svr.listen_after_bind(); });
  10883. auto se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. t.join();
  10886. });
  10887. svr.wait_until_ready();
  10888. auto res = Client(HOST, port).Get("/null");
  10889. ASSERT_TRUE(res);
  10890. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10891. }
  10892. #endif
  10893. #ifdef __linux__
  10894. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10895. TEST(MmapTest, FileIsNotMapped) {
  10896. const char *path = "mmap_not_mapped_test.txt";
  10897. {
  10898. std::ofstream f(path, std::ios::binary);
  10899. f << "hello";
  10900. }
  10901. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10902. detail::mmap m(path);
  10903. ASSERT_TRUE(m.is_open());
  10904. std::ifstream maps("/proc/self/maps");
  10905. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10906. std::istreambuf_iterator<char>());
  10907. EXPECT_EQ(std::string::npos, mappings.find(path));
  10908. }
  10909. #endif
  10910. TEST(KeepAliveTest, ReadTimeout) {
  10911. Server svr;
  10912. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10913. std::this_thread::sleep_for(std::chrono::seconds(2));
  10914. res.set_content("a", "text/plain");
  10915. });
  10916. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10917. res.set_content("b", "text/plain");
  10918. });
  10919. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10920. auto se = detail::scope_exit([&] {
  10921. svr.stop();
  10922. listen_thread.join();
  10923. ASSERT_FALSE(svr.is_running());
  10924. });
  10925. svr.wait_until_ready();
  10926. Client cli("localhost", PORT);
  10927. cli.set_keep_alive(true);
  10928. cli.set_read_timeout(std::chrono::seconds(1));
  10929. auto resa = cli.Get("/a");
  10930. ASSERT_FALSE(resa);
  10931. EXPECT_EQ(Error::Read, resa.error());
  10932. auto resb = cli.Get("/b");
  10933. ASSERT_TRUE(resb);
  10934. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10935. EXPECT_EQ("b", resb->body);
  10936. }
  10937. TEST(KeepAliveTest, MaxCount) {
  10938. size_t keep_alive_max_count = 3;
  10939. Server svr;
  10940. svr.set_keep_alive_max_count(keep_alive_max_count);
  10941. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10942. res.set_content("Hello World!", "text/plain");
  10943. });
  10944. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10945. auto se = detail::scope_exit([&] {
  10946. svr.stop();
  10947. listen_thread.join();
  10948. ASSERT_FALSE(svr.is_running());
  10949. });
  10950. svr.wait_until_ready();
  10951. Client cli(HOST, PORT);
  10952. cli.set_keep_alive(true);
  10953. for (size_t i = 0; i < 5; i++) {
  10954. auto result = cli.Get("/hi");
  10955. ASSERT_TRUE(result);
  10956. EXPECT_EQ(StatusCode::OK_200, result->status);
  10957. if (i == keep_alive_max_count - 1) {
  10958. EXPECT_EQ("close", result->get_header_value("Connection"));
  10959. } else {
  10960. EXPECT_FALSE(result->has_header("Connection"));
  10961. }
  10962. }
  10963. }
  10964. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10965. // can pull the next one into the server's buffer. The server must serve it
  10966. // without waiting for the socket to become readable again. The keep-alive
  10967. // timeout outlasts the client's read timeout, so a request left waiting for it
  10968. // shows up as a missing response.
  10969. static void serve_pipelining_routes(Server &svr,
  10970. const std::function<void(int)> &client) {
  10971. svr.set_keep_alive_timeout(5);
  10972. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10973. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10974. });
  10975. svr.Post("/echo", [](const Request &req, Response &res) {
  10976. res.set_content("echo " + req.body, "text/plain");
  10977. });
  10978. auto port = svr.bind_to_any_port(HOST);
  10979. thread t = thread([&] { svr.listen_after_bind(); });
  10980. auto se = detail::scope_exit([&] {
  10981. svr.stop();
  10982. t.join();
  10983. });
  10984. svr.wait_until_ready();
  10985. client(port);
  10986. }
  10987. static std::string
  10988. send_pipelined_requests(const std::vector<std::string> &parts) {
  10989. Server svr;
  10990. std::string res;
  10991. serve_pipelining_routes(svr, [&](int port) {
  10992. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10993. });
  10994. return res;
  10995. }
  10996. static void expect_in_order(const std::string &res,
  10997. const std::vector<std::string> &bodies) {
  10998. size_t pos = 0;
  10999. for (const auto &body : bodies) {
  11000. pos = res.find(body, pos);
  11001. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11002. pos += body.size();
  11003. }
  11004. }
  11005. TEST(KeepAliveTest, PipelinedRequests) {
  11006. auto res = send_pipelined_requests(
  11007. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11008. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11009. "Content-Length: 4\r\n\r\nbody"
  11010. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11011. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11012. }
  11013. // The second request starts in the server's buffer and ends on the socket.
  11014. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11015. auto res =
  11016. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11017. "GET /hi/2 HTTP/1.1\r\nHo",
  11018. "st: localhost\r\nConnection: close\r\n\r\n"});
  11019. expect_in_order(res, {"hi 1", "hi 2"});
  11020. }
  11021. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11022. // CRLF after a body does not turn into a 400 for the next request.
  11023. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11024. auto res = send_pipelined_requests(
  11025. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11026. "Content-Length: 4\r\n\r\nbody\r\n"
  11027. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11028. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11029. expect_in_order(res, {"echo body", "hi 2"});
  11030. }
  11031. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11032. // must not be served as the next request.
  11033. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11034. auto res = send_pipelined_requests(
  11035. {"INVALID REQUEST LINE\r\n\r\n"
  11036. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11037. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11038. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11039. }
  11040. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11041. // Over TLS, the next request is held by the TLS library as already decrypted
  11042. // data rather than on the socket.
  11043. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11045. std::string res;
  11046. serve_pipelining_routes(svr, [&](int port) {
  11047. // One part, so all three requests arrive in one TLS record
  11048. EXPECT_TRUE(send_ssl_request_in_parts(
  11049. 2,
  11050. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11051. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11052. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11053. &res, port));
  11054. });
  11055. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11056. }
  11057. #endif
  11058. TEST(KeepAliveTest, Issue1041) {
  11059. Server svr;
  11060. svr.set_keep_alive_timeout(3);
  11061. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11062. res.set_content("Hello World!", "text/plain");
  11063. });
  11064. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11065. auto se = detail::scope_exit([&] {
  11066. svr.stop();
  11067. listen_thread.join();
  11068. ASSERT_FALSE(svr.is_running());
  11069. });
  11070. svr.wait_until_ready();
  11071. Client cli(HOST, PORT);
  11072. cli.set_keep_alive(true);
  11073. auto result = cli.Get("/hi");
  11074. ASSERT_TRUE(result);
  11075. EXPECT_EQ(StatusCode::OK_200, result->status);
  11076. std::this_thread::sleep_for(std::chrono::seconds(5));
  11077. result = cli.Get("/hi");
  11078. ASSERT_TRUE(result);
  11079. EXPECT_EQ(StatusCode::OK_200, result->status);
  11080. }
  11081. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11082. Server svr;
  11083. svr.set_keep_alive_max_count(0);
  11084. std::set<int> remote_ports;
  11085. svr.Get("/hi", [&](const Request &req, Response &res) {
  11086. remote_ports.insert(req.remote_port);
  11087. res.set_content("hi", "text/plain");
  11088. });
  11089. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11090. auto se = detail::scope_exit([&] {
  11091. svr.stop();
  11092. listen_thread.join();
  11093. ASSERT_FALSE(svr.is_running());
  11094. });
  11095. svr.wait_until_ready();
  11096. Client cli(HOST, PORT);
  11097. cli.set_keep_alive(true);
  11098. for (int i = 0; i < 3; i++) {
  11099. auto res = cli.Get("/hi");
  11100. ASSERT_TRUE(res);
  11101. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11102. }
  11103. // All three over one connection
  11104. EXPECT_EQ(1u, remote_ports.size());
  11105. }
  11106. TEST(KeepAliveTest, Issue1959) {
  11107. Server svr;
  11108. svr.set_keep_alive_timeout(5);
  11109. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11110. res.set_content("a", "text/plain");
  11111. });
  11112. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11113. auto se = detail::scope_exit([&] {
  11114. if (!svr.is_running()) return;
  11115. svr.stop();
  11116. listen_thread.join();
  11117. ASSERT_FALSE(svr.is_running());
  11118. });
  11119. svr.wait_until_ready();
  11120. Client cli("localhost", PORT);
  11121. cli.set_keep_alive(true);
  11122. using namespace std::chrono;
  11123. auto start = steady_clock::now();
  11124. cli.Get("/a");
  11125. svr.stop();
  11126. listen_thread.join();
  11127. auto end = steady_clock::now();
  11128. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11129. EXPECT_LT(elapsed, 5000);
  11130. }
  11131. #ifdef CPPHTTPLIB_SSL_ENABLED
  11132. TEST(KeepAliveTest, SSLClientReconnection) {
  11133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11134. ASSERT_TRUE(svr.is_valid());
  11135. svr.set_keep_alive_timeout(1);
  11136. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11137. res.set_content("Hello World!", "text/plain");
  11138. });
  11139. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11140. auto se = detail::scope_exit([&] {
  11141. svr.stop();
  11142. listen_thread.join();
  11143. ASSERT_FALSE(svr.is_running());
  11144. });
  11145. svr.wait_until_ready();
  11146. SSLClient cli(HOST, PORT);
  11147. cli.enable_server_certificate_verification(false);
  11148. cli.set_keep_alive(true);
  11149. auto result = cli.Get("/hi");
  11150. ASSERT_TRUE(result);
  11151. EXPECT_EQ(StatusCode::OK_200, result->status);
  11152. result = cli.Get("/hi");
  11153. ASSERT_TRUE(result);
  11154. EXPECT_EQ(StatusCode::OK_200, result->status);
  11155. std::this_thread::sleep_for(std::chrono::seconds(2));
  11156. // Recoonect
  11157. result = cli.Get("/hi");
  11158. ASSERT_TRUE(result);
  11159. EXPECT_EQ(StatusCode::OK_200, result->status);
  11160. result = cli.Get("/hi");
  11161. ASSERT_TRUE(result);
  11162. EXPECT_EQ(StatusCode::OK_200, result->status);
  11163. }
  11164. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11165. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11166. ASSERT_TRUE(svr.is_valid());
  11167. svr.set_keep_alive_timeout(1);
  11168. std::string content = "reconnect";
  11169. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11170. res.set_content("Hello World!", "text/plain");
  11171. });
  11172. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11173. auto se = detail::scope_exit([&] {
  11174. svr.stop();
  11175. listen_thread.join();
  11176. ASSERT_FALSE(svr.is_running());
  11177. });
  11178. svr.wait_until_ready();
  11179. SSLClient cli(HOST, PORT);
  11180. cli.enable_server_certificate_verification(false);
  11181. cli.set_keep_alive(true);
  11182. auto result = cli.Post(
  11183. "/hi", content.size(),
  11184. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11185. sink.write(content.c_str(), content.size());
  11186. return true;
  11187. },
  11188. "text/plain");
  11189. ASSERT_TRUE(result);
  11190. EXPECT_EQ(200, result->status);
  11191. std::this_thread::sleep_for(std::chrono::seconds(2));
  11192. // Recoonect
  11193. result = cli.Post(
  11194. "/hi", content.size(),
  11195. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11196. sink.write(content.c_str(), content.size());
  11197. return true;
  11198. },
  11199. "text/plain");
  11200. ASSERT_TRUE(result);
  11201. EXPECT_EQ(200, result->status);
  11202. result = cli.Post(
  11203. "/hi", content.size(),
  11204. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11205. sink.write(content.c_str(), content.size());
  11206. return true;
  11207. },
  11208. "text/plain");
  11209. ASSERT_TRUE(result);
  11210. EXPECT_EQ(200, result->status);
  11211. }
  11212. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11213. using namespace httplib::tls;
  11214. {
  11215. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11216. ASSERT_TRUE(svr.is_valid());
  11217. svr.Get("/sni", [&](const Request &req, Response &res) {
  11218. std::string expected = req.sni();
  11219. EXPECT_EQ(expected, req.get_param_value("expected"));
  11220. res.set_content("ok", "text/plain");
  11221. });
  11222. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11223. auto se = detail::scope_exit([&] {
  11224. svr.stop();
  11225. listen_thread.join();
  11226. ASSERT_FALSE(svr.is_running());
  11227. });
  11228. svr.wait_until_ready();
  11229. {
  11230. SSLClient cli("localhost", PORT);
  11231. cli.enable_server_certificate_verification(false);
  11232. auto res = cli.Get("/sni?expected=localhost");
  11233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11234. }
  11235. {
  11236. SSLClient cli("::1", PORT);
  11237. cli.enable_server_certificate_verification(false);
  11238. auto res = cli.Get("/sni?expected=");
  11239. // NOTE: This may fail if the server is listening on IPv4 only
  11240. // (e.g., when localhost resolves to 127.0.0.1 only)
  11241. if (res) {
  11242. EXPECT_EQ(StatusCode::OK_200, res->status);
  11243. } else {
  11244. EXPECT_EQ(Error::Connection, res.error());
  11245. }
  11246. }
  11247. }
  11248. }
  11249. // The SNI of a failed handshake does not reach the next connection that the
  11250. // same worker thread serves
  11251. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11252. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11253. ASSERT_TRUE(svr.is_valid());
  11254. svr.new_task_queue = [] { return new ThreadPool(1); };
  11255. svr.Get("/sni", [](const Request &req, Response &res) {
  11256. res.set_content(req.sni(), "text/plain");
  11257. });
  11258. auto port = svr.bind_to_any_port("127.0.0.1");
  11259. ASSERT_LT(0, port);
  11260. thread t = thread([&] { svr.listen_after_bind(); });
  11261. auto se = detail::scope_exit([&] {
  11262. svr.stop();
  11263. t.join();
  11264. ASSERT_FALSE(svr.is_running());
  11265. });
  11266. svr.wait_until_ready();
  11267. {
  11268. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11269. SSLClient cli("localhost", port);
  11270. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11271. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11272. auto res = cli.Get("/sni");
  11273. ASSERT_FALSE(res);
  11274. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11275. }
  11276. // An IP host sends no SNI (RFC 6066)
  11277. SSLClient cli("127.0.0.1", port);
  11278. cli.enable_server_certificate_verification(false);
  11279. auto res = cli.Get("/sni");
  11280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11281. EXPECT_EQ("", res->body);
  11282. }
  11283. #endif
  11284. TEST(ClientProblemDetectionTest, ContentProvider) {
  11285. Server svr;
  11286. size_t content_length = 1024 * 1024;
  11287. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11288. res.set_content_provider(
  11289. content_length, "text/plain",
  11290. [&](size_t offset, size_t length, DataSink &sink) {
  11291. auto out_len = std::min(length, static_cast<size_t>(1024));
  11292. std::string out(out_len, '@');
  11293. sink.write(out.data(), out_len);
  11294. return offset < 4096;
  11295. },
  11296. [](bool success) { ASSERT_FALSE(success); });
  11297. });
  11298. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11299. res.set_content_provider(
  11300. 0, "text/plain",
  11301. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11302. EXPECT_TRUE(false);
  11303. return true;
  11304. },
  11305. [](bool success) { ASSERT_FALSE(success); });
  11306. });
  11307. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11308. auto se = detail::scope_exit([&] {
  11309. svr.stop();
  11310. listen_thread.join();
  11311. ASSERT_FALSE(svr.is_running());
  11312. });
  11313. svr.wait_until_ready();
  11314. Client cli("localhost", PORT);
  11315. {
  11316. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11317. size_t /*data_length*/) { return false; });
  11318. ASSERT_FALSE(res);
  11319. }
  11320. {
  11321. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11322. size_t /*data_length*/) { return false; });
  11323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11324. }
  11325. }
  11326. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11327. // A provider that reports success without writing anything and without
  11328. // calling done() used to be handed the same offset and length again on every
  11329. // pass, so it spun for as long as the peer stayed connected.
  11330. Server svr;
  11331. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11332. res.set_content("ok", "text/plain");
  11333. });
  11334. auto port = svr.bind_to_any_port(HOST);
  11335. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11336. auto se = detail::scope_exit([&] {
  11337. svr.stop();
  11338. listen_thread.join();
  11339. ASSERT_FALSE(svr.is_running());
  11340. });
  11341. svr.wait_until_ready();
  11342. std::atomic<int> call_count{0};
  11343. Client cli(HOST, port);
  11344. auto res = cli.Post(
  11345. "/", 1024,
  11346. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11347. // Give up after enough passes to show the spin, so that losing the
  11348. // check below fails this test instead of hanging it.
  11349. return ++call_count < 100;
  11350. },
  11351. "text/plain");
  11352. ASSERT_FALSE(res);
  11353. EXPECT_EQ(Error::Write, res.error());
  11354. EXPECT_EQ(1, call_count.load());
  11355. }
  11356. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11357. // A writer only has to assign `write`. The other three used to be left as
  11358. // empty std::functions, so a provider calling one threw
  11359. // std::bad_function_call out of the thread running it and took the whole
  11360. // process down.
  11361. DataSink sink;
  11362. std::string written;
  11363. sink.write = [&](const char *data, size_t data_len) {
  11364. written.append(data, data_len);
  11365. return true;
  11366. };
  11367. EXPECT_TRUE(sink.is_writable());
  11368. sink.done();
  11369. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11370. EXPECT_TRUE(written.empty());
  11371. }
  11372. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11373. // A sink that cannot carry trailers still has to finish.
  11374. DataSink sink;
  11375. auto done_count = 0;
  11376. sink.done = [&]() { done_count++; };
  11377. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11378. EXPECT_EQ(1, done_count);
  11379. }
  11380. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11381. Server svr;
  11382. const std::string body(4096, 'x');
  11383. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11384. res.set_content_provider(body.size(), "text/plain",
  11385. [&](size_t offset, size_t length, DataSink &sink) {
  11386. sink.write(body.data() + offset, length);
  11387. sink.done();
  11388. return true;
  11389. });
  11390. });
  11391. auto port = svr.bind_to_any_port(HOST);
  11392. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11393. auto se = detail::scope_exit([&] {
  11394. svr.stop();
  11395. listen_thread.join();
  11396. ASSERT_FALSE(svr.is_running());
  11397. });
  11398. svr.wait_until_ready();
  11399. Client cli(HOST, port);
  11400. auto res = cli.Get("/");
  11401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11402. EXPECT_EQ(StatusCode::OK_200, res->status);
  11403. EXPECT_EQ(body, res->body);
  11404. }
  11405. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11406. Server svr;
  11407. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11408. res.set_content_provider(
  11409. 1024, "text/plain",
  11410. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11411. sink.write("hello", 5);
  11412. sink.done(); // short of the 1024 bytes the response promised
  11413. return true;
  11414. });
  11415. });
  11416. auto port = svr.bind_to_any_port(HOST);
  11417. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11418. auto se = detail::scope_exit([&] {
  11419. svr.stop();
  11420. listen_thread.join();
  11421. ASSERT_FALSE(svr.is_running());
  11422. });
  11423. svr.wait_until_ready();
  11424. Client cli(HOST, port);
  11425. cli.set_read_timeout(5, 0);
  11426. // The response is short of its Content-Length, so the client cannot read a
  11427. // complete body. What matters is that this returns at all: a no-op done()
  11428. // would leave the writer looping over a provider that never makes progress.
  11429. auto res = cli.Get("/");
  11430. EXPECT_FALSE(res);
  11431. }
  11432. // Read as the next response by a peer that sees it after a framed body.
  11433. static const std::string smuggled_response =
  11434. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11435. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11436. Server svr;
  11437. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11438. res.set_content_provider(
  11439. 5, "text/plain",
  11440. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11441. auto data = "AAAAA" + smuggled_response;
  11442. sink.write(data.data(), data.size());
  11443. return true;
  11444. });
  11445. });
  11446. thread t = thread([&] { svr.listen(HOST, PORT); });
  11447. auto se = detail::scope_exit([&] {
  11448. svr.stop();
  11449. t.join();
  11450. ASSERT_FALSE(svr.is_running());
  11451. });
  11452. svr.wait_until_ready();
  11453. std::string resp;
  11454. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11455. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11456. resp.clear();
  11457. ASSERT_TRUE(send_request(
  11458. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11459. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11460. }
  11461. TEST(NoContentTest, BodyIsNotSent) {
  11462. Server svr;
  11463. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11464. res.status = StatusCode::NoContent_204;
  11465. res.set_content(smuggled_response, "text/plain");
  11466. });
  11467. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11468. res.status = StatusCode::NotModified_304;
  11469. res.set_chunked_content_provider(
  11470. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11471. sink.write(smuggled_response.data(), smuggled_response.size());
  11472. sink.done();
  11473. return true;
  11474. });
  11475. });
  11476. thread t = thread([&] { svr.listen(HOST, PORT); });
  11477. auto se = detail::scope_exit([&] {
  11478. svr.stop();
  11479. t.join();
  11480. ASSERT_FALSE(svr.is_running());
  11481. });
  11482. svr.wait_until_ready();
  11483. for (auto path : {"/204", "/304"}) {
  11484. std::string resp;
  11485. ASSERT_TRUE(send_request(
  11486. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11487. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11488. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11489. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11490. }
  11491. }
  11492. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11493. Server svr;
  11494. std::atomic<bool> smuggled(false);
  11495. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11496. res.set_content("ok", "text/plain");
  11497. });
  11498. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11499. smuggled = true;
  11500. });
  11501. auto port = svr.bind_to_any_port(HOST);
  11502. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11503. auto se = detail::scope_exit([&] {
  11504. svr.stop();
  11505. listen_thread.join();
  11506. ASSERT_FALSE(svr.is_running());
  11507. });
  11508. svr.wait_until_ready();
  11509. // What follows the body would be read as the next request.
  11510. Client cli(HOST, port);
  11511. auto res = cli.Post(
  11512. "/", 5,
  11513. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11514. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11515. sink.write(data.data(), data.size());
  11516. return true;
  11517. },
  11518. "text/plain");
  11519. ASSERT_FALSE(res);
  11520. EXPECT_EQ(Error::Write, res.error());
  11521. EXPECT_FALSE(smuggled);
  11522. }
  11523. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11524. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11525. // The compressed path builds the whole body before connecting, so this
  11526. // fails client-side and never reaches a server.
  11527. Client cli(HOST, PORT);
  11528. cli.set_compress(true);
  11529. auto res = cli.Post(
  11530. "/", 1024,
  11531. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11532. sink.write("hello", 5);
  11533. sink.done(); // short of the 1024 bytes the request announced
  11534. return true;
  11535. },
  11536. "text/plain");
  11537. ASSERT_FALSE(res);
  11538. EXPECT_EQ(Error::Write, res.error());
  11539. }
  11540. #endif
  11541. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11542. Server svr;
  11543. svr.set_error_handler([](Request const &, Response &res) -> void {
  11544. res.set_chunked_content_provider(
  11545. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11546. sink.os << "hello";
  11547. sink.os << "world";
  11548. sink.done();
  11549. return true;
  11550. });
  11551. });
  11552. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11553. auto se = detail::scope_exit([&] {
  11554. svr.stop();
  11555. listen_thread.join();
  11556. ASSERT_FALSE(svr.is_running());
  11557. });
  11558. svr.wait_until_ready();
  11559. Client cli("localhost", PORT);
  11560. auto res = cli.Get("/");
  11561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11562. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11563. EXPECT_EQ("helloworld", res->body);
  11564. }
  11565. // A body set after a content provider must replace it, not be sent through it.
  11566. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11567. Server svr;
  11568. svr.set_mount_point("/", "./www");
  11569. svr.set_file_request_handler([](const Request &req, Response &res) {
  11570. if (req.path == "/dir/test.html") {
  11571. res.status = StatusCode::Forbidden_403;
  11572. res.set_content(std::string(5000, 'D'), "text/plain");
  11573. } else if (req.path == "/file") {
  11574. res.status = StatusCode::Forbidden_403;
  11575. res.body = "Denied";
  11576. }
  11577. });
  11578. auto port = svr.bind_to_any_port(HOST);
  11579. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11580. auto se = detail::scope_exit([&] {
  11581. svr.stop();
  11582. t.join();
  11583. ASSERT_FALSE(svr.is_running());
  11584. });
  11585. svr.wait_until_ready();
  11586. Client cli(HOST, port);
  11587. {
  11588. auto res = cli.Get("/dir/test.html");
  11589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11590. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11591. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11592. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11593. }
  11594. {
  11595. auto res = cli.Get("/file");
  11596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11597. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11598. EXPECT_EQ("Denied", res->body);
  11599. }
  11600. {
  11601. auto res = cli.Get("/dir/index.html");
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::OK_200, res->status);
  11604. EXPECT_EQ(0U, res->body.find("<html>"));
  11605. }
  11606. }
  11607. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11608. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11609. Server svr;
  11610. std::vector<bool> released;
  11611. std::mutex released_mutex;
  11612. auto releaser = [&](bool success) {
  11613. std::lock_guard<std::mutex> guard(released_mutex);
  11614. released.push_back(success);
  11615. };
  11616. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11617. return sink.write(&"hello"[offset], length);
  11618. };
  11619. svr.Get("/sized", [&](const Request &, Response &res) {
  11620. res.status = StatusCode::NotFound_404;
  11621. res.set_content_provider(5, "text/plain", provider, releaser);
  11622. });
  11623. svr.Get("/chunked", [&](const Request &, Response &res) {
  11624. res.status = StatusCode::ServiceUnavailable_503;
  11625. res.set_chunked_content_provider(
  11626. "text/plain",
  11627. [](size_t, DataSink &sink) {
  11628. sink.os << "chunk";
  11629. sink.done();
  11630. return true;
  11631. },
  11632. releaser);
  11633. });
  11634. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11635. res.set_content_provider(5, "text/plain", provider, releaser);
  11636. throw std::runtime_error("after the provider");
  11637. });
  11638. svr.set_error_handler([](const Request &req, Response &res) {
  11639. // Leave the exception handler's content to it.
  11640. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11641. res.set_content(std::string(1000, 'E'), "text/html");
  11642. return Server::HandlerResponse::Handled;
  11643. });
  11644. svr.set_exception_handler(
  11645. [](const Request &, Response &res, std::exception_ptr) {
  11646. res.status = StatusCode::InternalServerError_500;
  11647. res.set_content(std::string(1000, 'X'), "text/html");
  11648. });
  11649. auto port = svr.bind_to_any_port(HOST);
  11650. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11651. auto se = detail::scope_exit([&] {
  11652. svr.stop();
  11653. t.join();
  11654. ASSERT_FALSE(svr.is_running());
  11655. });
  11656. svr.wait_until_ready();
  11657. Client cli(HOST, port);
  11658. {
  11659. auto res = cli.Get("/sized");
  11660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11661. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11662. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11663. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11664. }
  11665. {
  11666. auto res = cli.Get("/chunked");
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11669. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11670. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11671. }
  11672. {
  11673. auto res = cli.Get("/throw");
  11674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11675. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11676. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11677. }
  11678. std::lock_guard<std::mutex> guard(released_mutex);
  11679. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11680. }
  11681. #endif
  11682. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11683. Server svr;
  11684. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11685. return sink.write(&"abc"[offset], length);
  11686. };
  11687. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11688. res.set_file_content("./www/dir/test.html");
  11689. res.set_content("body", "text/plain");
  11690. });
  11691. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11692. res.set_content(std::string(100, 'B'), "text/plain");
  11693. res.set_file_content("./www/dir/test.html");
  11694. });
  11695. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11696. res.set_content(std::string(100, 'B'), "text/plain");
  11697. res.set_content_provider(3, "text/x-provider", abc);
  11698. });
  11699. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11700. res.set_content_provider(3, "text/x-provider", abc);
  11701. res.set_content(std::string(100, 'B'), "text/plain");
  11702. });
  11703. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11704. res.set_content_provider(3, "text/x-provider", abc);
  11705. res.set_file_content("./www/dir/test.html", "text/x-file");
  11706. });
  11707. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11708. res.set_file_content("./www/dir/test.html");
  11709. res.set_header("Content-Type", "text/x-handler");
  11710. });
  11711. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11712. res.set_content_provider(3, "text/plain", abc);
  11713. res.body = "direct";
  11714. });
  11715. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11716. res.set_file_content("./www/dir/test.html");
  11717. res.body = "direct";
  11718. });
  11719. auto port = svr.bind_to_any_port(HOST);
  11720. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11721. auto se = detail::scope_exit([&] {
  11722. svr.stop();
  11723. t.join();
  11724. ASSERT_FALSE(svr.is_running());
  11725. });
  11726. svr.wait_until_ready();
  11727. Client cli(HOST, port);
  11728. auto expect_body = [&](const char *path, const std::string &body,
  11729. const std::string &type) {
  11730. // Uncompressed, so Content-Length can be compared with the body.
  11731. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11732. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11733. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11734. EXPECT_EQ(body, res->body) << path;
  11735. EXPECT_EQ(std::to_string(body.size()),
  11736. res->get_header_value("Content-Length"))
  11737. << path;
  11738. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11739. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11740. };
  11741. expect_body("/file-then-body", "body", "text/plain");
  11742. expect_body("/body-then-file", "test.html", "text/html");
  11743. expect_body("/body-then-provider", "abc", "text/x-provider");
  11744. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11745. expect_body("/provider-then-file", "test.html", "text/x-file");
  11746. expect_body("/file-then-header", "test.html", "text/x-handler");
  11747. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11748. expect_body("/file-then-direct-body", "direct", "text/plain");
  11749. // Ranges are checked against the body, not the dropped provider.
  11750. {
  11751. auto res = cli.Get("/provider-then-direct-body",
  11752. Headers{{make_range_header({{1, 2}})}});
  11753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11754. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11755. EXPECT_EQ("ir", res->body);
  11756. }
  11757. {
  11758. auto res = cli.Get("/file-then-direct-body",
  11759. Headers{{make_range_header({{7, 8}})}});
  11760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11761. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11762. }
  11763. }
  11764. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11765. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11766. const char *path = "./truncated_while_served.txt";
  11767. const size_t size = 32 * 1024 * 1024;
  11768. {
  11769. std::ofstream f(path, std::ios::binary);
  11770. f << std::string(size, 'x');
  11771. }
  11772. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11773. // Over TLS, where the bytes are encrypted in this process rather than
  11774. // copied by send().
  11775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11776. svr.Get("/file", [&](const Request &, Response &res) {
  11777. res.set_file_content(path, "text/plain");
  11778. });
  11779. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11780. auto se = detail::scope_exit([&] {
  11781. svr.stop();
  11782. thread.join();
  11783. ASSERT_FALSE(svr.is_running());
  11784. });
  11785. svr.wait_until_ready();
  11786. // The file shrinks once the first bytes are in, as a rewrite in place
  11787. // would, and reading the mapping past its new end used to raise SIGBUS.
  11788. SSLClient cli(HOST, PORT);
  11789. cli.enable_server_certificate_verification(false);
  11790. size_t received = 0;
  11791. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11792. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11793. received += len;
  11794. return true;
  11795. });
  11796. EXPECT_FALSE(res);
  11797. EXPECT_LT(received, size);
  11798. }
  11799. #endif
  11800. // Forward declaration (see the base64_encode note).
  11801. namespace httplib {
  11802. namespace detail {
  11803. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11804. const std::string &content_type,
  11805. EncodingType encoding);
  11806. } // namespace detail
  11807. } // namespace httplib
  11808. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11809. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11810. ASSERT_TRUE(mm->is_open());
  11811. Response res;
  11812. detail::set_file_content_provider(res, mm, "text/html",
  11813. detail::EncodingType::None);
  11814. std::string out;
  11815. DataSink sink;
  11816. sink.write = [&](const char *d, size_t l) {
  11817. out.append(d, l);
  11818. return true;
  11819. };
  11820. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11821. EXPECT_EQ("test.html", out);
  11822. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11823. EXPECT_EQ("test.html", out);
  11824. }
  11825. TEST(LongPollingTest, ClientCloseDetection) {
  11826. Server svr;
  11827. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11828. res.set_chunked_content_provider(
  11829. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11830. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11831. sink.os << "hello";
  11832. auto count = 10;
  11833. while (count > 0 && sink.is_writable()) {
  11834. this_thread::sleep_for(chrono::milliseconds(10));
  11835. count--;
  11836. }
  11837. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11838. return true;
  11839. });
  11840. });
  11841. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11842. auto se = detail::scope_exit([&] {
  11843. svr.stop();
  11844. listen_thread.join();
  11845. ASSERT_FALSE(svr.is_running());
  11846. });
  11847. svr.wait_until_ready();
  11848. Client cli("localhost", PORT);
  11849. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11850. EXPECT_EQ("hello", string(data, data_length));
  11851. return false; // close the socket immediately.
  11852. });
  11853. ASSERT_FALSE(res);
  11854. }
  11855. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11856. Server svr;
  11857. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11858. res.set_chunked_content_provider(
  11859. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11860. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11861. sink.os << "hello";
  11862. EXPECT_TRUE(sink.os.good());
  11863. // Wait for the client to close the connection
  11864. auto count = 10;
  11865. while (count > 0 && sink.is_writable()) {
  11866. this_thread::sleep_for(chrono::milliseconds(10));
  11867. count--;
  11868. }
  11869. // After client disconnect, write repeatedly until the socket
  11870. // write actually fails (small writes may be absorbed by the
  11871. // kernel buffer)
  11872. std::string chunk(1024, 'x');
  11873. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11874. sink.os << chunk;
  11875. }
  11876. EXPECT_TRUE(sink.os.fail());
  11877. return true;
  11878. });
  11879. });
  11880. auto port = svr.bind_to_any_port("localhost");
  11881. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11882. auto se = detail::scope_exit([&] {
  11883. svr.stop();
  11884. listen_thread.join();
  11885. ASSERT_FALSE(svr.is_running());
  11886. });
  11887. svr.wait_until_ready();
  11888. Client cli("localhost", port);
  11889. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11890. EXPECT_EQ("hello", string(data, data_length));
  11891. return false; // close the socket immediately.
  11892. });
  11893. ASSERT_FALSE(res);
  11894. }
  11895. TEST(GetWithParametersTest, GetWithParameters) {
  11896. Server svr;
  11897. svr.Get("/", [&](const Request &req, Response &) {
  11898. EXPECT_EQ("world", req.get_param_value("hello"));
  11899. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11900. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11901. });
  11902. svr.Get("/params", [&](const Request &req, Response &) {
  11903. EXPECT_EQ("world", req.get_param_value("hello"));
  11904. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11905. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11906. });
  11907. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11908. EXPECT_EQ("resource-id", req.matches[1]);
  11909. EXPECT_EQ("foo", req.get_param_value("param1"));
  11910. EXPECT_EQ("bar", req.get_param_value("param2"));
  11911. });
  11912. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11913. EXPECT_EQ("user-id", req.path_params.at("id"));
  11914. EXPECT_EQ("foo", req.get_param_value("param1"));
  11915. EXPECT_EQ("bar", req.get_param_value("param2"));
  11916. });
  11917. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11918. auto se = detail::scope_exit([&] {
  11919. svr.stop();
  11920. listen_thread.join();
  11921. ASSERT_FALSE(svr.is_running());
  11922. });
  11923. svr.wait_until_ready();
  11924. {
  11925. Client cli(HOST, PORT);
  11926. Params params;
  11927. params.emplace("hello", "world");
  11928. params.emplace("hello2", "world2");
  11929. params.emplace("hello3", "world3");
  11930. auto res = cli.Get("/", params, Headers{});
  11931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11932. EXPECT_EQ(StatusCode::OK_200, res->status);
  11933. }
  11934. {
  11935. Client cli(HOST, PORT);
  11936. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11938. EXPECT_EQ(StatusCode::OK_200, res->status);
  11939. }
  11940. {
  11941. Client cli(HOST, PORT);
  11942. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11944. EXPECT_EQ(StatusCode::OK_200, res->status);
  11945. }
  11946. {
  11947. Client cli(HOST, PORT);
  11948. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11950. EXPECT_EQ(StatusCode::OK_200, res->status);
  11951. }
  11952. }
  11953. TEST(GetWithParametersTest, GetWithParameters2) {
  11954. Server svr;
  11955. svr.Get("/", [&](const Request &req, Response &res) {
  11956. auto text = req.get_param_value("hello");
  11957. res.set_content(text, "text/plain");
  11958. });
  11959. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11960. auto se = detail::scope_exit([&] {
  11961. svr.stop();
  11962. listen_thread.join();
  11963. ASSERT_FALSE(svr.is_running());
  11964. });
  11965. svr.wait_until_ready();
  11966. Client cli("localhost", PORT);
  11967. Params params;
  11968. params.emplace("hello", "world");
  11969. std::string body;
  11970. auto res = cli.Get("/", params, Headers{},
  11971. [&](const char *data, size_t data_length) {
  11972. body.append(data, data_length);
  11973. return true;
  11974. });
  11975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11976. EXPECT_EQ(StatusCode::OK_200, res->status);
  11977. EXPECT_EQ("world", body);
  11978. }
  11979. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11980. Server svr;
  11981. svr.Get("/search", [&](const Request &req, Response &res) {
  11982. auto q = req.get_param_value("q");
  11983. res.set_content(q, "text/plain");
  11984. });
  11985. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11986. auto se = detail::scope_exit([&] {
  11987. svr.stop();
  11988. listen_thread.join();
  11989. ASSERT_FALSE(svr.is_running());
  11990. });
  11991. svr.wait_until_ready();
  11992. Client cli("localhost", PORT);
  11993. // Verify that Get(path, params) works without requiring Headers argument
  11994. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11996. EXPECT_EQ(StatusCode::OK_200, res->status);
  11997. EXPECT_EQ("cpp-httplib", res->body);
  11998. }
  11999. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12000. auto host = "httpbingo.org";
  12001. auto path = std::string{"/range/32"};
  12002. #ifdef CPPHTTPLIB_SSL_ENABLED
  12003. SSLClient cli(host);
  12004. #else
  12005. Client cli(host);
  12006. #endif
  12007. cli.set_default_headers({make_range_header({{1, 10}})});
  12008. cli.set_connection_timeout(5);
  12009. {
  12010. auto res = cli.Get(path);
  12011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12012. EXPECT_EQ("bcdefghijk", res->body);
  12013. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12014. }
  12015. {
  12016. auto res = cli.Get(path);
  12017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12018. EXPECT_EQ("bcdefghijk", res->body);
  12019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12020. }
  12021. }
  12022. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12023. Server svr;
  12024. svr.set_default_headers({{"Hello", "World"}});
  12025. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12026. res.set_content("ok", "text/plain");
  12027. });
  12028. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12029. auto se = detail::scope_exit([&] {
  12030. svr.stop();
  12031. listen_thread.join();
  12032. ASSERT_FALSE(svr.is_running());
  12033. });
  12034. svr.wait_until_ready();
  12035. Client cli("localhost", PORT);
  12036. auto res = cli.Get("/");
  12037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12038. EXPECT_EQ(StatusCode::OK_200, res->status);
  12039. EXPECT_EQ("ok", res->body);
  12040. EXPECT_EQ("World", res->get_header_value("Hello"));
  12041. }
  12042. #ifdef CPPHTTPLIB_SSL_ENABLED
  12043. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12045. ASSERT_TRUE(svr.is_valid());
  12046. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12047. std::this_thread::sleep_for(std::chrono::seconds(2));
  12048. res.set_content("a", "text/plain");
  12049. });
  12050. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12051. res.set_content("b", "text/plain");
  12052. });
  12053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12054. auto se = detail::scope_exit([&] {
  12055. svr.stop();
  12056. listen_thread.join();
  12057. ASSERT_FALSE(svr.is_running());
  12058. });
  12059. svr.wait_until_ready();
  12060. SSLClient cli("localhost", PORT);
  12061. cli.enable_server_certificate_verification(false);
  12062. cli.set_keep_alive(true);
  12063. cli.set_read_timeout(std::chrono::seconds(1));
  12064. auto resa = cli.Get("/a");
  12065. ASSERT_TRUE(!resa);
  12066. EXPECT_EQ(Error::Read, resa.error());
  12067. auto resb = cli.Get("/b");
  12068. ASSERT_TRUE(resb);
  12069. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12070. EXPECT_EQ("b", resb->body);
  12071. }
  12072. // Closing an idle keep-alive connection sends close_notify and returns. The
  12073. // server must not wait for the client's close_notify: an idle client never
  12074. // sends one, so the worker would be held until the read timeout expires, and
  12075. // stop() would wait for it.
  12076. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12078. ASSERT_TRUE(svr.is_valid());
  12079. svr.set_keep_alive_timeout(1);
  12080. svr.set_read_timeout(10, 0);
  12081. svr.Get("/", [](const Request &, Response &res) {
  12082. res.set_content("ok", "text/plain");
  12083. });
  12084. auto port = svr.bind_to_any_port(HOST);
  12085. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12086. auto se = detail::scope_exit([&] {
  12087. if (listen_thread.joinable()) {
  12088. svr.stop();
  12089. listen_thread.join();
  12090. }
  12091. });
  12092. svr.wait_until_ready();
  12093. SSLClient cli(HOST, port);
  12094. cli.enable_server_certificate_verification(false);
  12095. cli.set_keep_alive(true);
  12096. auto res = cli.Get("/");
  12097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12098. EXPECT_EQ(StatusCode::OK_200, res->status);
  12099. // Stay idle past the keep-alive timeout so the server closes the connection.
  12100. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12101. auto start = std::chrono::steady_clock::now();
  12102. svr.stop();
  12103. listen_thread.join();
  12104. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12105. std::chrono::steady_clock::now() - start)
  12106. .count();
  12107. EXPECT_LT(elapsed, 3000);
  12108. }
  12109. #endif
  12110. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12111. protected:
  12112. ServerTestWithAI_PASSIVE()
  12113. : cli_(HOST, PORT)
  12114. #ifdef CPPHTTPLIB_SSL_ENABLED
  12115. ,
  12116. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12117. #endif
  12118. {
  12119. #ifdef CPPHTTPLIB_SSL_ENABLED
  12120. cli_.enable_server_certificate_verification(false);
  12121. #endif
  12122. }
  12123. virtual void SetUp() {
  12124. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12125. res.set_content("Hello World!", "text/plain");
  12126. });
  12127. t_ = thread(
  12128. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12129. svr_.wait_until_ready();
  12130. }
  12131. virtual void TearDown() {
  12132. svr_.stop();
  12133. t_.join();
  12134. }
  12135. #ifdef CPPHTTPLIB_SSL_ENABLED
  12136. SSLClient cli_;
  12137. SSLServer svr_;
  12138. #else
  12139. Client cli_;
  12140. Server svr_;
  12141. #endif
  12142. thread t_;
  12143. };
  12144. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12145. auto res = cli_.Get("/hi");
  12146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12147. EXPECT_EQ(StatusCode::OK_200, res->status);
  12148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12149. EXPECT_EQ("Hello World!", res->body);
  12150. }
  12151. class ServerUpDownTest : public ::testing::Test {
  12152. protected:
  12153. ServerUpDownTest() : cli_(HOST, PORT) {}
  12154. virtual void SetUp() {
  12155. t_ = thread([&]() {
  12156. svr_.bind_to_any_port(HOST);
  12157. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12158. ASSERT_TRUE(svr_.listen_after_bind());
  12159. });
  12160. svr_.wait_until_ready();
  12161. }
  12162. virtual void TearDown() {
  12163. svr_.stop();
  12164. t_.join();
  12165. }
  12166. Client cli_;
  12167. Server svr_;
  12168. thread t_;
  12169. };
  12170. TEST_F(ServerUpDownTest, QuickStartStop) {
  12171. // Should not crash, especially when run with
  12172. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12173. }
  12174. class PayloadMaxLengthTest : public ::testing::Test {
  12175. protected:
  12176. PayloadMaxLengthTest()
  12177. : cli_(HOST, PORT)
  12178. #ifdef CPPHTTPLIB_SSL_ENABLED
  12179. ,
  12180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12181. #endif
  12182. {
  12183. #ifdef CPPHTTPLIB_SSL_ENABLED
  12184. cli_.enable_server_certificate_verification(false);
  12185. #endif
  12186. }
  12187. virtual void SetUp() {
  12188. svr_.set_payload_max_length(8);
  12189. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12190. res.set_content("test", "text/plain");
  12191. });
  12192. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12193. svr_.wait_until_ready();
  12194. }
  12195. virtual void TearDown() {
  12196. svr_.stop();
  12197. t_.join();
  12198. }
  12199. #ifdef CPPHTTPLIB_SSL_ENABLED
  12200. SSLClient cli_;
  12201. SSLServer svr_;
  12202. #else
  12203. Client cli_;
  12204. Server svr_;
  12205. #endif
  12206. thread t_;
  12207. };
  12208. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12209. auto res = cli_.Post("/test", "123456789", "text/plain");
  12210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12211. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12212. res = cli_.Post("/test", "12345678", "text/plain");
  12213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12214. EXPECT_EQ(StatusCode::OK_200, res->status);
  12215. }
  12216. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12217. // Test chunked encoding with payload exceeding the 8-byte limit
  12218. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12219. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12221. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12222. }
  12223. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12224. // Test chunked encoding with payload within the 8-byte limit
  12225. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12226. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12228. EXPECT_EQ(StatusCode::OK_200, res->status);
  12229. }
  12230. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12231. // Test using send_request to send chunked data exceeding payload limit
  12232. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12233. "Host: " +
  12234. std::string(HOST) + ":" + std::to_string(PORT) +
  12235. "\r\n"
  12236. "Transfer-Encoding: chunked\r\n"
  12237. "Connection: close\r\n"
  12238. "\r\n"
  12239. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12240. "0123456789\r\n"
  12241. "0\r\n" // End chunk
  12242. "\r\n";
  12243. std::string response;
  12244. bool result = send_request(1, chunked_request, &response);
  12245. if (!result) {
  12246. // If send_request fails, it might be because the server closed the
  12247. // connection due to payload limit enforcement, which is acceptable
  12248. SUCCEED()
  12249. << "Server rejected oversized chunked request (connection closed)";
  12250. } else {
  12251. // If we got a response, check if it's an error response or connection was
  12252. // closed early Short response length indicates connection was closed due to
  12253. // payload limit
  12254. if (response.length() <= 10) {
  12255. SUCCEED() << "Server closed connection for oversized chunked request";
  12256. } else {
  12257. // Check for error status codes
  12258. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12259. response.find("Payload Too Large") != std::string::npos ||
  12260. response.find("400") != std::string::npos);
  12261. }
  12262. }
  12263. }
  12264. class LargePayloadMaxLengthTest : public ::testing::Test {
  12265. protected:
  12266. LargePayloadMaxLengthTest()
  12267. : cli_(HOST, PORT)
  12268. #ifdef CPPHTTPLIB_SSL_ENABLED
  12269. ,
  12270. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12271. #endif
  12272. {
  12273. #ifdef CPPHTTPLIB_SSL_ENABLED
  12274. cli_.enable_server_certificate_verification(false);
  12275. #endif
  12276. }
  12277. virtual void SetUp() {
  12278. // Set 10MB payload limit
  12279. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12280. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12281. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12282. res.set_content("Large payload test", "text/plain");
  12283. });
  12284. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12285. svr_.wait_until_ready();
  12286. }
  12287. virtual void TearDown() {
  12288. svr_.stop();
  12289. t_.join();
  12290. }
  12291. #ifdef CPPHTTPLIB_SSL_ENABLED
  12292. SSLClient cli_;
  12293. SSLServer svr_;
  12294. #else
  12295. Client cli_;
  12296. Server svr_;
  12297. #endif
  12298. thread t_;
  12299. };
  12300. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12301. // Test chunked encoding with payload within 10MB limit
  12302. std::string medium_payload(5 * 1024 * 1024,
  12303. 'A'); // 5MB payload, within 10MB limit
  12304. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12306. EXPECT_EQ(StatusCode::OK_200, res->status);
  12307. }
  12308. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12309. // Test chunked encoding with payload exceeding 10MB limit
  12310. std::string large_payload(12 * 1024 * 1024,
  12311. 'B'); // 12MB payload, exceeds 10MB limit
  12312. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12313. // Server may either return 413 or close the connection
  12314. if (res) {
  12315. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12316. } else {
  12317. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12318. }
  12319. }
  12320. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12321. Server svr;
  12322. svr.Get("/", [](const Request &, Response &res) {
  12323. // Claims the most the client accepts, far more than it sends, then drops
  12324. // the connection.
  12325. res.set_content_provider(std::string().max_size(), "text/plain",
  12326. [](size_t, size_t, DataSink &sink) {
  12327. sink.write("abc", 3);
  12328. return false;
  12329. });
  12330. });
  12331. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12332. auto se = detail::scope_exit([&] {
  12333. svr.stop();
  12334. thread.join();
  12335. ASSERT_FALSE(svr.is_running());
  12336. });
  12337. svr.wait_until_ready();
  12338. Client cli(HOST, PORT);
  12339. cli.set_payload_max_length(0);
  12340. EXPECT_FALSE(cli.Get("/"));
  12341. }
  12342. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12343. // Stream API does, not as a plain read failure
  12344. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12345. Server svr;
  12346. svr.Get("/big", [](const Request &, Response &res) {
  12347. res.set_content(std::string(100000, 'b'), "text/plain");
  12348. });
  12349. auto port = svr.bind_to_any_port(HOST);
  12350. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12351. auto se = detail::scope_exit([&] {
  12352. svr.stop();
  12353. thread.join();
  12354. });
  12355. svr.wait_until_ready();
  12356. Client cli(HOST, port);
  12357. cli.set_payload_max_length(1000);
  12358. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12359. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12360. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12361. [](const char *, size_t) { return true; });
  12362. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12363. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12364. // Small on the wire, over the limit once decompressed
  12365. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12366. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12367. #endif
  12368. }
  12369. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12370. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12371. // path.
  12372. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12373. Server svr;
  12374. const size_t LIMIT = 64 * 1024; // 64KB
  12375. svr.set_payload_max_length(LIMIT);
  12376. size_t total = 0;
  12377. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12378. const ContentReader &content_reader) {
  12379. content_reader([&](const char * /*data*/, size_t len) {
  12380. total += len;
  12381. return true;
  12382. });
  12383. res.status = 200;
  12384. res.set_content("stream_ok", "text/plain");
  12385. });
  12386. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12387. auto se = detail::scope_exit([&] {
  12388. svr.stop();
  12389. thread.join();
  12390. ASSERT_FALSE(svr.is_running());
  12391. });
  12392. svr.wait_until_ready();
  12393. // Prepare 256KB raw data and gzip-compress it
  12394. std::string raw(256 * 1024, 'A');
  12395. std::string gz;
  12396. {
  12397. z_stream zs{};
  12398. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12399. Z_DEFAULT_STRATEGY);
  12400. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12401. zs.avail_in = static_cast<uInt>(raw.size());
  12402. char outbuf[4096];
  12403. int ret;
  12404. do {
  12405. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12406. zs.avail_out = sizeof(outbuf);
  12407. ret = deflate(&zs, Z_FINISH);
  12408. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12409. } while (ret != Z_STREAM_END);
  12410. deflateEnd(&zs);
  12411. }
  12412. Client cli(HOST, PORT);
  12413. cli.set_connection_timeout(std::chrono::seconds(5));
  12414. Headers headers = {{"Content-Encoding", "gzip"}};
  12415. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12416. "application/octet-stream");
  12417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12418. // Server must reject oversized decompressed payloads with 413.
  12419. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12420. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12421. EXPECT_LE(total, LIMIT);
  12422. }
  12423. #endif
  12424. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12425. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12426. // the payload must be passed through untouched instead of being rejected.
  12427. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12428. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12429. Server svr;
  12430. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12431. res.set_content(body, "image/jpeg");
  12432. res.set_header("Content-Encoding", "UTF-8");
  12433. });
  12434. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12435. res.set_content(body, "image/jpeg");
  12436. res.set_header("Content-Encoding", "identity");
  12437. });
  12438. svr.Post("/echo", [](const Request &req, Response &res) {
  12439. res.set_content(req.body, "image/jpeg");
  12440. });
  12441. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12442. auto se = detail::scope_exit([&] {
  12443. svr.stop();
  12444. t.join();
  12445. ASSERT_FALSE(svr.is_running());
  12446. });
  12447. svr.wait_until_ready();
  12448. Client cli(HOST, PORT);
  12449. {
  12450. auto res = cli.Get("/image");
  12451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12452. EXPECT_EQ(StatusCode::OK_200, res->status);
  12453. EXPECT_EQ(body, res->body);
  12454. }
  12455. {
  12456. auto res = cli.Get("/identity");
  12457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12458. EXPECT_EQ(StatusCode::OK_200, res->status);
  12459. EXPECT_EQ(body, res->body);
  12460. }
  12461. {
  12462. // The same applies to a request body reaching the server.
  12463. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12464. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12466. EXPECT_EQ(StatusCode::OK_200, res->status);
  12467. EXPECT_EQ(body, res->body);
  12468. }
  12469. }
  12470. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12471. // gzip-encoded response even when the build has no zlib support.
  12472. static const char GZIPPED_HELLO_WORLD[] = {
  12473. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12474. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12475. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12476. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12477. // A content coding is a whole token, not something the field value merely
  12478. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12479. // as "fibre" look like Brotli, and turned a multi-coding value like
  12480. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12481. // it was never meant to see.
  12482. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12483. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12484. Server svr;
  12485. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12486. res.set_content(body, "image/jpeg");
  12487. res.set_header("Content-Encoding", "fibre");
  12488. });
  12489. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12490. res.set_content(body, "image/jpeg");
  12491. res.set_header("Content-Encoding", "gzip, br");
  12492. });
  12493. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12494. res.set_content(body, "image/jpeg");
  12495. res.set_header("Content-Encoding", "x-zstd-ish");
  12496. });
  12497. auto port = svr.bind_to_any_port(HOST);
  12498. thread t = thread([&]() { svr.listen_after_bind(); });
  12499. auto se = detail::scope_exit([&] {
  12500. svr.stop();
  12501. t.join();
  12502. ASSERT_FALSE(svr.is_running());
  12503. });
  12504. svr.wait_until_ready();
  12505. Client cli(HOST, port);
  12506. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12507. auto res = cli.Get(path);
  12508. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12509. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12510. // Not a coding we recognize, so the payload comes back untouched
  12511. EXPECT_EQ(body, res->body) << path;
  12512. }
  12513. }
  12514. // A content coding cpp-httplib recognizes but was not built with must be
  12515. // reported as such. Handing the still-compressed payload back to the caller
  12516. // would silently corrupt it.
  12517. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12518. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12519. Server svr;
  12520. // "image/jpeg" keeps the server from applying a content coding of its own,
  12521. // so the hand-crafted Content-Encoding below survives.
  12522. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12523. res.set_content(gzipped, "image/jpeg");
  12524. res.set_header("Content-Encoding", "gzip");
  12525. });
  12526. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12527. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12528. res.set_content(gzipped, "image/jpeg");
  12529. res.set_header("Content-Encoding", "GZIP");
  12530. });
  12531. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12532. auto se = detail::scope_exit([&] {
  12533. svr.stop();
  12534. t.join();
  12535. ASSERT_FALSE(svr.is_running());
  12536. });
  12537. svr.wait_until_ready();
  12538. Client cli(HOST, PORT);
  12539. {
  12540. auto res = cli.Get("/gzipped");
  12541. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12543. EXPECT_EQ("Hello World!", res->body);
  12544. #else
  12545. ASSERT_FALSE(res);
  12546. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12547. #endif
  12548. }
  12549. {
  12550. // open_stream() must behave the same way.
  12551. auto handle = cli.open_stream("GET", "/gzipped");
  12552. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12553. ASSERT_TRUE(handle.is_valid());
  12554. std::string received;
  12555. char buf[256];
  12556. ssize_t n;
  12557. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12558. received.append(buf, static_cast<size_t>(n));
  12559. }
  12560. EXPECT_EQ("Hello World!", received);
  12561. #else
  12562. EXPECT_FALSE(handle.is_valid());
  12563. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12564. #endif
  12565. }
  12566. {
  12567. // A differently-cased coding must not be mistaken for an unknown one, or
  12568. // the body would be handed back still compressed.
  12569. auto res = cli.Get("/gzipped-uppercase");
  12570. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12572. EXPECT_EQ("Hello World!", res->body);
  12573. #else
  12574. ASSERT_FALSE(res);
  12575. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12576. #endif
  12577. }
  12578. }
  12579. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12580. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12581. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12582. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12583. // body a second time and appending a second Content-Encoding field line, so
  12584. // clients that decode one coding per listed value handed back raw gzip bytes.
  12585. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12586. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12587. Server svr;
  12588. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12589. // keeps the server from applying a coding of its own.
  12590. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12591. res.set_content(gzipped, "text/plain");
  12592. res.set_header("Content-Encoding", "gzip");
  12593. });
  12594. auto port = svr.bind_to_any_port(HOST);
  12595. thread t = thread([&]() { svr.listen_after_bind(); });
  12596. auto se = detail::scope_exit([&] {
  12597. svr.stop();
  12598. t.join();
  12599. ASSERT_FALSE(svr.is_running());
  12600. });
  12601. svr.wait_until_ready();
  12602. Client cli(HOST, port);
  12603. Headers headers = {{"Accept-Encoding", "gzip"}};
  12604. auto res = cli.Get("/pre-gzipped", headers);
  12605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12606. EXPECT_EQ(StatusCode::OK_200, res->status);
  12607. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12608. EXPECT_EQ("Hello World!", res->body);
  12609. }
  12610. // set_compress(false) sends every handler response as it is, buffered or
  12611. // streamed
  12612. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12613. const std::string text(1000, 'a');
  12614. Server svr;
  12615. svr.set_compress(false);
  12616. svr.Get("/buffered", [&](const Request &, Response &res) {
  12617. res.set_content(text, "text/plain");
  12618. });
  12619. svr.Get("/streamed", [&](const Request &, Response &res) {
  12620. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12621. sink.write(text.data(), text.size());
  12622. sink.done();
  12623. return true;
  12624. });
  12625. });
  12626. auto port = svr.bind_to_any_port(HOST);
  12627. ASSERT_LT(0, port);
  12628. thread t = thread([&] { svr.listen_after_bind(); });
  12629. auto se = detail::scope_exit([&] {
  12630. svr.stop();
  12631. t.join();
  12632. ASSERT_FALSE(svr.is_running());
  12633. });
  12634. svr.wait_until_ready();
  12635. Client cli(HOST, port);
  12636. cli.set_decompress(false);
  12637. for (auto path : {"/buffered", "/streamed"}) {
  12638. SCOPED_TRACE(path);
  12639. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12641. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12642. EXPECT_EQ(text, res->body);
  12643. }
  12644. }
  12645. // A chunked provider settles its coding where the headers are written and
  12646. // reuses it at write time. Both ends of that have to hold: a handler's own
  12647. // Content-Encoding suppresses the coding, and a response without one is still
  12648. // compressed as it always was.
  12649. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12650. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12651. const std::string plain = "Hello World! Hello World! Hello World!";
  12652. Server svr;
  12653. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12654. res.set_header("Content-Encoding", "gzip");
  12655. res.set_chunked_content_provider(
  12656. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12657. sink.write(gzipped.data(), gzipped.size());
  12658. sink.done();
  12659. return true;
  12660. });
  12661. });
  12662. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12663. res.set_chunked_content_provider(
  12664. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12665. sink.write(plain.data(), plain.size());
  12666. sink.done();
  12667. return true;
  12668. });
  12669. });
  12670. auto port = svr.bind_to_any_port(HOST);
  12671. thread t = thread([&]() { svr.listen_after_bind(); });
  12672. auto se = detail::scope_exit([&] {
  12673. svr.stop();
  12674. t.join();
  12675. ASSERT_FALSE(svr.is_running());
  12676. });
  12677. svr.wait_until_ready();
  12678. Client cli(HOST, port);
  12679. Headers headers = {{"Accept-Encoding", "gzip"}};
  12680. {
  12681. auto res = cli.Get("/pre-gzipped", headers);
  12682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12683. EXPECT_EQ(StatusCode::OK_200, res->status);
  12684. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12685. EXPECT_EQ("Hello World!", res->body);
  12686. }
  12687. {
  12688. auto res = cli.Get("/negotiated", headers);
  12689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12690. EXPECT_EQ(StatusCode::OK_200, res->status);
  12691. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12692. EXPECT_EQ(plain, res->body);
  12693. }
  12694. }
  12695. #endif
  12696. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12697. // the same message as the comma-joined one, so both have to be read the same
  12698. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12699. // single gzip coding, and a body the sender says was encoded twice was handed
  12700. // back after one pass, still compressed but presented as decoded.
  12701. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12702. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12703. Server svr;
  12704. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12705. res.set_content(body, "image/jpeg");
  12706. res.headers.emplace("Content-Encoding", "gzip");
  12707. res.headers.emplace("Content-Encoding", "gzip");
  12708. });
  12709. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12710. res.set_content(body, "image/jpeg");
  12711. res.set_header("Content-Encoding", "gzip, gzip");
  12712. });
  12713. auto port = svr.bind_to_any_port(HOST);
  12714. thread t = thread([&]() { svr.listen_after_bind(); });
  12715. auto se = detail::scope_exit([&] {
  12716. svr.stop();
  12717. t.join();
  12718. ASSERT_FALSE(svr.is_running());
  12719. });
  12720. svr.wait_until_ready();
  12721. Client cli(HOST, port);
  12722. // Two codings is not something cpp-httplib decodes, so both representations
  12723. // take the pass-through path rather than one of them being gunzipped once.
  12724. for (const char *path : {"/split", "/joined"}) {
  12725. auto res = cli.Get(path);
  12726. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12727. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12728. EXPECT_EQ(body, res->body) << path;
  12729. }
  12730. }
  12731. // Regression test for DoS vulnerability: a malicious server sending a response
  12732. // without Content-Length header must not cause unbounded memory consumption on
  12733. // the client side. The client should stop reading after a reasonable limit,
  12734. // similar to the server-side set_payload_max_length protection.
  12735. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12736. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12737. #ifndef _WIN32
  12738. signal(SIGPIPE, SIG_IGN);
  12739. #endif
  12740. auto server_thread = std::thread([] {
  12741. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12742. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12743. default_socket_options(srv);
  12744. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12745. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12746. sockaddr_in addr{};
  12747. addr.sin_family = AF_INET;
  12748. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12749. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12750. int opt = 1;
  12751. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12752. #ifdef _WIN32
  12753. reinterpret_cast<const char *>(&opt),
  12754. #else
  12755. &opt,
  12756. #endif
  12757. sizeof(opt));
  12758. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12759. ::listen(srv, 1);
  12760. sockaddr_in cli_addr{};
  12761. socklen_t cli_len = sizeof(cli_addr);
  12762. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12763. if (cli != INVALID_SOCKET) {
  12764. char buf[4096];
  12765. ::recv(cli, buf, sizeof(buf), 0);
  12766. // Malicious response: no Content-Length, no chunked encoding
  12767. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12768. "Connection: close\r\n"
  12769. "\r\n";
  12770. ::send(cli,
  12771. #ifdef _WIN32
  12772. static_cast<const char *>(response_header.c_str()),
  12773. static_cast<int>(response_header.size()),
  12774. #else
  12775. response_header.c_str(), response_header.size(),
  12776. #endif
  12777. 0);
  12778. // Send 10MB of data
  12779. std::string chunk(64 * 1024, 'A');
  12780. size_t total_sent = 0;
  12781. while (total_sent < MALICIOUS_DATA_SIZE) {
  12782. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12783. auto sent = ::send(cli,
  12784. #ifdef _WIN32
  12785. static_cast<const char *>(chunk.c_str()),
  12786. static_cast<int>(to_send),
  12787. #else
  12788. chunk.c_str(), to_send,
  12789. #endif
  12790. 0);
  12791. if (sent <= 0) break;
  12792. total_sent += static_cast<size_t>(sent);
  12793. }
  12794. detail::close_socket(cli);
  12795. }
  12796. detail::close_socket(srv);
  12797. });
  12798. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12799. size_t total_read = 0;
  12800. {
  12801. Client cli("127.0.0.1", PORT + 2);
  12802. cli.set_read_timeout(5, 0);
  12803. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12804. auto stream = cli.open_stream("GET", "/malicious");
  12805. ASSERT_TRUE(stream.is_valid());
  12806. char buffer[64 * 1024];
  12807. ssize_t n;
  12808. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12809. total_read += static_cast<size_t>(n);
  12810. }
  12811. } // StreamHandle and Client destroyed here, closing the socket
  12812. server_thread.join();
  12813. // With set_payload_max_length, the client must stop reading before consuming
  12814. // all 10MB. The read loop should be cut off at or near the configured limit.
  12815. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12816. << "Client read " << total_read << " bytes, exceeding the configured "
  12817. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12818. }
  12819. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12820. // the entire response body without truncation.
  12821. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12822. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12823. #ifndef _WIN32
  12824. signal(SIGPIPE, SIG_IGN);
  12825. #endif
  12826. auto server_thread = std::thread([] {
  12827. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12828. default_socket_options(srv);
  12829. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12830. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12831. sockaddr_in addr{};
  12832. addr.sin_family = AF_INET;
  12833. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12834. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12835. int opt = 1;
  12836. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12837. #ifdef _WIN32
  12838. reinterpret_cast<const char *>(&opt),
  12839. #else
  12840. &opt,
  12841. #endif
  12842. sizeof(opt));
  12843. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12844. ::listen(srv, 1);
  12845. sockaddr_in cli_addr{};
  12846. socklen_t cli_len = sizeof(cli_addr);
  12847. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12848. if (cli != INVALID_SOCKET) {
  12849. char buf[4096];
  12850. ::recv(cli, buf, sizeof(buf), 0);
  12851. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12852. "Connection: close\r\n"
  12853. "\r\n";
  12854. ::send(cli,
  12855. #ifdef _WIN32
  12856. static_cast<const char *>(response_header.c_str()),
  12857. static_cast<int>(response_header.size()),
  12858. #else
  12859. response_header.c_str(), response_header.size(),
  12860. #endif
  12861. 0);
  12862. std::string chunk(64 * 1024, 'A');
  12863. size_t total_sent = 0;
  12864. while (total_sent < DATA_SIZE) {
  12865. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12866. auto sent = ::send(cli,
  12867. #ifdef _WIN32
  12868. static_cast<const char *>(chunk.c_str()),
  12869. static_cast<int>(to_send),
  12870. #else
  12871. chunk.c_str(), to_send,
  12872. #endif
  12873. 0);
  12874. if (sent <= 0) break;
  12875. total_sent += static_cast<size_t>(sent);
  12876. }
  12877. #ifdef _WIN32
  12878. ::shutdown(cli, SD_SEND);
  12879. #else
  12880. ::shutdown(cli, SHUT_WR);
  12881. #endif
  12882. // Drain until the client closes its end, ensuring all data is delivered
  12883. char drain[1024];
  12884. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12885. detail::close_socket(cli);
  12886. }
  12887. detail::close_socket(srv);
  12888. });
  12889. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12890. size_t total_read = 0;
  12891. {
  12892. Client cli("127.0.0.1", PORT + 2);
  12893. cli.set_read_timeout(5, 0);
  12894. cli.set_payload_max_length(0); // 0 means no limit
  12895. auto stream = cli.open_stream("GET", "/data");
  12896. ASSERT_TRUE(stream.is_valid());
  12897. char buffer[64 * 1024];
  12898. ssize_t n;
  12899. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12900. total_read += static_cast<size_t>(n);
  12901. }
  12902. }
  12903. server_thread.join();
  12904. EXPECT_EQ(total_read, DATA_SIZE)
  12905. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12906. << " bytes without truncation, but only read " << total_read << " bytes.";
  12907. }
  12908. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12909. // enormous Content-Length must not cause the client to pre-allocate a huge
  12910. // response body buffer. The reservation is capped at payload_max_length_, and
  12911. // the read itself fails when the body exceeds the limit.
  12912. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12913. #ifndef _WIN32
  12914. signal(SIGPIPE, SIG_IGN);
  12915. #endif
  12916. auto server_thread = std::thread([] {
  12917. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12918. default_socket_options(srv);
  12919. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12920. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12921. sockaddr_in addr{};
  12922. addr.sin_family = AF_INET;
  12923. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12924. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12925. int opt = 1;
  12926. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12927. #ifdef _WIN32
  12928. reinterpret_cast<const char *>(&opt),
  12929. #else
  12930. &opt,
  12931. #endif
  12932. sizeof(opt));
  12933. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12934. ::listen(srv, 1);
  12935. sockaddr_in cli_addr{};
  12936. socklen_t cli_len = sizeof(cli_addr);
  12937. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12938. if (cli != INVALID_SOCKET) {
  12939. char buf[4096];
  12940. ::recv(cli, buf, sizeof(buf), 0);
  12941. // Malicious response: claim a 20GB body but send only a tiny payload.
  12942. std::string response = "HTTP/1.1 200 OK\r\n"
  12943. "Content-Length: 20000000000\r\n"
  12944. "\r\n"
  12945. "abc";
  12946. ::send(cli,
  12947. #ifdef _WIN32
  12948. static_cast<const char *>(response.c_str()),
  12949. static_cast<int>(response.size()),
  12950. #else
  12951. response.c_str(), response.size(),
  12952. #endif
  12953. 0);
  12954. detail::close_socket(cli);
  12955. }
  12956. detail::close_socket(srv);
  12957. });
  12958. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12959. {
  12960. Client cli("127.0.0.1", PORT + 2);
  12961. cli.set_read_timeout(5, 0);
  12962. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12963. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12964. // (server claims more bytes than payload_max_length permits), but it must
  12965. // not exhaust memory before getting there.
  12966. auto res = cli.Get("/malicious");
  12967. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12968. }
  12969. server_thread.join();
  12970. }
  12971. // Verify that content_receiver bypasses the default payload_max_length,
  12972. // allowing streaming downloads larger than 100MB without requiring an explicit
  12973. // set_payload_max_length call.
  12974. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12975. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12976. #ifndef _WIN32
  12977. signal(SIGPIPE, SIG_IGN);
  12978. #endif
  12979. auto server_thread = std::thread([] {
  12980. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12981. default_socket_options(srv);
  12982. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12983. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12984. sockaddr_in addr{};
  12985. addr.sin_family = AF_INET;
  12986. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12987. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12988. int opt = 1;
  12989. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12990. #ifdef _WIN32
  12991. reinterpret_cast<const char *>(&opt),
  12992. #else
  12993. &opt,
  12994. #endif
  12995. sizeof(opt));
  12996. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12997. ::listen(srv, 1);
  12998. sockaddr_in cli_addr{};
  12999. socklen_t cli_len = sizeof(cli_addr);
  13000. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13001. if (cli != INVALID_SOCKET) {
  13002. char buf[4096];
  13003. ::recv(cli, buf, sizeof(buf), 0);
  13004. // Response with Content-Length larger than default 100MB limit
  13005. auto content_length = std::to_string(DATA_SIZE);
  13006. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13007. "Content-Length: " +
  13008. content_length +
  13009. "\r\n"
  13010. "Connection: close\r\n"
  13011. "\r\n";
  13012. ::send(cli,
  13013. #ifdef _WIN32
  13014. static_cast<const char *>(response_header.c_str()),
  13015. static_cast<int>(response_header.size()),
  13016. #else
  13017. response_header.c_str(), response_header.size(),
  13018. #endif
  13019. 0);
  13020. std::string chunk(64 * 1024, 'A');
  13021. size_t total_sent = 0;
  13022. while (total_sent < DATA_SIZE) {
  13023. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13024. auto sent = ::send(cli,
  13025. #ifdef _WIN32
  13026. static_cast<const char *>(chunk.c_str()),
  13027. static_cast<int>(to_send),
  13028. #else
  13029. chunk.c_str(), to_send,
  13030. #endif
  13031. 0);
  13032. if (sent <= 0) break;
  13033. total_sent += static_cast<size_t>(sent);
  13034. }
  13035. detail::close_socket(cli);
  13036. }
  13037. detail::close_socket(srv);
  13038. });
  13039. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13040. size_t total_received = 0;
  13041. {
  13042. Client cli("127.0.0.1", PORT + 2);
  13043. cli.set_read_timeout(10, 0);
  13044. // Do NOT call set_payload_max_length — use the default 100MB limit
  13045. auto res =
  13046. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13047. total_received += data_length;
  13048. return true;
  13049. });
  13050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13051. EXPECT_EQ(StatusCode::OK_200, res->status);
  13052. }
  13053. server_thread.join();
  13054. EXPECT_EQ(total_received, DATA_SIZE)
  13055. << "With content_receiver, the client should read all " << DATA_SIZE
  13056. << " bytes despite the default 100MB payload_max_length, but only read "
  13057. << total_received << " bytes.";
  13058. }
  13059. // Verify that an explicit set_payload_max_length smaller than the response is
  13060. // enforced even when a content_receiver is used.
  13061. TEST(ClientVulnerabilityTest,
  13062. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13063. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13064. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13065. #ifndef _WIN32
  13066. signal(SIGPIPE, SIG_IGN);
  13067. #endif
  13068. auto server_thread = std::thread([] {
  13069. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13070. default_socket_options(srv);
  13071. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13072. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13073. sockaddr_in addr{};
  13074. addr.sin_family = AF_INET;
  13075. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13076. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13077. int opt = 1;
  13078. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13079. #ifdef _WIN32
  13080. reinterpret_cast<const char *>(&opt),
  13081. #else
  13082. &opt,
  13083. #endif
  13084. sizeof(opt));
  13085. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13086. ::listen(srv, 1);
  13087. sockaddr_in cli_addr{};
  13088. socklen_t cli_len = sizeof(cli_addr);
  13089. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13090. if (cli != INVALID_SOCKET) {
  13091. char buf[4096];
  13092. ::recv(cli, buf, sizeof(buf), 0);
  13093. auto content_length = std::to_string(DATA_SIZE);
  13094. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13095. "Content-Length: " +
  13096. content_length +
  13097. "\r\n"
  13098. "Connection: close\r\n"
  13099. "\r\n";
  13100. ::send(cli,
  13101. #ifdef _WIN32
  13102. static_cast<const char *>(response_header.c_str()),
  13103. static_cast<int>(response_header.size()),
  13104. #else
  13105. response_header.c_str(), response_header.size(),
  13106. #endif
  13107. 0);
  13108. std::string chunk(64 * 1024, 'A');
  13109. size_t total_sent = 0;
  13110. while (total_sent < DATA_SIZE) {
  13111. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13112. auto sent = ::send(cli,
  13113. #ifdef _WIN32
  13114. static_cast<const char *>(chunk.c_str()),
  13115. static_cast<int>(to_send),
  13116. #else
  13117. chunk.c_str(), to_send,
  13118. #endif
  13119. 0);
  13120. if (sent <= 0) break;
  13121. total_sent += static_cast<size_t>(sent);
  13122. }
  13123. detail::close_socket(cli);
  13124. }
  13125. detail::close_socket(srv);
  13126. });
  13127. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13128. size_t total_received = 0;
  13129. {
  13130. Client cli("127.0.0.1", PORT + 2);
  13131. cli.set_read_timeout(10, 0);
  13132. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13133. auto res =
  13134. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13135. total_received += data_length;
  13136. return true;
  13137. });
  13138. // Should fail because 200MB exceeds the explicit 150MB limit
  13139. EXPECT_FALSE(res);
  13140. }
  13141. server_thread.join();
  13142. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13143. << "Client with content_receiver should respect the explicit "
  13144. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13145. << total_received << " bytes.";
  13146. }
  13147. // Verify that an explicit set_payload_max_length larger than the response
  13148. // allows the content_receiver to read all data successfully.
  13149. TEST(ClientVulnerabilityTest,
  13150. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13151. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13152. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13153. #ifndef _WIN32
  13154. signal(SIGPIPE, SIG_IGN);
  13155. #endif
  13156. auto server_thread = std::thread([] {
  13157. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13158. default_socket_options(srv);
  13159. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13160. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13161. sockaddr_in addr{};
  13162. addr.sin_family = AF_INET;
  13163. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13164. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13165. int opt = 1;
  13166. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13167. #ifdef _WIN32
  13168. reinterpret_cast<const char *>(&opt),
  13169. #else
  13170. &opt,
  13171. #endif
  13172. sizeof(opt));
  13173. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13174. ::listen(srv, 1);
  13175. sockaddr_in cli_addr{};
  13176. socklen_t cli_len = sizeof(cli_addr);
  13177. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13178. if (cli != INVALID_SOCKET) {
  13179. char buf[4096];
  13180. ::recv(cli, buf, sizeof(buf), 0);
  13181. auto content_length = std::to_string(DATA_SIZE);
  13182. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13183. "Content-Length: " +
  13184. content_length +
  13185. "\r\n"
  13186. "Connection: close\r\n"
  13187. "\r\n";
  13188. ::send(cli,
  13189. #ifdef _WIN32
  13190. static_cast<const char *>(response_header.c_str()),
  13191. static_cast<int>(response_header.size()),
  13192. #else
  13193. response_header.c_str(), response_header.size(),
  13194. #endif
  13195. 0);
  13196. std::string chunk(64 * 1024, 'A');
  13197. size_t total_sent = 0;
  13198. while (total_sent < DATA_SIZE) {
  13199. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13200. auto sent = ::send(cli,
  13201. #ifdef _WIN32
  13202. static_cast<const char *>(chunk.c_str()),
  13203. static_cast<int>(to_send),
  13204. #else
  13205. chunk.c_str(), to_send,
  13206. #endif
  13207. 0);
  13208. if (sent <= 0) break;
  13209. total_sent += static_cast<size_t>(sent);
  13210. }
  13211. #ifdef _WIN32
  13212. ::shutdown(cli, SD_SEND);
  13213. #else
  13214. ::shutdown(cli, SHUT_WR);
  13215. #endif
  13216. char drain[1024];
  13217. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13218. detail::close_socket(cli);
  13219. }
  13220. detail::close_socket(srv);
  13221. });
  13222. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13223. size_t total_received = 0;
  13224. {
  13225. Client cli("127.0.0.1", PORT + 2);
  13226. cli.set_read_timeout(10, 0);
  13227. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13228. auto res =
  13229. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13230. total_received += data_length;
  13231. return true;
  13232. });
  13233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13234. EXPECT_EQ(StatusCode::OK_200, res->status);
  13235. }
  13236. server_thread.join();
  13237. EXPECT_EQ(total_received, DATA_SIZE)
  13238. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13239. << " bytes (larger than " << DATA_SIZE
  13240. << " bytes response), content_receiver should read all data, but only "
  13241. "read "
  13242. << total_received << " bytes.";
  13243. }
  13244. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13245. // Regression test for "zip bomb" attack on the client side: a malicious server
  13246. // sends a small gzip-compressed response that decompresses to a huge payload.
  13247. // The client must enforce payload_max_length on the decompressed size.
  13248. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13249. constexpr size_t DECOMPRESSED_SIZE =
  13250. 10 * 1024 * 1024; // 10MB after decompression
  13251. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13252. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13253. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13254. std::string compressed;
  13255. {
  13256. httplib::detail::gzip_compressor compressor;
  13257. bool ok =
  13258. compressor.compress(uncompressed.data(), uncompressed.size(),
  13259. /*last=*/true, [&](const char *buf, size_t len) {
  13260. compressed.append(buf, len);
  13261. return true;
  13262. });
  13263. ASSERT_TRUE(ok);
  13264. }
  13265. // Sanity: compressed data should be much smaller than the decompressed size
  13266. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13267. #ifndef _WIN32
  13268. signal(SIGPIPE, SIG_IGN);
  13269. #endif
  13270. // Set up the listening socket in the main thread so the server is guaranteed
  13271. // to be ready before the client connects (eliminates race condition).
  13272. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13273. default_socket_options(srv);
  13274. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13275. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13276. sockaddr_in addr{};
  13277. addr.sin_family = AF_INET;
  13278. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13279. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13280. int opt = 1;
  13281. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13282. #ifdef _WIN32
  13283. reinterpret_cast<const char *>(&opt),
  13284. #else
  13285. &opt,
  13286. #endif
  13287. sizeof(opt));
  13288. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13289. ASSERT_EQ(0, ::listen(srv, 1));
  13290. auto server_thread = std::thread([&compressed, srv] {
  13291. sockaddr_in cli_addr{};
  13292. socklen_t cli_len = sizeof(cli_addr);
  13293. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13294. if (cli != INVALID_SOCKET) {
  13295. // Read the full HTTP request (until \r\n\r\n)
  13296. char buf[4096];
  13297. size_t total = 0;
  13298. while (total < sizeof(buf)) {
  13299. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13300. if (n <= 0) break;
  13301. total += static_cast<size_t>(n);
  13302. // Check for end of headers
  13303. if (total >= 4) {
  13304. std::string req(buf, total);
  13305. if (req.find("\r\n\r\n") != std::string::npos) break;
  13306. }
  13307. }
  13308. // Malicious response: gzip-compressed body, no Content-Length
  13309. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13310. "Content-Encoding: gzip\r\n"
  13311. "Connection: close\r\n"
  13312. "\r\n";
  13313. ::send(cli,
  13314. #ifdef _WIN32
  13315. static_cast<const char *>(response_header.c_str()),
  13316. static_cast<int>(response_header.size()),
  13317. #else
  13318. response_header.c_str(), response_header.size(),
  13319. #endif
  13320. 0);
  13321. // Send the compressed payload (small on the wire, huge when decompressed)
  13322. size_t total_sent = 0;
  13323. while (total_sent < compressed.size()) {
  13324. auto to_send = std::min(compressed.size() - total_sent,
  13325. static_cast<size_t>(64 * 1024));
  13326. auto sent =
  13327. ::send(cli,
  13328. #ifdef _WIN32
  13329. static_cast<const char *>(compressed.c_str() + total_sent),
  13330. static_cast<int>(to_send),
  13331. #else
  13332. compressed.c_str() + total_sent, to_send,
  13333. #endif
  13334. 0);
  13335. if (sent <= 0) break;
  13336. total_sent += static_cast<size_t>(sent);
  13337. }
  13338. detail::close_socket(cli);
  13339. }
  13340. });
  13341. auto se = detail::scope_exit([&] {
  13342. detail::close_socket(srv);
  13343. server_thread.join();
  13344. });
  13345. size_t total_decompressed = 0;
  13346. {
  13347. Client cli("127.0.0.1", PORT + 3);
  13348. cli.set_read_timeout(5, 0);
  13349. cli.set_decompress(true);
  13350. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13351. auto stream = cli.open_stream("GET", "/zipbomb");
  13352. ASSERT_TRUE(stream.is_valid());
  13353. char buffer[64 * 1024];
  13354. ssize_t n;
  13355. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13356. total_decompressed += static_cast<size_t>(n);
  13357. }
  13358. }
  13359. // The decompressed size must be capped by payload_max_length. Without
  13360. // protection, the client would decompress the full 10MB from a tiny
  13361. // compressed payload, enabling a zip bomb DoS attack.
  13362. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13363. << "Client decompressed " << total_decompressed
  13364. << " bytes from a gzip response. The decompressed size should be "
  13365. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13366. }
  13367. #endif
  13368. TEST(HostAndPortPropertiesTest, NoSSL) {
  13369. httplib::Client cli("www.google.com", 1234);
  13370. ASSERT_EQ("www.google.com", cli.host());
  13371. ASSERT_EQ(1234, cli.port());
  13372. }
  13373. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13374. httplib::Client cli("www.google.com:1234");
  13375. ASSERT_EQ("www.google.com", cli.host());
  13376. ASSERT_EQ(1234, cli.port());
  13377. }
  13378. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13379. // Port number that overflows int — should not crash, client becomes invalid
  13380. httplib::Client cli("http://www.google.com:99999999999999999999");
  13381. ASSERT_FALSE(cli.is_valid());
  13382. }
  13383. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13384. // Port 99999 exceeds valid range (1-65535) — should not crash
  13385. httplib::Client cli("http://www.google.com:99999");
  13386. ASSERT_FALSE(cli.is_valid());
  13387. auto res = cli.Get("/");
  13388. EXPECT_FALSE(res);
  13389. EXPECT_EQ(Error::Connection, res.error());
  13390. }
  13391. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13392. httplib::Client cli("http://user:pass@localhost:1234");
  13393. ASSERT_FALSE(cli.is_valid());
  13394. EXPECT_FALSE(cli.Get("/"));
  13395. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13396. }
  13397. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13398. httplib::Client cli("http://www.google.com:80abc");
  13399. ASSERT_FALSE(cli.is_valid());
  13400. }
  13401. #ifdef CPPHTTPLIB_SSL_ENABLED
  13402. TEST(HostAndPortPropertiesTest, SSL) {
  13403. httplib::SSLClient cli("www.google.com");
  13404. ASSERT_EQ("www.google.com", cli.host());
  13405. ASSERT_EQ(443, cli.port());
  13406. }
  13407. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13408. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13409. std::string cert;
  13410. read_file(CA_CERT_FILE, cert);
  13411. httplib::SSLClient httplib_client("www.google.com");
  13412. // Load CA store first time
  13413. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13414. // Load CA store second time (update)
  13415. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13416. // Verify client is still valid and can make connections
  13417. httplib_client.enable_server_certificate_verification(true);
  13418. auto res = httplib_client.Get("/");
  13419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13420. // Google may return 200 or 301 depending on various factors
  13421. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13422. res->status == StatusCode::MovedPermanently_301);
  13423. }
  13424. TEST(SSLClientTest, ServerNameIndication_Online) {
  13425. auto host = "httpbingo.org";
  13426. auto path = std::string{"/get"};
  13427. SSLClient cli(host, 443);
  13428. auto res = cli.Get(path);
  13429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13430. ASSERT_EQ(StatusCode::OK_200, res->status);
  13431. }
  13432. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13433. // Use a site that will cause SSL verification failure due to self-signed cert
  13434. SSLClient cli("self-signed.badssl.com", 443);
  13435. cli.enable_server_certificate_verification(true);
  13436. auto res = cli.Get("/");
  13437. ASSERT_TRUE(!res);
  13438. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13439. // Verify backend error is captured for SSLServerVerification
  13440. // This occurs when certificate verification fails
  13441. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13442. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13443. EXPECT_NE(0UL, res.ssl_backend_error());
  13444. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13445. res.ssl_error());
  13446. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13447. #if !defined(_WIN32) || \
  13448. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13449. // On non-Windows or when Windows Schannel is disabled, the error comes
  13450. // from OpenSSL's verification
  13451. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13452. res.ssl_backend_error());
  13453. #endif
  13454. #endif
  13455. }
  13456. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13457. // Use a site where hostname doesn't match the certificate
  13458. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13459. SSLClient cli("wrong.host.badssl.com", 443);
  13460. cli.enable_server_certificate_verification(true);
  13461. cli.enable_server_hostname_verification(true);
  13462. auto res = cli.Get("/");
  13463. ASSERT_TRUE(!res);
  13464. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13465. // Verify backend error is captured for hostname verification failure
  13466. EXPECT_NE(0UL, res.ssl_backend_error());
  13467. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13468. res.ssl_error());
  13469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13470. #if !defined(_WIN32) || \
  13471. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13472. // On non-Windows or when Windows Schannel is disabled, the error comes
  13473. // from OpenSSL's hostname verification
  13474. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13475. res.ssl_backend_error());
  13476. #endif
  13477. #endif
  13478. }
  13479. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13480. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13481. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13482. SSLClient cli("www.google.com", 443);
  13483. cli.enable_server_certificate_verification(true);
  13484. auto res = cli.Get("/");
  13485. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13486. }
  13487. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13488. SSLClient cli("www.google.com", 443);
  13489. cli.enable_server_certificate_verification(true);
  13490. cli.enable_windows_certificate_verification(false);
  13491. auto res = cli.Get("/");
  13492. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13493. }
  13494. // The server sends an intermediate cross-signed by a root Windows trusts,
  13495. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13496. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13497. SSLClient cli("accounts.spotify.com", 443);
  13498. auto res = cli.Get("/");
  13499. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13500. << " ssl_backend_error=" << res.ssl_backend_error();
  13501. }
  13502. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13503. // policy status, which no backend reports for a self-signed certificate.
  13504. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13505. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13506. ASSERT_TRUE(svr.is_valid());
  13507. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13508. auto se = detail::scope_exit([&] {
  13509. svr.stop();
  13510. t.join();
  13511. ASSERT_FALSE(svr.is_running());
  13512. });
  13513. svr.wait_until_ready();
  13514. SSLClient cli("127.0.0.1", PORT);
  13515. cli.set_connection_timeout(30);
  13516. auto res = cli.Get("/");
  13517. ASSERT_FALSE(res);
  13518. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13519. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13520. }
  13521. #endif
  13522. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13523. Client cli("https://google.com");
  13524. auto res = cli.Get("/");
  13525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13526. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13527. }
  13528. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13529. SSLClient cli("google.com");
  13530. cli.set_ca_cert_path(CA_CERT_FILE);
  13531. auto res = cli.Get("/");
  13532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13533. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13534. }
  13535. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13536. SSLClient cli("google.com");
  13537. cli.enable_server_certificate_verification(true);
  13538. cli.set_ca_cert_path("hello");
  13539. auto res = cli.Get("/");
  13540. ASSERT_TRUE(!res);
  13541. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13542. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13543. // should be set
  13544. EXPECT_EQ(0, res.ssl_error());
  13545. // Verify backend error is captured for SSLLoadingCerts
  13546. // This error occurs when loading CA certificates fails
  13547. EXPECT_NE(0UL, res.ssl_backend_error());
  13548. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13549. // OpenSSL specific error codes:
  13550. // > openssl errstr 0x80000002
  13551. // error:80000002:system library::No such file or directory
  13552. // > openssl errstr 0xA000126
  13553. // error:0A000126:SSL routines::unexpected eof while reading
  13554. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13555. res.ssl_backend_error() == 0xA000126);
  13556. #endif
  13557. }
  13558. TEST(SSLClientTest, ServerCertificateVerification4) {
  13559. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13560. ASSERT_TRUE(svr.is_valid());
  13561. svr.Get("/test", [&](const Request &, Response &res) {
  13562. res.set_content("test", "text/plain");
  13563. svr.stop();
  13564. ASSERT_TRUE(true);
  13565. });
  13566. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13567. auto se = detail::scope_exit([&] {
  13568. t.join();
  13569. ASSERT_FALSE(svr.is_running());
  13570. });
  13571. svr.wait_until_ready();
  13572. SSLClient cli("127.0.0.1", PORT);
  13573. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13574. cli.enable_server_certificate_verification(true);
  13575. cli.set_connection_timeout(30);
  13576. auto res = cli.Get("/test");
  13577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13578. ASSERT_EQ(StatusCode::OK_200, res->status);
  13579. }
  13580. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13581. std::string cert;
  13582. read_file(CA_CERT_FILE, cert);
  13583. SSLClient cli("google.com");
  13584. cli.load_ca_cert_store(cert.data(), cert.size());
  13585. const auto res = cli.Get("/");
  13586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13587. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13588. }
  13589. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13590. // clang-format off
  13591. static constexpr char cert[] =
  13592. "GlobalSign Root CA\n"
  13593. "==================\n"
  13594. "-----BEGIN CERTIFICATE-----\n"
  13595. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13596. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13597. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13598. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13599. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13600. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13601. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13602. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13603. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13604. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13605. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13606. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13607. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13608. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13609. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13610. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13611. "-----END CERTIFICATE-----\n";
  13612. // clang-format on
  13613. SSLClient cli("google.com");
  13614. cli.load_ca_cert_store(cert, sizeof(cert));
  13615. const auto res = cli.Get("/");
  13616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13617. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13618. }
  13619. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13620. SSLClient cli("www.youtube.com");
  13621. cli.set_ca_cert_path(CA_CERT_FILE);
  13622. cli.enable_server_certificate_verification(true);
  13623. cli.set_follow_location(true);
  13624. auto res = cli.Get("/");
  13625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13626. ASSERT_EQ(StatusCode::OK_200, res->status);
  13627. }
  13628. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13629. SSLClient cli("wWw.YouTube.Com");
  13630. cli.set_ca_cert_path(CA_CERT_FILE);
  13631. cli.enable_server_certificate_verification(true);
  13632. cli.enable_server_hostname_verification(true);
  13633. cli.set_follow_location(true);
  13634. auto res = cli.Get("/");
  13635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13636. ASSERT_EQ(StatusCode::OK_200, res->status);
  13637. }
  13638. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13639. SSLClient cli("gOoGlE.COm");
  13640. cli.enable_server_certificate_verification(true);
  13641. cli.enable_server_hostname_verification(true);
  13642. cli.set_follow_location(true);
  13643. auto res = cli.Get("/");
  13644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13645. ASSERT_EQ(StatusCode::OK_200, res->status);
  13646. }
  13647. TEST(SSLClientTest, Issue2004_Online) {
  13648. Client client("https://google.com");
  13649. client.set_follow_location(true);
  13650. auto res = client.Get("/");
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. ASSERT_EQ(StatusCode::OK_200, res->status);
  13653. auto body = res->body;
  13654. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13655. }
  13656. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13657. // Create SSLClient with invalid cert/key to make is_valid() return false
  13658. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13659. "nonexistent_key.pem");
  13660. // is_valid() should be false due to cert loading failure
  13661. ASSERT_FALSE(cli.is_valid());
  13662. auto res = cli.Get("/");
  13663. ASSERT_FALSE(res);
  13664. EXPECT_EQ(Error::SSLConnection, res.error());
  13665. }
  13666. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13667. // Test for Issue #2251: SSL error not properly reported when client cert
  13668. // and key paths are swapped or mismatched
  13669. // This simulates the scenario where user accidentally swaps the cert and key
  13670. // files
  13671. // Using client cert file as private key and vice versa (completely wrong)
  13672. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13673. // Should fail validation due to cert/key mismatch
  13674. ASSERT_FALSE(cli.is_valid());
  13675. // Attempt to make a request should fail with proper error
  13676. auto res = cli.Get("/");
  13677. ASSERT_FALSE(res);
  13678. EXPECT_EQ(Error::SSLConnection, res.error());
  13679. // SSL error should be recorded in the Result object (this is the key fix for
  13680. // Issue #2251)
  13681. auto backend_error = res.ssl_backend_error();
  13682. EXPECT_NE(0u, backend_error);
  13683. }
  13684. // Tests cert/key mismatch detection at the TLS context level
  13685. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13686. // Test that using mismatched cert/key causes connection failure.
  13687. // We verify this at the SSLClient level rather than through internal
  13688. // TLS API functions.
  13689. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13690. cli.enable_server_certificate_verification(false);
  13691. cli.set_connection_timeout(2);
  13692. // The mismatch should cause a connection or handshake error
  13693. auto res = cli.Get("/test");
  13694. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13695. // Either way, the request should fail
  13696. EXPECT_FALSE(res);
  13697. }
  13698. #endif
  13699. #if 0
  13700. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13701. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13702. ASSERT_TRUE(cli != nullptr);
  13703. cli->set_address_family(AF_INET6);
  13704. cli->set_interface("en0");
  13705. auto res = cli->Get("/get");
  13706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13707. ASSERT_EQ(StatusCode::OK_200, res->status);
  13708. }
  13709. #endif
  13710. // Client certificate tests - work with all TLS backends
  13711. #ifdef CPPHTTPLIB_SSL_ENABLED
  13712. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13713. void ClientCertPresent(
  13714. const std::string &client_cert_file,
  13715. const std::string &client_private_key_file,
  13716. const std::string &client_encrypted_private_key_pass = std::string(),
  13717. const ClientCertServerSetup &setup = nullptr) {
  13718. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13719. ASSERT_TRUE(svr.is_valid());
  13720. if (setup) { setup(svr); }
  13721. svr.Get("/test", [&](const Request &req, Response &res) {
  13722. res.set_content("test", "text/plain");
  13723. auto cert = req.peer_cert();
  13724. ASSERT_TRUE(static_cast<bool>(cert));
  13725. std::string common_name = cert.subject_cn();
  13726. EXPECT_EQ("Common Name", common_name);
  13727. });
  13728. auto port = svr.bind_to_any_port(HOST);
  13729. ASSERT_LT(0, port);
  13730. thread t = thread([&]() { svr.listen_after_bind(); });
  13731. auto se = detail::scope_exit([&] {
  13732. svr.stop();
  13733. t.join();
  13734. ASSERT_FALSE(svr.is_running());
  13735. });
  13736. svr.wait_until_ready();
  13737. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13738. client_encrypted_private_key_pass);
  13739. cli.enable_server_certificate_verification(false);
  13740. cli.set_connection_timeout(30);
  13741. auto res = cli.Get("/test");
  13742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13743. ASSERT_EQ(StatusCode::OK_200, res->status);
  13744. }
  13745. TEST(SSLClientServerTest, ClientCertPresent) {
  13746. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13747. }
  13748. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13749. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13750. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13751. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13752. }
  13753. // Expects svr, which must require client certificates, to reject a client
  13754. // that has none
  13755. void RejectsClientWithoutCert(SSLServer &svr) {
  13756. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13757. auto port = svr.bind_to_any_port(HOST);
  13758. ASSERT_LT(0, port);
  13759. thread t = thread([&]() { svr.listen_after_bind(); });
  13760. auto se = detail::scope_exit([&] {
  13761. svr.stop();
  13762. t.join();
  13763. ASSERT_FALSE(svr.is_running());
  13764. });
  13765. svr.wait_until_ready();
  13766. SSLClient cli(HOST, port);
  13767. cli.set_connection_timeout(30);
  13768. // Skip the server certificate check, so that the request fails because the
  13769. // client certificate is missing rather than because cert.pem is not trusted
  13770. cli.enable_server_certificate_verification(false);
  13771. auto res = cli.Get("/test");
  13772. ASSERT_FALSE(res);
  13773. // The server rejects the client during the handshake, or on TLS 1.3 right
  13774. // after it, which the client notices on its first write or read
  13775. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13776. res.error() == Error::Write || res.error() == Error::Read)
  13777. << to_string(res.error());
  13778. if (res.error() == Error::SSLConnection) {
  13779. EXPECT_NE(0UL, res.ssl_backend_error());
  13780. }
  13781. // A rejection noticed on the write keeps the TLS error the write hit
  13782. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13783. }
  13784. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13786. ASSERT_TRUE(svr.is_valid());
  13787. if (setup) { setup(svr); }
  13788. RejectsClientWithoutCert(svr);
  13789. }
  13790. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13791. // A server that requires client certificates must keep requiring them after
  13792. // setup changes it, and keep accepting a client that has one
  13793. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13794. ClientCertMissing(setup);
  13795. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13796. setup);
  13797. }
  13798. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13799. ClientCertStillRequired([](SSLServer &svr) {
  13800. ASSERT_TRUE(tls::set_verify_callback(
  13801. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13802. });
  13803. }
  13804. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13805. ClientCertStillRequired([](SSLServer &svr) {
  13806. ASSERT_TRUE(tls::set_verify_callback(
  13807. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13808. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13809. });
  13810. }
  13811. // The client verifies the server certificate during the handshake, so a
  13812. // server that fails the check never gets the client certificate, even when a
  13813. // verifier of the client's own accepts it
  13814. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13815. struct Case {
  13816. const char *trusted_ca;
  13817. const char *host;
  13818. Error error;
  13819. };
  13820. // cert2.pem names localhost: the first client does not trust it, and the
  13821. // second trusts it but asks for another name
  13822. for (const auto &c :
  13823. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13824. Case{SERVER_CERT2_FILE, "example.com",
  13825. Error::SSLServerHostnameVerification}}) {
  13826. for (auto with_verifier : {false, true}) {
  13827. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13828. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13829. CLIENT_CA_CERT_FILE);
  13830. ASSERT_TRUE(svr.is_valid());
  13831. std::atomic<bool> got_client_cert{false};
  13832. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13833. [&](const tls::VerifyContext &) {
  13834. got_client_cert = true;
  13835. return true;
  13836. }));
  13837. auto port = svr.bind_to_any_port("127.0.0.1");
  13838. ASSERT_LT(0, port);
  13839. thread t = thread([&] { svr.listen_after_bind(); });
  13840. svr.wait_until_ready();
  13841. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13842. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13843. cli.set_ca_cert_path(c.trusted_ca);
  13844. if (with_verifier) {
  13845. cli.set_server_certificate_verifier(
  13846. [](const tls::VerifyContext &) { return true; });
  13847. }
  13848. auto res = cli.Get("/");
  13849. EXPECT_FALSE(res);
  13850. EXPECT_EQ(c.error, res.error());
  13851. svr.stop();
  13852. t.join();
  13853. EXPECT_FALSE(got_client_cert);
  13854. }
  13855. }
  13856. }
  13857. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13858. std::string cert_pem, key_pem, ca_pem;
  13859. read_file(SERVER_CERT_FILE, cert_pem);
  13860. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13861. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13862. ASSERT_TRUE(
  13863. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13864. }
  13865. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13866. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13867. ASSERT_TRUE(svr.is_valid());
  13868. UpdateCertsPemWithClientCA(svr);
  13869. RejectsClientWithoutCert(svr);
  13870. }
  13871. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13872. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13873. }
  13874. // A TLS error from one request must not show up in a later request's Result
  13875. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13877. ASSERT_TRUE(svr.is_valid());
  13878. svr.Get("/test", [](const Request &, Response &res) {
  13879. res.set_content("test", "text/plain");
  13880. });
  13881. auto port = svr.bind_to_any_port(HOST);
  13882. ASSERT_LT(0, port);
  13883. thread t = thread([&]() { svr.listen_after_bind(); });
  13884. auto se = detail::scope_exit([&] {
  13885. svr.stop();
  13886. t.join();
  13887. ASSERT_FALSE(svr.is_running());
  13888. });
  13889. svr.wait_until_ready();
  13890. SSLClient cli(HOST, port);
  13891. cli.set_connection_timeout(30);
  13892. cli.enable_server_hostname_verification(false);
  13893. // cert.pem is not trusted, so the handshake fails
  13894. ASSERT_FALSE(cli.Get("/test"));
  13895. cli.enable_server_certificate_verification(false);
  13896. auto res = cli.Get("/test");
  13897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13898. EXPECT_EQ(0, res.ssl_error());
  13899. EXPECT_EQ(0UL, res.ssl_backend_error());
  13900. }
  13901. // PEM memory-based constructor tests (works with all TLS backends).
  13902. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13903. // terminator after it.
  13904. void PemMemoryClientCertPresent(
  13905. const std::string &client_cert_file,
  13906. const std::string &client_private_key_file,
  13907. const std::string &client_encrypted_private_key_pass = std::string(),
  13908. bool exact_size = false) {
  13909. // Read PEM files into memory
  13910. std::string server_cert_pem, server_key_pem;
  13911. std::string client_ca_pem;
  13912. std::string client_cert_pem, client_key_pem;
  13913. read_file(SERVER_CERT_FILE, server_cert_pem);
  13914. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13915. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13916. read_file(client_cert_file, client_cert_pem);
  13917. read_file(client_private_key_file, client_key_pem);
  13918. std::list<std::vector<char>> exact_copies;
  13919. auto data = [&](const std::string &pem) -> const char * {
  13920. if (!exact_size) { return pem.c_str(); }
  13921. exact_copies.emplace_back(pem.begin(), pem.end());
  13922. return exact_copies.back().data();
  13923. };
  13924. // Create server with PEM memory
  13925. SSLServer::PemMemory server_pem = {
  13926. data(server_cert_pem),
  13927. server_cert_pem.size(),
  13928. data(server_key_pem),
  13929. server_key_pem.size(),
  13930. data(client_ca_pem),
  13931. client_ca_pem.size(),
  13932. nullptr // no password for server key
  13933. };
  13934. SSLServer svr(server_pem);
  13935. ASSERT_TRUE(svr.is_valid());
  13936. svr.Get("/test", [&](const Request &req, Response &res) {
  13937. res.set_content("test", "text/plain");
  13938. auto cert = req.peer_cert();
  13939. ASSERT_TRUE(static_cast<bool>(cert));
  13940. EXPECT_EQ("Common Name", cert.subject_cn());
  13941. });
  13942. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13943. auto se = detail::scope_exit([&] {
  13944. svr.stop();
  13945. t.join();
  13946. ASSERT_FALSE(svr.is_running());
  13947. });
  13948. svr.wait_until_ready();
  13949. // Create client with PEM memory
  13950. const char *password = client_encrypted_private_key_pass.empty()
  13951. ? nullptr
  13952. : client_encrypted_private_key_pass.c_str();
  13953. SSLClient::PemMemory client_pem = {
  13954. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13955. client_key_pem.size(), password};
  13956. SSLClient cli(HOST, PORT, client_pem);
  13957. cli.enable_server_certificate_verification(false);
  13958. cli.set_connection_timeout(30);
  13959. auto res = cli.Get("/test");
  13960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13961. ASSERT_EQ(StatusCode::OK_200, res->status);
  13962. }
  13963. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13964. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13965. }
  13966. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13967. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13968. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13969. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13970. }
  13971. // A server built from PEM memory with a client CA requires client certificates,
  13972. // also when the CA is a NUL-terminated string passed with a length of 0
  13973. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13974. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13975. read_file(SERVER_CERT_FILE, server_cert_pem);
  13976. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13977. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13978. SSLServer::PemMemory server_pem = {
  13979. server_cert_pem.c_str(),
  13980. server_cert_pem.size(),
  13981. server_key_pem.c_str(),
  13982. server_key_pem.size(),
  13983. client_ca_pem.c_str(),
  13984. client_ca_pem.size(),
  13985. nullptr // no password for server key
  13986. };
  13987. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13988. SCOPED_TRACE(client_ca_pem_len);
  13989. server_pem.client_ca_pem_len = client_ca_pem_len;
  13990. SSLServer svr(server_pem);
  13991. ASSERT_TRUE(svr.is_valid());
  13992. RejectsClientWithoutCert(svr);
  13993. }
  13994. // An empty CA fails to load instead of turning the check off
  13995. server_pem.client_ca_pem = "";
  13996. server_pem.client_ca_pem_len = 0;
  13997. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13998. }
  13999. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14000. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14001. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14002. true);
  14003. }
  14004. // A length shorter than the PEM cuts it short, so it no longer loads
  14005. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14006. std::string cert, key;
  14007. read_file(SERVER_CERT_FILE, cert);
  14008. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14009. for (auto cut_cert : {true, false}) {
  14010. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14011. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14012. SSLServer::PemMemory server_pem = {
  14013. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14014. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14015. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14016. key_len, nullptr};
  14017. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14018. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14019. key.c_str(), key_len, nullptr};
  14020. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14021. }
  14022. }
  14023. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14024. class NoListenSSLServer : public SSLServer {
  14025. public:
  14026. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14027. const char *client_ca_cert_file_path,
  14028. const char *client_ca_cert_dir_path = nullptr)
  14029. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14030. client_ca_cert_dir_path),
  14031. stop_(false) {}
  14032. std::atomic_bool stop_;
  14033. private:
  14034. bool process_and_close_socket(socket_t /*sock*/) override {
  14035. // Don't create SSL context
  14036. while (!stop_.load()) {
  14037. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14038. }
  14039. return true;
  14040. }
  14041. };
  14042. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14043. CLIENT_CA_CERT_FILE);
  14044. ASSERT_TRUE(svr.is_valid());
  14045. svr.Get("/test", [&](const Request &, Response &res) {
  14046. res.set_content("test", "text/plain");
  14047. });
  14048. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14049. auto se = detail::scope_exit([&] {
  14050. svr.stop_ = true;
  14051. svr.stop();
  14052. t.join();
  14053. ASSERT_FALSE(svr.is_running());
  14054. });
  14055. svr.wait_until_ready();
  14056. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14057. cli.enable_server_certificate_verification(false);
  14058. cli.set_connection_timeout(1);
  14059. auto res = cli.Get("/test");
  14060. ASSERT_TRUE(!res);
  14061. EXPECT_EQ(Error::SSLConnection, res.error());
  14062. // Timeout results in WantRead error code (maps to backend-specific value)
  14063. EXPECT_NE(0, res.ssl_error());
  14064. }
  14065. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14066. // Test SSLServer with client certificate verification using the standard
  14067. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14068. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14069. CLIENT_CA_CERT_DIR);
  14070. ASSERT_TRUE(svr.is_valid());
  14071. svr.Get("/test", [&](const Request &req, Response &res) {
  14072. res.set_content("test", "text/plain");
  14073. auto cert = req.peer_cert();
  14074. ASSERT_TRUE(static_cast<bool>(cert));
  14075. auto common_name = cert.subject_cn();
  14076. EXPECT_EQ("Common Name", common_name);
  14077. });
  14078. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14079. auto se = detail::scope_exit([&] {
  14080. svr.stop();
  14081. t.join();
  14082. ASSERT_FALSE(svr.is_running());
  14083. });
  14084. svr.wait_until_ready();
  14085. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14086. cli.enable_server_certificate_verification(false);
  14087. cli.set_connection_timeout(30);
  14088. auto res = cli.Get("/test");
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. ASSERT_EQ(StatusCode::OK_200, res->status);
  14091. }
  14092. // Test verify_hostname on every backend: a host is named by a SAN only
  14093. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14094. using namespace httplib::tls;
  14095. // We need a running server to test against
  14096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14097. ASSERT_TRUE(svr.is_valid());
  14098. svr.Get("/test", [](const Request &, Response &res) {
  14099. res.set_content("ok", "text/plain");
  14100. });
  14101. thread t([&]() { svr.listen(HOST, PORT); });
  14102. auto se = detail::scope_exit([&] {
  14103. svr.stop();
  14104. t.join();
  14105. });
  14106. svr.wait_until_ready();
  14107. bool verify_callback_called = false;
  14108. bool verify_result_wrong = false;
  14109. SSLClient cli(HOST, PORT);
  14110. cli.enable_server_certificate_verification(true);
  14111. cli.set_ca_cert_path(CA_CERT_FILE);
  14112. cli.set_connection_timeout(5);
  14113. // Note: Test certificate has CN="Common Name", not "localhost"
  14114. bool verify_result_cn = false;
  14115. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14116. verify_callback_called = true;
  14117. if (!ctx.cert) return false;
  14118. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14119. verify_result_cn = ctx.check_hostname("Common Name");
  14120. // Test 2: wrong hostname should not match
  14121. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14122. return true; // Accept for the purpose of this test
  14123. });
  14124. auto res = cli.Get("/test");
  14125. // The request may succeed or fail depending on cert configuration
  14126. // but the callback should have been called
  14127. ASSERT_TRUE(verify_callback_called)
  14128. << "Verify callback should have been called";
  14129. EXPECT_FALSE(verify_result_cn)
  14130. << "verify_hostname must not match the certificate CN (no SAN)";
  14131. // Wrong hostname should not match
  14132. EXPECT_FALSE(verify_result_wrong)
  14133. << "verify_hostname should not match 'wronghost.example.com'";
  14134. }
  14135. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14136. // backend verifies it.
  14137. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14138. // Certificate CN is "localhost" and it carries no SAN.
  14139. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14140. ASSERT_TRUE(svr.is_valid());
  14141. svr.Get("/test", [](const Request &, Response &res) {
  14142. res.set_content("ok", "text/plain");
  14143. });
  14144. auto port = svr.bind_to_any_port(HOST);
  14145. thread t([&]() { svr.listen_after_bind(); });
  14146. auto se = detail::scope_exit([&] {
  14147. svr.stop();
  14148. t.join();
  14149. });
  14150. svr.wait_until_ready();
  14151. SSLClient cli("localhost", port);
  14152. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14153. cli.enable_server_certificate_verification(true);
  14154. cli.set_connection_timeout(5);
  14155. auto res = cli.Get("/test");
  14156. ASSERT_FALSE(res);
  14157. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14158. // The same certificate is accepted once host name verification is off, so the
  14159. // failure above is the host name and not the chain.
  14160. cli.enable_server_hostname_verification(false);
  14161. res = cli.Get("/test");
  14162. ASSERT_TRUE(res) << to_string(res.error());
  14163. EXPECT_EQ(StatusCode::OK_200, res->status);
  14164. }
  14165. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14166. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14167. // X509_check_ip behavior and must hold for every backend.
  14168. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14169. using namespace httplib::tls;
  14170. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14171. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14172. ASSERT_TRUE(svr.is_valid());
  14173. svr.Get("/test", [](const Request &, Response &res) {
  14174. res.set_content("ok", "text/plain");
  14175. });
  14176. thread t([&]() { svr.listen(HOST, PORT); });
  14177. auto se = detail::scope_exit([&] {
  14178. svr.stop();
  14179. t.join();
  14180. });
  14181. svr.wait_until_ready();
  14182. bool verify_callback_called = false;
  14183. bool ip_matched_via_cn = true;
  14184. SSLClient cli(HOST, PORT);
  14185. cli.enable_server_certificate_verification(true);
  14186. cli.set_ca_cert_path(CA_CERT_FILE);
  14187. cli.set_connection_timeout(5);
  14188. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14189. verify_callback_called = true;
  14190. if (!ctx.cert) return false;
  14191. // The IP appears only in the CN, so it must NOT be accepted.
  14192. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14193. return true; // Accept for the purpose of this test
  14194. });
  14195. cli.Get("/test");
  14196. ASSERT_TRUE(verify_callback_called)
  14197. << "Verify callback should have been called";
  14198. EXPECT_FALSE(ip_matched_via_cn)
  14199. << "An IP host must not be authenticated via the certificate CN";
  14200. }
  14201. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14202. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14203. using namespace httplib::tls;
  14204. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14205. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14206. ASSERT_TRUE(svr.is_valid());
  14207. svr.Get("/test", [](const Request &, Response &res) {
  14208. res.set_content("ok", "text/plain");
  14209. });
  14210. thread t([&]() { svr.listen(HOST, PORT); });
  14211. auto se = detail::scope_exit([&] {
  14212. svr.stop();
  14213. t.join();
  14214. });
  14215. svr.wait_until_ready();
  14216. bool verify_callback_called = false;
  14217. bool san_matched = false;
  14218. bool wrong_ipv6_matched = true;
  14219. bool cn_ipv6_matched = true;
  14220. SSLClient cli(HOST, PORT);
  14221. cli.enable_server_certificate_verification(true);
  14222. cli.set_ca_cert_path(CA_CERT_FILE);
  14223. cli.set_connection_timeout(5);
  14224. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14225. verify_callback_called = true;
  14226. if (!ctx.cert) return false;
  14227. // Matches the IPv6 iPAddress SAN.
  14228. san_matched = ctx.check_hostname("2001:db8::1");
  14229. // A different IPv6 address must not match.
  14230. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14231. // "::1" lives only in the CN, so it must not be accepted.
  14232. cn_ipv6_matched = ctx.check_hostname("::1");
  14233. return true; // Accept for the purpose of this test
  14234. });
  14235. cli.Get("/test");
  14236. ASSERT_TRUE(verify_callback_called)
  14237. << "Verify callback should have been called";
  14238. EXPECT_TRUE(san_matched)
  14239. << "verify_hostname should match an IPv6 iPAddress SAN";
  14240. EXPECT_FALSE(wrong_ipv6_matched)
  14241. << "verify_hostname should not match a non-matching IPv6 address";
  14242. EXPECT_FALSE(cn_ipv6_matched)
  14243. << "An IPv6 host must not be authenticated via the certificate CN";
  14244. }
  14245. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14246. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14247. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14248. using namespace httplib::tls;
  14249. // SANs: DNS:a.zz, IP:42.46.122.122
  14250. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14251. ASSERT_TRUE(svr.is_valid());
  14252. svr.Get("/test", [](const Request &, Response &res) {
  14253. res.set_content("ok", "text/plain");
  14254. });
  14255. auto port = svr.bind_to_any_port(HOST);
  14256. thread t([&]() { svr.listen_after_bind(); });
  14257. auto se = detail::scope_exit([&] {
  14258. svr.stop();
  14259. t.join();
  14260. });
  14261. svr.wait_until_ready();
  14262. bool verify_callback_called = false;
  14263. bool dns_san_matched = false;
  14264. bool ip_san_matched = false;
  14265. bool ip_matched_via_dns_san = true;
  14266. bool dns_matched_via_ip_san = true;
  14267. bool cn_matched_next_to_dns_san = true;
  14268. SSLClient cli(HOST, port);
  14269. cli.enable_server_certificate_verification(true);
  14270. cli.set_ca_cert_path(CA_CERT_FILE);
  14271. cli.set_connection_timeout(5);
  14272. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14273. verify_callback_called = true;
  14274. if (!ctx.cert) return false;
  14275. dns_san_matched = ctx.check_hostname("a.zz");
  14276. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14277. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14278. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14279. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14280. return true; // Accept for the purpose of this test
  14281. });
  14282. cli.Get("/test");
  14283. ASSERT_TRUE(verify_callback_called)
  14284. << "Verify callback should have been called";
  14285. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14286. EXPECT_TRUE(ip_san_matched)
  14287. << "verify_hostname should match an iPAddress SAN";
  14288. EXPECT_FALSE(ip_matched_via_dns_san)
  14289. << "An IP host must not be authenticated via a dNSName SAN";
  14290. EXPECT_FALSE(dns_matched_via_ip_san)
  14291. << "A DNS host must not be authenticated via an iPAddress SAN";
  14292. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14293. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14294. }
  14295. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14296. // "www.*.example.test" names one host and not every host under example.test.
  14297. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14298. using namespace httplib::tls;
  14299. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14300. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14301. ASSERT_TRUE(svr.is_valid());
  14302. svr.Get("/test", [](const Request &, Response &res) {
  14303. res.set_content("ok", "text/plain");
  14304. });
  14305. auto port = svr.bind_to_any_port(HOST);
  14306. thread t([&]() { svr.listen_after_bind(); });
  14307. auto se = detail::scope_exit([&] {
  14308. svr.stop();
  14309. t.join();
  14310. });
  14311. svr.wait_until_ready();
  14312. bool verify_callback_called = false;
  14313. bool leftmost_wildcard_matched = false;
  14314. bool wildcard_spanned_labels = true;
  14315. bool inner_wildcard_matched = true;
  14316. SSLClient cli(HOST, port);
  14317. cli.enable_server_certificate_verification(true);
  14318. cli.set_ca_cert_path(CA_CERT_FILE);
  14319. cli.set_connection_timeout(5);
  14320. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14321. verify_callback_called = true;
  14322. if (!ctx.cert) return false;
  14323. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14324. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14325. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14326. return true; // Accept for the purpose of this test
  14327. });
  14328. cli.Get("/test");
  14329. ASSERT_TRUE(verify_callback_called)
  14330. << "Verify callback should have been called";
  14331. EXPECT_TRUE(leftmost_wildcard_matched)
  14332. << "A leftmost wildcard should match a single label";
  14333. EXPECT_FALSE(wildcard_spanned_labels)
  14334. << "A wildcard label must not match more than one label";
  14335. EXPECT_FALSE(inner_wildcard_matched)
  14336. << "A wildcard outside the leftmost label must not be honoured";
  14337. }
  14338. // sans() must report each SAN entry under its own type.
  14339. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14340. using namespace httplib::tls;
  14341. // SANs: DNS:a.zz, IP:42.46.122.122
  14342. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14343. ASSERT_TRUE(svr.is_valid());
  14344. svr.Get("/test", [](const Request &, Response &res) {
  14345. res.set_content("ok", "text/plain");
  14346. });
  14347. auto port = svr.bind_to_any_port(HOST);
  14348. thread t([&]() { svr.listen_after_bind(); });
  14349. auto se = detail::scope_exit([&] {
  14350. svr.stop();
  14351. t.join();
  14352. });
  14353. svr.wait_until_ready();
  14354. bool verify_callback_called = false;
  14355. std::vector<SanEntry> sans;
  14356. SSLClient cli(HOST, port);
  14357. cli.enable_server_certificate_verification(true);
  14358. cli.set_ca_cert_path(CA_CERT_FILE);
  14359. cli.set_connection_timeout(5);
  14360. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14361. verify_callback_called = true;
  14362. if (!ctx.cert) return false;
  14363. sans = ctx.sans();
  14364. return true; // Accept for the purpose of this test
  14365. });
  14366. cli.Get("/test");
  14367. ASSERT_TRUE(verify_callback_called)
  14368. << "Verify callback should have been called";
  14369. auto has_san = [&](SanType type, const std::string &value) {
  14370. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14371. return san.type == type && san.value == value;
  14372. });
  14373. };
  14374. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14375. << "sans() should report the dNSName SAN";
  14376. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14377. << "sans() should report the iPAddress SAN";
  14378. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14379. << "sans() must not report the dNSName SAN as an address";
  14380. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14381. << "sans() must not report the iPAddress SAN as a DNS name";
  14382. }
  14383. #endif
  14384. // mbedTLS-specific callback constructor test
  14385. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14386. #ifdef CPPHTTPLIB_SSL_ENABLED
  14387. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14389. ASSERT_TRUE(svr.is_valid());
  14390. // Set up a handler to verify client certificate is present
  14391. bool client_cert_verified = false;
  14392. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14393. // Verify that client certificate was provided
  14394. client_cert_verified = true;
  14395. res.set_content("success", "text/plain");
  14396. });
  14397. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14398. auto se = detail::scope_exit([&] {
  14399. svr.stop();
  14400. t.join();
  14401. ASSERT_FALSE(svr.is_running());
  14402. });
  14403. svr.wait_until_ready();
  14404. // Client with certificate
  14405. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14406. cli.enable_server_certificate_verification(false);
  14407. cli.set_connection_timeout(30);
  14408. auto res = cli.Get("/test");
  14409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14410. ASSERT_EQ(StatusCode::OK_200, res->status);
  14411. ASSERT_TRUE(client_cert_verified);
  14412. EXPECT_EQ("success", res->body);
  14413. }
  14414. #endif
  14415. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14416. // backends
  14417. #ifdef CPPHTTPLIB_SSL_ENABLED
  14418. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14419. using namespace httplib::tls;
  14420. // Test that when client CA cert file is provided,
  14421. // the server properly requests and validates client certificates
  14422. // Create a server with client authentication
  14423. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14424. ASSERT_TRUE(svr.is_valid());
  14425. bool handler_called = false;
  14426. svr.Get("/test", [&](const Request &req, Response &res) {
  14427. handler_called = true;
  14428. // Verify that a client certificate was provided
  14429. auto cert = req.peer_cert();
  14430. ASSERT_TRUE(static_cast<bool>(cert));
  14431. // Get the issuer name
  14432. std::string issuer_str = cert.issuer_name();
  14433. ASSERT_FALSE(issuer_str.empty());
  14434. // The client certificate should be issued by our test CA
  14435. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14436. res.set_content("authenticated", "text/plain");
  14437. });
  14438. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14439. auto se = detail::scope_exit([&] {
  14440. svr.stop();
  14441. t.join();
  14442. ASSERT_FALSE(svr.is_running());
  14443. });
  14444. svr.wait_until_ready();
  14445. // Connect with a client certificate issued by the CA
  14446. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14447. cli.enable_server_certificate_verification(false);
  14448. cli.set_connection_timeout(30);
  14449. auto res = cli.Get("/test");
  14450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14451. ASSERT_EQ(StatusCode::OK_200, res->status);
  14452. ASSERT_TRUE(handler_called);
  14453. EXPECT_EQ("authenticated", res->body);
  14454. }
  14455. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14456. using namespace httplib::tls;
  14457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14458. ASSERT_TRUE(svr.is_valid());
  14459. svr.Get("/test", [](const Request &, Response &res) {
  14460. res.set_content("ok", "text/plain");
  14461. });
  14462. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14463. auto se = detail::scope_exit([&] {
  14464. svr.stop();
  14465. t.join();
  14466. });
  14467. svr.wait_until_ready();
  14468. SSLClient cli(HOST, PORT);
  14469. cli.enable_server_certificate_verification(false);
  14470. cli.set_connection_timeout(30);
  14471. bool cert_checked = false;
  14472. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14473. if (ctx.cert) {
  14474. auto sans = ctx.sans();
  14475. // Test certificate may or may not have SANs - just verify the API
  14476. // works If SANs exist, verify the types are valid
  14477. for (const auto &san : sans) {
  14478. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14479. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14480. san.type == SanType::OTHER);
  14481. EXPECT_FALSE(san.value.empty());
  14482. }
  14483. cert_checked = true;
  14484. }
  14485. return true;
  14486. });
  14487. auto res = cli.Get("/test");
  14488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14489. EXPECT_TRUE(cert_checked);
  14490. }
  14491. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14492. using namespace httplib::tls;
  14493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14494. ASSERT_TRUE(svr.is_valid());
  14495. svr.Get("/test", [](const Request &, Response &res) {
  14496. res.set_content("ok", "text/plain");
  14497. });
  14498. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14499. auto se = detail::scope_exit([&] {
  14500. svr.stop();
  14501. t.join();
  14502. });
  14503. svr.wait_until_ready();
  14504. SSLClient cli(HOST, PORT);
  14505. cli.enable_server_certificate_verification(false);
  14506. cli.set_connection_timeout(30);
  14507. bool validity_checked = false;
  14508. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14509. if (ctx.cert) {
  14510. time_t not_before = 0, not_after = 0;
  14511. bool result = ctx.validity(not_before, not_after);
  14512. EXPECT_TRUE(result);
  14513. // Verify that not_before < now < not_after for a valid cert
  14514. time_t now = time(nullptr);
  14515. EXPECT_LT(not_before, now);
  14516. EXPECT_GT(not_after, now);
  14517. validity_checked = true;
  14518. }
  14519. return true;
  14520. });
  14521. auto res = cli.Get("/test");
  14522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14523. EXPECT_TRUE(validity_checked);
  14524. }
  14525. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14526. using namespace httplib::tls;
  14527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14528. ASSERT_TRUE(svr.is_valid());
  14529. svr.Get("/test", [](const Request &, Response &res) {
  14530. res.set_content("ok", "text/plain");
  14531. });
  14532. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14533. auto se = detail::scope_exit([&] {
  14534. svr.stop();
  14535. t.join();
  14536. });
  14537. svr.wait_until_ready();
  14538. SSLClient cli(HOST, PORT);
  14539. cli.enable_server_certificate_verification(false);
  14540. cli.set_connection_timeout(30);
  14541. bool serial_checked = false;
  14542. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14543. if (ctx.cert) {
  14544. std::string serial = ctx.serial();
  14545. EXPECT_FALSE(serial.empty());
  14546. // Serial should be a hex string
  14547. for (char c : serial) {
  14548. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14549. (c >= 'a' && c <= 'f'));
  14550. }
  14551. serial_checked = true;
  14552. }
  14553. return true;
  14554. });
  14555. auto res = cli.Get("/test");
  14556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14557. EXPECT_TRUE(serial_checked);
  14558. }
  14559. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14560. // Test 1: Valid CA file - no error should be recorded
  14561. {
  14562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14563. CLIENT_CA_CERT_FILE);
  14564. ASSERT_TRUE(svr.is_valid());
  14565. // With valid setup, last_ssl_error should be 0
  14566. EXPECT_EQ(0, svr.ssl_last_error());
  14567. }
  14568. // Test 2: Invalid CA file content
  14569. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14570. {
  14571. // Create a temporary file with completely invalid content
  14572. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14573. {
  14574. std::ofstream ofs(temp_invalid_ca);
  14575. ofs << "This is not a certificate file at all\n";
  14576. ofs << "Just plain text content\n";
  14577. }
  14578. // Create server with invalid CA file
  14579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14580. // Clean up temporary file
  14581. std::remove(temp_invalid_ca);
  14582. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14583. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14584. // Note: SSL_CTX_load_verify_locations typically fails first,
  14585. // but our error handling code path is still exercised
  14586. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14587. }
  14588. }
  14589. TEST(VerifyCallbackTest, VerifyContextFields) {
  14590. using namespace httplib::tls;
  14591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14592. ASSERT_TRUE(svr.is_valid());
  14593. svr.Get("/test", [](const Request &, Response &res) {
  14594. res.set_content("ok", "text/plain");
  14595. });
  14596. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14597. auto se = detail::scope_exit([&] {
  14598. svr.stop();
  14599. t.join();
  14600. });
  14601. svr.wait_until_ready();
  14602. SSLClient cli(HOST, PORT);
  14603. cli.enable_server_certificate_verification(false);
  14604. cli.set_connection_timeout(30);
  14605. int callback_count = 0;
  14606. bool saw_leaf_cert = false;
  14607. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14608. if (ctx.cert) {
  14609. callback_count++;
  14610. // We should see at least one certificate (the leaf)
  14611. std::string cn = ctx.subject_cn();
  14612. if (!cn.empty()) { saw_leaf_cert = true; }
  14613. // Verify context fields are populated
  14614. EXPECT_NE(ctx.session, nullptr);
  14615. EXPECT_GE(ctx.depth, 0);
  14616. }
  14617. return true;
  14618. });
  14619. auto res = cli.Get("/test");
  14620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14621. EXPECT_GT(callback_count, 0);
  14622. EXPECT_TRUE(saw_leaf_cert);
  14623. }
  14624. // A verifier that accepts runs alongside the built-in verification, and is the
  14625. // only check once that is turned off.
  14626. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14627. using namespace httplib::tls;
  14628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14629. ASSERT_TRUE(svr.is_valid());
  14630. svr.Get("/test", [](const Request &, Response &res) {
  14631. res.set_content("ok", "text/plain");
  14632. });
  14633. auto port = svr.bind_to_any_port(HOST);
  14634. thread t([&]() { svr.listen_after_bind(); });
  14635. auto se = detail::scope_exit([&] {
  14636. svr.stop();
  14637. t.join();
  14638. });
  14639. svr.wait_until_ready();
  14640. SSLClient cli(HOST, port);
  14641. cli.enable_server_hostname_verification(false);
  14642. auto calls = 0;
  14643. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14644. calls++;
  14645. return true;
  14646. });
  14647. // cert.pem is not trusted
  14648. auto res = cli.Get("/test");
  14649. ASSERT_FALSE(res);
  14650. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14651. EXPECT_GT(calls, 0);
  14652. cli.enable_server_certificate_verification(false);
  14653. res = cli.Get("/test");
  14654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14655. EXPECT_EQ("ok", res->body);
  14656. }
  14657. // A verifier belongs to the client that set it, not to the thread that set it.
  14658. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14659. using namespace httplib::tls;
  14660. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14661. ASSERT_TRUE(svr.is_valid());
  14662. svr.Get("/test", [](const Request &, Response &res) {
  14663. res.set_content("ok", "text/plain");
  14664. });
  14665. auto port = svr.bind_to_any_port(HOST);
  14666. thread t([&]() { svr.listen_after_bind(); });
  14667. auto se = detail::scope_exit([&] {
  14668. svr.stop();
  14669. t.join();
  14670. });
  14671. svr.wait_until_ready();
  14672. auto rejecting_calls = 0;
  14673. SSLClient rejecting(HOST, port);
  14674. rejecting.enable_server_certificate_verification(false);
  14675. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14676. rejecting_calls++;
  14677. return false;
  14678. });
  14679. auto accepting_calls = 0;
  14680. SSLClient accepting(HOST, port);
  14681. accepting.enable_server_certificate_verification(false);
  14682. // Set on another thread than the requests below.
  14683. thread([&]() {
  14684. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14685. accepting_calls++;
  14686. return true;
  14687. });
  14688. }).join();
  14689. // Requested on another thread than the verifier was set on.
  14690. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14691. EXPECT_GT(rejecting_calls, 0);
  14692. auto res = accepting.Get("/test");
  14693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14694. EXPECT_GT(accepting_calls, 0);
  14695. }
  14696. // A verifier replaced while a handshake runs it lives until it returns.
  14697. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14698. using namespace httplib::tls;
  14699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14700. ASSERT_TRUE(svr.is_valid());
  14701. svr.Get("/test", [](const Request &, Response &res) {
  14702. res.set_content("ok", "text/plain");
  14703. });
  14704. auto port = svr.bind_to_any_port(HOST);
  14705. thread t([&]() { svr.listen_after_bind(); });
  14706. auto se = detail::scope_exit([&] {
  14707. svr.stop();
  14708. t.join();
  14709. });
  14710. svr.wait_until_ready();
  14711. SSLClient cli(HOST, port);
  14712. cli.enable_server_certificate_verification(false);
  14713. std::promise<void> entered;
  14714. std::promise<void> replaced;
  14715. auto replaced_future = replaced.get_future();
  14716. auto first_call = true;
  14717. // Long enough to live on the heap
  14718. std::string expected(64, 'v');
  14719. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14720. if (first_call) {
  14721. first_call = false;
  14722. entered.set_value();
  14723. replaced_future.wait();
  14724. }
  14725. return expected == std::string(64, 'v');
  14726. });
  14727. thread request([&]() {
  14728. auto res = cli.Get("/test");
  14729. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14730. });
  14731. entered.get_future().wait();
  14732. cli.set_server_certificate_verifier(
  14733. [](const VerifyContext &) { return true; });
  14734. replaced.set_value();
  14735. request.join();
  14736. }
  14737. // VerifyContext::session is the same handle the other tls:: functions take.
  14738. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14739. using namespace httplib::tls;
  14740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14741. ASSERT_TRUE(svr.is_valid());
  14742. svr.Get("/test", [](const Request &, Response &res) {
  14743. res.set_content("ok", "text/plain");
  14744. });
  14745. auto port = svr.bind_to_any_port(HOST);
  14746. thread t([&]() { svr.listen_after_bind(); });
  14747. auto se = detail::scope_exit([&] {
  14748. svr.stop();
  14749. t.join();
  14750. });
  14751. svr.wait_until_ready();
  14752. SSLClient cli(HOST, port);
  14753. cli.enable_server_certificate_verification(false);
  14754. session_t verifier_session = nullptr;
  14755. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14756. verifier_session = ctx.session;
  14757. return true;
  14758. });
  14759. session_t session_verifier_session = nullptr;
  14760. cli.set_session_verifier([&](session_t session) {
  14761. session_verifier_session = session;
  14762. return SSLVerifierResponse::NoDecisionMade;
  14763. });
  14764. auto res = cli.Get("/test");
  14765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14766. EXPECT_NE(nullptr, verifier_session);
  14767. EXPECT_EQ(session_verifier_session, verifier_session);
  14768. }
  14769. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14770. using httplib::tls::TlsError;
  14771. // Test that verify_error_to_string returns empty for success
  14772. std::string success_str = TlsError::verify_error_to_string(0);
  14773. EXPECT_TRUE(success_str.empty());
  14774. // Test that verify_error_to_string returns non-empty for error codes
  14775. // Using a common error code (certificate expired)
  14776. std::string error_str =
  14777. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14778. EXPECT_FALSE(error_str.empty());
  14779. }
  14780. TEST(SessionVerifierTest, CertificateAccepted) {
  14781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14782. ASSERT_TRUE(svr.is_valid());
  14783. svr.Get("/test", [](const Request &, Response &res) {
  14784. res.set_content("ok", "text/plain");
  14785. });
  14786. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14787. auto se = detail::scope_exit([&] {
  14788. svr.stop();
  14789. t.join();
  14790. });
  14791. svr.wait_until_ready();
  14792. SSLClient cli(HOST, PORT);
  14793. cli.enable_server_certificate_verification(false);
  14794. cli.set_connection_timeout(30);
  14795. bool callback_called = false;
  14796. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14797. EXPECT_NE(session, nullptr);
  14798. callback_called = true;
  14799. return SSLVerifierResponse::CertificateAccepted;
  14800. });
  14801. auto res = cli.Get("/test");
  14802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14803. EXPECT_EQ(200, res->status);
  14804. EXPECT_TRUE(callback_called);
  14805. }
  14806. TEST(SessionVerifierTest, CertificateRejected) {
  14807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14808. ASSERT_TRUE(svr.is_valid());
  14809. svr.Get("/test", [](const Request &, Response &res) {
  14810. res.set_content("ok", "text/plain");
  14811. });
  14812. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14813. auto se = detail::scope_exit([&] {
  14814. svr.stop();
  14815. t.join();
  14816. });
  14817. svr.wait_until_ready();
  14818. SSLClient cli(HOST, PORT);
  14819. cli.enable_server_certificate_verification(false);
  14820. cli.set_connection_timeout(30);
  14821. bool callback_called = false;
  14822. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14823. EXPECT_NE(session, nullptr);
  14824. callback_called = true;
  14825. return SSLVerifierResponse::CertificateRejected;
  14826. });
  14827. auto res = cli.Get("/test");
  14828. EXPECT_FALSE(res);
  14829. EXPECT_TRUE(callback_called);
  14830. }
  14831. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14832. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14833. ASSERT_TRUE(svr.is_valid());
  14834. svr.Get("/test", [](const Request &, Response &res) {
  14835. res.set_content("ok", "text/plain");
  14836. });
  14837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14838. auto se = detail::scope_exit([&] {
  14839. svr.stop();
  14840. t.join();
  14841. });
  14842. svr.wait_until_ready();
  14843. // NoDecisionMade with verification disabled should succeed (no default check)
  14844. SSLClient cli(HOST, PORT);
  14845. cli.enable_server_certificate_verification(false);
  14846. cli.set_connection_timeout(30);
  14847. bool callback_called = false;
  14848. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14849. EXPECT_NE(session, nullptr);
  14850. callback_called = true;
  14851. return SSLVerifierResponse::NoDecisionMade;
  14852. });
  14853. auto res = cli.Get("/test");
  14854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14855. EXPECT_EQ(200, res->status);
  14856. EXPECT_TRUE(callback_called);
  14857. }
  14858. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14860. ASSERT_TRUE(svr.is_valid());
  14861. svr.Get("/test", [](const Request &, Response &res) {
  14862. res.set_content("ok", "text/plain");
  14863. });
  14864. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14865. auto se = detail::scope_exit([&] {
  14866. svr.stop();
  14867. t.join();
  14868. });
  14869. svr.wait_until_ready();
  14870. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14871. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14872. // so we only check that the request fails, not whether the callback was
  14873. // called.
  14874. SSLClient cli(HOST, PORT);
  14875. cli.enable_server_certificate_verification(true);
  14876. cli.set_connection_timeout(30);
  14877. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14878. EXPECT_NE(session, nullptr);
  14879. return SSLVerifierResponse::NoDecisionMade;
  14880. });
  14881. auto res = cli.Get("/test");
  14882. EXPECT_FALSE(res);
  14883. }
  14884. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14885. // Test SSL server using PemMemory constructor with client CA certificates
  14886. // Read PEM files
  14887. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14888. read_file(SERVER_CERT_FILE, server_cert_pem);
  14889. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14890. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14891. // Create SSLServer with PemMemory constructor including client CA
  14892. SSLServer::PemMemory server_pem = {
  14893. server_cert_pem.c_str(),
  14894. server_cert_pem.size(),
  14895. server_key_pem.c_str(),
  14896. server_key_pem.size(),
  14897. client_ca_pem.c_str(),
  14898. client_ca_pem.size(),
  14899. nullptr // no password for server key
  14900. };
  14901. SSLServer svr(server_pem);
  14902. ASSERT_TRUE(svr.is_valid());
  14903. // No SSL error should be recorded for valid setup
  14904. EXPECT_EQ(0, svr.ssl_last_error());
  14905. // Set up server endpoints
  14906. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14907. res.set_content("ok", "text/plain");
  14908. });
  14909. // Start server in a thread
  14910. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14911. svr.wait_until_ready();
  14912. // Connect with client certificate (using constructor with paths)
  14913. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14914. cli.enable_server_certificate_verification(false);
  14915. auto res = cli.Get("/test-pem-ca");
  14916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14917. EXPECT_EQ(200, res->status);
  14918. EXPECT_EQ("ok", res->body);
  14919. svr.stop();
  14920. server_thread.join();
  14921. }
  14922. #endif
  14923. #ifdef _WIN32
  14924. TEST(CleanupTest, WSACleanup) {
  14925. int ret = WSACleanup();
  14926. ASSERT_EQ(0, ret);
  14927. }
  14928. #endif
  14929. #ifndef CPPHTTPLIB_SSL_ENABLED
  14930. TEST(NoSSLSupport, SimpleInterface) {
  14931. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14932. }
  14933. #endif
  14934. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14935. TEST(InvalidScheme, SimpleInterface) {
  14936. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14937. }
  14938. #endif
  14939. TEST(NoScheme, SimpleInterface) {
  14940. Client cli("yahoo.com:80");
  14941. ASSERT_TRUE(cli.is_valid());
  14942. }
  14943. TEST(SendAPI, SimpleInterface_Online) {
  14944. Client cli("http://yahoo.com");
  14945. Request req;
  14946. req.method = "GET";
  14947. req.path = "/";
  14948. auto res = cli.send(req);
  14949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14950. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14951. }
  14952. TEST(SendAPI, WithParamsInRequest) {
  14953. Server svr;
  14954. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14955. EXPECT_TRUE(req.has_param("test"));
  14956. EXPECT_EQ("test_value", req.get_param_value("test"));
  14957. });
  14958. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14959. auto se = detail::scope_exit([&] {
  14960. svr.stop();
  14961. t.join();
  14962. ASSERT_FALSE(svr.is_running());
  14963. });
  14964. svr.wait_until_ready();
  14965. Client cli(HOST, PORT);
  14966. {
  14967. Request req;
  14968. req.method = "GET";
  14969. req.path = "/";
  14970. req.params.emplace("test", "test_value");
  14971. auto res = cli.send(req);
  14972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14973. }
  14974. {
  14975. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14977. }
  14978. }
  14979. TEST(ClientImplMethods, GetSocketTest) {
  14980. httplib::Server svr;
  14981. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14982. res.status = StatusCode::OK_200;
  14983. });
  14984. auto port = svr.bind_to_any_port("127.0.0.1");
  14985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14986. auto se = detail::scope_exit([&] {
  14987. svr.stop();
  14988. thread.join();
  14989. ASSERT_FALSE(svr.is_running());
  14990. });
  14991. svr.wait_until_ready();
  14992. {
  14993. httplib::Client cli("127.0.0.1", port);
  14994. cli.set_keep_alive(true);
  14995. // Use the behavior of cpp-httplib of opening the connection
  14996. // only when the first request happens. If that changes,
  14997. // this test would be obsolete.
  14998. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14999. // This also implicitly tests the server. But other tests would fail much
  15000. // earlier than this one to be considered.
  15001. auto res = cli.Get("/");
  15002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15003. EXPECT_EQ(StatusCode::OK_200, res->status);
  15004. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15005. }
  15006. }
  15007. #ifdef CPPHTTPLIB_SSL_ENABLED
  15008. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15009. Client cli("http://yahoo.com");
  15010. auto res = cli.Get("/");
  15011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15012. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15013. cli.set_follow_location(true);
  15014. res = cli.Get("/");
  15015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15016. EXPECT_EQ(StatusCode::OK_200, res->status);
  15017. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15018. }
  15019. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15020. Client cli("https://yahoo.com");
  15021. auto res = cli.Get("/");
  15022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15023. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15024. cli.set_follow_location(true);
  15025. res = cli.Get("/");
  15026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15027. EXPECT_EQ(StatusCode::OK_200, res->status);
  15028. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15029. }
  15030. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15031. Client cli("https://yahoo.com");
  15032. auto res = cli.Get("/");
  15033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15034. ASSERT_FALSE(!res);
  15035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15036. ASSERT_FALSE(res == nullptr);
  15037. ASSERT_TRUE(res != nullptr);
  15038. EXPECT_EQ(Error::Success, res.error());
  15039. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15040. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15041. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15042. cli.set_follow_location(true);
  15043. res = cli.Get("/");
  15044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15045. EXPECT_EQ(Error::Success, res.error());
  15046. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15047. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15048. EXPECT_EQ(StatusCode::OK_200, res->status);
  15049. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15050. }
  15051. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15052. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15053. Client cli("https://cdnjs.cloudflare.com");
  15054. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15055. Headers{{"Accept-Encoding", "br"}});
  15056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15057. EXPECT_EQ(StatusCode::OK_200, res->status);
  15058. EXPECT_EQ(287630U, res->body.size());
  15059. EXPECT_EQ("application/javascript; charset=utf-8",
  15060. res->get_header_value("Content-Type"));
  15061. }
  15062. #endif
  15063. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15064. #undef REDIR_HOST // Silence compiler warning
  15065. #define REDIR_HOST "https://httpbingo.org"
  15066. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15067. Client cli(REDIR_HOST);
  15068. cli.set_follow_location(true);
  15069. auto res =
  15070. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15072. EXPECT_EQ(StatusCode::OK_200, res->status);
  15073. }
  15074. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15075. Client cli(REDIR_HOST);
  15076. cli.set_follow_location(true);
  15077. Params params;
  15078. params.emplace("url", "http://example.com");
  15079. params.emplace("status_code", "302");
  15080. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15082. EXPECT_EQ(StatusCode::OK_200, res->status);
  15083. }
  15084. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15085. Client cli(REDIR_HOST);
  15086. cli.set_follow_location(true);
  15087. Params params;
  15088. params.emplace("url", "http://example.com");
  15089. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15091. EXPECT_EQ(StatusCode::OK_200, res->status);
  15092. }
  15093. TEST(HttpToHttpsRedirectTest, CertFile) {
  15094. auto ssl_port = PORT + 1;
  15095. Server svr;
  15096. ASSERT_TRUE(svr.is_valid());
  15097. svr.Get("/index", [&](const Request &, Response &res) {
  15098. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15099. "/index");
  15100. svr.stop();
  15101. });
  15102. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15103. ASSERT_TRUE(ssl_svr.is_valid());
  15104. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15105. res.set_content("test", "text/plain");
  15106. ssl_svr.stop();
  15107. });
  15108. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15109. thread t2 =
  15110. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15111. auto se = detail::scope_exit([&] {
  15112. t2.join();
  15113. t.join();
  15114. ASSERT_FALSE(svr.is_running());
  15115. });
  15116. svr.wait_until_ready();
  15117. ssl_svr.wait_until_ready();
  15118. Client cli("127.0.0.1", PORT);
  15119. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15120. cli.enable_server_certificate_verification(true);
  15121. cli.set_follow_location(true);
  15122. cli.set_connection_timeout(30);
  15123. auto res = cli.Get("/index");
  15124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15125. ASSERT_EQ(StatusCode::OK_200, res->status);
  15126. }
  15127. TEST(SSLClientRedirectTest, CertFile) {
  15128. auto ssl_port = PORT + 1;
  15129. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15130. ASSERT_TRUE(ssl_svr1.is_valid());
  15131. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15132. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15133. "/index");
  15134. ssl_svr1.stop();
  15135. });
  15136. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15137. ASSERT_TRUE(ssl_svr2.is_valid());
  15138. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15139. res.set_content("test", "text/plain");
  15140. ssl_svr2.stop();
  15141. });
  15142. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15143. thread t2 =
  15144. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15145. auto se = detail::scope_exit([&] {
  15146. t2.join();
  15147. t.join();
  15148. ASSERT_FALSE(ssl_svr1.is_running());
  15149. });
  15150. ssl_svr1.wait_until_ready();
  15151. ssl_svr2.wait_until_ready();
  15152. SSLClient cli("127.0.0.1", PORT);
  15153. std::string cert;
  15154. read_file(SERVER_CERT2_FILE, cert);
  15155. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15156. cli.enable_server_certificate_verification(true);
  15157. cli.set_follow_location(true);
  15158. cli.set_connection_timeout(30);
  15159. auto res = cli.Get("/index");
  15160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15161. ASSERT_EQ(StatusCode::OK_200, res->status);
  15162. }
  15163. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15164. // another port, so the client follows it with a new client.
  15165. static Result GetThroughTlsRedirectToDifferentPort(
  15166. const std::function<void(SSLClient &)> &setup,
  15167. const char *target_cert = SERVER_CERT2_FILE,
  15168. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15169. auto ssl_port = PORT + 1;
  15170. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15171. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15172. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15173. "/index");
  15174. });
  15175. SSLServer ssl_svr2(target_cert, target_key);
  15176. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15177. res.set_content("test", "text/plain");
  15178. });
  15179. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15180. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15181. auto se = detail::scope_exit([&] {
  15182. ssl_svr2.stop();
  15183. ssl_svr1.stop();
  15184. t2.join();
  15185. t.join();
  15186. });
  15187. ssl_svr1.wait_until_ready();
  15188. ssl_svr2.wait_until_ready();
  15189. SSLClient cli("127.0.0.1", PORT);
  15190. cli.set_follow_location(true);
  15191. cli.set_connection_timeout(30);
  15192. setup(cli);
  15193. return cli.Get("/index");
  15194. }
  15195. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15196. auto calls = 0;
  15197. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15198. cli.enable_server_certificate_verification(false);
  15199. // Accept the first server only.
  15200. cli.set_session_verifier([&](tls::session_t) {
  15201. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15202. : SSLVerifierResponse::CertificateRejected;
  15203. });
  15204. });
  15205. ASSERT_FALSE(res);
  15206. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15207. EXPECT_EQ(2, calls);
  15208. }
  15209. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15210. std::string pinned;
  15211. auto res = GetThroughTlsRedirectToDifferentPort(
  15212. [&](SSLClient &cli) {
  15213. cli.enable_server_certificate_verification(false);
  15214. // Pin the first certificate seen.
  15215. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15216. if (pinned.empty()) { pinned = ctx.serial(); }
  15217. return ctx.serial() == pinned;
  15218. });
  15219. },
  15220. // A certificate other than the first server's.
  15221. SERVER_CERT_FILE);
  15222. EXPECT_FALSE(res);
  15223. EXPECT_FALSE(pinned.empty());
  15224. }
  15225. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15226. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15227. std::string cert;
  15228. read_file(SERVER_CERT2_FILE, cert);
  15229. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15230. });
  15231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15232. EXPECT_EQ(StatusCode::OK_200, res->status);
  15233. }
  15234. // The target's certificate is signed by the root CA, which the first server's
  15235. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15236. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15237. auto res = GetThroughTlsRedirectToDifferentPort(
  15238. [](SSLClient &cli) {
  15239. std::string root_ca, cert;
  15240. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15241. read_file(SERVER_CERT2_FILE, cert);
  15242. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15243. cli.load_ca_cert_store(cert.data(), cert.size());
  15244. cli.enable_server_hostname_verification(false);
  15245. },
  15246. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15248. EXPECT_EQ(StatusCode::OK_200, res->status);
  15249. }
  15250. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15251. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15252. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15253. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15254. auto res = GetThroughTlsRedirectToDifferentPort(
  15255. [](SSLClient &cli) {
  15256. std::string root_ca, cert;
  15257. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15258. read_file(SERVER_CERT2_FILE, cert);
  15259. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15260. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15261. cli.enable_server_hostname_verification(false);
  15262. },
  15263. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15264. ASSERT_FALSE(res);
  15265. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15266. }
  15267. #endif
  15268. #endif
  15269. #ifdef CPPHTTPLIB_SSL_ENABLED
  15270. // Test that set_ca_cert_store() skips system certs (consistent with
  15271. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15272. // should be trusted - system certs should NOT be loaded.
  15273. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15274. // Load a specific cert that is NOT a system CA cert
  15275. std::string cert;
  15276. read_file(SERVER_CERT2_FILE, cert);
  15277. SSLClient cli("google.com");
  15278. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15279. cli.enable_server_certificate_verification(true);
  15280. // This should FAIL because:
  15281. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15282. // 2. System certs should NOT be loaded when custom store is set
  15283. // If system certs WERE loaded, this would succeed
  15284. auto res = cli.Get("/");
  15285. ASSERT_FALSE(res);
  15286. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15287. }
  15288. // Same as above, but through the native store handle path. Regression test:
  15289. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15290. // merged system certs into the user-provided store.
  15291. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15292. std::string cert;
  15293. read_file(SERVER_CERT2_FILE, cert);
  15294. SSLClient cli("google.com");
  15295. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15296. cli.enable_server_certificate_verification(true);
  15297. auto res = cli.Get("/");
  15298. ASSERT_FALSE(res);
  15299. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15300. }
  15301. // A custom store set via the native handle must still verify a server whose
  15302. // cert it does contain.
  15303. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15304. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15305. ASSERT_TRUE(svr.is_valid());
  15306. svr.Get("/test", [&](const Request &, Response &res) {
  15307. res.set_content("test", "text/plain");
  15308. });
  15309. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15310. auto se = detail::scope_exit([&] {
  15311. svr.stop();
  15312. t.join();
  15313. ASSERT_FALSE(svr.is_running());
  15314. });
  15315. svr.wait_until_ready();
  15316. SSLClient cli("127.0.0.1", PORT);
  15317. std::string cert;
  15318. read_file(SERVER_CERT2_FILE, cert);
  15319. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15320. cli.enable_server_certificate_verification(true);
  15321. cli.set_connection_timeout(30);
  15322. auto res = cli.Get("/test");
  15323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15324. ASSERT_EQ(StatusCode::OK_200, res->status);
  15325. }
  15326. // CA certs loaded through the universal Client must be transferred to the
  15327. // client created internally for following an HTTPS redirect. Regression test:
  15328. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15329. // the CA data for redirect transfer.
  15330. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15331. auto ssl_port = PORT + 1;
  15332. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15333. ASSERT_TRUE(ssl_svr1.is_valid());
  15334. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15335. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15336. "/index");
  15337. });
  15338. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15339. ASSERT_TRUE(ssl_svr2.is_valid());
  15340. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15341. res.set_content("test", "text/plain");
  15342. });
  15343. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15344. thread t2 =
  15345. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15346. auto se = detail::scope_exit([&] {
  15347. ssl_svr2.stop();
  15348. ssl_svr1.stop();
  15349. t2.join();
  15350. t.join();
  15351. ASSERT_FALSE(ssl_svr1.is_running());
  15352. });
  15353. ssl_svr1.wait_until_ready();
  15354. ssl_svr2.wait_until_ready();
  15355. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15356. std::string cert;
  15357. read_file(SERVER_CERT2_FILE, cert);
  15358. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15359. cli.enable_server_certificate_verification(true);
  15360. cli.set_follow_location(true);
  15361. cli.set_connection_timeout(30);
  15362. auto res = cli.Get("/index");
  15363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15364. ASSERT_EQ(StatusCode::OK_200, res->status);
  15365. }
  15366. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15367. // so a host signed by a system CA verifies even though a custom CA is set
  15368. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15369. std::string cert;
  15370. read_file(SERVER_CERT2_FILE, cert);
  15371. SSLClient cli("google.com");
  15372. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15373. cli.enable_system_ca(true);
  15374. cli.enable_server_certificate_verification(true);
  15375. auto res = cli.Get("/");
  15376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15377. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15378. }
  15379. // The custom CA remains effective when combined with the system CA
  15380. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15381. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15382. ASSERT_TRUE(svr.is_valid());
  15383. svr.Get("/test", [&](const Request &, Response &res) {
  15384. res.set_content("test", "text/plain");
  15385. });
  15386. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15387. auto se = detail::scope_exit([&] {
  15388. svr.stop();
  15389. t.join();
  15390. ASSERT_FALSE(svr.is_running());
  15391. });
  15392. svr.wait_until_ready();
  15393. SSLClient cli("127.0.0.1", PORT);
  15394. std::string cert;
  15395. read_file(SERVER_CERT2_FILE, cert);
  15396. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15397. cli.enable_system_ca(true);
  15398. cli.enable_server_certificate_verification(true);
  15399. cli.set_connection_timeout(30);
  15400. auto res = cli.Get("/test");
  15401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15402. ASSERT_EQ(StatusCode::OK_200, res->status);
  15403. }
  15404. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15405. // skip chain verification entirely (only the certificate identity was
  15406. // checked), so a server presenting an untrusted certificate with a matching
  15407. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15408. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15409. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15410. ASSERT_TRUE(svr.is_valid());
  15411. svr.Get("/test", [&](const Request &, Response &res) {
  15412. res.set_content("test", "text/plain");
  15413. });
  15414. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15415. auto se = detail::scope_exit([&] {
  15416. svr.stop();
  15417. t.join();
  15418. ASSERT_FALSE(svr.is_running());
  15419. });
  15420. svr.wait_until_ready();
  15421. SSLClient cli("127.0.0.1", PORT);
  15422. std::string cert;
  15423. // A trusted CA that did not sign the server certificate. The server cert
  15424. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15425. // this connection.
  15426. read_file(CLIENT_CA_CERT_FILE, cert);
  15427. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15428. cli.enable_server_certificate_verification(true);
  15429. cli.set_connection_timeout(30);
  15430. auto res = cli.Get("/test");
  15431. ASSERT_FALSE(res);
  15432. }
  15433. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15434. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15435. // CA that failed to come through fails verification instead of trusting them.
  15436. // (wolfSSL does not list the system CAs it loaded.)
  15437. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15438. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15439. ASSERT_TRUE(svr.is_valid());
  15440. auto port = svr.bind_to_any_port("127.0.0.1");
  15441. ASSERT_LT(0, port);
  15442. thread t = thread([&] { svr.listen_after_bind(); });
  15443. auto se = detail::scope_exit([&] {
  15444. svr.stop();
  15445. t.join();
  15446. ASSERT_FALSE(svr.is_running());
  15447. });
  15448. svr.wait_until_ready();
  15449. // The CAs a client trusts once its first request has loaded them
  15450. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15451. Client cli("https://127.0.0.1:" + std::to_string(port));
  15452. setup(cli);
  15453. cli.Get("/");
  15454. return tls::get_ca_names(cli.tls_context()).size();
  15455. };
  15456. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15457. EXPECT_EQ(0u,
  15458. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15459. }
  15460. #endif
  15461. // A TLS setting changed between requests applies to the next one, not just to
  15462. // the next connection
  15463. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15464. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15465. ASSERT_TRUE(svr.is_valid());
  15466. svr.Get("/", [](const Request &req, Response &res) {
  15467. res.set_content(std::to_string(req.remote_port), "text/plain");
  15468. });
  15469. auto port = svr.bind_to_any_port("127.0.0.1");
  15470. ASSERT_LT(0, port);
  15471. thread t = thread([&] { svr.listen_after_bind(); });
  15472. auto se = detail::scope_exit([&] {
  15473. svr.stop();
  15474. t.join();
  15475. ASSERT_FALSE(svr.is_running());
  15476. });
  15477. svr.wait_until_ready();
  15478. SSLClient cli("127.0.0.1", port);
  15479. cli.set_keep_alive(true);
  15480. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15481. cli.enable_server_certificate_verification(false);
  15482. // The port the request went out from, so a new one means a new connection
  15483. auto client_port = [&] {
  15484. auto res = cli.Get("/");
  15485. return res ? res->body : std::string();
  15486. };
  15487. auto last = client_port();
  15488. ASSERT_FALSE(last.empty());
  15489. // Setting a value it already has keeps the connection
  15490. cli.enable_server_certificate_verification(false);
  15491. cli.enable_server_hostname_verification(true);
  15492. EXPECT_EQ(last, client_port());
  15493. cli.enable_server_certificate_verification(true);
  15494. auto res = cli.Get("/");
  15495. EXPECT_FALSE(res);
  15496. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15497. std::string ca;
  15498. read_file(SERVER_CERT2_FILE, ca);
  15499. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15500. last = client_port();
  15501. ASSERT_FALSE(last.empty());
  15502. std::vector<std::function<void()>> setters = {
  15503. [&] { cli.enable_server_hostname_verification(false); },
  15504. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15505. [&] {
  15506. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15507. },
  15508. [&] {
  15509. cli.set_server_certificate_verifier(
  15510. [](const tls::VerifyContext &) { return true; });
  15511. },
  15512. [&] {
  15513. cli.set_session_verifier(
  15514. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15515. },
  15516. };
  15517. for (const auto &setter : setters) {
  15518. setter();
  15519. auto next = client_port();
  15520. ASSERT_FALSE(next.empty());
  15521. EXPECT_NE(last, next);
  15522. last = next;
  15523. }
  15524. cli.set_session_verifier(
  15525. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15526. auto handle = cli.open_stream("GET", "/");
  15527. EXPECT_FALSE(handle.is_valid());
  15528. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15529. }
  15530. // A PEM given to create_ca_store() needs no NUL after it
  15531. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15532. std::string pem;
  15533. read_file(SERVER_CERT2_FILE, pem);
  15534. auto buf = pem + "X";
  15535. auto store = tls::create_ca_store(buf.data(), pem.size());
  15536. EXPECT_TRUE(store != nullptr);
  15537. SSLClient cli("localhost");
  15538. cli.set_ca_cert_store(store);
  15539. }
  15540. // enable_system_ca(false) prevents system CA loading entirely
  15541. TEST(SSLClientTest, DisableSystemCa_Online) {
  15542. SSLClient cli("google.com");
  15543. cli.enable_system_ca(false);
  15544. cli.enable_server_certificate_verification(true);
  15545. auto res = cli.Get("/");
  15546. ASSERT_FALSE(res);
  15547. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15548. // itself when the CA chain is empty
  15549. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15550. res.error() == Error::SSLConnection);
  15551. }
  15552. // The universal Client forwards enable_system_ca()
  15553. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15554. std::string cert;
  15555. read_file(SERVER_CERT2_FILE, cert);
  15556. Client cli("https://google.com");
  15557. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15558. cli.enable_system_ca(true);
  15559. cli.enable_server_certificate_verification(true);
  15560. auto res = cli.Get("/");
  15561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15562. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15563. }
  15564. // The system CA policy must carry over to the client created internally for
  15565. // following a cross-host HTTPS redirect
  15566. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15567. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15568. ASSERT_TRUE(svr.is_valid());
  15569. svr.Get("/index", [&](const Request &, Response &res) {
  15570. res.set_redirect("https://www.google.com/");
  15571. });
  15572. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15573. auto se = detail::scope_exit([&] {
  15574. svr.stop();
  15575. t.join();
  15576. ASSERT_FALSE(svr.is_running());
  15577. });
  15578. svr.wait_until_ready();
  15579. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15580. std::string cert;
  15581. read_file(SERVER_CERT2_FILE, cert);
  15582. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15583. cli.enable_system_ca(true);
  15584. cli.enable_server_certificate_verification(true);
  15585. cli.set_follow_location(true);
  15586. cli.set_connection_timeout(30);
  15587. // Receiving any response proves the redirect client completed the TLS
  15588. // handshake with a system-CA-signed host
  15589. auto res = cli.Get("/index");
  15590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15591. }
  15592. TEST(MultipartFormDataTest, LargeData) {
  15593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15594. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15595. const ContentReader &content_reader) {
  15596. if (req.is_multipart_form_data()) {
  15597. std::vector<FormData> items;
  15598. content_reader(
  15599. [&](const FormData &file) {
  15600. items.push_back(file);
  15601. return true;
  15602. },
  15603. [&](const char *data, size_t data_length) {
  15604. items.back().content.append(data, data_length);
  15605. return true;
  15606. });
  15607. EXPECT_TRUE(std::string(items[0].name) == "document");
  15608. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15609. EXPECT_TRUE(items[0].filename == "2MB_data");
  15610. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15611. EXPECT_TRUE(items[1].name == "hello");
  15612. EXPECT_TRUE(items[1].content == "world");
  15613. EXPECT_TRUE(items[1].filename == "");
  15614. EXPECT_TRUE(items[1].content_type == "");
  15615. } else {
  15616. std::string body;
  15617. content_reader([&](const char *data, size_t data_length) {
  15618. body.append(data, data_length);
  15619. return true;
  15620. });
  15621. }
  15622. });
  15623. auto port = svr.bind_to_any_port(HOST);
  15624. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15625. auto se = detail::scope_exit([&] {
  15626. svr.stop();
  15627. t.join();
  15628. ASSERT_FALSE(svr.is_running());
  15629. });
  15630. svr.wait_until_ready();
  15631. {
  15632. std::string data(1024 * 1024 * 2, '.');
  15633. std::stringstream buffer;
  15634. buffer << data;
  15635. SSLClient cli(HOST, port);
  15636. cli.enable_server_certificate_verification(false);
  15637. UploadFormDataItems items{
  15638. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15639. {"hello", "world", "", ""},
  15640. };
  15641. auto res = cli.Post("/post", items);
  15642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15643. ASSERT_EQ(StatusCode::OK_200, res->status);
  15644. }
  15645. }
  15646. TEST(MultipartFormDataTest, DataProviderItems) {
  15647. std::random_device seed_gen;
  15648. std::mt19937 random(seed_gen());
  15649. std::string rand1;
  15650. rand1.resize(1000);
  15651. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15652. std::string rand2;
  15653. rand2.resize(3000);
  15654. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15655. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15656. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15657. const ContentReader &content_reader) {
  15658. ASSERT_FALSE(req.is_multipart_form_data());
  15659. std::string body;
  15660. content_reader([&](const char *data, size_t data_length) {
  15661. body.append(data, data_length);
  15662. return true;
  15663. });
  15664. EXPECT_EQ(body, "");
  15665. });
  15666. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15667. const ContentReader &content_reader) {
  15668. ASSERT_TRUE(req.is_multipart_form_data());
  15669. std::vector<FormData> items;
  15670. content_reader(
  15671. [&](const FormData &file) {
  15672. items.push_back(file);
  15673. return true;
  15674. },
  15675. [&](const char *data, size_t data_length) {
  15676. items.back().content.append(data, data_length);
  15677. return true;
  15678. });
  15679. ASSERT_TRUE(items.size() == 2);
  15680. EXPECT_EQ(std::string(items[0].name), "name1");
  15681. EXPECT_EQ(items[0].content, "Testing123");
  15682. EXPECT_EQ(items[0].filename, "filename1");
  15683. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15684. EXPECT_EQ(items[1].name, "name2");
  15685. EXPECT_EQ(items[1].content, "Testing456");
  15686. EXPECT_EQ(items[1].filename, "");
  15687. EXPECT_EQ(items[1].content_type, "");
  15688. });
  15689. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15690. const ContentReader &content_reader) {
  15691. ASSERT_TRUE(req.is_multipart_form_data());
  15692. std::vector<FormData> items;
  15693. content_reader(
  15694. [&](const FormData &file) {
  15695. items.push_back(file);
  15696. return true;
  15697. },
  15698. [&](const char *data, size_t data_length) {
  15699. items.back().content.append(data, data_length);
  15700. return true;
  15701. });
  15702. ASSERT_TRUE(items.size() == 2);
  15703. EXPECT_EQ(items[0].name, "name3");
  15704. EXPECT_EQ(items[0].content, rand1);
  15705. EXPECT_EQ(items[0].filename, "filename3");
  15706. EXPECT_EQ(items[0].content_type, "");
  15707. EXPECT_EQ(items[1].name, "name4");
  15708. EXPECT_EQ(items[1].content, rand2);
  15709. EXPECT_EQ(items[1].filename, "filename4");
  15710. EXPECT_EQ(items[1].content_type, "");
  15711. });
  15712. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15713. const ContentReader &content_reader) {
  15714. ASSERT_TRUE(req.is_multipart_form_data());
  15715. std::vector<FormData> items;
  15716. content_reader(
  15717. [&](const FormData &file) {
  15718. items.push_back(file);
  15719. return true;
  15720. },
  15721. [&](const char *data, size_t data_length) {
  15722. items.back().content.append(data, data_length);
  15723. return true;
  15724. });
  15725. ASSERT_TRUE(items.size() == 4);
  15726. EXPECT_EQ(std::string(items[0].name), "name1");
  15727. EXPECT_EQ(items[0].content, "Testing123");
  15728. EXPECT_EQ(items[0].filename, "filename1");
  15729. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15730. EXPECT_EQ(items[1].name, "name2");
  15731. EXPECT_EQ(items[1].content, "Testing456");
  15732. EXPECT_EQ(items[1].filename, "");
  15733. EXPECT_EQ(items[1].content_type, "");
  15734. EXPECT_EQ(items[2].name, "name3");
  15735. EXPECT_EQ(items[2].content, rand1);
  15736. EXPECT_EQ(items[2].filename, "filename3");
  15737. EXPECT_EQ(items[2].content_type, "");
  15738. EXPECT_EQ(items[3].name, "name4");
  15739. EXPECT_EQ(items[3].content, rand2);
  15740. EXPECT_EQ(items[3].filename, "filename4");
  15741. EXPECT_EQ(items[3].content_type, "");
  15742. });
  15743. auto port = svr.bind_to_any_port("localhost");
  15744. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15745. auto se = detail::scope_exit([&] {
  15746. svr.stop();
  15747. t.join();
  15748. ASSERT_FALSE(svr.is_running());
  15749. });
  15750. svr.wait_until_ready();
  15751. {
  15752. SSLClient cli("localhost", port);
  15753. cli.enable_server_certificate_verification(false);
  15754. UploadFormDataItems items{
  15755. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15756. {"name2", "Testing456", "", ""}, // not a file
  15757. };
  15758. {
  15759. auto res = cli.Post("/post-none", {}, {}, {});
  15760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15761. ASSERT_EQ(StatusCode::OK_200, res->status);
  15762. }
  15763. FormDataProviderItems providers;
  15764. {
  15765. auto res =
  15766. cli.Post("/post-items", {}, items, providers); // empty providers
  15767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15768. ASSERT_EQ(StatusCode::OK_200, res->status);
  15769. }
  15770. providers.push_back({"name3",
  15771. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15772. // test the offset is given correctly at each step
  15773. if (!offset)
  15774. sink.os.write(rand1.data(), 30);
  15775. else if (offset == 30)
  15776. sink.os.write(rand1.data() + 30, 300);
  15777. else if (offset == 330)
  15778. sink.os.write(rand1.data() + 330, 670);
  15779. else if (offset == rand1.size())
  15780. sink.done();
  15781. return true;
  15782. },
  15783. "filename3",
  15784. {}});
  15785. providers.push_back({"name4",
  15786. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15787. // test the offset is given correctly at each step
  15788. if (!offset)
  15789. sink.os.write(rand2.data(), 2000);
  15790. else if (offset == 2000)
  15791. sink.os.write(rand2.data() + 2000, 1);
  15792. else if (offset == 2001)
  15793. sink.os.write(rand2.data() + 2001, 999);
  15794. else if (offset == rand2.size())
  15795. sink.done();
  15796. return true;
  15797. },
  15798. "filename4",
  15799. {}});
  15800. {
  15801. auto res = cli.Post("/post-providers", {}, {}, providers);
  15802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15803. ASSERT_EQ(StatusCode::OK_200, res->status);
  15804. }
  15805. {
  15806. auto res = cli.Post("/post-both", {}, items, providers);
  15807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15808. ASSERT_EQ(StatusCode::OK_200, res->status);
  15809. }
  15810. }
  15811. }
  15812. TEST(MultipartFormDataTest, BadHeader) {
  15813. Server svr;
  15814. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15815. res.set_content("ok", "text/plain");
  15816. });
  15817. thread t = thread([&] { svr.listen(HOST, PORT); });
  15818. auto se = detail::scope_exit([&] {
  15819. svr.stop();
  15820. t.join();
  15821. ASSERT_FALSE(svr.is_running());
  15822. });
  15823. svr.wait_until_ready();
  15824. const std::string body =
  15825. "This is the preamble. It is to be ignored, though it\r\n"
  15826. "is a handy place for composition agents to include an\r\n"
  15827. "explanatory note to non-MIME conformant readers.\r\n"
  15828. "\r\n"
  15829. "\r\n"
  15830. "--simple boundary\r\n"
  15831. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15832. ": BAD...\r\n"
  15833. "\r\n"
  15834. "value1\r\n"
  15835. "--simple boundary\r\n"
  15836. "Content-Disposition: form-data; name=\"field2\"; "
  15837. "filename=\"example.txt\"\r\n"
  15838. "\r\n"
  15839. "value2\r\n"
  15840. "--simple boundary--\r\n"
  15841. "This is the epilogue. It is also to be ignored.\r\n";
  15842. std::string content_type =
  15843. R"(multipart/form-data; boundary="simple boundary")";
  15844. Client cli(HOST, PORT);
  15845. auto res = cli.Post("/post", body, content_type.c_str());
  15846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15847. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15848. }
  15849. TEST(MultipartFormDataTest, WithPreamble) {
  15850. Server svr;
  15851. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15852. res.set_content("ok", "text/plain");
  15853. });
  15854. thread t = thread([&] { svr.listen(HOST, PORT); });
  15855. auto se = detail::scope_exit([&] {
  15856. svr.stop();
  15857. t.join();
  15858. ASSERT_FALSE(svr.is_running());
  15859. });
  15860. svr.wait_until_ready();
  15861. const std::string body =
  15862. "This is the preamble. It is to be ignored, though it\r\n"
  15863. "is a handy place for composition agents to include an\r\n"
  15864. "explanatory note to non-MIME conformant readers.\r\n"
  15865. "\r\n"
  15866. "\r\n"
  15867. "--simple boundary\r\n"
  15868. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15869. "\r\n"
  15870. "value1\r\n"
  15871. "--simple boundary\r\n"
  15872. "Content-Disposition: form-data; name=\"field2\"; "
  15873. "filename=\"example.txt\"\r\n"
  15874. "\r\n"
  15875. "value2\r\n"
  15876. "--simple boundary--\r\n"
  15877. "This is the epilogue. It is also to be ignored.\r\n";
  15878. std::string content_type =
  15879. R"(multipart/form-data; boundary="simple boundary")";
  15880. Client cli(HOST, PORT);
  15881. auto res = cli.Post("/post", body, content_type.c_str());
  15882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15883. EXPECT_EQ(StatusCode::OK_200, res->status);
  15884. }
  15885. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15886. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15887. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15888. const ContentReader &content_reader) {
  15889. if (req.is_multipart_form_data()) {
  15890. std::vector<FormData> items;
  15891. content_reader(
  15892. [&](const FormData &file) {
  15893. items.push_back(file);
  15894. return true;
  15895. },
  15896. [&](const char *data, size_t data_length) {
  15897. items.back().content.append(data, data_length);
  15898. return true;
  15899. });
  15900. EXPECT_TRUE(std::string(items[0].name) == "document");
  15901. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15902. EXPECT_TRUE(items[0].filename == "2MB_data");
  15903. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15904. EXPECT_TRUE(items[1].name == "hello");
  15905. EXPECT_TRUE(items[1].content == "world");
  15906. EXPECT_TRUE(items[1].filename == "");
  15907. EXPECT_TRUE(items[1].content_type == "");
  15908. } else {
  15909. std::string body;
  15910. content_reader([&](const char *data, size_t data_length) {
  15911. body.append(data, data_length);
  15912. return true;
  15913. });
  15914. }
  15915. });
  15916. auto port = svr.bind_to_any_port("localhost");
  15917. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15918. auto se = detail::scope_exit([&] {
  15919. svr.stop();
  15920. t.join();
  15921. ASSERT_FALSE(svr.is_running());
  15922. });
  15923. svr.wait_until_ready();
  15924. {
  15925. std::string data(1024 * 1024 * 2, '.');
  15926. std::stringstream buffer;
  15927. buffer << data;
  15928. SSLClient cli("localhost", port);
  15929. cli.enable_server_certificate_verification(false);
  15930. UploadFormDataItems items{
  15931. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15932. {"hello", "world", "", ""},
  15933. };
  15934. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15936. ASSERT_EQ(StatusCode::OK_200, res->status);
  15937. }
  15938. }
  15939. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15940. std::string data(1024 * 1024 * 2, '&');
  15941. std::stringstream buffer;
  15942. buffer << data;
  15943. Client cli("https://localhost:8080");
  15944. UploadFormDataItems items{
  15945. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15946. {"hello", "world", "", ""},
  15947. };
  15948. for (const char &c : " \t\r\n") {
  15949. auto res =
  15950. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15951. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15952. ASSERT_FALSE(res);
  15953. }
  15954. }
  15955. TEST(MultipartFormDataTest, PutFormData) {
  15956. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15957. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15958. const ContentReader &content_reader) {
  15959. if (req.is_multipart_form_data()) {
  15960. std::vector<FormData> items;
  15961. content_reader(
  15962. [&](const FormData &file) {
  15963. items.push_back(file);
  15964. return true;
  15965. },
  15966. [&](const char *data, size_t data_length) {
  15967. items.back().content.append(data, data_length);
  15968. return true;
  15969. });
  15970. EXPECT_TRUE(std::string(items[0].name) == "document");
  15971. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15972. EXPECT_TRUE(items[0].filename == "2MB_data");
  15973. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15974. EXPECT_TRUE(items[1].name == "hello");
  15975. EXPECT_TRUE(items[1].content == "world");
  15976. EXPECT_TRUE(items[1].filename == "");
  15977. EXPECT_TRUE(items[1].content_type == "");
  15978. } else {
  15979. std::string body;
  15980. content_reader([&](const char *data, size_t data_length) {
  15981. body.append(data, data_length);
  15982. return true;
  15983. });
  15984. }
  15985. });
  15986. auto port = svr.bind_to_any_port("localhost");
  15987. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15988. auto se = detail::scope_exit([&] {
  15989. svr.stop();
  15990. t.join();
  15991. ASSERT_FALSE(svr.is_running());
  15992. });
  15993. svr.wait_until_ready();
  15994. {
  15995. std::string data(1024 * 1024 * 2, '&');
  15996. std::stringstream buffer;
  15997. buffer << data;
  15998. SSLClient cli("localhost", port);
  15999. cli.enable_server_certificate_verification(false);
  16000. UploadFormDataItems items{
  16001. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16002. {"hello", "world", "", ""},
  16003. };
  16004. auto res = cli.Put("/put", items);
  16005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16006. ASSERT_EQ(StatusCode::OK_200, res->status);
  16007. }
  16008. }
  16009. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16011. svr.Put("/put_customboundary",
  16012. [&](const Request &req, const Response & /*res*/,
  16013. const ContentReader &content_reader) {
  16014. if (req.is_multipart_form_data()) {
  16015. std::vector<FormData> items;
  16016. content_reader(
  16017. [&](const FormData &file) {
  16018. items.push_back(file);
  16019. return true;
  16020. },
  16021. [&](const char *data, size_t data_length) {
  16022. items.back().content.append(data, data_length);
  16023. return true;
  16024. });
  16025. EXPECT_TRUE(std::string(items[0].name) == "document");
  16026. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16027. EXPECT_TRUE(items[0].filename == "2MB_data");
  16028. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16029. EXPECT_TRUE(items[1].name == "hello");
  16030. EXPECT_TRUE(items[1].content == "world");
  16031. EXPECT_TRUE(items[1].filename == "");
  16032. EXPECT_TRUE(items[1].content_type == "");
  16033. } else {
  16034. std::string body;
  16035. content_reader([&](const char *data, size_t data_length) {
  16036. body.append(data, data_length);
  16037. return true;
  16038. });
  16039. }
  16040. });
  16041. auto port = svr.bind_to_any_port("localhost");
  16042. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16043. auto se = detail::scope_exit([&] {
  16044. svr.stop();
  16045. t.join();
  16046. ASSERT_FALSE(svr.is_running());
  16047. });
  16048. svr.wait_until_ready();
  16049. {
  16050. std::string data(1024 * 1024 * 2, '&');
  16051. std::stringstream buffer;
  16052. buffer << data;
  16053. SSLClient cli("localhost", port);
  16054. cli.enable_server_certificate_verification(false);
  16055. UploadFormDataItems items{
  16056. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16057. {"hello", "world", "", ""},
  16058. };
  16059. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16061. ASSERT_EQ(StatusCode::OK_200, res->status);
  16062. }
  16063. }
  16064. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16065. std::string data(1024 * 1024 * 2, '&');
  16066. std::stringstream buffer;
  16067. buffer << data;
  16068. Client cli("https://localhost:8080");
  16069. cli.enable_server_certificate_verification(false);
  16070. UploadFormDataItems items{
  16071. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16072. {"hello", "world", "", ""},
  16073. };
  16074. for (const char &c : " \t\r\n") {
  16075. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16076. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16077. ASSERT_FALSE(res);
  16078. }
  16079. }
  16080. TEST(MultipartFormDataTest, AlternateFilename) {
  16081. auto handled = false;
  16082. Server svr;
  16083. svr.Post("/test", [&](const Request &req, Response &res) {
  16084. ASSERT_EQ(2u, req.form.files.size());
  16085. ASSERT_EQ(1u, req.form.fields.size());
  16086. // Test files
  16087. const auto &file1 = req.form.get_file("file1");
  16088. ASSERT_EQ("file1", file1.name);
  16089. ASSERT_EQ("A.txt", file1.filename);
  16090. ASSERT_EQ("text/plain", file1.content_type);
  16091. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16092. const auto &file2 = req.form.get_file("file2");
  16093. ASSERT_EQ("file2", file2.name);
  16094. ASSERT_EQ("a.html", file2.filename);
  16095. ASSERT_EQ("text/html", file2.content_type);
  16096. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16097. file2.content);
  16098. // Test text field
  16099. const auto &text = req.form.get_field("text");
  16100. ASSERT_EQ("text default", text);
  16101. res.set_content("ok", "text/plain");
  16102. handled = true;
  16103. });
  16104. thread t = thread([&] { svr.listen(HOST, PORT); });
  16105. auto se = detail::scope_exit([&] {
  16106. svr.stop();
  16107. t.join();
  16108. ASSERT_FALSE(svr.is_running());
  16109. ASSERT_TRUE(handled);
  16110. });
  16111. svr.wait_until_ready();
  16112. auto req = "POST /test HTTP/1.1\r\n"
  16113. "Host: localhost\r\n"
  16114. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16115. "Content-Length: 399\r\n"
  16116. "\r\n"
  16117. "----------\r\n"
  16118. "Content-Disposition: form-data; name=\"text\"\r\n"
  16119. "\r\n"
  16120. "text default\r\n"
  16121. "----------\r\n"
  16122. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16123. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16124. "Content-Type: text/plain\r\n"
  16125. "\r\n"
  16126. "Content of a.txt.\r\n"
  16127. "\r\n"
  16128. "----------\r\n"
  16129. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16130. "\"a.html\"\r\n"
  16131. "Content-Type: text/html\r\n"
  16132. "\r\n"
  16133. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16134. "\r\n"
  16135. "------------\r\n";
  16136. ASSERT_TRUE(send_request(1, req));
  16137. }
  16138. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16139. auto handled = false;
  16140. Server svr;
  16141. svr.Post("/test", [&](const Request &req, Response &res) {
  16142. // Case-insensitive "utf-8''" prefix with a long value
  16143. const auto &file = req.form.get_file("file1");
  16144. ASSERT_EQ("file1", file.name);
  16145. // 8000 chars exercises both the Content-Disposition parser and the
  16146. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16147. // Prior to the fix, std::regex_match on this header would cause O(N)
  16148. // stack recursion in libstdc++, leading to SIGSEGV.
  16149. std::string expected_filename(8000, 'A');
  16150. ASSERT_EQ(expected_filename, file.filename);
  16151. res.set_content("ok", "text/plain");
  16152. handled = true;
  16153. });
  16154. thread t = thread([&] { svr.listen(HOST, PORT); });
  16155. auto se = detail::scope_exit([&] {
  16156. svr.stop();
  16157. t.join();
  16158. ASSERT_FALSE(svr.is_running());
  16159. ASSERT_TRUE(handled);
  16160. });
  16161. svr.wait_until_ready();
  16162. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16163. // Regression test for GHSA-qq6v-r583-3h69
  16164. std::string long_filename(8000, 'A');
  16165. std::string body = "----------\r\n"
  16166. "Content-Disposition: form-data; name=\"file1\"; "
  16167. "filename*=\"Utf-8''" +
  16168. long_filename +
  16169. "\"\r\n"
  16170. "\r\n"
  16171. "hello\r\n"
  16172. "------------\r\n";
  16173. auto req = "POST /test HTTP/1.1\r\n"
  16174. "Host: localhost\r\n"
  16175. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16176. "Content-Length: " +
  16177. std::to_string(body.size()) + "\r\n\r\n" + body;
  16178. ASSERT_TRUE(send_request(1, req));
  16179. }
  16180. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16181. auto handled = false;
  16182. Server svr;
  16183. svr.Post("/test", [&](const Request &req, Response &) {
  16184. ASSERT_EQ(2u, req.form.fields.size());
  16185. const auto &text1 = req.form.get_field("text1");
  16186. ASSERT_EQ("text1", text1);
  16187. const auto &text2 = req.form.get_field("text2");
  16188. ASSERT_EQ("text2", text2);
  16189. handled = true;
  16190. });
  16191. thread t = thread([&] { svr.listen(HOST, PORT); });
  16192. auto se = detail::scope_exit([&] {
  16193. svr.stop();
  16194. t.join();
  16195. ASSERT_FALSE(svr.is_running());
  16196. ASSERT_TRUE(handled);
  16197. });
  16198. svr.wait_until_ready();
  16199. auto req = "POST /test HTTP/1.1\r\n"
  16200. "Host: localhost\r\n"
  16201. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16202. "Content-Length: 146\r\n"
  16203. "\r\n----------\r\n"
  16204. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16205. "\r\n"
  16206. "text1"
  16207. "\r\n----------\r\n"
  16208. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16209. "\r\n"
  16210. "text2"
  16211. "\r\n------------";
  16212. std::string response;
  16213. ASSERT_TRUE(send_request(1, req, &response));
  16214. ASSERT_EQ("200", response.substr(9, 3));
  16215. }
  16216. TEST(MultipartFormDataTest, ContentLength) {
  16217. auto handled = false;
  16218. Server svr;
  16219. svr.Post("/test", [&](const Request &req, Response &) {
  16220. ASSERT_EQ(2u, req.form.fields.size());
  16221. const auto &text1 = req.form.get_field("text1");
  16222. ASSERT_EQ("text1", text1);
  16223. const auto &text2 = req.form.get_field("text2");
  16224. ASSERT_EQ("text2", text2);
  16225. handled = true;
  16226. });
  16227. thread t = thread([&] { svr.listen(HOST, PORT); });
  16228. auto se = detail::scope_exit([&] {
  16229. svr.stop();
  16230. t.join();
  16231. ASSERT_FALSE(svr.is_running());
  16232. ASSERT_TRUE(handled);
  16233. });
  16234. svr.wait_until_ready();
  16235. auto req = "POST /test HTTP/1.1\r\n"
  16236. "Host: localhost\r\n"
  16237. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16238. "Content-Length: 167\r\n"
  16239. "\r\n----------\r\n"
  16240. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16241. "Content-Length: 5\r\n"
  16242. "\r\n"
  16243. "text1"
  16244. "\r\n----------\r\n"
  16245. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16246. "\r\n"
  16247. "text2"
  16248. "\r\n------------\r\n";
  16249. std::string response;
  16250. ASSERT_TRUE(send_request(1, req, &response));
  16251. ASSERT_EQ("200", response.substr(9, 3));
  16252. }
  16253. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16254. auto handled = false;
  16255. Server svr;
  16256. svr.Post("/test", [&](const Request &req, Response &) {
  16257. ASSERT_EQ(2u, req.form.fields.size());
  16258. const auto &text1 = req.form.get_field("text1");
  16259. ASSERT_EQ("text1", text1);
  16260. // TODO: Add header access for text fields if needed
  16261. const auto &text2 = req.form.get_field("text2");
  16262. ASSERT_EQ("text2", text2);
  16263. // TODO: Header access for text fields needs to be implemented
  16264. // auto &headers = it->second.headers;
  16265. // ASSERT_EQ(3U, headers.size());
  16266. // auto custom_header = headers.find("x-whatever");
  16267. // ASSERT_TRUE(custom_header != headers.end());
  16268. // ASSERT_NE("customvalue", custom_header->second);
  16269. // ASSERT_EQ("CustomValue", custom_header->second);
  16270. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16271. handled = true;
  16272. });
  16273. thread t = thread([&] { svr.listen(HOST, PORT); });
  16274. auto se = detail::scope_exit([&] {
  16275. svr.stop();
  16276. t.join();
  16277. ASSERT_FALSE(svr.is_running());
  16278. ASSERT_TRUE(handled);
  16279. });
  16280. svr.wait_until_ready();
  16281. auto req = "POST /test HTTP/1.1\r\n"
  16282. "Host: localhost\r\n"
  16283. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16284. "Content-Length: 232\r\n"
  16285. "\r\n----------\r\n"
  16286. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16287. "Content-Length: 5\r\n"
  16288. "X-Test: 1\r\n"
  16289. "\r\n"
  16290. "text1"
  16291. "\r\n----------\r\n"
  16292. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16293. "Content-Type: text/plain\r\n"
  16294. "X-Whatever: CustomValue\r\n"
  16295. "\r\n"
  16296. "text2"
  16297. "\r\n------------\r\n"
  16298. "That should be disregarded. Not even read";
  16299. std::string response;
  16300. ASSERT_TRUE(send_request(1, req, &response));
  16301. ASSERT_EQ("200", response.substr(9, 3));
  16302. }
  16303. TEST(MultipartFormDataTest, LargeHeader) {
  16304. auto handled = false;
  16305. Server svr;
  16306. svr.Post("/test", [&](const Request &req, Response &) {
  16307. ASSERT_EQ(1u, req.form.fields.size());
  16308. const auto &text = req.form.get_field("name1");
  16309. ASSERT_EQ("text1", text);
  16310. handled = true;
  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. ASSERT_TRUE(handled);
  16318. });
  16319. svr.wait_until_ready();
  16320. auto boundary = std::string("cpp-httplib-multipart-data");
  16321. std::string content = "--" + boundary +
  16322. "\r\n"
  16323. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16324. "\r\n"
  16325. "text1\r\n"
  16326. "--" +
  16327. boundary + "--\r\n";
  16328. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16329. "Host: localhost\r\n"
  16330. "Content-Type: multipart/form-data;boundary=" +
  16331. boundary +
  16332. "\r\n"
  16333. "Content-Length: " +
  16334. std::to_string(content.size()) +
  16335. "\r\n"
  16336. "Dummy-Header: ";
  16337. std::string header_suffix = "\r\n"
  16338. "\r\n";
  16339. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16340. size_t header_dummy_size =
  16341. read_buff_size -
  16342. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16343. auto header_dummy = std::string(header_dummy_size, '@');
  16344. auto req = header_prefix + header_dummy + header_suffix + content;
  16345. std::string response;
  16346. ASSERT_TRUE(send_request(1, req, &response));
  16347. ASSERT_EQ("200", response.substr(9, 3));
  16348. }
  16349. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16350. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16351. // (not chunked Transfer-Encoding) after the streaming refactor.
  16352. auto handled = false;
  16353. Server svr;
  16354. svr.Post("/upload", [&](const Request &req, Response &res) {
  16355. auto cl_it = req.headers.find("Content-Length");
  16356. EXPECT_TRUE(cl_it != req.headers.end());
  16357. auto te_it = req.headers.find("Transfer-Encoding");
  16358. EXPECT_TRUE(te_it == req.headers.end());
  16359. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16360. res.set_content("ok", "text/plain");
  16361. handled = true;
  16362. });
  16363. auto port = svr.bind_to_any_port(HOST);
  16364. auto t = thread([&] { svr.listen_after_bind(); });
  16365. auto se = detail::scope_exit([&] {
  16366. svr.stop();
  16367. t.join();
  16368. ASSERT_FALSE(svr.is_running());
  16369. ASSERT_TRUE(handled);
  16370. });
  16371. svr.wait_until_ready();
  16372. UploadFormDataItems items = {
  16373. {"field1", "hello", "", "text/plain"},
  16374. {"file1", "world", "test.txt", "application/octet-stream"},
  16375. };
  16376. Client cli(HOST, port);
  16377. auto res = cli.Post("/upload", {}, items);
  16378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16379. EXPECT_EQ(StatusCode::OK_200, res->status);
  16380. }
  16381. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16382. // Verify that make_multipart_content_provider coalesces many small segments
  16383. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16384. constexpr size_t kItemCount = 1000;
  16385. UploadFormDataItems items;
  16386. items.reserve(kItemCount);
  16387. for (size_t i = 0; i < kItemCount; i++) {
  16388. items.push_back(
  16389. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16390. }
  16391. const std::string boundary = "----test-boundary";
  16392. auto content_length = detail::get_multipart_content_length(items, boundary);
  16393. auto provider = detail::make_multipart_content_provider(items, boundary);
  16394. // Drive the provider the same way write_content_with_progress does
  16395. size_t write_count = 0;
  16396. size_t total_bytes = 0;
  16397. DataSink sink;
  16398. size_t offset = 0;
  16399. sink.write = [&](const char *d, size_t l) -> bool {
  16400. (void)d;
  16401. write_count++;
  16402. total_bytes += l;
  16403. offset += l;
  16404. return true;
  16405. };
  16406. sink.is_writable = []() -> bool { return true; };
  16407. while (offset < content_length) {
  16408. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16409. }
  16410. EXPECT_EQ(content_length, total_bytes);
  16411. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16412. // With buffering into 64KB blocks, write_count should be much smaller.
  16413. auto segment_count = 3 * kItemCount + 1;
  16414. EXPECT_LT(write_count, segment_count / 10);
  16415. }
  16416. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16417. // Integration test: send many UploadFormDataItems and verify the server
  16418. // receives all of them correctly (#2410).
  16419. constexpr size_t kItemCount = 500;
  16420. auto handled = false;
  16421. Server svr;
  16422. svr.Post("/upload", [&](const Request &req, Response &res) {
  16423. EXPECT_EQ(kItemCount, req.form.fields.size());
  16424. for (size_t i = 0; i < kItemCount; i++) {
  16425. auto key = "field" + std::to_string(i);
  16426. auto val = "value" + std::to_string(i);
  16427. auto it = req.form.fields.find(key);
  16428. if (it != req.form.fields.end()) {
  16429. EXPECT_EQ(val, it->second.content);
  16430. } else {
  16431. ADD_FAILURE() << "Missing field: " << key;
  16432. }
  16433. }
  16434. res.set_content("ok", "text/plain");
  16435. handled = true;
  16436. });
  16437. auto port = svr.bind_to_any_port(HOST);
  16438. auto t = thread([&] { svr.listen_after_bind(); });
  16439. auto se = detail::scope_exit([&] {
  16440. svr.stop();
  16441. t.join();
  16442. ASSERT_FALSE(svr.is_running());
  16443. ASSERT_TRUE(handled);
  16444. });
  16445. svr.wait_until_ready();
  16446. UploadFormDataItems items;
  16447. items.reserve(kItemCount);
  16448. for (size_t i = 0; i < kItemCount; i++) {
  16449. items.push_back(
  16450. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16451. }
  16452. Client cli(HOST, port);
  16453. auto res = cli.Post("/upload", items);
  16454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16455. EXPECT_EQ(StatusCode::OK_200, res->status);
  16456. }
  16457. TEST(MultipartFormDataTest, MakeFileProvider) {
  16458. // Verify make_file_provider sends a file's contents correctly.
  16459. const std::string file_content(4096, 'Z');
  16460. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16461. {
  16462. std::ofstream ofs(tmp_path, std::ios::binary);
  16463. ofs.write(file_content.data(),
  16464. static_cast<std::streamsize>(file_content.size()));
  16465. }
  16466. auto handled = false;
  16467. Server svr;
  16468. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16469. const ContentReader &content_reader) {
  16470. ASSERT_TRUE(req.is_multipart_form_data());
  16471. std::vector<FormData> items;
  16472. content_reader(
  16473. [&](const FormData &file) {
  16474. items.push_back(file);
  16475. return true;
  16476. },
  16477. [&](const char *data, size_t data_length) {
  16478. items.back().content.append(data, data_length);
  16479. return true;
  16480. });
  16481. ASSERT_EQ(1u, items.size());
  16482. EXPECT_EQ("myfile", items[0].name);
  16483. EXPECT_EQ("data.bin", items[0].filename);
  16484. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16485. EXPECT_EQ(file_content, items[0].content);
  16486. handled = true;
  16487. });
  16488. auto port = svr.bind_to_any_port(HOST);
  16489. auto t = thread([&] { svr.listen_after_bind(); });
  16490. auto se = detail::scope_exit([&] {
  16491. svr.stop();
  16492. t.join();
  16493. ASSERT_FALSE(svr.is_running());
  16494. ASSERT_TRUE(handled);
  16495. std::remove(tmp_path.c_str());
  16496. });
  16497. svr.wait_until_ready();
  16498. FormDataProviderItems providers;
  16499. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16500. "application/octet-stream"));
  16501. Client cli(HOST, port);
  16502. auto res = cli.Post("/upload", {}, {}, providers);
  16503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16504. EXPECT_EQ(StatusCode::OK_200, res->status);
  16505. }
  16506. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16507. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16508. // (100) headers is rejected with a 400 Bad Request response.
  16509. Server svr;
  16510. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16511. res.set_content("ok", "text/plain");
  16512. });
  16513. thread t = thread([&] { svr.listen(HOST, PORT); });
  16514. auto se = detail::scope_exit([&] {
  16515. svr.stop();
  16516. t.join();
  16517. ASSERT_FALSE(svr.is_running());
  16518. });
  16519. svr.wait_until_ready();
  16520. // Build a multipart part with 101 custom headers (exceeding
  16521. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16522. std::stringstream body;
  16523. body << "--simpleboundary\r\n"
  16524. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16525. for (int i = 0; i < 101; i++) {
  16526. body << "X-Custom-Header-" << i << ": value\r\n";
  16527. }
  16528. body << "\r\n"
  16529. << "value1\r\n"
  16530. << "--simpleboundary--\r\n";
  16531. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16532. Client cli(HOST, PORT);
  16533. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16535. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16536. }
  16537. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16538. // A body that never contains the declared boundary must not be accumulated
  16539. // while the parser waits for it. Buffering it would also make every read
  16540. // rescan everything seen so far, which is quadratic in the body size.
  16541. Server svr;
  16542. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16543. res.set_content("ok", "text/plain");
  16544. });
  16545. auto port = svr.bind_to_any_port(HOST);
  16546. thread t = thread([&] { svr.listen_after_bind(); });
  16547. auto se = detail::scope_exit([&] {
  16548. svr.stop();
  16549. t.join();
  16550. ASSERT_FALSE(svr.is_running());
  16551. });
  16552. svr.wait_until_ready();
  16553. Client cli(HOST, port);
  16554. cli.set_read_timeout(60, 0);
  16555. cli.set_write_timeout(60, 0);
  16556. // '-' is the worst case: it matches the first character of the boundary, so
  16557. // every position has to be checked against it.
  16558. auto post_dashes = [&](size_t size) {
  16559. const std::string body(size, '-');
  16560. auto start = std::chrono::steady_clock::now();
  16561. auto res =
  16562. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16563. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16564. std::chrono::steady_clock::now() - start)
  16565. .count();
  16566. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16567. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16568. return ms;
  16569. };
  16570. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16571. // Windows.
  16572. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16573. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16574. // Comparing the two sizes rather than checking an absolute duration keeps
  16575. // this meaningful across build types and CI load, both of which move the
  16576. // absolute numbers by more than an order of magnitude. Four times the bytes
  16577. // costs about four times the time when parsing is linear, and about sixteen
  16578. // times when the body is buffered and rescanned.
  16579. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16580. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16581. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16582. << "ms, which suggests the body is being buffered and rescanned";
  16583. }
  16584. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16585. // A boundary can only be followed by CRLF or by "--", so anything else is
  16586. // malformed no matter what comes next. The parser must say so right away
  16587. // instead of buffering the rest of the declared body.
  16588. Server svr;
  16589. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16590. res.set_content("ok", "text/plain");
  16591. });
  16592. auto port = svr.bind_to_any_port(HOST);
  16593. thread t = thread([&] { svr.listen_after_bind(); });
  16594. auto se = detail::scope_exit([&] {
  16595. svr.stop();
  16596. t.join();
  16597. ASSERT_FALSE(svr.is_running());
  16598. });
  16599. svr.wait_until_ready();
  16600. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16601. // buffers instead of failing would still be waiting for the remaining bytes.
  16602. const std::string body = "--zzzz\r\n"
  16603. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16604. "\r\n"
  16605. "text1"
  16606. "\r\n--zzzzXX";
  16607. const std::string req = "POST /post HTTP/1.1\r\n"
  16608. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16609. "Content-Length: 1048576\r\n"
  16610. "\r\n" +
  16611. body;
  16612. std::string response;
  16613. ASSERT_TRUE(send_request(3, req, &response, port));
  16614. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16615. EXPECT_EQ("400", response.substr(9, 3));
  16616. }
  16617. // Posts a multipart body split into two writes, so that the server sees the
  16618. // split at whatever offset the caller chose, and expects the single "text1"
  16619. // field to come through.
  16620. static void expect_split_multipart_ok(const std::string &body1,
  16621. const std::string &body2) {
  16622. auto handled = false;
  16623. Server svr;
  16624. svr.Post("/post", [&](const Request &req, Response &) {
  16625. EXPECT_EQ(1u, req.form.fields.size());
  16626. EXPECT_EQ("text1", req.form.get_field("text1"));
  16627. handled = true;
  16628. });
  16629. auto port = svr.bind_to_any_port(HOST);
  16630. thread t = thread([&] { svr.listen_after_bind(); });
  16631. auto se = detail::scope_exit([&] {
  16632. svr.stop();
  16633. t.join();
  16634. ASSERT_FALSE(svr.is_running());
  16635. ASSERT_TRUE(handled);
  16636. });
  16637. svr.wait_until_ready();
  16638. // "Connection: close" makes the server close once it has answered, so the
  16639. // response drain ends immediately instead of idling until the read timeout.
  16640. const std::string head =
  16641. "POST /post HTTP/1.1\r\n"
  16642. "Host: localhost\r\n"
  16643. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16644. "Connection: close\r\n"
  16645. "Content-Length: " +
  16646. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16647. std::string response;
  16648. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16649. ASSERT_GE(response.size(), 12u) << "no response";
  16650. EXPECT_EQ("200", response.substr(9, 3));
  16651. }
  16652. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16653. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16654. // ignored, including when it does not arrive in the same read as the
  16655. // close-delimiter itself.
  16656. expect_split_multipart_ok("--zzzz\r\n"
  16657. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16658. "\r\n"
  16659. "text1"
  16660. "\r\n--zzzz--",
  16661. "\r\nthis epilogue must be ignored\r\n");
  16662. }
  16663. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16664. // The initial boundary may be preceded by a preamble of any length and may
  16665. // straddle a read boundary. Discarding data while waiting for it must not
  16666. // throw away a partial boundary sitting at the end of the buffer.
  16667. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16668. "zz\r\n"
  16669. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16670. "\r\n"
  16671. "text1"
  16672. "\r\n--zzzz--\r\n");
  16673. }
  16674. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16675. // The received boundary was only checked for being non-empty, so it could be
  16676. // as long as a header is allowed to be. The parser scans the body for
  16677. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16678. // costs a nearly full comparison at nearly every position, making the
  16679. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16680. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16681. Server svr;
  16682. svr.Post("/post", [](const Request &req, Response &res) {
  16683. EXPECT_EQ(1u, req.form.fields.size());
  16684. EXPECT_EQ("text1", req.form.get_field("text1"));
  16685. res.set_content("ok", "text/plain");
  16686. });
  16687. auto port = svr.bind_to_any_port(HOST);
  16688. thread t = thread([&] { svr.listen_after_bind(); });
  16689. auto se = detail::scope_exit([&] {
  16690. svr.stop();
  16691. t.join();
  16692. ASSERT_FALSE(svr.is_running());
  16693. });
  16694. svr.wait_until_ready();
  16695. Client cli(HOST, port);
  16696. auto post_with_boundary_of_length = [&](size_t len) {
  16697. const std::string boundary(len, 'a');
  16698. const std::string body =
  16699. "--" + boundary +
  16700. "\r\n"
  16701. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16702. "\r\n"
  16703. "text1"
  16704. "\r\n--" +
  16705. boundary + "--\r\n";
  16706. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16707. };
  16708. auto res = post_with_boundary_of_length(70);
  16709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16710. EXPECT_EQ(StatusCode::OK_200, res->status);
  16711. res = post_with_boundary_of_length(71);
  16712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16713. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16714. }
  16715. TEST(MakeFileBodyTest, Basic) {
  16716. const std::string file_content(4096, 'Z');
  16717. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16718. {
  16719. std::ofstream ofs(tmp_path, std::ios::binary);
  16720. ofs.write(file_content.data(),
  16721. static_cast<std::streamsize>(file_content.size()));
  16722. }
  16723. auto handled = false;
  16724. Server svr;
  16725. svr.Post("/upload", [&](const Request &req, Response &res) {
  16726. EXPECT_EQ(file_content, req.body);
  16727. handled = true;
  16728. res.status = StatusCode::OK_200;
  16729. });
  16730. auto port = svr.bind_to_any_port(HOST);
  16731. auto t = thread([&] { svr.listen_after_bind(); });
  16732. auto se = detail::scope_exit([&] {
  16733. svr.stop();
  16734. t.join();
  16735. ASSERT_FALSE(svr.is_running());
  16736. ASSERT_TRUE(handled);
  16737. std::remove(tmp_path.c_str());
  16738. });
  16739. svr.wait_until_ready();
  16740. auto fb = make_file_body(tmp_path);
  16741. ASSERT_GT(fb.first, 0u);
  16742. Client cli(HOST, port);
  16743. auto res =
  16744. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16746. EXPECT_EQ(StatusCode::OK_200, res->status);
  16747. }
  16748. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16749. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16750. {
  16751. std::ofstream ofs(path, std::ios::binary);
  16752. const std::string content(100, 'A');
  16753. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16754. }
  16755. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16756. auto body = make_file_body(path);
  16757. ASSERT_EQ(100u, body.first);
  16758. ASSERT_TRUE(static_cast<bool>(body.second));
  16759. // Rewritten shorter after its length was measured - and, on a server, after
  16760. // that length has already gone out as Content-Length.
  16761. {
  16762. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16763. const std::string content(10, 'A');
  16764. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16765. }
  16766. std::string written;
  16767. DataSink sink;
  16768. sink.write = [&](const char *d, size_t l) {
  16769. written.append(d, l);
  16770. return true;
  16771. };
  16772. // The provider has to report failure. write_content_with_progress() advances
  16773. // its offset only by what was written, so a provider that returns true
  16774. // without completing the length it promised is called again straight away,
  16775. // and again.
  16776. EXPECT_FALSE(body.second(0, body.first, sink));
  16777. EXPECT_EQ(std::string(10, 'A'), written);
  16778. }
  16779. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16780. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16781. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16782. {
  16783. std::ofstream ofs(path, std::ios::binary);
  16784. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16785. }
  16786. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16787. auto body = make_file_body(path);
  16788. ASSERT_EQ(content.size(), body.first);
  16789. ASSERT_TRUE(static_cast<bool>(body.second));
  16790. std::string written;
  16791. DataSink sink;
  16792. sink.write = [&](const char *d, size_t l) {
  16793. written.append(d, l);
  16794. return true;
  16795. };
  16796. EXPECT_TRUE(body.second(0, body.first, sink));
  16797. EXPECT_EQ(content, written);
  16798. }
  16799. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16800. static constexpr unsigned int number_of_tasks{1000000};
  16801. std::atomic_uint count{0};
  16802. std::unique_ptr<TaskQueue> task_queue{
  16803. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16804. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16805. auto queued = task_queue->enqueue(
  16806. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16807. EXPECT_TRUE(queued);
  16808. }
  16809. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16810. task_queue->shutdown();
  16811. #else
  16812. EXPECT_NO_THROW(task_queue->shutdown());
  16813. #endif
  16814. EXPECT_EQ(number_of_tasks, count.load());
  16815. }
  16816. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16817. static constexpr unsigned int number_of_tasks{1000000};
  16818. static constexpr unsigned int qlimit{2};
  16819. unsigned int queued_count{0};
  16820. std::atomic_uint count{0};
  16821. std::unique_ptr<TaskQueue> task_queue{
  16822. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16823. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16824. if (task_queue->enqueue(
  16825. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16826. queued_count++;
  16827. }
  16828. }
  16829. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16830. task_queue->shutdown();
  16831. #else
  16832. EXPECT_NO_THROW(task_queue->shutdown());
  16833. #endif
  16834. EXPECT_EQ(queued_count, count.load());
  16835. EXPECT_TRUE(queued_count <= number_of_tasks);
  16836. EXPECT_TRUE(queued_count >= qlimit);
  16837. }
  16838. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16839. // Use a short idle timeout so a dynamic thread spawns, times out and
  16840. // exits during the test, and the pool keeps working afterwards.
  16841. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16842. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16843. /*idle_timeout_sec=*/1}};
  16844. std::atomic_uint count{0};
  16845. std::condition_variable cv;
  16846. std::mutex mtx;
  16847. bool release = false;
  16848. // Block the base thread so the second task spawns a dynamic thread.
  16849. EXPECT_TRUE(task_queue->enqueue([&] {
  16850. std::unique_lock<std::mutex> lock(mtx);
  16851. while (!release) {
  16852. cv.wait(lock);
  16853. }
  16854. count++;
  16855. }));
  16856. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16857. // Let the dynamic thread finish its task and exceed the idle timeout.
  16858. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16859. {
  16860. std::unique_lock<std::mutex> lock(mtx);
  16861. release = true;
  16862. }
  16863. cv.notify_all();
  16864. // The pool must still accept and run tasks after the dynamic thread exited.
  16865. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16866. task_queue->shutdown();
  16867. EXPECT_EQ(3u, count.load());
  16868. }
  16869. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16870. static constexpr size_t number_of_tasks{32};
  16871. std::unique_ptr<TaskQueue> task_queue{
  16872. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16873. // Let the base threads go idle so the burst below finds them waiting.
  16874. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16875. std::mutex mtx;
  16876. std::condition_variable cv;
  16877. size_t running = 0;
  16878. bool release = false;
  16879. for (size_t i = 0; i < number_of_tasks; i++) {
  16880. EXPECT_TRUE(task_queue->enqueue([&] {
  16881. std::unique_lock<std::mutex> lock(mtx);
  16882. running++;
  16883. cv.notify_all();
  16884. cv.wait(lock, [&] { return release; });
  16885. }));
  16886. }
  16887. {
  16888. std::unique_lock<std::mutex> lock(mtx);
  16889. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16890. [&] { return running == number_of_tasks; }));
  16891. release = true;
  16892. }
  16893. cv.notify_all();
  16894. task_queue->shutdown();
  16895. }
  16896. TEST(TaskQueueTest, MaxQueuedRequests) {
  16897. static constexpr unsigned int qlimit{3};
  16898. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16899. std::condition_variable sem_cv;
  16900. std::mutex sem_mtx;
  16901. int credits = 0;
  16902. bool queued;
  16903. /* Fill up the queue with tasks that will block until we give them credits to
  16904. * complete. */
  16905. for (unsigned int n = 0; n <= qlimit;) {
  16906. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16907. std::unique_lock<std::mutex> lock(sem_mtx);
  16908. while (credits <= 0) {
  16909. sem_cv.wait(lock);
  16910. }
  16911. /* Consume the credit and signal the test code if they are all gone. */
  16912. if (--credits == 0) { sem_cv.notify_one(); }
  16913. });
  16914. if (n < qlimit) {
  16915. /* The first qlimit enqueues must succeed. */
  16916. EXPECT_TRUE(queued);
  16917. } else {
  16918. /* The last one will succeed only when the worker thread
  16919. * starts and dequeues the first blocking task. Although
  16920. * not necessary for the correctness of this test, we sleep for
  16921. * a short while to avoid busy waiting. */
  16922. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16923. }
  16924. if (queued) { n++; }
  16925. }
  16926. /* Further enqueues must fail since the queue is full. */
  16927. for (auto i = 0; i < 4; i++) {
  16928. queued = task_queue->enqueue([] {});
  16929. EXPECT_FALSE(queued);
  16930. }
  16931. /* Give the credits to allow the previous tasks to complete. */
  16932. {
  16933. std::unique_lock<std::mutex> lock(sem_mtx);
  16934. credits += qlimit + 1;
  16935. }
  16936. sem_cv.notify_all();
  16937. /* Wait for all the credits to be consumed. */
  16938. {
  16939. std::unique_lock<std::mutex> lock(sem_mtx);
  16940. while (credits > 0) {
  16941. sem_cv.wait(lock);
  16942. }
  16943. }
  16944. /* Check that we are able again to enqueue at least qlimit tasks. */
  16945. for (unsigned int i = 0; i < qlimit; i++) {
  16946. queued = task_queue->enqueue([] {});
  16947. EXPECT_TRUE(queued);
  16948. }
  16949. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16950. task_queue->shutdown();
  16951. #else
  16952. EXPECT_NO_THROW(task_queue->shutdown());
  16953. #endif
  16954. }
  16955. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16956. Server svr;
  16957. std::string method;
  16958. std::string body;
  16959. auto has_content_length = false;
  16960. auto has_transfer_encoding = false;
  16961. std::atomic<int> bad_requests{0};
  16962. // Leftover body bytes get parsed as a malformed request and answered with
  16963. // 400
  16964. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16965. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16966. });
  16967. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16968. res.set_redirect("/down", StatusCode::SeeOther_303);
  16969. });
  16970. svr.Get("/down", [&](const Request &req, Response &res) {
  16971. method = req.method;
  16972. body = req.body;
  16973. has_content_length = req.has_header("Content-Length");
  16974. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16975. res.set_content("ok", "text/plain");
  16976. });
  16977. auto port = svr.bind_to_any_port(HOST);
  16978. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16979. auto se = detail::scope_exit([&] {
  16980. svr.stop();
  16981. thread.join();
  16982. ASSERT_FALSE(svr.is_running());
  16983. });
  16984. svr.wait_until_ready();
  16985. const std::string payload = "SECRET-BODY";
  16986. auto check = [&](Client &cli, const Result &res) {
  16987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16988. EXPECT_EQ(StatusCode::OK_200, res->status);
  16989. EXPECT_EQ("ok", res->body);
  16990. EXPECT_EQ("GET", method);
  16991. EXPECT_TRUE(body.empty());
  16992. EXPECT_FALSE(has_content_length);
  16993. EXPECT_FALSE(has_transfer_encoding);
  16994. // Nothing of the original body may be left on the connection
  16995. auto res2 = cli.Get("/down");
  16996. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16997. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16998. EXPECT_EQ("ok", res2->body);
  16999. EXPECT_EQ(0, bad_requests);
  17000. };
  17001. // With content length
  17002. {
  17003. Client cli(HOST, port);
  17004. cli.set_keep_alive(true);
  17005. cli.set_follow_location(true);
  17006. auto res = cli.Post(
  17007. "/up", payload.size(),
  17008. [&](size_t offset, size_t length, DataSink &sink) {
  17009. return sink.write(payload.data() + offset, length);
  17010. },
  17011. "text/plain");
  17012. check(cli, res);
  17013. }
  17014. // Without content length (chunked)
  17015. {
  17016. Client cli(HOST, port);
  17017. cli.set_keep_alive(true);
  17018. cli.set_follow_location(true);
  17019. auto res = cli.Post(
  17020. "/up",
  17021. [&](size_t /*offset*/, DataSink &sink) {
  17022. sink.write(payload.data(), payload.size());
  17023. sink.done();
  17024. return true;
  17025. },
  17026. "text/plain");
  17027. check(cli, res);
  17028. }
  17029. }
  17030. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17031. Server svr;
  17032. std::string target;
  17033. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17034. // Echo the still-encoded name back in the Location
  17035. const std::string prefix = "/start/";
  17036. res.status = StatusCode::Found_302;
  17037. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17038. });
  17039. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17040. target = req.target;
  17041. res.set_content("ok", "text/plain");
  17042. });
  17043. auto port = svr.bind_to_any_port(HOST);
  17044. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17045. auto se = detail::scope_exit([&] {
  17046. svr.stop();
  17047. thread.join();
  17048. ASSERT_FALSE(svr.is_running());
  17049. });
  17050. svr.wait_until_ready();
  17051. // Decoding the Location path would turn the first four into a path
  17052. // separator, a query delimiter, a fragment delimiter and a different
  17053. // percent-encoded octet. The rest must keep reaching the server as they are.
  17054. const std::vector<std::string> names = {
  17055. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17056. };
  17057. for (auto path_encode : {true, false}) {
  17058. Client cli(HOST, port);
  17059. cli.set_follow_location(true);
  17060. cli.set_path_encode(path_encode);
  17061. for (const auto &name : names) {
  17062. target.clear();
  17063. auto res = cli.Get("/start/" + name);
  17064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17065. EXPECT_EQ(StatusCode::OK_200, res->status);
  17066. EXPECT_EQ("/dest/" + name, target);
  17067. }
  17068. }
  17069. }
  17070. TEST(RedirectTest, NotModifiedIsReturned) {
  17071. Server svr;
  17072. svr.Get("/cached", [](const Request &, Response &res) {
  17073. res.status = StatusCode::NotModified_304;
  17074. });
  17075. auto port = svr.bind_to_any_port(HOST);
  17076. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17077. auto se = detail::scope_exit([&] {
  17078. svr.stop();
  17079. thread.join();
  17080. ASSERT_FALSE(svr.is_running());
  17081. });
  17082. svr.wait_until_ready();
  17083. Client cli(HOST, port);
  17084. cli.set_follow_location(true);
  17085. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17087. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17088. }
  17089. TEST(RedirectTest, NoLocationIsReturned) {
  17090. Server svr;
  17091. svr.Get("/no-location", [](const Request &, Response &res) {
  17092. res.status = StatusCode::Found_302;
  17093. res.set_content("no location", "text/plain");
  17094. });
  17095. auto port = svr.bind_to_any_port(HOST);
  17096. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17097. auto se = detail::scope_exit([&] {
  17098. svr.stop();
  17099. thread.join();
  17100. ASSERT_FALSE(svr.is_running());
  17101. });
  17102. svr.wait_until_ready();
  17103. Client cli(HOST, port);
  17104. cli.set_follow_location(true);
  17105. auto res = cli.Get("/no-location");
  17106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17107. EXPECT_EQ(StatusCode::Found_302, res->status);
  17108. EXPECT_EQ("no location", res->body);
  17109. // The callbacks see the body of the response that is returned
  17110. auto handler_called = false;
  17111. auto progress_called = false;
  17112. std::string body;
  17113. auto res2 = cli.Get(
  17114. "/no-location",
  17115. [&](const Response &) {
  17116. handler_called = true;
  17117. return true;
  17118. },
  17119. [&](const char *data, size_t data_length) {
  17120. body.append(data, data_length);
  17121. return true;
  17122. },
  17123. [&](size_t, size_t) {
  17124. progress_called = true;
  17125. return true;
  17126. });
  17127. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17128. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17129. EXPECT_TRUE(handler_called);
  17130. EXPECT_TRUE(progress_called);
  17131. EXPECT_EQ("no location", body);
  17132. }
  17133. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17134. Server svr;
  17135. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17136. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17137. });
  17138. svr.Get("/hello", [](const Request &req, Response &res) {
  17139. res.set_content(req.get_param_value("key"), "text/plain");
  17140. });
  17141. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17142. auto se = detail::scope_exit([&] {
  17143. svr.stop();
  17144. thread.join();
  17145. ASSERT_FALSE(svr.is_running());
  17146. });
  17147. svr.wait_until_ready();
  17148. {
  17149. Client cli(HOST, PORT);
  17150. cli.set_follow_location(true);
  17151. auto res = cli.Get("/");
  17152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17153. EXPECT_EQ(StatusCode::OK_200, res->status);
  17154. EXPECT_EQ("val&key2=val2", res->body);
  17155. }
  17156. }
  17157. #endif
  17158. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17159. Server svr;
  17160. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17161. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17162. });
  17163. svr.Get("/hello", [](const Request &req, Response &res) {
  17164. res.set_content(req.get_param_value("key"), "text/plain");
  17165. });
  17166. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17167. auto se = detail::scope_exit([&] {
  17168. svr.stop();
  17169. thread.join();
  17170. ASSERT_FALSE(svr.is_running());
  17171. });
  17172. svr.wait_until_ready();
  17173. {
  17174. Client cli(HOST, PORT);
  17175. cli.set_follow_location(true);
  17176. auto res = cli.Get("/");
  17177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17178. EXPECT_EQ(StatusCode::OK_200, res->status);
  17179. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17180. }
  17181. }
  17182. TEST(RedirectTest, RedirectWithPlusInPath) {
  17183. Server svr;
  17184. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17185. res.set_redirect("/a+b");
  17186. });
  17187. // Route pattern uses regex; escape + as \\+
  17188. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17189. res.set_content(req.path, "text/plain");
  17190. });
  17191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17192. auto se = detail::scope_exit([&] {
  17193. svr.stop();
  17194. thread.join();
  17195. ASSERT_FALSE(svr.is_running());
  17196. });
  17197. svr.wait_until_ready();
  17198. {
  17199. Client cli(HOST, PORT);
  17200. cli.set_follow_location(true);
  17201. auto res = cli.Get("/");
  17202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17203. EXPECT_EQ(StatusCode::OK_200, res->status);
  17204. EXPECT_EQ("/a+b", res->body);
  17205. }
  17206. }
  17207. TEST(RedirectTest, ResolveRelativeLocation) {
  17208. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17209. const std::vector<std::pair<std::string, std::string>> cases = {
  17210. {"g", "/b/c/g"},
  17211. {"./g", "/b/c/g"},
  17212. {"g/", "/b/c/g/"},
  17213. {"?y", "/b/c/d;p?y"},
  17214. {"g?y", "/b/c/g?y"},
  17215. {"#s", "/b/c/d;p?q#s"},
  17216. {"g#s", "/b/c/g#s"},
  17217. {"g?y#s", "/b/c/g?y#s"},
  17218. {";x", "/b/c/;x"},
  17219. {"g;x", "/b/c/g;x"},
  17220. {".", "/b/c/"},
  17221. {"./", "/b/c/"},
  17222. {"..", "/b/"},
  17223. {"../", "/b/"},
  17224. {"../g", "/b/g"},
  17225. {"../..", "/"},
  17226. {"../../", "/"},
  17227. {"../../g", "/g"},
  17228. {"../../../g", "/g"},
  17229. {"g.", "/b/c/g."},
  17230. {".g", "/b/c/.g"},
  17231. {"g..", "/b/c/g.."},
  17232. {"..g", "/b/c/..g"},
  17233. {"./../g", "/b/g"},
  17234. {"./g/.", "/b/c/g/"},
  17235. {"g/./h", "/b/c/g/h"},
  17236. {"g/../h", "/b/c/h"},
  17237. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17238. {"g;x=1/../y", "/b/c/y"},
  17239. {"g?y/./x", "/b/c/g?y/./x"},
  17240. {"g#s/../x", "/b/c/g#s/../x"},
  17241. // Not relative-path references, so left for parse_url.
  17242. {"/g", "/g"},
  17243. {"//g", "//g"},
  17244. {"http://g/x", "http://g/x"},
  17245. {"g:h", "g:h"},
  17246. };
  17247. for (const auto &c : cases) {
  17248. EXPECT_EQ(c.second,
  17249. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17250. << c.first;
  17251. }
  17252. }
  17253. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17254. Server svr;
  17255. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17256. res.set_redirect(req.get_param_value("to"));
  17257. });
  17258. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17259. res.set_content(req.target, "text/plain");
  17260. });
  17261. svr.Get("/other", [](const Request &req, Response &res) {
  17262. res.set_content(req.target, "text/plain");
  17263. });
  17264. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17265. auto se = detail::scope_exit([&] {
  17266. svr.stop();
  17267. thread.join();
  17268. ASSERT_FALSE(svr.is_running());
  17269. });
  17270. svr.wait_until_ready();
  17271. const std::vector<std::pair<std::string, std::string>> cases = {
  17272. {"next", "/dir/next"},
  17273. {"./next?x=1", "/dir/next?x=1"},
  17274. {"../other", "/other"},
  17275. };
  17276. for (const auto &c : cases) {
  17277. Client cli(HOST, PORT);
  17278. cli.set_follow_location(true);
  17279. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17280. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17281. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17282. EXPECT_EQ(c.second, res->body) << c.first;
  17283. }
  17284. }
  17285. #ifdef CPPHTTPLIB_SSL_ENABLED
  17286. TEST(RedirectTest, Issue2185_Online) {
  17287. SSLClient client("github.com");
  17288. client.set_follow_location(true);
  17289. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17290. "Coollab-Windows.zip");
  17291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17292. EXPECT_EQ(StatusCode::OK_200, res->status);
  17293. EXPECT_EQ(9920427U, res->body.size());
  17294. }
  17295. #endif
  17296. TEST(VulnerabilityTest, CRLFInjection) {
  17297. Server svr;
  17298. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17299. res.set_content("Hello 1", "text/plain");
  17300. });
  17301. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17302. res.set_content("Hello 2", "text/plain");
  17303. });
  17304. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17305. res.set_content("Hello 3", "text/plain");
  17306. });
  17307. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17308. res.set_content("Hello 4", "text/plain");
  17309. });
  17310. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17311. for (const auto &x : req.headers) {
  17312. auto key = x.first;
  17313. EXPECT_STRNE("evil", key.c_str());
  17314. }
  17315. });
  17316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17317. auto se = detail::scope_exit([&] {
  17318. svr.stop();
  17319. thread.join();
  17320. ASSERT_FALSE(svr.is_running());
  17321. });
  17322. svr.wait_until_ready();
  17323. {
  17324. Client cli(HOST, PORT);
  17325. cli.Post("/test1", "A=B",
  17326. "application/x-www-form-urlencoded\r\nevil: hello1");
  17327. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17328. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17329. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17330. }
  17331. }
  17332. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17333. auto server_thread = std::thread([] {
  17334. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17335. default_socket_options(srv);
  17336. sockaddr_in addr{};
  17337. addr.sin_family = AF_INET;
  17338. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17339. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17340. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17341. ::listen(srv, 1);
  17342. sockaddr_in cli_addr{};
  17343. socklen_t cli_len = sizeof(cli_addr);
  17344. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17345. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17346. std::string buf_all;
  17347. char buf[2048];
  17348. ssize_t n;
  17349. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17350. buf_all.append(buf, static_cast<size_t>(n));
  17351. size_t pos;
  17352. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17353. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17354. auto e = request_block.find("\r\n");
  17355. if (e != std::string::npos) {
  17356. auto request_line = request_block.substr(0, e);
  17357. std::string msg =
  17358. "CRLF injection detected in request line: '" + request_line + "'";
  17359. EXPECT_FALSE(true) << msg;
  17360. }
  17361. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17362. ::send(cli,
  17363. #ifdef _WIN32
  17364. static_cast<const char *>(resp.c_str()),
  17365. static_cast<int>(resp.size()),
  17366. #else
  17367. resp.c_str(), resp.size(),
  17368. #endif
  17369. 0);
  17370. buf_all.erase(0, pos + 4);
  17371. }
  17372. }
  17373. detail::close_socket(cli);
  17374. detail::close_socket(srv);
  17375. });
  17376. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17377. auto cli = Client("127.0.0.1", PORT + 1);
  17378. auto headers = Headers{
  17379. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17380. {"Connection", "keep-alive"}};
  17381. auto res = cli.Get("/hi", headers);
  17382. EXPECT_FALSE(res);
  17383. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17384. server_thread.join();
  17385. }
  17386. // A request rejected before any byte reaches the socket must fail right away
  17387. // instead of waiting for a response the server will never send.
  17388. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17389. // The kernel completes the TCP handshake from the listen backlog, so the
  17390. // client connects, but nothing ever reads, responds or closes.
  17391. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17392. default_socket_options(srv);
  17393. sockaddr_in addr{};
  17394. addr.sin_family = AF_INET;
  17395. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17396. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17397. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17398. ASSERT_EQ(0, ::listen(srv, 8));
  17399. auto cli = Client("127.0.0.1", PORT + 1);
  17400. cli.set_read_timeout(10, 0);
  17401. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17402. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17403. std::chrono::steady_clock::now() - start)
  17404. .count();
  17405. };
  17406. {
  17407. Request req;
  17408. req.method = "GE T";
  17409. req.path = "/";
  17410. auto start = std::chrono::steady_clock::now();
  17411. auto res = cli.send(req);
  17412. EXPECT_FALSE(res);
  17413. EXPECT_EQ(Error::Write, res.error());
  17414. EXPECT_LT(elapsed_ms(start), 1000);
  17415. }
  17416. {
  17417. auto start = std::chrono::steady_clock::now();
  17418. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17419. EXPECT_FALSE(res);
  17420. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17421. EXPECT_LT(elapsed_ms(start), 1000);
  17422. }
  17423. EXPECT_FALSE(cli.is_socket_open());
  17424. detail::close_socket(srv);
  17425. }
  17426. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17427. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17428. default_socket_options(srv);
  17429. sockaddr_in addr{};
  17430. addr.sin_family = AF_INET;
  17431. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17432. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17433. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17434. ASSERT_EQ(0, ::listen(srv, 1));
  17435. std::string received;
  17436. auto server_thread = std::thread([&] {
  17437. auto sock = ::accept(srv, nullptr, nullptr);
  17438. if (sock == INVALID_SOCKET) { return; }
  17439. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17440. char buf[2048];
  17441. ssize_t n;
  17442. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17443. received.append(buf, static_cast<size_t>(n));
  17444. }
  17445. detail::close_socket(sock);
  17446. });
  17447. {
  17448. auto cli = Client("127.0.0.1", PORT + 1);
  17449. // "Z" sorts after the default headers, so writing straight to the socket
  17450. // would have sent the request line and those headers before the rejection.
  17451. auto handle =
  17452. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17453. EXPECT_FALSE(handle.is_valid());
  17454. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17455. }
  17456. server_thread.join();
  17457. detail::close_socket(srv);
  17458. EXPECT_TRUE(received.empty()) << received;
  17459. }
  17460. TEST(PathParamsTest, StaticMatch) {
  17461. const auto pattern = "/users/all";
  17462. detail::PathParamsMatcher matcher(pattern);
  17463. Request request;
  17464. request.path = "/users/all";
  17465. ASSERT_TRUE(matcher.match(request));
  17466. std::unordered_map<std::string, std::string> expected_params = {};
  17467. EXPECT_EQ(request.path_params, expected_params);
  17468. }
  17469. TEST(PathParamsTest, StaticMismatch) {
  17470. const auto pattern = "/users/all";
  17471. detail::PathParamsMatcher matcher(pattern);
  17472. Request request;
  17473. request.path = "/users/1";
  17474. ASSERT_FALSE(matcher.match(request));
  17475. }
  17476. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17477. const auto pattern = "/users/:id/subscriptions";
  17478. detail::PathParamsMatcher matcher(pattern);
  17479. Request request;
  17480. request.path = "/users/42/subscriptions";
  17481. ASSERT_TRUE(matcher.match(request));
  17482. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17483. EXPECT_EQ(request.path_params, expected_params);
  17484. }
  17485. TEST(PathParamsTest, SingleParamInTheEnd) {
  17486. const auto pattern = "/users/:id";
  17487. detail::PathParamsMatcher matcher(pattern);
  17488. Request request;
  17489. request.path = "/users/24";
  17490. ASSERT_TRUE(matcher.match(request));
  17491. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17492. EXPECT_EQ(request.path_params, expected_params);
  17493. }
  17494. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17495. const auto pattern = "/users/:id/";
  17496. detail::PathParamsMatcher matcher(pattern);
  17497. Request request;
  17498. request.path = "/users/42/";
  17499. ASSERT_TRUE(matcher.match(request));
  17500. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17501. EXPECT_EQ(request.path_params, expected_params);
  17502. }
  17503. TEST(PathParamsTest, EmptyParam) {
  17504. const auto pattern = "/users/:id/";
  17505. detail::PathParamsMatcher matcher(pattern);
  17506. Request request;
  17507. request.path = "/users//";
  17508. ASSERT_TRUE(matcher.match(request));
  17509. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17510. EXPECT_EQ(request.path_params, expected_params);
  17511. }
  17512. TEST(PathParamsTest, FragmentMismatch) {
  17513. const auto pattern = "/users/:id/";
  17514. detail::PathParamsMatcher matcher(pattern);
  17515. Request request;
  17516. request.path = "/admins/24/";
  17517. ASSERT_FALSE(matcher.match(request));
  17518. }
  17519. TEST(PathParamsTest, ExtraFragments) {
  17520. const auto pattern = "/users/:id";
  17521. detail::PathParamsMatcher matcher(pattern);
  17522. Request request;
  17523. request.path = "/users/42/subscriptions";
  17524. ASSERT_FALSE(matcher.match(request));
  17525. }
  17526. TEST(PathParamsTest, MissingTrailingParam) {
  17527. const auto pattern = "/users/:id";
  17528. detail::PathParamsMatcher matcher(pattern);
  17529. Request request;
  17530. request.path = "/users";
  17531. ASSERT_FALSE(matcher.match(request));
  17532. }
  17533. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17534. const auto pattern = "/users/:id/subscriptions";
  17535. detail::PathParamsMatcher matcher(pattern);
  17536. Request request;
  17537. request.path = "/users/subscriptions";
  17538. ASSERT_FALSE(matcher.match(request));
  17539. }
  17540. TEST(PathParamsTest, MultipleParams) {
  17541. const auto pattern = "/users/:userid/subscriptions/:subid";
  17542. detail::PathParamsMatcher matcher(pattern);
  17543. Request request;
  17544. request.path = "/users/42/subscriptions/2";
  17545. ASSERT_TRUE(matcher.match(request));
  17546. std::unordered_map<std::string, std::string> expected_params = {
  17547. {"userid", "42"}, {"subid", "2"}};
  17548. EXPECT_EQ(request.path_params, expected_params);
  17549. }
  17550. TEST(PathParamsTest, SequenceOfParams) {
  17551. const auto pattern = "/values/:x/:y/:z";
  17552. detail::PathParamsMatcher matcher(pattern);
  17553. Request request;
  17554. request.path = "/values/1/2/3";
  17555. ASSERT_TRUE(matcher.match(request));
  17556. std::unordered_map<std::string, std::string> expected_params = {
  17557. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17558. EXPECT_EQ(request.path_params, expected_params);
  17559. }
  17560. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17561. const auto pattern = "/prefix:suffix";
  17562. detail::PathParamsMatcher matcher(pattern);
  17563. Request request;
  17564. request.path = "/prefix:suffix";
  17565. ASSERT_TRUE(matcher.match(request));
  17566. const std::unordered_map<std::string, std::string> expected_params = {};
  17567. EXPECT_EQ(request.path_params, expected_params);
  17568. }
  17569. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17570. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17571. // calling thread's stack on a long enough path for a quantified pattern;
  17572. // RegexMatcher must refuse to run regex matching on paths beyond
  17573. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17574. detail::RegexMatcher matcher("/files/(.*)");
  17575. Request within_limit;
  17576. within_limit.path = "/files/" + std::string(10, 'A');
  17577. EXPECT_TRUE(matcher.match(within_limit));
  17578. Request over_limit;
  17579. over_limit.path =
  17580. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17581. EXPECT_FALSE(matcher.match(over_limit));
  17582. }
  17583. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17584. Server svr;
  17585. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17586. res.set_content("ok", "text/plain");
  17587. });
  17588. auto port = svr.bind_to_any_port(HOST);
  17589. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17590. auto se = detail::scope_exit([&] {
  17591. svr.stop();
  17592. thread.join();
  17593. ASSERT_FALSE(svr.is_running());
  17594. });
  17595. svr.wait_until_ready();
  17596. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17597. // request URI limit; this used to be able to crash the process.
  17598. std::string path =
  17599. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17600. std::string req = "GET " + path +
  17601. " HTTP/1.1\r\n"
  17602. "Host: " +
  17603. std::string(HOST) + ":" + std::to_string(port) +
  17604. "\r\n"
  17605. "Connection: close\r\n"
  17606. "\r\n";
  17607. std::string response;
  17608. ASSERT_TRUE(send_request(5, req, &response, port));
  17609. EXPECT_NE(std::string::npos, response.find("404"));
  17610. }
  17611. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17612. Server svr;
  17613. auto handler = [](const Request & /*req*/, Response &res) {
  17614. res.set_content("hit", "text/plain");
  17615. };
  17616. // No regex metacharacter, so this one is compared literally
  17617. svr.Get("/literal/route", handler);
  17618. // '.' is a regex metacharacter, so this one must keep regex semantics
  17619. svr.Get("/a.c", handler);
  17620. auto port = svr.bind_to_any_port(HOST);
  17621. std::thread t([&]() { svr.listen_after_bind(); });
  17622. auto se = detail::scope_exit([&] {
  17623. svr.stop();
  17624. t.join();
  17625. ASSERT_FALSE(svr.is_running());
  17626. });
  17627. svr.wait_until_ready();
  17628. Client cli(HOST, port);
  17629. struct {
  17630. const char *path;
  17631. int status;
  17632. } cases[] = {
  17633. {"/literal/route", StatusCode::OK_200},
  17634. {"/literal/routes", StatusCode::NotFound_404},
  17635. {"/literal/rout", StatusCode::NotFound_404},
  17636. {"/abc", StatusCode::OK_200},
  17637. {"/a.c", StatusCode::OK_200},
  17638. };
  17639. for (const auto &x : cases) {
  17640. auto res = cli.Get(x.path);
  17641. ASSERT_TRUE(res) << x.path;
  17642. EXPECT_EQ(x.status, res->status) << x.path;
  17643. }
  17644. }
  17645. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17646. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17647. // from exhausting the stack, so it must only constrain routes that actually
  17648. // run a regular expression. A literal route is matched by comparison and
  17649. // stays usable at any length.
  17650. Server svr;
  17651. const std::string pattern =
  17652. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17653. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17654. res.set_content("hit", "text/plain");
  17655. });
  17656. auto port = svr.bind_to_any_port(HOST);
  17657. std::thread t([&]() { svr.listen_after_bind(); });
  17658. auto se = detail::scope_exit([&] {
  17659. svr.stop();
  17660. t.join();
  17661. ASSERT_FALSE(svr.is_running());
  17662. });
  17663. svr.wait_until_ready();
  17664. Client cli(HOST, port);
  17665. auto res = cli.Get(pattern);
  17666. ASSERT_TRUE(res);
  17667. EXPECT_EQ(StatusCode::OK_200, res->status);
  17668. }
  17669. TEST(ParseUrlTest, VariousPatterns) {
  17670. {
  17671. detail::UrlComponents uc;
  17672. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17673. EXPECT_EQ("http", uc.scheme);
  17674. EXPECT_EQ("example.com", uc.host);
  17675. EXPECT_EQ("8080", uc.port);
  17676. EXPECT_EQ("/path", uc.path);
  17677. EXPECT_EQ("?q=1", uc.query);
  17678. }
  17679. {
  17680. detail::UrlComponents uc;
  17681. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17682. EXPECT_EQ("https", uc.scheme);
  17683. EXPECT_EQ("example.com", uc.host);
  17684. EXPECT_TRUE(uc.port.empty());
  17685. EXPECT_EQ("/path", uc.path);
  17686. }
  17687. {
  17688. detail::UrlComponents uc;
  17689. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17690. EXPECT_EQ("::1", uc.host);
  17691. EXPECT_EQ("8080", uc.port);
  17692. EXPECT_EQ("/path", uc.path);
  17693. }
  17694. {
  17695. detail::UrlComponents uc;
  17696. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17697. }
  17698. {
  17699. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17700. // the path while the connection still targets the bracketed host.
  17701. detail::UrlComponents uc;
  17702. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17703. }
  17704. {
  17705. detail::UrlComponents uc;
  17706. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17707. }
  17708. {
  17709. detail::UrlComponents uc;
  17710. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17711. EXPECT_EQ("::1", uc.host);
  17712. EXPECT_TRUE(uc.port.empty());
  17713. EXPECT_EQ("/path", uc.path);
  17714. }
  17715. {
  17716. detail::UrlComponents uc;
  17717. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17718. EXPECT_TRUE(uc.scheme.empty());
  17719. EXPECT_EQ("example.com", uc.host);
  17720. EXPECT_EQ("/path", uc.path);
  17721. EXPECT_EQ("?q=1", uc.query);
  17722. }
  17723. {
  17724. detail::UrlComponents uc;
  17725. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17726. EXPECT_TRUE(uc.host.empty());
  17727. EXPECT_EQ("/path", uc.path);
  17728. EXPECT_EQ("?q=1", uc.query);
  17729. }
  17730. {
  17731. detail::UrlComponents uc;
  17732. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17733. EXPECT_EQ("example.com", uc.host);
  17734. EXPECT_EQ("8080", uc.port);
  17735. }
  17736. {
  17737. // Unix socket path — must not be parsed as host
  17738. detail::UrlComponents uc;
  17739. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17740. EXPECT_TRUE(uc.host.empty());
  17741. }
  17742. {
  17743. detail::UrlComponents uc;
  17744. ASSERT_TRUE(detail::parse_url("", uc));
  17745. EXPECT_TRUE(uc.host.empty());
  17746. EXPECT_TRUE(uc.path.empty());
  17747. }
  17748. {
  17749. detail::UrlComponents uc;
  17750. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17751. }
  17752. {
  17753. detail::UrlComponents uc;
  17754. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17755. }
  17756. {
  17757. // Accepted by parse_url; callers restrict to http/https
  17758. detail::UrlComponents uc;
  17759. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17760. EXPECT_EQ("ftp", uc.scheme);
  17761. }
  17762. {
  17763. detail::UrlComponents uc;
  17764. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17765. }
  17766. {
  17767. detail::UrlComponents uc;
  17768. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17769. }
  17770. }
  17771. TEST(ParseUrlTest, FragmentHandling) {
  17772. {
  17773. detail::UrlComponents uc;
  17774. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17775. EXPECT_EQ("/path", uc.path);
  17776. EXPECT_TRUE(uc.query.empty());
  17777. }
  17778. {
  17779. detail::UrlComponents uc;
  17780. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17781. EXPECT_TRUE(uc.path.empty());
  17782. EXPECT_TRUE(uc.query.empty());
  17783. }
  17784. }
  17785. TEST(ParseUrlTest, UserinfoHandling) {
  17786. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17787. // parsers would see evil.com as the host.
  17788. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17789. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17790. for (auto url : urls) {
  17791. detail::UrlComponents uc;
  17792. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17793. }
  17794. }
  17795. TEST(ParseUrlTest, IPv6EdgeCases) {
  17796. {
  17797. detail::UrlComponents uc;
  17798. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17799. EXPECT_TRUE(uc.scheme.empty());
  17800. EXPECT_EQ("::1", uc.host);
  17801. EXPECT_EQ("8080", uc.port);
  17802. }
  17803. {
  17804. // Zone ID '%25' is not in [a-fA-F0-9:]
  17805. detail::UrlComponents uc;
  17806. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17807. }
  17808. }
  17809. TEST(ParseUrlTest, SchemeEdgeCases) {
  17810. {
  17811. detail::UrlComponents uc;
  17812. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17813. }
  17814. {
  17815. detail::UrlComponents uc;
  17816. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17817. }
  17818. {
  17819. detail::UrlComponents uc;
  17820. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17821. }
  17822. }
  17823. TEST(ParseUrlTest, PortEdgeCases) {
  17824. {
  17825. detail::UrlComponents uc;
  17826. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17827. EXPECT_TRUE(uc.port.empty());
  17828. EXPECT_EQ("/path", uc.path);
  17829. }
  17830. {
  17831. // parse_url accepts any port string; validation is done by parse_port
  17832. detail::UrlComponents uc;
  17833. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17834. EXPECT_EQ("abc", uc.port);
  17835. }
  17836. }
  17837. TEST(ParseUrlTest, WebSocketPatterns) {
  17838. {
  17839. detail::UrlComponents uc;
  17840. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17841. EXPECT_EQ("ws", uc.scheme);
  17842. EXPECT_EQ("echo.example.com", uc.host);
  17843. EXPECT_EQ("8080", uc.port);
  17844. EXPECT_EQ("/ws", uc.path);
  17845. }
  17846. {
  17847. detail::UrlComponents uc;
  17848. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17849. EXPECT_EQ("wss", uc.scheme);
  17850. EXPECT_EQ("echo.example.com", uc.host);
  17851. EXPECT_TRUE(uc.port.empty());
  17852. EXPECT_EQ("/ws", uc.path);
  17853. }
  17854. }
  17855. TEST(ParseUrlTest, QueryOnly) {
  17856. detail::UrlComponents uc;
  17857. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17858. EXPECT_TRUE(uc.host.empty());
  17859. EXPECT_TRUE(uc.path.empty());
  17860. EXPECT_EQ("?q=1&r=2", uc.query);
  17861. }
  17862. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17863. detail::UrlComponents uc;
  17864. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17865. EXPECT_TRUE(uc.scheme.empty());
  17866. EXPECT_EQ("example.com", uc.host);
  17867. EXPECT_EQ("443", uc.port);
  17868. EXPECT_EQ("/path", uc.path);
  17869. }
  17870. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17871. // If ipv6 regex working, regex match codepath is taken.
  17872. // else port will default to 80 in Client impl
  17873. int clientImplMagicPort = 80;
  17874. int port = 4321;
  17875. // above ports must be different to avoid false negative
  17876. EXPECT_NE(clientImplMagicPort, port);
  17877. std::string ipV6TestURL = "http://[ff06::c3]";
  17878. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17879. CLIENT_PRIVATE_KEY_FILE);
  17880. EXPECT_EQ(cli.port(), port);
  17881. }
  17882. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17883. auto file_path = "./www/dir/index.html";
  17884. auto dir_path = "./www/dir";
  17885. detail::FileStat stat_file(file_path);
  17886. EXPECT_TRUE(stat_file.is_file());
  17887. EXPECT_FALSE(stat_file.is_dir());
  17888. detail::FileStat stat_dir(dir_path);
  17889. EXPECT_FALSE(stat_dir.is_file());
  17890. EXPECT_TRUE(stat_dir.is_dir());
  17891. }
  17892. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17893. // IPv4 with default HTTP port (80)
  17894. EXPECT_EQ("example.com",
  17895. detail::make_host_and_port_string("example.com", 80, false));
  17896. // IPv4 with default HTTPS port (443)
  17897. EXPECT_EQ("example.com",
  17898. detail::make_host_and_port_string("example.com", 443, true));
  17899. // IPv4 with non-default HTTP port
  17900. EXPECT_EQ("example.com:8080",
  17901. detail::make_host_and_port_string("example.com", 8080, false));
  17902. // IPv4 with non-default HTTPS port
  17903. EXPECT_EQ("example.com:8443",
  17904. detail::make_host_and_port_string("example.com", 8443, true));
  17905. // IPv6 with default HTTP port (80)
  17906. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17907. // IPv6 with default HTTPS port (443)
  17908. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17909. // IPv6 with non-default HTTP port
  17910. EXPECT_EQ("[::1]:8080",
  17911. detail::make_host_and_port_string("::1", 8080, false));
  17912. // IPv6 with non-default HTTPS port
  17913. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17914. // IPv6 full address with default port
  17915. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17916. detail::make_host_and_port_string(
  17917. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17918. // IPv6 full address with non-default port
  17919. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17920. detail::make_host_and_port_string(
  17921. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17922. // IPv6 localhost with non-default port
  17923. EXPECT_EQ("[::1]:3000",
  17924. detail::make_host_and_port_string("::1", 3000, false));
  17925. // IPv6 with zone ID (link-local address) with default port
  17926. EXPECT_EQ("[fe80::1%eth0]",
  17927. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17928. // IPv6 with zone ID (link-local address) with non-default port
  17929. EXPECT_EQ("[fe80::1%eth0]:8080",
  17930. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17931. // Edge case: Port 443 with is_ssl=false (should add port)
  17932. EXPECT_EQ("example.com:443",
  17933. detail::make_host_and_port_string("example.com", 443, false));
  17934. // Edge case: Port 80 with is_ssl=true (should add port)
  17935. EXPECT_EQ("example.com:80",
  17936. detail::make_host_and_port_string("example.com", 80, true));
  17937. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17938. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17939. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17940. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17941. // Security fix: Already bracketed IPv6 should not get double brackets
  17942. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17943. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17944. EXPECT_EQ("[::1]:8080",
  17945. detail::make_host_and_port_string("[::1]", 8080, false));
  17946. EXPECT_EQ("[2001:db8::1]:8080",
  17947. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17948. EXPECT_EQ("[fe80::1%eth0]",
  17949. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17950. EXPECT_EQ("[fe80::1%eth0]:8080",
  17951. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17952. // Edge case: Empty host (should return as-is)
  17953. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17954. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17955. // This is a known limitation but shouldn't crash
  17956. EXPECT_EQ("[host:name]",
  17957. detail::make_host_and_port_string("host:name", 80, false));
  17958. // Port number edge cases (no validation, but should not crash)
  17959. EXPECT_EQ("example.com:0",
  17960. detail::make_host_and_port_string("example.com", 0, false));
  17961. EXPECT_EQ("example.com:-1",
  17962. detail::make_host_and_port_string("example.com", -1, false));
  17963. EXPECT_EQ("example.com:65535",
  17964. detail::make_host_and_port_string("example.com", 65535, false));
  17965. EXPECT_EQ("example.com:65536",
  17966. detail::make_host_and_port_string("example.com", 65536, false));
  17967. }
  17968. #ifdef CPPHTTPLIB_SSL_ENABLED
  17969. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17970. httplib::SSLClient cli("roblox.com", 443);
  17971. cli.set_follow_location(true);
  17972. auto res = cli.Get("/");
  17973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17974. EXPECT_EQ(StatusCode::OK_200, res->status);
  17975. }
  17976. #endif
  17977. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17978. Server svr;
  17979. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17980. EXPECT_EQ(res.status, 400);
  17981. });
  17982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17983. auto se = detail::scope_exit([&] {
  17984. svr.stop();
  17985. thread.join();
  17986. ASSERT_FALSE(svr.is_running());
  17987. });
  17988. svr.wait_until_ready();
  17989. Client cli(HOST, PORT);
  17990. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17991. }
  17992. TEST(InvalidHeaderCharsTest, is_field_name) {
  17993. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17994. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17995. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17996. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17997. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17998. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17999. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18000. EXPECT_FALSE(detail::fields::is_field_name(""));
  18001. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18002. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18003. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18004. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18005. }
  18006. TEST(InvalidHeaderCharsTest, is_field_value) {
  18007. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18008. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18009. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18010. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18011. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18012. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18013. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18014. EXPECT_TRUE(detail::fields::is_field_value(""));
  18015. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18016. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18017. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18018. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18019. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18020. }
  18021. TEST(InvalidHeaderCharsTest, OnServer) {
  18022. Server svr;
  18023. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18024. std::string header = "Not Set";
  18025. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18026. res.set_header(header, "value");
  18027. res.set_content("Page Content Page Content", "text/plain");
  18028. });
  18029. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18030. std::string header = "Not Set";
  18031. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18032. res.set_header("X-Test", header);
  18033. res.set_content("Page Content Page Content", "text/plain");
  18034. });
  18035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18036. auto se = detail::scope_exit([&] {
  18037. svr.stop();
  18038. thread.join();
  18039. ASSERT_FALSE(svr.is_running());
  18040. });
  18041. svr.wait_until_ready();
  18042. Client cli(HOST, PORT);
  18043. {
  18044. auto res = cli.Get(
  18045. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18047. EXPECT_EQ("Page Content Page Content", res->body);
  18048. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18049. }
  18050. {
  18051. auto res = cli.Get(
  18052. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18054. EXPECT_EQ("Page Content Page Content", res->body);
  18055. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18056. }
  18057. }
  18058. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18059. auto handled = false;
  18060. Server svr;
  18061. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18062. thread t = thread([&] { svr.listen(HOST, PORT); });
  18063. auto se = detail::scope_exit([&] {
  18064. svr.stop();
  18065. t.join();
  18066. ASSERT_FALSE(svr.is_running());
  18067. ASSERT_FALSE(handled);
  18068. });
  18069. svr.wait_until_ready();
  18070. auto req = "POST /test HTTP/1.1\r\n"
  18071. "Content-Length: x\r\n"
  18072. "\r\n";
  18073. std::string response;
  18074. ASSERT_TRUE(send_request(1, req, &response));
  18075. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18076. response.substr(0, response.find("\r\n")));
  18077. }
  18078. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18079. // case-insensitive, and a server that receives a 100-continue expectation in
  18080. // an HTTP/1.0 request MUST ignore it.
  18081. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18082. std::string response;
  18083. ASSERT_TRUE(send_request(1, req, &response, port));
  18084. *got_100 = response.find("100 Continue") != std::string::npos;
  18085. }
  18086. class ExpectTokenTest : public ::testing::Test {
  18087. protected:
  18088. void SetUp() override {
  18089. svr_.Post("/p", [](const Request &, Response &res) {
  18090. res.set_content("ok", "text/plain");
  18091. });
  18092. port_ = svr_.bind_to_any_port(HOST);
  18093. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18094. svr_.wait_until_ready();
  18095. }
  18096. void TearDown() override {
  18097. svr_.stop();
  18098. if (thread_.joinable()) { thread_.join(); }
  18099. }
  18100. std::string request(const char *version, const char *expect_value) const {
  18101. return std::string("POST /p ") + version +
  18102. "\r\n"
  18103. "Host: localhost\r\n"
  18104. "Content-Length: 2\r\n"
  18105. "Connection: close\r\n"
  18106. "Expect: " +
  18107. expect_value +
  18108. "\r\n"
  18109. "\r\n"
  18110. "hi";
  18111. }
  18112. Server svr_;
  18113. int port_ = 0;
  18114. thread thread_;
  18115. };
  18116. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18117. bool got_100 = false;
  18118. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18119. EXPECT_TRUE(got_100);
  18120. }
  18121. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18122. bool got_100 = true;
  18123. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18124. EXPECT_FALSE(got_100);
  18125. }
  18126. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18127. bool got_100 = false;
  18128. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18129. EXPECT_TRUE(got_100);
  18130. }
  18131. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18132. bool got_100 = false;
  18133. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18134. EXPECT_TRUE(got_100);
  18135. }
  18136. // `100 Continue` is sent only when the server starts reading the body, so a
  18137. // request rejected before that never invites the client to send it. The
  18138. // requests below carry the expectation but withhold the body, as a client
  18139. // waiting for `100 Continue` would.
  18140. // A POST that expects `100 Continue` and withholds its two-byte body.
  18141. static std::string expect_headers_only(const std::string &path) {
  18142. return "POST " + path +
  18143. " HTTP/1.1\r\n"
  18144. "Host: localhost\r\n"
  18145. "Content-Length: 2\r\n"
  18146. "Expect: 100-continue\r\n"
  18147. "\r\n";
  18148. }
  18149. class ExpectLazyContinueTest : public ::testing::Test {
  18150. protected:
  18151. void SetUp() override {
  18152. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18153. if (req.path == "/pre-routing") {
  18154. res.status = StatusCode::Unauthorized_401;
  18155. return Server::HandlerResponse::Handled;
  18156. }
  18157. return Server::HandlerResponse::Unhandled;
  18158. });
  18159. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18160. if (req.matched_route == "/pre-request") {
  18161. res.status = StatusCode::Forbidden_403;
  18162. return Server::HandlerResponse::Handled;
  18163. }
  18164. return Server::HandlerResponse::Unhandled;
  18165. });
  18166. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18167. res.set_content("ok", "text/plain");
  18168. });
  18169. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18170. res.set_content("ok", "text/plain");
  18171. });
  18172. svr_.Post("/reader-used", [](const Request &, Response &res,
  18173. const ContentReader &content_reader) {
  18174. std::string body;
  18175. content_reader([&](const char *data, size_t len) {
  18176. body.append(data, len);
  18177. return true;
  18178. });
  18179. res.set_content(body, "text/plain");
  18180. });
  18181. svr_.Post("/reader-unused",
  18182. [](const Request &, Response &res, const ContentReader &) {
  18183. res.set_content("ignored", "text/plain");
  18184. });
  18185. port_ = svr_.bind_to_any_port(HOST);
  18186. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18187. svr_.wait_until_ready();
  18188. }
  18189. void TearDown() override {
  18190. svr_.stop();
  18191. if (thread_.joinable()) { thread_.join(); }
  18192. }
  18193. // Sends `req` and reads until the server closes the connection. Returns
  18194. // false if the read had to wait for the client-side timeout instead.
  18195. bool send_until_closed(const std::string &req, std::string *resp) const {
  18196. auto start = std::chrono::steady_clock::now();
  18197. if (!send_request(3, req, resp, port_)) { return false; }
  18198. auto elapsed = std::chrono::steady_clock::now() - start;
  18199. return elapsed < std::chrono::seconds(2);
  18200. }
  18201. // The final response comes without `100 Continue`, and the server closes
  18202. // the connection since the body may or may not follow.
  18203. void expect_final_without_interim(const std::string &path,
  18204. const char *status_line) const {
  18205. std::string resp;
  18206. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18207. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18208. EXPECT_EQ(0u, resp.find(status_line));
  18209. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18210. }
  18211. Server svr_;
  18212. int port_ = 0;
  18213. thread thread_;
  18214. };
  18215. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18216. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18217. }
  18218. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18219. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18220. }
  18221. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18222. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18223. }
  18224. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18225. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18226. }
  18227. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18228. // The body follows once `100 Continue` has had time to arrive.
  18229. auto req = expect_headers_only("/reader-used");
  18230. req.insert(req.size() - 2, "Connection: close\r\n");
  18231. std::string resp;
  18232. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18233. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18234. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18235. EXPECT_NE(std::string::npos, resp.find("hi"));
  18236. }
  18237. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18238. // Large enough for the client to add `Expect: 100-continue` itself.
  18239. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18240. std::atomic<bool> body_sent{false};
  18241. Client cli(HOST, port_);
  18242. auto res = cli.Post(
  18243. "/pre-request", length,
  18244. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18245. body_sent = true;
  18246. std::string chunk(len, 'x');
  18247. sink.write(chunk.data(), chunk.size());
  18248. return true;
  18249. },
  18250. "application/octet-stream");
  18251. ASSERT_TRUE(res);
  18252. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18253. EXPECT_FALSE(body_sent);
  18254. }
  18255. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18256. Server svr;
  18257. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18258. return StatusCode::ExpectationFailed_417;
  18259. });
  18260. svr.Post("/p", [](const Request &, Response &res) {
  18261. res.set_content("ok", "text/plain");
  18262. });
  18263. auto port = svr.bind_to_any_port(HOST);
  18264. thread t = thread([&] { svr.listen_after_bind(); });
  18265. auto se = detail::scope_exit([&] {
  18266. svr.stop();
  18267. t.join();
  18268. });
  18269. svr.wait_until_ready();
  18270. std::string resp;
  18271. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18272. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18273. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18274. // Exactly one response: the route handler must not run after the 417.
  18275. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18276. }
  18277. #ifndef _WIN32
  18278. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18279. static constexpr char reject[] = "Unauthorized";
  18280. static constexpr char accept[] = "Upload accepted";
  18281. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18282. Server svr;
  18283. svr.set_expect_100_continue_handler(
  18284. [](const Request & /*req*/, Response &res) {
  18285. res.status = StatusCode::Unauthorized_401;
  18286. res.set_content(reject, "text/plain");
  18287. return res.status;
  18288. });
  18289. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18290. res.set_content(accept, "text/plain");
  18291. });
  18292. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18293. auto se = detail::scope_exit([&] {
  18294. svr.stop();
  18295. thread.join();
  18296. ASSERT_FALSE(svr.is_running());
  18297. });
  18298. svr.wait_until_ready();
  18299. {
  18300. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18301. curl_easy_init(), &curl_easy_cleanup};
  18302. ASSERT_NE(curl, nullptr);
  18303. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18304. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18305. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18306. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18307. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18308. &curl_slist_free_all};
  18309. ASSERT_NE(list, nullptr);
  18310. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18311. struct read_data {
  18312. uint64_t read_size;
  18313. uint64_t total_size;
  18314. } data = {0, total_size};
  18315. using read_callback_t =
  18316. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18317. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18318. void *userdata) -> size_t {
  18319. read_data *d = (read_data *)userdata;
  18320. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18321. std::fill_n(ptr, size * nmemb, 'A');
  18322. d->read_size += size * nmemb;
  18323. return size * nmemb;
  18324. };
  18325. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18326. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18327. std::vector<char> buffer;
  18328. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18329. using write_callback_t =
  18330. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18331. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18332. void *userdata) -> size_t {
  18333. std::vector<char> *buf = (std::vector<char> *)userdata;
  18334. buf->reserve(buf->size() + size * nmemb + 1);
  18335. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18336. return size * nmemb;
  18337. };
  18338. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18339. {
  18340. const auto res = curl_easy_perform(curl.get());
  18341. ASSERT_EQ(res, CURLE_OK);
  18342. }
  18343. {
  18344. auto response_code = long{};
  18345. const auto res =
  18346. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18347. ASSERT_EQ(res, CURLE_OK);
  18348. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18349. }
  18350. {
  18351. auto dl = curl_off_t{};
  18352. const auto res =
  18353. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18354. ASSERT_EQ(res, CURLE_OK);
  18355. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18356. }
  18357. {
  18358. buffer.push_back('\0');
  18359. ASSERT_STRCASEEQ(buffer.data(), reject);
  18360. }
  18361. }
  18362. }
  18363. #endif
  18364. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18365. // Regression test for #2458.
  18366. //
  18367. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18368. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18369. // ticket can make the client socket spuriously readable during the
  18370. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18371. // the client withholds the body and then blocks reading a response that never
  18372. // comes, failing with `Failed to read connection`.
  18373. //
  18374. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18375. // within the timeout. This raw OpenSSL server deliberately never sends
  18376. // `100 Continue`; the client must still deliver the body and receive 200.
  18377. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18378. signal(SIGPIPE, SIG_IGN);
  18379. const auto port = PORT + 4;
  18380. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18381. ASSERT_NE(srv, INVALID_SOCKET);
  18382. int opt = 1;
  18383. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18384. sockaddr_in addr{};
  18385. addr.sin_family = AF_INET;
  18386. addr.sin_port = htons(static_cast<uint16_t>(port));
  18387. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18388. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18389. ASSERT_EQ(0, ::listen(srv, 1));
  18390. std::atomic<size_t> server_body_bytes{0};
  18391. auto server_thread = std::thread([&] {
  18392. sockaddr_in cli_addr{};
  18393. socklen_t cli_len = sizeof(cli_addr);
  18394. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18395. if (cli == INVALID_SOCKET) { return; }
  18396. // Bound the lifetime of the server side so a buggy client (which never
  18397. // sends the body) cannot make this thread block forever on join.
  18398. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18399. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18400. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18401. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18402. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18403. SSL *ssl = SSL_new(ctx);
  18404. SSL_set_fd(ssl, static_cast<int>(cli));
  18405. if (SSL_accept(ssl) > 0) {
  18406. // Read the request headers. Reading here also flushes the TLS 1.3
  18407. // session tickets to the client. Deliberately do NOT send
  18408. // `100 Continue`.
  18409. std::string buf;
  18410. char tmp[1024];
  18411. while (buf.find("\r\n\r\n") == std::string::npos) {
  18412. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18413. if (n <= 0) { break; }
  18414. buf.append(tmp, static_cast<size_t>(n));
  18415. }
  18416. // A correct client sends the body now; count what arrives.
  18417. auto pos = buf.find("\r\n\r\n");
  18418. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18419. while (body < 4096) {
  18420. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18421. if (n <= 0) { break; }
  18422. body += static_cast<size_t>(n);
  18423. }
  18424. server_body_bytes = body;
  18425. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18426. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18427. SSL_shutdown(ssl);
  18428. }
  18429. SSL_free(ssl);
  18430. detail::close_socket(cli);
  18431. SSL_CTX_free(ctx);
  18432. });
  18433. auto se = detail::scope_exit([&] {
  18434. server_thread.join();
  18435. detail::close_socket(srv);
  18436. });
  18437. SSLClient cli("127.0.0.1", port);
  18438. cli.enable_server_certificate_verification(false);
  18439. cli.set_connection_timeout(5, 0);
  18440. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18441. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18442. std::string body(4096, 'A');
  18443. auto res = cli.Put("/api/test", body, "application/json");
  18444. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18445. EXPECT_EQ(StatusCode::OK_200, res->status);
  18446. EXPECT_EQ(body.size(), server_body_bytes.load());
  18447. }
  18448. #endif
  18449. template <typename S, typename C>
  18450. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18451. svr.Get("/stream", [&](const Request &, Response &res) {
  18452. auto data = new std::string("01234567890123456789");
  18453. res.set_content_provider(
  18454. data->size(), "text/plain",
  18455. [&, data](size_t offset, size_t length, DataSink &sink) {
  18456. const size_t DATA_CHUNK_SIZE = 4;
  18457. const auto &d = *data;
  18458. std::this_thread::sleep_for(std::chrono::seconds(1));
  18459. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18460. return true;
  18461. },
  18462. [data](bool success) {
  18463. EXPECT_FALSE(success);
  18464. delete data;
  18465. });
  18466. });
  18467. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18468. auto i = new size_t(0);
  18469. res.set_content_provider(
  18470. "text/plain",
  18471. [i](size_t, DataSink &sink) {
  18472. if (*i < 5) {
  18473. std::this_thread::sleep_for(std::chrono::seconds(1));
  18474. sink.write("abcd", 4);
  18475. (*i)++;
  18476. } else {
  18477. sink.done();
  18478. }
  18479. return true;
  18480. },
  18481. [i](bool success) {
  18482. EXPECT_FALSE(success);
  18483. delete i;
  18484. });
  18485. });
  18486. svr.Get("/chunked", [&](const Request &, Response &res) {
  18487. auto i = new size_t(0);
  18488. res.set_chunked_content_provider(
  18489. "text/plain",
  18490. [i](size_t, DataSink &sink) {
  18491. if (*i < 5) {
  18492. std::this_thread::sleep_for(std::chrono::seconds(1));
  18493. sink.os << "abcd";
  18494. (*i)++;
  18495. } else {
  18496. sink.done();
  18497. }
  18498. return true;
  18499. },
  18500. [i](bool success) {
  18501. EXPECT_FALSE(success);
  18502. delete i;
  18503. });
  18504. });
  18505. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18506. auto se = detail::scope_exit([&] {
  18507. svr.stop();
  18508. listen_thread.join();
  18509. ASSERT_FALSE(svr.is_running());
  18510. });
  18511. svr.wait_until_ready();
  18512. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18513. {
  18514. auto start = std::chrono::steady_clock::now();
  18515. auto res = cli.Get("/stream");
  18516. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18517. std::chrono::steady_clock::now() - start)
  18518. .count();
  18519. ASSERT_FALSE(res);
  18520. EXPECT_EQ(Error::Read, res.error());
  18521. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18522. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18523. }
  18524. {
  18525. auto start = std::chrono::steady_clock::now();
  18526. auto res = cli.Get("/stream_without_length");
  18527. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18528. std::chrono::steady_clock::now() - start)
  18529. .count();
  18530. ASSERT_FALSE(res);
  18531. EXPECT_EQ(Error::Read, res.error());
  18532. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18533. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18534. }
  18535. {
  18536. auto start = std::chrono::steady_clock::now();
  18537. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18538. EXPECT_EQ("abcd", string(data, data_length));
  18539. return true;
  18540. });
  18541. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18542. std::chrono::steady_clock::now() - start)
  18543. .count();
  18544. ASSERT_FALSE(res);
  18545. EXPECT_EQ(Error::Read, res.error());
  18546. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18547. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18548. }
  18549. }
  18550. TEST(MaxTimeoutTest, ContentStream) {
  18551. time_t timeout = 2000;
  18552. time_t threshold = 200;
  18553. Server svr;
  18554. Client cli("localhost", PORT);
  18555. max_timeout_test(svr, cli, timeout, threshold);
  18556. }
  18557. #ifdef CPPHTTPLIB_SSL_ENABLED
  18558. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18559. time_t timeout = 2000;
  18560. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18562. SSLClient cli("localhost", PORT);
  18563. cli.enable_server_certificate_verification(false);
  18564. max_timeout_test(svr, cli, timeout, threshold);
  18565. }
  18566. #endif
  18567. class EventDispatcher {
  18568. public:
  18569. EventDispatcher() {}
  18570. bool wait_event(DataSink *sink) {
  18571. unique_lock<mutex> lk(m_);
  18572. int id = id_;
  18573. // Wait with timeout to prevent hanging if client disconnects
  18574. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18575. [&] { return cid_ == id; })) {
  18576. return false; // Timeout occurred
  18577. }
  18578. sink->write(message_.data(), message_.size());
  18579. return true;
  18580. }
  18581. void send_event(const string &message) {
  18582. lock_guard<mutex> lk(m_);
  18583. cid_ = id_++;
  18584. message_ = message;
  18585. cv_.notify_all();
  18586. }
  18587. private:
  18588. mutex m_;
  18589. condition_variable cv_;
  18590. atomic_int id_{0};
  18591. atomic_int cid_{-1};
  18592. string message_;
  18593. };
  18594. TEST(ClientInThreadTest, Issue2068) {
  18595. EventDispatcher ed;
  18596. Server svr;
  18597. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18598. res.set_chunked_content_provider("text/event-stream",
  18599. [&](size_t /*offset*/, DataSink &sink) {
  18600. return ed.wait_event(&sink);
  18601. });
  18602. });
  18603. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18604. svr.wait_until_ready();
  18605. thread event_thread([&] {
  18606. int id = 0;
  18607. while (svr.is_running()) {
  18608. this_thread::sleep_for(chrono::milliseconds(500));
  18609. std::stringstream ss;
  18610. ss << "data: " << id << "\n\n";
  18611. ed.send_event(ss.str());
  18612. id++;
  18613. }
  18614. });
  18615. auto se = detail::scope_exit([&] {
  18616. svr.stop();
  18617. listen_thread.join();
  18618. event_thread.join();
  18619. ASSERT_FALSE(svr.is_running());
  18620. });
  18621. {
  18622. auto client = detail::make_unique<Client>(HOST, PORT);
  18623. client->set_read_timeout(std::chrono::minutes(10));
  18624. std::atomic<bool> stop{false};
  18625. std::thread t([&] {
  18626. client->Get("/event1",
  18627. [&](const char *, size_t) -> bool { return !stop; });
  18628. });
  18629. std::this_thread::sleep_for(std::chrono::seconds(2));
  18630. stop = true;
  18631. client->stop();
  18632. t.join();
  18633. // Reset client after thread has finished
  18634. client.reset();
  18635. }
  18636. }
  18637. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18638. auto handled = false;
  18639. Server svr;
  18640. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18641. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18642. auto se = detail::scope_exit([&] {
  18643. svr.stop();
  18644. t.join();
  18645. ASSERT_FALSE(svr.is_running());
  18646. ASSERT_FALSE(handled);
  18647. });
  18648. svr.wait_until_ready();
  18649. // Two Content-Length headers with different values — must be rejected
  18650. auto req = "POST /test HTTP/1.1\r\n"
  18651. "Content-Length: 5\r\n"
  18652. "Content-Length: 10\r\n"
  18653. "\r\n"
  18654. "hello";
  18655. std::string response;
  18656. ASSERT_TRUE(send_request(1, req, &response));
  18657. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18658. response.substr(0, response.find("\r\n")));
  18659. }
  18660. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18661. auto handled = false;
  18662. Server svr;
  18663. svr.Post("/test", [&](const Request &, Response &res) {
  18664. handled = true;
  18665. res.set_content("ok", "text/plain");
  18666. });
  18667. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18668. auto se = detail::scope_exit([&] {
  18669. svr.stop();
  18670. t.join();
  18671. ASSERT_FALSE(svr.is_running());
  18672. ASSERT_TRUE(handled);
  18673. });
  18674. svr.wait_until_ready();
  18675. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18676. auto req = "POST /test HTTP/1.1\r\n"
  18677. "Host: localhost\r\n"
  18678. "Content-Length: 5\r\n"
  18679. "Content-Length: 5\r\n"
  18680. "\r\n"
  18681. "hello";
  18682. std::string response;
  18683. ASSERT_TRUE(send_request(1, req, &response));
  18684. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18685. }
  18686. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18687. Server svr;
  18688. svr.Get("/test", [](const Request &, Response &res) {
  18689. res.set_content("ok", "text/plain");
  18690. });
  18691. auto port = svr.bind_to_any_port(HOST);
  18692. thread t = thread([&] { svr.listen_after_bind(); });
  18693. auto se = detail::scope_exit([&] {
  18694. svr.stop();
  18695. t.join();
  18696. ASSERT_FALSE(svr.is_running());
  18697. });
  18698. svr.wait_until_ready();
  18699. auto status_line = [&](const std::string &host_lines) {
  18700. std::string res;
  18701. send_request(
  18702. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18703. &res, port);
  18704. return res.substr(0, res.find("\r\n"));
  18705. };
  18706. const char *accepted[] = {
  18707. "Host: localhost\r\n",
  18708. "Host: a.example:8080\r\n",
  18709. "Host: my_service\r\n",
  18710. "Host: [::1]:8080\r\n",
  18711. "Host: [fe80::1%25eth0]\r\n",
  18712. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18713. };
  18714. for (auto host_lines : accepted) {
  18715. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18716. }
  18717. const char *rejected[] = {
  18718. "Host: a.example\r\nHost: b.example\r\n",
  18719. "Host: a.example\r\nHost: a.example\r\n",
  18720. "Host: a@b.example\r\n",
  18721. "Host: a.example/b\r\n",
  18722. "Host: a.example\\b\r\n",
  18723. "Host: a.example?b\r\n",
  18724. "Host: a.example#b\r\n",
  18725. "Host: a.example b.example\r\n",
  18726. };
  18727. for (auto host_lines : rejected) {
  18728. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18729. << host_lines;
  18730. }
  18731. }
  18732. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18733. Server svr;
  18734. svr.Get("/", [](const Request &req, Response &res) {
  18735. EXPECT_EQ(2U, req.trailers.size());
  18736. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18737. // Denied
  18738. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18739. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18740. // Accepted
  18741. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18742. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18743. EXPECT_TRUE(req.has_trailer("X-World"));
  18744. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18745. res.set_content("ok", "text/plain");
  18746. });
  18747. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18748. auto se = detail::scope_exit([&] {
  18749. svr.stop();
  18750. t.join();
  18751. ASSERT_FALSE(svr.is_running());
  18752. });
  18753. svr.wait_until_ready();
  18754. const std::string req = "GET / HTTP/1.1\r\n"
  18755. "Transfer-Encoding: chunked\r\n"
  18756. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18757. "\r\n"
  18758. "0\r\n"
  18759. "Content-Length: 10\r\n"
  18760. "Host: internal.local\r\n"
  18761. "Content-Type: malicious/content\r\n"
  18762. "Cookie: any\r\n"
  18763. "Set-Cookie: any\r\n"
  18764. "X-Forwarded-For: attacker.com\r\n"
  18765. "X-Real-Ip: 1.1.1.1\r\n"
  18766. "X-Hello: hello\r\n"
  18767. "X-World: world\r\n"
  18768. "\r\n";
  18769. std::string res;
  18770. ASSERT_TRUE(send_request(1, req, &res));
  18771. }
  18772. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18773. // several field lines, and the combined value is what has to be parsed. A
  18774. // Trailer field split across lines therefore declares every name it lists;
  18775. // reading only the first line silently drops the trailers the later lines
  18776. // declare. The prohibited-trailer filter still applies to every line.
  18777. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18778. Server svr;
  18779. size_t observed_trailer_count = 0;
  18780. std::string observed_hello;
  18781. std::string observed_world;
  18782. bool observed_content_length = true;
  18783. svr.Get("/", [&](const Request &req, Response &res) {
  18784. observed_trailer_count = req.trailers.size();
  18785. observed_hello = req.get_trailer_value("X-Hello");
  18786. observed_world = req.get_trailer_value("X-World");
  18787. observed_content_length = req.has_trailer("Content-Length");
  18788. res.set_content("ok", "text/plain");
  18789. });
  18790. auto port = svr.bind_to_any_port(HOST);
  18791. thread t = thread([&]() { svr.listen_after_bind(); });
  18792. auto se = detail::scope_exit([&] {
  18793. svr.stop();
  18794. t.join();
  18795. ASSERT_FALSE(svr.is_running());
  18796. });
  18797. svr.wait_until_ready();
  18798. const std::string req = "GET / HTTP/1.1\r\n"
  18799. "Host: localhost\r\n"
  18800. "Transfer-Encoding: chunked\r\n"
  18801. "Trailer: X-Hello\r\n"
  18802. "Trailer: X-World, Content-Length\r\n"
  18803. "\r\n"
  18804. "0\r\n"
  18805. "X-Hello: hello\r\n"
  18806. "X-World: world\r\n"
  18807. "Content-Length: 10\r\n"
  18808. "\r\n";
  18809. std::string res;
  18810. ASSERT_TRUE(send_request(1, req, &res, port));
  18811. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18812. // Accepted: both field lines contribute to the declared set
  18813. EXPECT_EQ(2U, observed_trailer_count);
  18814. EXPECT_EQ(observed_hello, "hello");
  18815. EXPECT_EQ(observed_world, "world");
  18816. // Denied: a prohibited name stays prohibited on a later field line
  18817. EXPECT_FALSE(observed_content_length);
  18818. }
  18819. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18820. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18821. // unbounded run of fields that are never declared, because the counter would
  18822. // only advance for declared fields.
  18823. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18824. Server svr;
  18825. bool handler_called = false;
  18826. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18827. handler_called = true;
  18828. res.set_content("ok", "text/plain");
  18829. });
  18830. auto port = svr.bind_to_any_port(HOST);
  18831. thread t = thread([&]() { svr.listen_after_bind(); });
  18832. auto se = detail::scope_exit([&] {
  18833. svr.stop();
  18834. t.join();
  18835. ASSERT_FALSE(svr.is_running());
  18836. });
  18837. svr.wait_until_ready();
  18838. // Declare nothing, then send far more undeclared trailer fields than the
  18839. // header-count limit. Parsing must stop and reject the request rather than
  18840. // read every line.
  18841. std::string req = "GET / HTTP/1.1\r\n"
  18842. "Transfer-Encoding: chunked\r\n"
  18843. "\r\n"
  18844. "0\r\n";
  18845. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18846. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18847. }
  18848. req += "\r\n";
  18849. std::string res;
  18850. ASSERT_TRUE(send_request(1, req, &res, port));
  18851. // The request is rejected before the handler runs.
  18852. EXPECT_FALSE(handler_called);
  18853. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18854. }
  18855. // The set of declared trailer names is capped so a peer cannot grow it without
  18856. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18857. // declared past the cap is not honored, even if the field is actually sent.
  18858. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18859. Server svr;
  18860. // One name inside the cap and one past it, so the test tracks the cap rather
  18861. // than a fixed count.
  18862. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18863. const std::string within_cap_name = "X-T-0";
  18864. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18865. bool observed_within_cap = false;
  18866. bool observed_past_cap = false;
  18867. svr.Get("/", [&](const Request &req, Response &res) {
  18868. observed_within_cap = req.has_trailer(within_cap_name);
  18869. observed_past_cap = req.has_trailer(past_cap_name);
  18870. res.set_content("ok", "text/plain");
  18871. });
  18872. auto port = svr.bind_to_any_port(HOST);
  18873. thread t = thread([&]() { svr.listen_after_bind(); });
  18874. auto se = detail::scope_exit([&] {
  18875. svr.stop();
  18876. t.join();
  18877. ASSERT_FALSE(svr.is_running());
  18878. });
  18879. svr.wait_until_ready();
  18880. // Declare more trailer names than the cap in a single Trailer field, then
  18881. // actually send the first (within the cap) and the last (past it).
  18882. std::string trailer_decl = "Trailer: ";
  18883. for (int i = 0; i < declared_count; i++) {
  18884. if (i != 0) { trailer_decl += ", "; }
  18885. trailer_decl += "X-T-" + std::to_string(i);
  18886. }
  18887. trailer_decl += "\r\n";
  18888. const std::string req = "GET / HTTP/1.1\r\n"
  18889. "Host: localhost\r\n"
  18890. "Transfer-Encoding: chunked\r\n" +
  18891. trailer_decl +
  18892. "\r\n"
  18893. "0\r\n" +
  18894. within_cap_name + ": a\r\n" + past_cap_name +
  18895. ": b\r\n"
  18896. "\r\n";
  18897. std::string res;
  18898. ASSERT_TRUE(send_request(1, req, &res, port));
  18899. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18900. // A name within the cap is honored; one declared past the cap is dropped.
  18901. EXPECT_TRUE(observed_within_cap);
  18902. EXPECT_FALSE(observed_past_cap);
  18903. }
  18904. // A direct client that is not listed in trusted_proxies must not be able to
  18905. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18906. // the peer address on the actual TCP connection determines whether the
  18907. // header is honored.
  18908. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18909. Server svr;
  18910. // Deliberately does NOT include the loopback address the test client
  18911. // actually connects from, so the direct connection is not a trusted proxy.
  18912. svr.set_trusted_proxies({"203.0.113.66"});
  18913. std::string observed_remote_addr;
  18914. svr.Get("/ip", [&](const Request &req, Response &res) {
  18915. observed_remote_addr = req.remote_addr;
  18916. res.set_content("ok", "text/plain");
  18917. });
  18918. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18919. auto se = detail::scope_exit([&] {
  18920. svr.stop();
  18921. t.join();
  18922. ASSERT_FALSE(svr.is_running());
  18923. });
  18924. svr.wait_until_ready();
  18925. Client cli(HOST, PORT);
  18926. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18928. EXPECT_EQ(StatusCode::OK_200, res->status);
  18929. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18930. // ignored entirely and the real connection-level address retained.
  18931. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18932. observed_remote_addr == "127.0.0.1");
  18933. }
  18934. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18935. Server svr;
  18936. std::string observed_remote_addr;
  18937. std::string observed_xff;
  18938. svr.Get("/ip", [&](const Request &req, Response &res) {
  18939. observed_remote_addr = req.remote_addr;
  18940. observed_xff = req.get_header_value("X-Forwarded-For");
  18941. res.set_content("ok", "text/plain");
  18942. });
  18943. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18944. auto se = detail::scope_exit([&] {
  18945. svr.stop();
  18946. t.join();
  18947. ASSERT_FALSE(svr.is_running());
  18948. });
  18949. svr.wait_until_ready();
  18950. Client cli(HOST, PORT);
  18951. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18953. EXPECT_EQ(StatusCode::OK_200, res->status);
  18954. EXPECT_EQ(observed_xff, "203.0.113.66");
  18955. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18956. observed_remote_addr == "127.0.0.1");
  18957. }
  18958. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18959. Server svr;
  18960. svr.set_trusted_proxies({"203.0.113.66"});
  18961. std::string observed_remote_addr;
  18962. std::string observed_xff;
  18963. svr.Get("/ip", [&](const Request &req, Response &res) {
  18964. observed_remote_addr = req.remote_addr;
  18965. observed_xff = req.get_header_value("X-Forwarded-For");
  18966. res.set_content("ok", "text/plain");
  18967. });
  18968. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18969. auto se = detail::scope_exit([&] {
  18970. svr.stop();
  18971. t.join();
  18972. ASSERT_FALSE(svr.is_running());
  18973. });
  18974. svr.wait_until_ready();
  18975. Client cli(HOST, PORT);
  18976. auto res = cli.Get("/ip");
  18977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18978. EXPECT_EQ(StatusCode::OK_200, res->status);
  18979. EXPECT_EQ(observed_xff, "");
  18980. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18981. observed_remote_addr == "127.0.0.1");
  18982. }
  18983. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18984. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18985. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18986. Server svr;
  18987. svr.set_trusted_proxies({"127.0.0.1"});
  18988. svr.Get("/ip", [](const Request &req, Response &res) {
  18989. res.set_content(req.remote_addr, "text/plain");
  18990. });
  18991. auto port = svr.bind_to_any_port("::");
  18992. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  18993. thread t = thread([&] { svr.listen_after_bind(); });
  18994. auto se = detail::scope_exit([&] {
  18995. svr.stop();
  18996. t.join();
  18997. ASSERT_FALSE(svr.is_running());
  18998. });
  18999. svr.wait_until_ready();
  19000. Client cli("127.0.0.1", port);
  19001. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19003. EXPECT_EQ("198.51.100.23", res->body);
  19004. }
  19005. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19006. Server svr;
  19007. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19008. svr.Get("/ip", [](const Request &req, Response &res) {
  19009. res.set_content(req.remote_addr, "text/plain");
  19010. });
  19011. auto port = svr.bind_to_any_port(HOST);
  19012. ASSERT_GT(port, 0);
  19013. thread t = thread([&] { svr.listen_after_bind(); });
  19014. auto se = detail::scope_exit([&] {
  19015. svr.stop();
  19016. t.join();
  19017. ASSERT_FALSE(svr.is_running());
  19018. });
  19019. svr.wait_until_ready();
  19020. Client cli(HOST, port);
  19021. auto res = cli.Get(
  19022. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19024. EXPECT_EQ("198.51.100.23", res->body);
  19025. }
  19026. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19027. Server svr;
  19028. // Include the loopback address the test client actually connects from, so
  19029. // the direct connection itself is recognized as the trusted proxy hop.
  19030. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19031. std::string observed_remote_addr;
  19032. std::string observed_xff;
  19033. svr.Get("/ip", [&](const Request &req, Response &res) {
  19034. observed_remote_addr = req.remote_addr;
  19035. observed_xff = req.get_header_value("X-Forwarded-For");
  19036. res.set_content("ok", "text/plain");
  19037. });
  19038. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19039. auto se = detail::scope_exit([&] {
  19040. svr.stop();
  19041. t.join();
  19042. ASSERT_FALSE(svr.is_running());
  19043. });
  19044. svr.wait_until_ready();
  19045. Client cli(HOST, PORT);
  19046. auto res = cli.Get(
  19047. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19049. EXPECT_EQ(StatusCode::OK_200, res->status);
  19050. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19051. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19052. }
  19053. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19054. Server svr;
  19055. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19056. std::string observed_remote_addr;
  19057. std::string observed_xff;
  19058. svr.Get("/ip", [&](const Request &req, Response &res) {
  19059. observed_remote_addr = req.remote_addr;
  19060. observed_xff = req.get_header_value("X-Forwarded-For");
  19061. res.set_content("ok", "text/plain");
  19062. });
  19063. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19064. auto se = detail::scope_exit([&] {
  19065. svr.stop();
  19066. t.join();
  19067. ASSERT_FALSE(svr.is_running());
  19068. });
  19069. svr.wait_until_ready();
  19070. Client cli(HOST, PORT);
  19071. auto res = cli.Get(
  19072. "/ip",
  19073. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19075. EXPECT_EQ(StatusCode::OK_200, res->status);
  19076. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19077. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19078. }
  19079. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19080. Server svr;
  19081. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19082. std::string observed_remote_addr;
  19083. std::string observed_xff;
  19084. svr.Get("/ip", [&](const Request &req, Response &res) {
  19085. observed_remote_addr = req.remote_addr;
  19086. observed_xff = req.get_header_value("X-Forwarded-For");
  19087. res.set_content("ok", "text/plain");
  19088. });
  19089. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19090. auto se = detail::scope_exit([&] {
  19091. svr.stop();
  19092. t.join();
  19093. ASSERT_FALSE(svr.is_running());
  19094. });
  19095. svr.wait_until_ready();
  19096. Client cli(HOST, PORT);
  19097. auto res = cli.Get(
  19098. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19100. EXPECT_EQ(StatusCode::OK_200, res->status);
  19101. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19102. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19103. // and must not be selected.
  19104. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19105. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19106. }
  19107. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19108. Server svr;
  19109. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19110. std::string observed_remote_addr;
  19111. svr.Get("/ip", [&](const Request &req, Response &res) {
  19112. observed_remote_addr = req.remote_addr;
  19113. res.set_content("ok", "text/plain");
  19114. });
  19115. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19116. auto se = detail::scope_exit([&] {
  19117. svr.stop();
  19118. t.join();
  19119. ASSERT_FALSE(svr.is_running());
  19120. });
  19121. svr.wait_until_ready();
  19122. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19123. // a forged address and the trusted proxy's own address; the forged value must
  19124. // not win over the address the trusted proxy actually recorded.
  19125. Client cli(HOST, PORT);
  19126. auto res = cli.Get(
  19127. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19129. EXPECT_EQ(StatusCode::OK_200, res->status);
  19130. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19131. }
  19132. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19133. Server svr;
  19134. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19135. std::string observed_remote_addr;
  19136. std::string observed_xff;
  19137. svr.Get("/ip", [&](const Request &req, Response &res) {
  19138. observed_remote_addr = req.remote_addr;
  19139. observed_xff = req.get_header_value("X-Forwarded-For");
  19140. res.set_content("ok", "text/plain");
  19141. });
  19142. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19143. auto se = detail::scope_exit([&] {
  19144. svr.stop();
  19145. t.join();
  19146. ASSERT_FALSE(svr.is_running());
  19147. });
  19148. svr.wait_until_ready();
  19149. Client cli(HOST, PORT);
  19150. auto res = cli.Get(
  19151. "/ip",
  19152. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19154. EXPECT_EQ(StatusCode::OK_200, res->status);
  19155. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19156. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19157. }
  19158. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19159. Server svr;
  19160. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19161. std::string observed_remote_addr;
  19162. std::string observed_xff;
  19163. svr.Get("/ip", [&](const Request &req, Response &res) {
  19164. observed_remote_addr = req.remote_addr;
  19165. observed_xff = req.get_header_value("X-Forwarded-For");
  19166. res.set_content("ok", "text/plain");
  19167. });
  19168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19169. auto se = detail::scope_exit([&] {
  19170. svr.stop();
  19171. t.join();
  19172. ASSERT_FALSE(svr.is_running());
  19173. });
  19174. svr.wait_until_ready();
  19175. std::string raw_req =
  19176. "GET /ip HTTP/1.1\r\n"
  19177. "Host: localhost\r\n"
  19178. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19179. "Connection: close\r\n"
  19180. "\r\n";
  19181. std::string out;
  19182. ASSERT_TRUE(send_request(5, raw_req, &out));
  19183. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19184. // Header parser trims surrounding whitespace of the header value
  19185. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19186. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19187. }
  19188. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19189. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19190. // their own X-Forwarded-For as a separate field line rather than extending the
  19191. // one the client sent, so every occurrence has to be taken into account.
  19192. // Reading only the first one hands back the address the client chose.
  19193. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19194. Server svr;
  19195. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19196. std::string observed_remote_addr;
  19197. size_t observed_xff_count = 0;
  19198. svr.Get("/ip", [&](const Request &req, Response &res) {
  19199. observed_remote_addr = req.remote_addr;
  19200. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19201. res.set_content("ok", "text/plain");
  19202. });
  19203. auto port = svr.bind_to_any_port(HOST);
  19204. thread t = thread([&]() { svr.listen_after_bind(); });
  19205. auto se = detail::scope_exit([&] {
  19206. svr.stop();
  19207. t.join();
  19208. ASSERT_FALSE(svr.is_running());
  19209. });
  19210. svr.wait_until_ready();
  19211. // The client supplies the first field line; the trusted proxy appends the
  19212. // address it observed as a second one.
  19213. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19214. "Host: localhost\r\n"
  19215. "X-Forwarded-For: 1.2.3.4\r\n"
  19216. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19217. "Connection: close\r\n"
  19218. "\r\n";
  19219. std::string out;
  19220. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19221. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19222. EXPECT_EQ(observed_xff_count, 2U);
  19223. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19224. // The same chain spread over one field line per hop derives the same client
  19225. // address, i.e. the split and the comma-joined representations agree.
  19226. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19227. "Host: localhost\r\n"
  19228. "X-Forwarded-For: 1.2.3.4\r\n"
  19229. "X-Forwarded-For: 198.51.100.23\r\n"
  19230. "X-Forwarded-For: 192.0.2.45\r\n"
  19231. "Connection: close\r\n"
  19232. "\r\n";
  19233. out.clear();
  19234. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19235. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19236. EXPECT_EQ(observed_xff_count, 3U);
  19237. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19238. }
  19239. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19240. // crash the server (it used to call front() on an empty vector inside
  19241. // get_client_ip). The connection-level remote address must be retained instead.
  19242. static void run_malformed_xff_test(const std::string &xff_value) {
  19243. Server svr;
  19244. svr.set_trusted_proxies({"192.0.2.45"});
  19245. std::string observed_remote_addr;
  19246. svr.Get("/ip", [&](const Request &req, Response &res) {
  19247. observed_remote_addr = req.remote_addr;
  19248. res.set_content("ok", "text/plain");
  19249. });
  19250. int port = 0;
  19251. thread t = thread([&]() {
  19252. port = svr.bind_to_any_port(HOST);
  19253. svr.listen_after_bind();
  19254. });
  19255. auto se = detail::scope_exit([&] {
  19256. svr.stop();
  19257. t.join();
  19258. ASSERT_FALSE(svr.is_running());
  19259. });
  19260. svr.wait_until_ready();
  19261. Client cli(HOST, port);
  19262. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19264. EXPECT_EQ(StatusCode::OK_200, res->status);
  19265. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19266. observed_remote_addr == "127.0.0.1");
  19267. }
  19268. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19269. run_malformed_xff_test("");
  19270. }
  19271. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19272. run_malformed_xff_test(",");
  19273. }
  19274. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19275. run_malformed_xff_test(", , ,");
  19276. }
  19277. // The same rule applies to Accept: a request whose acceptable types are spread
  19278. // over several field lines must be negotiated against all of them.
  19279. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19280. // case-insensitive connection options. Comparing the whole field value against
  19281. // one option misses a client that sends several of them, and misses every
  19282. // casing but the one written in the comparison.
  19283. //
  19284. // Sends req, reads the response, then reuses the same socket for a second
  19285. // request to find out whether the server kept the connection.
  19286. static void probe_connection_reuse(int port, const std::string &req,
  19287. bool *announced_close, bool *reusable) {
  19288. auto error = Error::Success;
  19289. auto sock = detail::create_client_socket(
  19290. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19291. /*connection_timeout_sec=*/5, 0,
  19292. /*read_timeout_sec=*/1, 0,
  19293. /*write_timeout_sec=*/5, 0, std::string(), error);
  19294. ASSERT_NE(sock, INVALID_SOCKET);
  19295. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19296. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19297. "Host: localhost\r\n"
  19298. "Connection: close\r\n"
  19299. "\r\n";
  19300. std::string first_response;
  19301. std::string second_response;
  19302. detail::process_client_socket(
  19303. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19304. [&](Stream &strm) {
  19305. if (strm.write(req.data(), req.size()) !=
  19306. static_cast<ssize_t>(req.size())) {
  19307. return false;
  19308. }
  19309. char buf[512];
  19310. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19311. // Headers plus the two-byte body of the handler below
  19312. while (reader.getline()) {
  19313. first_response += reader.ptr();
  19314. if (first_response.find("ok") != std::string::npos) { break; }
  19315. }
  19316. if (strm.write(second.data(), second.size()) !=
  19317. static_cast<ssize_t>(second.size())) {
  19318. return true;
  19319. }
  19320. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19321. while (reader2.getline()) {
  19322. second_response += reader2.ptr();
  19323. if (second_response.find("ok") != std::string::npos) { break; }
  19324. }
  19325. return true;
  19326. });
  19327. *announced_close =
  19328. first_response.find("Connection: close") != std::string::npos;
  19329. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19330. }
  19331. class ConnectionTokenTest : public ::testing::Test {
  19332. protected:
  19333. void SetUp() override {
  19334. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19335. res.set_content("ok", "text/plain");
  19336. });
  19337. port_ = svr_.bind_to_any_port(HOST);
  19338. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19339. svr_.wait_until_ready();
  19340. }
  19341. void TearDown() override {
  19342. svr_.stop();
  19343. if (thread_.joinable()) { thread_.join(); }
  19344. }
  19345. Server svr_;
  19346. int port_ = 0;
  19347. thread thread_;
  19348. };
  19349. // "close" alongside another option still closes the connection, and the
  19350. // response says so rather than leaving the peer to discover it.
  19351. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19352. bool announced_close = false;
  19353. bool reusable = true;
  19354. probe_connection_reuse(port_,
  19355. "GET /keepalive HTTP/1.1\r\n"
  19356. "Host: localhost\r\n"
  19357. "Connection: keep-alive, close\r\n"
  19358. "\r\n",
  19359. &announced_close, &reusable);
  19360. EXPECT_TRUE(announced_close);
  19361. EXPECT_FALSE(reusable);
  19362. }
  19363. // "close" split over two field lines is the same list, so it is honored too.
  19364. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19365. bool announced_close = false;
  19366. bool reusable = true;
  19367. probe_connection_reuse(port_,
  19368. "GET /keepalive HTTP/1.1\r\n"
  19369. "Host: localhost\r\n"
  19370. "Connection: keep-alive\r\n"
  19371. "Connection: close\r\n"
  19372. "\r\n",
  19373. &announced_close, &reusable);
  19374. EXPECT_TRUE(announced_close);
  19375. EXPECT_FALSE(reusable);
  19376. }
  19377. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19378. // keep-alive in the spelling everyone actually sends keeps its connection.
  19379. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19380. bool announced_close = false;
  19381. bool reusable = false;
  19382. probe_connection_reuse(port_,
  19383. "GET /keepalive HTTP/1.0\r\n"
  19384. "Host: localhost\r\n"
  19385. "Connection: keep-alive\r\n"
  19386. "\r\n",
  19387. &announced_close, &reusable);
  19388. EXPECT_FALSE(announced_close);
  19389. EXPECT_TRUE(reusable);
  19390. }
  19391. // A token the value merely contains is not the token itself.
  19392. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19393. bool announced_close = false;
  19394. bool reusable = false;
  19395. probe_connection_reuse(port_,
  19396. "GET /keepalive HTTP/1.1\r\n"
  19397. "Host: localhost\r\n"
  19398. "Connection: notclose\r\n"
  19399. "\r\n",
  19400. &announced_close, &reusable);
  19401. EXPECT_FALSE(announced_close);
  19402. EXPECT_TRUE(reusable);
  19403. }
  19404. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19405. Server svr;
  19406. std::vector<std::string> observed_types;
  19407. svr.Get("/", [&](const Request &req, Response &res) {
  19408. observed_types = req.accept_content_types;
  19409. res.set_content("ok", "text/plain");
  19410. });
  19411. auto port = svr.bind_to_any_port(HOST);
  19412. thread t = thread([&]() { svr.listen_after_bind(); });
  19413. auto se = detail::scope_exit([&] {
  19414. svr.stop();
  19415. t.join();
  19416. ASSERT_FALSE(svr.is_running());
  19417. });
  19418. svr.wait_until_ready();
  19419. Client cli(HOST, port);
  19420. Headers headers;
  19421. headers.emplace("Accept", "text/plain;q=0.5");
  19422. headers.emplace("Accept", "application/json");
  19423. auto res = cli.Get("/", headers);
  19424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19425. EXPECT_EQ(StatusCode::OK_200, res->status);
  19426. // Sorted by q-value, so the second field line's type comes first
  19427. ASSERT_EQ(2U, observed_types.size());
  19428. EXPECT_EQ("application/json", observed_types[0]);
  19429. EXPECT_EQ("text/plain", observed_types[1]);
  19430. }
  19431. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19432. // empty field line must not contribute a bare comma to the combined value.
  19433. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19434. Server svr;
  19435. std::vector<std::string> observed_types;
  19436. svr.Get("/", [&](const Request &req, Response &res) {
  19437. observed_types = req.accept_content_types;
  19438. res.set_content("ok", "text/plain");
  19439. });
  19440. auto port = svr.bind_to_any_port(HOST);
  19441. thread t = thread([&]() { svr.listen_after_bind(); });
  19442. auto se = detail::scope_exit([&] {
  19443. svr.stop();
  19444. t.join();
  19445. ASSERT_FALSE(svr.is_running());
  19446. });
  19447. svr.wait_until_ready();
  19448. // Empty first field line, then a real one
  19449. std::string raw_req = "GET / HTTP/1.1\r\n"
  19450. "Host: localhost\r\n"
  19451. "Accept:\r\n"
  19452. "Accept: application/json\r\n"
  19453. "Connection: close\r\n"
  19454. "\r\n";
  19455. std::string out;
  19456. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19457. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19458. ASSERT_EQ(1U, observed_types.size());
  19459. EXPECT_EQ("application/json", observed_types[0]);
  19460. }
  19461. // The skip in get_combined_header_value() is what keeps an empty field line
  19462. // from contributing a bare comma. Only a trailing empty field line exercises
  19463. // it: a leading one is already covered by the "combined is still empty" check,
  19464. // and parse_accept_header() now ignores the empty element either way, so the
  19465. // request-level test above can no longer tell the two apart.
  19466. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19467. Headers headers;
  19468. headers.emplace("Accept", "text/html");
  19469. headers.emplace("Accept", "");
  19470. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19471. headers.clear();
  19472. headers.emplace("Accept", "");
  19473. headers.emplace("Accept", "application/json");
  19474. EXPECT_EQ("application/json",
  19475. detail::get_combined_header_value(headers, "Accept"));
  19476. }
  19477. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19478. // An encoding offered on a later Accept-Encoding field line is still offered.
  19479. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19480. Server svr;
  19481. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19482. res.set_content(std::string(1024, 'x'), "text/plain");
  19483. });
  19484. auto port = svr.bind_to_any_port(HOST);
  19485. thread t = thread([&]() { svr.listen_after_bind(); });
  19486. auto se = detail::scope_exit([&] {
  19487. svr.stop();
  19488. t.join();
  19489. ASSERT_FALSE(svr.is_running());
  19490. });
  19491. svr.wait_until_ready();
  19492. Client cli(HOST, port);
  19493. cli.set_decompress(false);
  19494. Headers headers;
  19495. headers.emplace("Accept-Encoding", "identity");
  19496. headers.emplace("Accept-Encoding", "gzip");
  19497. auto res = cli.Get("/", headers);
  19498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19499. EXPECT_EQ(StatusCode::OK_200, res->status);
  19500. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19501. }
  19502. #endif
  19503. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19504. // Transfer-Encoding is not its body.
  19505. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19506. Server svr;
  19507. svr.set_payload_max_length(8);
  19508. svr.Post("/test", [](const Request &, Response &res) {
  19509. res.set_content("ok", "text/plain");
  19510. });
  19511. auto port = svr.bind_to_any_port(HOST);
  19512. ASSERT_GT(port, 0);
  19513. thread t = thread([&] { svr.listen_after_bind(); });
  19514. auto se = detail::scope_exit([&] {
  19515. svr.stop();
  19516. t.join();
  19517. ASSERT_FALSE(svr.is_running());
  19518. });
  19519. svr.wait_until_ready();
  19520. std::string resp;
  19521. ASSERT_TRUE(send_request(1,
  19522. "POST /test HTTP/1.1\r\n"
  19523. "Host: localhost\r\n"
  19524. "Connection: close\r\n"
  19525. "\r\n" +
  19526. std::string(16, 'X'),
  19527. &resp, port));
  19528. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19529. }
  19530. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19531. Server svr;
  19532. svr.Post("/post", [&](const Request &req, Response &res) {
  19533. res.set_content(req.body, "text/plain");
  19534. });
  19535. svr.Put("/put", [&](const Request &req, Response &res) {
  19536. res.set_content(req.body, "text/plain");
  19537. });
  19538. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19539. res.set_content(req.body, "text/plain");
  19540. });
  19541. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19542. res.set_content(req.body, "text/plain");
  19543. });
  19544. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19545. auto se = detail::scope_exit([&] {
  19546. svr.stop();
  19547. t.join();
  19548. ASSERT_FALSE(svr.is_running());
  19549. });
  19550. svr.wait_until_ready();
  19551. std::string resp;
  19552. // POST without Content-Length
  19553. ASSERT_TRUE(send_request(5,
  19554. "POST /post HTTP/1.1\r\n"
  19555. "Host: localhost\r\n"
  19556. "Connection: close\r\n"
  19557. "\r\n",
  19558. &resp));
  19559. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19560. // PUT without Content-Length
  19561. resp.clear();
  19562. ASSERT_TRUE(send_request(5,
  19563. "PUT /put HTTP/1.1\r\n"
  19564. "Host: localhost\r\n"
  19565. "Connection: close\r\n"
  19566. "\r\n",
  19567. &resp));
  19568. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19569. // PATCH without Content-Length
  19570. resp.clear();
  19571. ASSERT_TRUE(send_request(5,
  19572. "PATCH /patch HTTP/1.1\r\n"
  19573. "Host: localhost\r\n"
  19574. "Connection: close\r\n"
  19575. "\r\n",
  19576. &resp));
  19577. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19578. // DELETE without Content-Length
  19579. resp.clear();
  19580. ASSERT_TRUE(send_request(5,
  19581. "DELETE /delete HTTP/1.1\r\n"
  19582. "Host: localhost\r\n"
  19583. "Connection: close\r\n"
  19584. "\r\n",
  19585. &resp));
  19586. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19587. }
  19588. //==============================================================================
  19589. // open_stream() Tests
  19590. //==============================================================================
  19591. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19592. std::string result;
  19593. char buf[8192];
  19594. ssize_t n;
  19595. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19596. result.append(buf, static_cast<size_t>(n));
  19597. }
  19598. return result;
  19599. }
  19600. // Mock stream for unit tests
  19601. class MockStream : public Stream {
  19602. public:
  19603. std::string data;
  19604. size_t pos = 0;
  19605. ssize_t error_after = -1; // -1 = no error
  19606. explicit MockStream(const std::string &d, ssize_t err = -1)
  19607. : data(d), error_after(err) {}
  19608. bool is_readable() const override { return true; }
  19609. bool wait_readable() const override { return true; }
  19610. bool wait_writable() const override { return true; }
  19611. ssize_t read(char *ptr, size_t size) override {
  19612. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19613. if (pos >= data.size()) return 0;
  19614. size_t limit =
  19615. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19616. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19617. std::memcpy(ptr, data.data() + pos, to_read);
  19618. pos += to_read;
  19619. return static_cast<ssize_t>(to_read);
  19620. }
  19621. ssize_t write(const char *, size_t) override { return -1; }
  19622. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19623. ip = "127.0.0.1";
  19624. port = 0;
  19625. }
  19626. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19627. ip = "127.0.0.1";
  19628. port = 0;
  19629. }
  19630. socket_t socket() const override { return INVALID_SOCKET; }
  19631. time_t duration() const override { return 0; }
  19632. };
  19633. TEST(StreamHandleTest, Basic) {
  19634. ClientImpl::StreamHandle handle;
  19635. EXPECT_FALSE(handle.is_valid());
  19636. handle.response = detail::make_unique<Response>();
  19637. handle.error = Error::Connection;
  19638. EXPECT_FALSE(handle.is_valid());
  19639. handle.error = Error::Success;
  19640. EXPECT_TRUE(handle.is_valid());
  19641. }
  19642. TEST(BodyReaderTest, Basic) {
  19643. MockStream stream("Hello, World!");
  19644. detail::BodyReader reader;
  19645. reader.stream = &stream;
  19646. reader.content_length = 13;
  19647. char buf[32];
  19648. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19649. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19650. EXPECT_TRUE(reader.eof);
  19651. }
  19652. TEST(BodyReaderTest, NoStream) {
  19653. detail::BodyReader reader;
  19654. char buf[32];
  19655. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19656. EXPECT_EQ(Error::Connection, reader.last_error);
  19657. }
  19658. TEST(BodyReaderTest, Error) {
  19659. MockStream stream("Hello, World!", 5);
  19660. detail::BodyReader reader;
  19661. reader.stream = &stream;
  19662. reader.content_length = 13;
  19663. char buf[32];
  19664. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19665. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19666. EXPECT_EQ(Error::Read, reader.last_error);
  19667. }
  19668. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19669. // Mock-based StreamHandle tests relying on private internals are removed.
  19670. class OpenStreamTest : public ::testing::Test {
  19671. protected:
  19672. void SetUp() override {
  19673. svr_.Get("/hello", [](const Request &, Response &res) {
  19674. res.set_content("Hello World!", "text/plain");
  19675. });
  19676. svr_.Get("/large", [](const Request &, Response &res) {
  19677. res.set_content(std::string(10000, 'X'), "text/plain");
  19678. });
  19679. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19680. res.set_content("Hello World!", "image/jpeg");
  19681. res.set_header("Content-Encoding", "UTF-8");
  19682. });
  19683. svr_.Get("/chunked", [](const Request &, Response &res) {
  19684. res.set_chunked_content_provider("text/plain",
  19685. [](size_t offset, DataSink &sink) {
  19686. if (offset < 15) {
  19687. sink.write("chunk", 5);
  19688. return true;
  19689. }
  19690. sink.done();
  19691. return true;
  19692. });
  19693. });
  19694. svr_.Get("/compressible", [](const Request &, Response &res) {
  19695. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19696. DataSink &sink) {
  19697. if (offset < 100 * 1024) {
  19698. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19699. sink.write(chunk.data(), chunk.size());
  19700. return true;
  19701. }
  19702. sink.done();
  19703. return true;
  19704. });
  19705. });
  19706. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19707. [](const Request & /*req*/, Response &res) {
  19708. auto i = new int(0);
  19709. res.set_header("Trailer", "Content-Length, X-Allowed");
  19710. res.set_chunked_content_provider(
  19711. "text/plain",
  19712. [i](size_t /*offset*/, DataSink &sink) {
  19713. switch (*i) {
  19714. case 0: sink.os << "123"; break;
  19715. case 1: sink.os << "456"; break;
  19716. case 2: sink.os << "789"; break;
  19717. case 3: {
  19718. sink.done_with_trailer(
  19719. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19720. } break;
  19721. }
  19722. (*i)++;
  19723. return true;
  19724. },
  19725. [i](bool success) {
  19726. EXPECT_TRUE(success);
  19727. delete i;
  19728. });
  19729. });
  19730. // Echo headers endpoint for header-related tests
  19731. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19732. std::string body;
  19733. for (const auto &h : req.headers) {
  19734. body.append(h.first);
  19735. body.push_back(':');
  19736. body.append(h.second);
  19737. body.push_back('\n');
  19738. }
  19739. res.set_content(body, "text/plain");
  19740. });
  19741. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19742. std::string body;
  19743. for (const auto &h : req.headers) {
  19744. body.append(h.first);
  19745. body.push_back(':');
  19746. body.append(h.second);
  19747. body.push_back('\n');
  19748. }
  19749. res.set_content(body, "text/plain");
  19750. });
  19751. port_ = svr_.bind_to_any_port("127.0.0.1");
  19752. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19753. svr_.wait_until_ready();
  19754. }
  19755. void TearDown() override {
  19756. svr_.stop();
  19757. if (thread_.joinable()) thread_.join();
  19758. }
  19759. Server svr_;
  19760. std::thread thread_;
  19761. int port_ = 0;
  19762. };
  19763. TEST_F(OpenStreamTest, Basic) {
  19764. Client cli("127.0.0.1", port_);
  19765. auto handle = cli.open_stream("GET", "/hello");
  19766. EXPECT_TRUE(handle.is_valid());
  19767. EXPECT_EQ("Hello World!", read_all(handle));
  19768. }
  19769. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19770. Client cli("127.0.0.1", port_);
  19771. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19772. ASSERT_TRUE(handle.is_valid());
  19773. EXPECT_EQ("Hello World!", read_all(handle));
  19774. }
  19775. TEST_F(OpenStreamTest, SmallBuffer) {
  19776. Client cli("127.0.0.1", port_);
  19777. auto handle = cli.open_stream("GET", "/hello");
  19778. std::string result;
  19779. char buf[4];
  19780. ssize_t n;
  19781. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19782. result.append(buf, static_cast<size_t>(n));
  19783. EXPECT_EQ("Hello World!", result);
  19784. }
  19785. TEST_F(OpenStreamTest, DefaultHeaders) {
  19786. Client cli("127.0.0.1", port_);
  19787. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19788. {
  19789. auto handle = cli.open_stream("GET", "/echo-headers");
  19790. ASSERT_TRUE(handle.is_valid());
  19791. auto body = read_all(handle);
  19792. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19793. std::string::npos);
  19794. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19795. std::string::npos);
  19796. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19797. }
  19798. // open_stream POST with body and no explicit content_type should NOT add
  19799. // text/plain Content-Type (behavior differs from non-streaming path), but
  19800. // should include Content-Length
  19801. {
  19802. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19803. ASSERT_TRUE(handle.is_valid());
  19804. auto body = read_all(handle);
  19805. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19806. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19807. }
  19808. // open_stream POST with explicit Content-Type should preserve it
  19809. {
  19810. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19811. {{"Content-Type", "application/custom"}},
  19812. "{}", "application/custom");
  19813. ASSERT_TRUE(handle.is_valid());
  19814. auto body = read_all(handle);
  19815. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19816. }
  19817. // User-specified User-Agent must not be overwritten for stream API
  19818. {
  19819. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19820. {{"User-Agent", "MyAgent/1.2"}});
  19821. ASSERT_TRUE(handle.is_valid());
  19822. auto body = read_all(handle);
  19823. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19824. }
  19825. }
  19826. TEST_F(OpenStreamTest, Large) {
  19827. Client cli("127.0.0.1", port_);
  19828. auto handle = cli.open_stream("GET", "/large");
  19829. EXPECT_EQ(10000u, read_all(handle).size());
  19830. }
  19831. TEST_F(OpenStreamTest, ConnectionError) {
  19832. Client cli("127.0.0.1", 9999);
  19833. auto handle = cli.open_stream("GET", "/hello");
  19834. EXPECT_FALSE(handle.is_valid());
  19835. }
  19836. TEST_F(OpenStreamTest, Chunked) {
  19837. Client cli("127.0.0.1", port_);
  19838. auto handle = cli.open_stream("GET", "/chunked");
  19839. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19840. "Transfer-Encoding") == "chunked");
  19841. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19842. }
  19843. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19844. Client cli("127.0.0.1", port_);
  19845. auto handle =
  19846. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19847. ASSERT_TRUE(handle.is_valid());
  19848. // Consume body to allow trailers to be received/parsed
  19849. auto body = read_all(handle);
  19850. // Explicitly parse trailers (ensure trailers are available for assertion)
  19851. handle.parse_trailers_if_needed();
  19852. EXPECT_EQ(std::string("123456789"), body);
  19853. // The response should include a Trailer header declaring both names
  19854. ASSERT_TRUE(handle.response);
  19855. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19856. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19857. handle.response->get_header_value("Trailer"));
  19858. // Prohibited trailer must not be present
  19859. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19860. // Allowed trailer should be present
  19861. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19862. EXPECT_EQ(std::string("yes"),
  19863. handle.response->get_trailer_value("X-Allowed"));
  19864. // Verify trailers are NOT present as regular headers
  19865. EXPECT_EQ(std::string(""),
  19866. handle.response->get_header_value("Content-Length"));
  19867. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19868. }
  19869. // Accepts one connection on an OS-assigned port, which it hands over through
  19870. // port_promise, reads the request head and sends back response. after_send,
  19871. // if given, runs on the connection before it is closed.
  19872. static std::thread
  19873. serve_single_response(std::promise<int> &port_promise,
  19874. const std::string &response,
  19875. std::function<void(socket_t)> after_send = nullptr) {
  19876. return std::thread([&port_promise, response, after_send] {
  19877. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19878. default_socket_options(srv);
  19879. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19880. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19881. sockaddr_in addr{};
  19882. addr.sin_family = AF_INET;
  19883. addr.sin_port = htons(0); // Let OS assign a free port
  19884. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19885. int opt = 1;
  19886. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19887. #ifdef _WIN32
  19888. reinterpret_cast<const char *>(&opt),
  19889. #else
  19890. &opt,
  19891. #endif
  19892. sizeof(opt));
  19893. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19894. ::listen(srv, 1) != 0) {
  19895. port_promise.set_value(-1);
  19896. detail::close_socket(srv);
  19897. return;
  19898. }
  19899. socklen_t addr_len = sizeof(addr);
  19900. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19901. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19902. sockaddr_in cli_addr{};
  19903. socklen_t cli_len = sizeof(cli_addr);
  19904. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19905. if (cli != INVALID_SOCKET) {
  19906. // Read the complete HTTP request (until the blank line that terminates
  19907. // headers) before sending the response. If the server closes the socket
  19908. // while the client's request data is still unread in the kernel receive
  19909. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19910. // connection on both sides: it discards the client's receive buffer
  19911. // (which already holds our response) and causes any in-progress write on
  19912. // the client to fail with ECONNRESET. Reading all request data first
  19913. // ensures close() emits a graceful FIN.
  19914. {
  19915. char rbuf[256];
  19916. std::string req;
  19917. while (req.find("\r\n\r\n") == std::string::npos) {
  19918. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19919. if (n <= 0) { break; }
  19920. req.append(rbuf, static_cast<size_t>(n));
  19921. }
  19922. }
  19923. ::send(cli,
  19924. #ifdef _WIN32
  19925. static_cast<const char *>(response.c_str()),
  19926. static_cast<int>(response.size()),
  19927. #else
  19928. response.c_str(), response.size(),
  19929. #endif
  19930. 0);
  19931. if (after_send) { after_send(cli); }
  19932. detail::close_socket(cli);
  19933. }
  19934. detail::close_socket(srv);
  19935. });
  19936. }
  19937. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19938. #ifndef _WIN32
  19939. signal(SIGPIPE, SIG_IGN);
  19940. #endif
  19941. std::promise<int> port_promise;
  19942. auto port_future = port_promise.get_future();
  19943. auto server_thread =
  19944. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19945. "Content-Type: text/plain\r\n"
  19946. "Content-Length: not-a-number\r\n"
  19947. "Connection: close\r\n"
  19948. "\r\n"
  19949. "hello");
  19950. auto port = port_future.get();
  19951. ASSERT_GT(port, 0);
  19952. Client cli("127.0.0.1", port);
  19953. auto handle = cli.open_stream("GET", "/");
  19954. EXPECT_FALSE(handle.is_valid());
  19955. server_thread.join();
  19956. }
  19957. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19958. #ifndef _WIN32
  19959. signal(SIGPIPE, SIG_IGN);
  19960. #endif
  19961. std::promise<int> port_promise;
  19962. auto port_future = port_promise.get_future();
  19963. auto server_thread = serve_single_response(
  19964. port_promise, "HTTP/1.1 200 OK\r\n"
  19965. "Content-Type: text/plain\r\n"
  19966. "Content-Length: 99999999999999999999999999\r\n"
  19967. "Connection: close\r\n"
  19968. "\r\n"
  19969. "hello");
  19970. auto port = port_future.get();
  19971. ASSERT_GT(port, 0);
  19972. // Historically std::stoull would throw std::out_of_range here and crash
  19973. // the process, then parsing silently clamped to a bogus framing length and
  19974. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19975. // so the stream fails to open, matching the not-a-number case above. The
  19976. // process still must NOT terminate.
  19977. Client cli("127.0.0.1", port);
  19978. auto handle = cli.open_stream("GET", "/");
  19979. EXPECT_FALSE(handle.is_valid());
  19980. server_thread.join();
  19981. }
  19982. // Serves `response` to the single request `fn` makes with a fresh client.
  19983. template <typename Fn>
  19984. static void with_single_response(const std::string &response, Fn fn) {
  19985. #ifndef _WIN32
  19986. signal(SIGPIPE, SIG_IGN);
  19987. #endif
  19988. std::promise<int> port_promise;
  19989. auto port_future = port_promise.get_future();
  19990. auto server_thread = serve_single_response(port_promise, response);
  19991. auto se = detail::scope_exit([&] { server_thread.join(); });
  19992. auto port = port_future.get();
  19993. ASSERT_GT(port, 0);
  19994. Client cli("127.0.0.1", port);
  19995. fn(cli);
  19996. }
  19997. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  19998. // too, also in a build without the decoder for the advertised coding.
  19999. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20000. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20001. const auto response = "HTTP/1.1 200 OK\r\n"
  20002. "Content-Encoding: gzip\r\n"
  20003. "Content-Length: " +
  20004. std::to_string(gzipped.size()) +
  20005. "\r\n"
  20006. "Connection: close\r\n\r\n" +
  20007. gzipped;
  20008. with_single_response(response, [&](Client &cli) {
  20009. cli.set_decompress(false);
  20010. auto handle = cli.open_stream("GET", "/");
  20011. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20012. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20013. EXPECT_EQ(gzipped, read_all(handle));
  20014. EXPECT_FALSE(handle.has_read_error());
  20015. });
  20016. with_single_response(response, [&](Client &cli) {
  20017. cli.set_decompress(false);
  20018. auto res = stream::Get(cli, "/", 7);
  20019. ASSERT_TRUE(res) << to_string(res.error());
  20020. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20021. EXPECT_EQ(gzipped, res.read_all());
  20022. EXPECT_FALSE(res.has_read_error());
  20023. });
  20024. }
  20025. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20026. // Neither Content-Length nor chunked: the body ends at the close
  20027. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20028. "Connection: close\r\n"
  20029. "\r\n"
  20030. "hello";
  20031. with_single_response(close_delimited, [](Client &cli) {
  20032. auto handle = cli.open_stream("GET", "/");
  20033. ASSERT_TRUE(handle.is_valid());
  20034. EXPECT_EQ("hello", read_all(handle));
  20035. EXPECT_FALSE(handle.has_read_error());
  20036. });
  20037. // A close before the end of the Content-Length is still an error
  20038. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20039. "Content-Length: 10\r\n"
  20040. "\r\n"
  20041. "hello";
  20042. with_single_response(short_content_length, [](Client &cli) {
  20043. auto handle = cli.open_stream("GET", "/");
  20044. ASSERT_TRUE(handle.is_valid());
  20045. read_all(handle);
  20046. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20047. });
  20048. // So is a close before the last chunk
  20049. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20050. "Transfer-Encoding: chunked\r\n"
  20051. "\r\n"
  20052. "5\r\nhello\r\n";
  20053. with_single_response(short_chunked, [](Client &cli) {
  20054. auto handle = cli.open_stream("GET", "/");
  20055. ASSERT_TRUE(handle.is_valid());
  20056. read_all(handle);
  20057. EXPECT_TRUE(handle.has_read_error());
  20058. });
  20059. }
  20060. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20061. const char *responses[] = {
  20062. "HTTP/1.1 103 Early Hints\r\n"
  20063. "Link: </style.css>; rel=preload\r\n"
  20064. "\r\n"
  20065. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20066. "HTTP/1.1 100 Continue\r\n"
  20067. "X-Note: interim\r\n"
  20068. "\r\n"
  20069. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20070. };
  20071. for (auto response : responses) {
  20072. with_single_response(response, [](Client &cli) {
  20073. auto res = cli.Get("/");
  20074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20075. EXPECT_EQ(StatusCode::OK_200, res->status);
  20076. EXPECT_EQ("ok", res->body);
  20077. });
  20078. }
  20079. }
  20080. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20081. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20082. const std::string final_response =
  20083. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20084. std::string interims;
  20085. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20086. interims += interim;
  20087. }
  20088. with_single_response(interims + final_response, [](Client &cli) {
  20089. auto res = cli.Get("/");
  20090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20091. EXPECT_EQ("ok", res->body);
  20092. });
  20093. with_single_response(interims + interim + final_response, [](Client &cli) {
  20094. auto res = cli.Get("/");
  20095. ASSERT_FALSE(res);
  20096. EXPECT_EQ(Error::Read, res.error());
  20097. });
  20098. }
  20099. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20100. #ifndef _WIN32
  20101. signal(SIGPIPE, SIG_IGN);
  20102. #endif
  20103. // The server answers the head without asking for the body. Bytes it then
  20104. // reads on the connection would be taken for the body the request declared.
  20105. auto closed_by_client = false;
  20106. std::promise<int> port_promise;
  20107. auto server_thread = serve_single_response(
  20108. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20109. [&](socket_t sock) {
  20110. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20111. char buf[256];
  20112. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20113. });
  20114. Client cli("127.0.0.1", port_promise.get_future().get());
  20115. cli.set_keep_alive(true);
  20116. cli.set_read_timeout(1, 0);
  20117. // Long enough for the client to send Expect: 100-continue.
  20118. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20120. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20121. cli.Get("/second");
  20122. server_thread.join();
  20123. EXPECT_TRUE(closed_by_client);
  20124. }
  20125. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20126. // Long enough for the client to send Expect: 100-continue
  20127. with_single_response(
  20128. "HTTP/1.1 103 Early Hints\r\n"
  20129. "Link: </style.css>; rel=preload\r\n"
  20130. "\r\n"
  20131. "HTTP/1.1 401 Unauthorized\r\n"
  20132. "Content-Length: 0\r\n\r\n",
  20133. [](Client &cli) {
  20134. cli.set_read_timeout(2, 0);
  20135. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20137. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20138. });
  20139. }
  20140. #ifdef CPPHTTPLIB_SSL_ENABLED
  20141. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20142. #ifndef _WIN32
  20143. signal(SIGPIPE, SIG_IGN);
  20144. #endif
  20145. auto reused = false;
  20146. std::promise<int> port_promise;
  20147. auto server_thread = serve_single_response(
  20148. port_promise,
  20149. "HTTP/1.1 401 Unauthorized\r\n"
  20150. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20151. "Content-Length: 0\r\n\r\n",
  20152. [&](socket_t sock) {
  20153. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20154. char buf[256];
  20155. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20156. });
  20157. Client cli("127.0.0.1", port_promise.get_future().get());
  20158. cli.set_keep_alive(true);
  20159. cli.set_digest_auth("user", "pass");
  20160. cli.set_read_timeout(1, 0);
  20161. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20162. server_thread.join();
  20163. EXPECT_FALSE(reused);
  20164. }
  20165. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20166. // Any other answer to CONNECT would read as the origin's response.
  20167. struct {
  20168. const char *response;
  20169. bool passed_on;
  20170. } cases[] = {
  20171. {"HTTP/1.1 201 Created\r\n"
  20172. "Set-Cookie: session=from-proxy\r\n"
  20173. "Content-Length: 0\r\n\r\n",
  20174. false},
  20175. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20176. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20177. "Content-Length: 0\r\n\r\n",
  20178. true},
  20179. };
  20180. for (const auto &c : cases) {
  20181. std::promise<int> port_promise;
  20182. auto server_thread = serve_single_response(port_promise, c.response);
  20183. SSLClient cli("example.com", 443);
  20184. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20185. auto res = cli.Get("/");
  20186. server_thread.join();
  20187. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20188. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20189. if (res) {
  20190. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20191. }
  20192. }
  20193. }
  20194. #endif
  20195. // Records the client's error logger calls as "error METHOD path", or
  20196. // "error null" for a call without a request
  20197. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20198. return [&log](const Error &err, const Request *req) {
  20199. log.push_back(to_string(err) + " " +
  20200. (req ? req->method + " " + req->path : "null"));
  20201. };
  20202. }
  20203. // A failed request is reported once, with the request the caller made
  20204. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20205. Server svr;
  20206. svr.Get("/big", [](const Request &, Response &res) {
  20207. res.set_content(std::string(100000, 'b'), "text/plain");
  20208. });
  20209. auto port = svr.bind_to_any_port(HOST);
  20210. std::thread t([&]() { svr.listen_after_bind(); });
  20211. auto se = detail::scope_exit([&] {
  20212. svr.stop();
  20213. t.join();
  20214. });
  20215. svr.wait_until_ready();
  20216. Client cli(HOST, port);
  20217. std::vector<std::string> log;
  20218. cli.set_error_logger(record_errors(log));
  20219. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20220. cli.Get("/big", [](const char *, size_t) { return false; });
  20221. EXPECT_EQ(expected, log);
  20222. log.clear();
  20223. cli.Get("/big", [](size_t, size_t) { return false; });
  20224. EXPECT_EQ(expected, log);
  20225. }
  20226. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20227. // Fails while the body is read
  20228. auto broken = [](const Request &, Response &res) {
  20229. res.set_content_provider(10, "text/plain",
  20230. [](size_t, size_t, DataSink &) { return false; });
  20231. };
  20232. Server other;
  20233. other.Get("/broken", broken);
  20234. auto other_port = other.bind_to_any_port(HOST);
  20235. std::thread other_t([&]() { other.listen_after_bind(); });
  20236. auto other_se = detail::scope_exit([&] {
  20237. other.stop();
  20238. other_t.join();
  20239. });
  20240. other.wait_until_ready();
  20241. Server svr;
  20242. svr.Get("/broken", broken);
  20243. svr.Get("/same-origin",
  20244. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20245. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20246. res.set_redirect("http://" + std::string(HOST) + ":" +
  20247. std::to_string(other_port) + "/broken");
  20248. });
  20249. auto port = svr.bind_to_any_port(HOST);
  20250. std::thread t([&]() { svr.listen_after_bind(); });
  20251. auto se = detail::scope_exit([&] {
  20252. svr.stop();
  20253. t.join();
  20254. });
  20255. svr.wait_until_ready();
  20256. Client cli(HOST, port);
  20257. cli.set_follow_location(true);
  20258. std::vector<std::string> log;
  20259. cli.set_error_logger(record_errors(log));
  20260. for (auto path : {"/same-origin", "/cross-origin"}) {
  20261. log.clear();
  20262. auto res = cli.Get(path);
  20263. ASSERT_FALSE(res);
  20264. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20265. log);
  20266. }
  20267. }
  20268. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20269. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20270. std::vector<std::string> log;
  20271. cli.set_error_logger(record_errors(log));
  20272. auto handle = cli.open_stream("GET", "/x");
  20273. EXPECT_FALSE(handle.is_valid());
  20274. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20275. log);
  20276. });
  20277. }
  20278. #ifdef CPPHTTPLIB_SSL_ENABLED
  20279. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20280. // Not a TLS server, so the handshake fails. It waits for a request line in
  20281. // the handshake bytes, so a short read timeout lets it close quickly.
  20282. Server svr;
  20283. svr.set_read_timeout(0, 100000);
  20284. svr.Get("/x", [](const Request &, Response &res) {
  20285. res.set_content("x", "text/plain");
  20286. });
  20287. auto port = svr.bind_to_any_port(HOST);
  20288. std::thread t([&]() { svr.listen_after_bind(); });
  20289. auto se = detail::scope_exit([&] {
  20290. svr.stop();
  20291. t.join();
  20292. });
  20293. svr.wait_until_ready();
  20294. std::vector<std::string> log;
  20295. SSLClient cli(HOST, port);
  20296. cli.enable_server_certificate_verification(false);
  20297. cli.set_error_logger(record_errors(log));
  20298. auto res = cli.Get("/x");
  20299. ASSERT_FALSE(res);
  20300. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20301. log.clear();
  20302. auto handle = cli.open_stream("GET", "/x");
  20303. EXPECT_FALSE(handle.is_valid());
  20304. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20305. log.clear();
  20306. SSLClient no_ca(HOST, port);
  20307. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20308. no_ca.set_error_logger(record_errors(log));
  20309. res = no_ca.Get("/x");
  20310. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20311. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20312. }
  20313. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20314. #ifndef _WIN32
  20315. signal(SIGPIPE, SIG_IGN);
  20316. #endif
  20317. // Refused, answered with a challenge, or closed without an answer
  20318. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20319. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20320. "Content-Length: 0\r\n\r\n",
  20321. ""}) {
  20322. std::promise<int> port_promise;
  20323. auto server_thread = serve_single_response(port_promise, response);
  20324. SSLClient cli("example.com", 443);
  20325. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20326. std::vector<std::string> log;
  20327. cli.set_error_logger(record_errors(log));
  20328. auto res = cli.Get("/");
  20329. server_thread.join();
  20330. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20331. << response;
  20332. }
  20333. }
  20334. #endif
  20335. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20336. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20337. // the chunked coding and drop Content-Length, so a front-end that trusts
  20338. // Content-Length would disagree about where the body ends (response
  20339. // smuggling). The client must reject such a response.
  20340. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20341. for (const char *te : {"chunked", "gzip, chunked"}) {
  20342. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20343. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20344. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20345. "5\r\nhello\r\n0\r\n\r\n";
  20346. with_single_response(response, [&](Client &cli) {
  20347. auto res = cli.Get("/");
  20348. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20349. EXPECT_EQ(Error::Read, res.error()) << te;
  20350. });
  20351. with_single_response(response, [&](Client &cli) {
  20352. auto handle = cli.open_stream("GET", "/");
  20353. EXPECT_FALSE(handle.is_valid()) << te;
  20354. EXPECT_EQ(Error::Read, handle.error) << te;
  20355. });
  20356. }
  20357. }
  20358. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20359. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20360. // closing the connection (unlike a request, which must be rejected).
  20361. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20362. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20363. "Transfer-Encoding: chunked\r\n"
  20364. "Connection: close\r\n"
  20365. "\r\n"
  20366. "5\r\nhello\r\n0\r\n\r\n",
  20367. "HTTP/1.1 200 OK\r\n"
  20368. "Transfer-Encoding: gzip\r\n"
  20369. "Connection: close\r\n"
  20370. "\r\n"
  20371. "hello"}) {
  20372. with_single_response(response, [&](Client &cli) {
  20373. auto res = cli.Get("/");
  20374. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20375. EXPECT_EQ("hello", res->body);
  20376. });
  20377. with_single_response(response, [&](Client &cli) {
  20378. auto handle = cli.open_stream("GET", "/");
  20379. ASSERT_TRUE(handle.is_valid()) << response;
  20380. EXPECT_EQ("hello", read_all(handle));
  20381. });
  20382. }
  20383. }
  20384. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20385. // framing headers describe nothing to read and must not be rejected.
  20386. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20387. const std::string framing = "Content-Length: 5\r\n"
  20388. "Transfer-Encoding: chunked\r\n"
  20389. "Connection: close\r\n"
  20390. "\r\n";
  20391. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20392. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20393. });
  20394. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20395. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20396. });
  20397. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20398. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20399. with_single_response(response, [&](Client &cli) {
  20400. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20401. });
  20402. with_single_response(response, [&](Client &cli) {
  20403. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20404. });
  20405. }
  20406. }
  20407. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20408. // header section, so a stream opened on one has nothing to read, whatever
  20409. // framing or coding headers it carries.
  20410. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20411. struct Case {
  20412. const char *method;
  20413. const char *status;
  20414. };
  20415. // A reader of the declared body reports an early close when nothing
  20416. // follows, and hands back what does.
  20417. struct Framing {
  20418. const char *headers;
  20419. const char *after;
  20420. };
  20421. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20422. Case{"GET", "304 Not Modified"}}) {
  20423. for (const auto &f :
  20424. {Framing{"Content-Length: 5\r\n", ""},
  20425. Framing{"Content-Length: 5\r\n", "hello"},
  20426. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20427. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20428. // Not decoded, so a build without Brotli opens it too
  20429. Framing{"Content-Encoding: br\r\n", ""}}) {
  20430. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20431. "Connection: close\r\n"
  20432. "\r\n" +
  20433. f.after;
  20434. with_single_response(response, [&](Client &cli) {
  20435. auto handle = cli.open_stream(c.method, "/");
  20436. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20437. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20438. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20439. });
  20440. }
  20441. }
  20442. }
  20443. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20444. // response, is faulty framing, so the connection is not reused after it.
  20445. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20446. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20447. "Content-Length: 0\r\n"
  20448. "Transfer-Encoding: chunked\r\n"
  20449. "\r\n"
  20450. "5\r\nhello\r\n0\r\n\r\n",
  20451. "HTTP/1.0 200 Connection established\r\n"
  20452. "Connection: keep-alive\r\n"
  20453. "Transfer-Encoding: chunked\r\n"
  20454. "\r\n"
  20455. "5\r\nhello\r\n0\r\n\r\n"}) {
  20456. with_single_response(response, [&](Client &cli) {
  20457. cli.set_keep_alive(true);
  20458. auto res = cli.Get("/");
  20459. ASSERT_TRUE(res) << response;
  20460. EXPECT_EQ("hello", res->body);
  20461. EXPECT_FALSE(cli.is_socket_open()) << response;
  20462. });
  20463. }
  20464. }
  20465. // A payload max length of 0 means no limit, however the body is framed.
  20466. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20467. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20468. "Transfer-Encoding: chunked\r\n"
  20469. "\r\n"
  20470. "5\r\nhello\r\n0\r\n\r\n",
  20471. "HTTP/1.1 200 OK\r\n"
  20472. "Connection: close\r\n"
  20473. "\r\n"
  20474. "hello"}) {
  20475. with_single_response(response, [&](Client &cli) {
  20476. cli.set_payload_max_length(0);
  20477. auto res = cli.Get("/");
  20478. ASSERT_TRUE(res) << response;
  20479. EXPECT_EQ("hello", res->body) << response;
  20480. });
  20481. }
  20482. }
  20483. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20484. Server svr;
  20485. svr.set_payload_max_length(0);
  20486. svr.Post("/echo", [](const Request &req, Response &res) {
  20487. res.set_content(req.body, "text/plain");
  20488. });
  20489. auto port = svr.bind_to_any_port(HOST);
  20490. thread t = thread([&] { svr.listen_after_bind(); });
  20491. auto se = detail::scope_exit([&] {
  20492. svr.stop();
  20493. t.join();
  20494. ASSERT_FALSE(svr.is_running());
  20495. });
  20496. svr.wait_until_ready();
  20497. Client cli(HOST, port);
  20498. auto res = cli.Post(
  20499. "/echo",
  20500. [](size_t /*offset*/, DataSink &sink) {
  20501. sink.write("hello", 5);
  20502. sink.done();
  20503. return true;
  20504. },
  20505. "text/plain");
  20506. ASSERT_TRUE(res);
  20507. EXPECT_EQ(StatusCode::OK_200, res->status);
  20508. EXPECT_EQ("hello", res->body);
  20509. }
  20510. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20511. TEST_F(OpenStreamTest, Gzip) {
  20512. Client cli("127.0.0.1", port_);
  20513. auto handle = cli.open_stream("GET", "/compressible", {},
  20514. {{"Accept-Encoding", "gzip"}});
  20515. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20516. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20517. }
  20518. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20519. Client cli("127.0.0.1", port_);
  20520. auto handle =
  20521. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20522. {{"Accept-Encoding", "gzip"}});
  20523. ASSERT_TRUE(handle.is_valid());
  20524. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20525. EXPECT_EQ("123456789", read_all(handle));
  20526. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20527. }
  20528. #endif
  20529. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20530. TEST_F(OpenStreamTest, Brotli) {
  20531. Client cli("127.0.0.1", port_);
  20532. auto handle =
  20533. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20534. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20535. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20536. }
  20537. #endif
  20538. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20539. TEST_F(OpenStreamTest, Zstd) {
  20540. Client cli("127.0.0.1", port_);
  20541. auto handle = cli.open_stream("GET", "/compressible", {},
  20542. {{"Accept-Encoding", "zstd"}});
  20543. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20544. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20545. }
  20546. #endif
  20547. #ifdef CPPHTTPLIB_SSL_ENABLED
  20548. class SSLOpenStreamTest : public ::testing::Test {
  20549. protected:
  20550. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20551. void SetUp() override {
  20552. svr_.Get("/hello", [](const Request &, Response &res) {
  20553. res.set_content("Hello SSL World!", "text/plain");
  20554. });
  20555. svr_.Get("/chunked", [](const Request &, Response &res) {
  20556. res.set_chunked_content_provider("text/plain",
  20557. [](size_t offset, DataSink &sink) {
  20558. if (offset < 15) {
  20559. sink.write("chunk", 5);
  20560. return true;
  20561. }
  20562. sink.done();
  20563. return true;
  20564. });
  20565. });
  20566. svr_.Post("/echo", [](const Request &req, Response &res) {
  20567. res.set_content(req.body, req.get_header_value("Content-Type"));
  20568. });
  20569. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20570. std::string body = req.body;
  20571. res.set_chunked_content_provider(
  20572. "text/plain", [body](size_t offset, DataSink &sink) {
  20573. if (offset < body.size()) {
  20574. sink.write(body.data() + offset, body.size() - offset);
  20575. }
  20576. sink.done();
  20577. return true;
  20578. });
  20579. });
  20580. port_ = svr_.bind_to_any_port("127.0.0.1");
  20581. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20582. svr_.wait_until_ready();
  20583. }
  20584. void TearDown() override {
  20585. svr_.stop();
  20586. if (thread_.joinable()) thread_.join();
  20587. }
  20588. SSLServer svr_;
  20589. std::thread thread_;
  20590. int port_ = 0;
  20591. };
  20592. TEST_F(SSLOpenStreamTest, Basic) {
  20593. SSLClient cli("127.0.0.1", port_);
  20594. cli.enable_server_certificate_verification(false);
  20595. auto handle = cli.open_stream("GET", "/hello");
  20596. ASSERT_TRUE(handle.is_valid());
  20597. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20598. }
  20599. TEST_F(SSLOpenStreamTest, Chunked) {
  20600. SSLClient cli("127.0.0.1", port_);
  20601. cli.enable_server_certificate_verification(false);
  20602. auto handle = cli.open_stream("GET", "/chunked");
  20603. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20604. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20605. "Transfer-Encoding") == "chunked");
  20606. auto body = read_all(handle);
  20607. EXPECT_EQ("chunkchunkchunk", body);
  20608. }
  20609. TEST_F(SSLOpenStreamTest, Post) {
  20610. SSLClient cli("127.0.0.1", port_);
  20611. cli.enable_server_certificate_verification(false);
  20612. auto handle =
  20613. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20614. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20615. EXPECT_EQ(200, handle.response->status);
  20616. auto body = read_all(handle);
  20617. EXPECT_EQ("Hello SSL POST", body);
  20618. }
  20619. TEST_F(SSLOpenStreamTest, PostChunked) {
  20620. SSLClient cli("127.0.0.1", port_);
  20621. cli.enable_server_certificate_verification(false);
  20622. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20623. "Chunked SSL Data", "text/plain");
  20624. ASSERT_TRUE(handle.is_valid());
  20625. EXPECT_EQ(200, handle.response->status);
  20626. auto body = read_all(handle);
  20627. EXPECT_EQ("Chunked SSL Data", body);
  20628. }
  20629. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20630. // Content-Length is terminated by the server closing the connection. When the
  20631. // SSL peer sends a close_notify after the body, the client must treat it as a
  20632. // clean EOF and return a successful response rather than an error.
  20633. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20635. ASSERT_TRUE(svr.is_valid());
  20636. svr.set_keep_alive_max_count(1);
  20637. const std::string expected_body = "Hello from connection-close response!";
  20638. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20639. res.set_content_provider("text/plain",
  20640. [&](size_t offset, DataSink &sink) -> bool {
  20641. if (offset < expected_body.size()) {
  20642. sink.write(expected_body.data() + offset,
  20643. expected_body.size() - offset);
  20644. }
  20645. sink.done();
  20646. return true;
  20647. });
  20648. });
  20649. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20650. auto se = detail::scope_exit([&] {
  20651. svr.stop();
  20652. listen_thread.join();
  20653. ASSERT_FALSE(svr.is_running());
  20654. });
  20655. svr.wait_until_ready();
  20656. SSLClient cli(HOST, PORT);
  20657. cli.enable_server_certificate_verification(false);
  20658. auto res = cli.Get("/no-content-length");
  20659. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20660. EXPECT_EQ(StatusCode::OK_200, res->status);
  20661. EXPECT_EQ(expected_body, res->body);
  20662. }
  20663. #endif // CPPHTTPLIB_SSL_ENABLED
  20664. //==============================================================================
  20665. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20666. // results for various scenarios.
  20667. //==============================================================================
  20668. TEST(ParityTest, GetVsOpenStream) {
  20669. Server svr;
  20670. const std::string path = "/parity";
  20671. const std::string content = "Parity test content: hello world";
  20672. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20673. res.set_content(content, "text/plain");
  20674. });
  20675. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20676. auto se = detail::scope_exit([&] {
  20677. svr.stop();
  20678. t.join();
  20679. ASSERT_FALSE(svr.is_running());
  20680. });
  20681. svr.wait_until_ready();
  20682. Client cli(HOST, PORT);
  20683. // Non-stream path
  20684. auto r1 = cli.Get(path);
  20685. ASSERT_TRUE(r1);
  20686. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20687. // Stream path
  20688. auto h = cli.open_stream("GET", path);
  20689. ASSERT_TRUE(h.is_valid());
  20690. EXPECT_EQ(r1->body, read_all(h));
  20691. }
  20692. // Helper to compress data with provided compressor type T
  20693. template <typename Compressor>
  20694. static std::string compress_payload_for_parity(const std::string &in) {
  20695. std::string out;
  20696. Compressor compressor;
  20697. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20698. [&](const char *data, size_t n) {
  20699. out.append(data, n);
  20700. return true;
  20701. });
  20702. EXPECT_TRUE(ok);
  20703. return out;
  20704. }
  20705. // Helper function for compression parity tests
  20706. template <typename Compressor>
  20707. static void test_compression_parity(const std::string &original,
  20708. const std::string &path,
  20709. const std::string &encoding) {
  20710. const std::string compressed =
  20711. compress_payload_for_parity<Compressor>(original);
  20712. Server svr;
  20713. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20714. res.set_content(compressed, "application/octet-stream");
  20715. res.set_header("Content-Encoding", encoding);
  20716. });
  20717. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20718. auto se = detail::scope_exit([&] {
  20719. svr.stop();
  20720. t.join();
  20721. ASSERT_FALSE(svr.is_running());
  20722. });
  20723. svr.wait_until_ready();
  20724. Client cli(HOST, PORT);
  20725. // Non-streaming
  20726. {
  20727. auto res = cli.Get(path);
  20728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20729. EXPECT_EQ(StatusCode::OK_200, res->status);
  20730. EXPECT_EQ(original, res->body);
  20731. }
  20732. // Streaming
  20733. {
  20734. auto h = cli.open_stream("GET", path);
  20735. ASSERT_TRUE(h.is_valid());
  20736. EXPECT_EQ(original, read_all(h));
  20737. }
  20738. }
  20739. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20740. TEST(ParityTest, Gzip) {
  20741. test_compression_parity<detail::gzip_compressor>(
  20742. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20743. }
  20744. #endif
  20745. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20746. TEST(ParityTest, Brotli) {
  20747. test_compression_parity<detail::brotli_compressor>(
  20748. "Hello, brotli parity test payload", "/parity-br", "br");
  20749. }
  20750. #endif
  20751. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20752. TEST(ParityTest, Zstd) {
  20753. test_compression_parity<detail::zstd_compressor>(
  20754. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20755. }
  20756. #endif
  20757. //==============================================================================
  20758. // New Stream API Tests
  20759. //==============================================================================
  20760. inline std::string read_body(httplib::stream::Result &result) {
  20761. std::string body;
  20762. while (result.next()) {
  20763. body.append(result.data(), result.size());
  20764. }
  20765. return body;
  20766. }
  20767. TEST(ClientConnectionTest, Basic) {
  20768. httplib::ClientConnection conn;
  20769. EXPECT_FALSE(conn.is_open());
  20770. conn.sock = 1;
  20771. EXPECT_TRUE(conn.is_open());
  20772. httplib::ClientConnection conn2(std::move(conn));
  20773. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20774. conn2.sock = INVALID_SOCKET;
  20775. }
  20776. // Unified test server for all stream::* tests
  20777. class StreamApiTest : public ::testing::Test {
  20778. protected:
  20779. void SetUp() override {
  20780. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20781. res.set_content("Hello World!", "text/plain");
  20782. });
  20783. svr_.Get("/echo-params",
  20784. [](const httplib::Request &req, httplib::Response &res) {
  20785. std::string r;
  20786. for (const auto &p : req.params) {
  20787. if (!r.empty()) r += "&";
  20788. r += p.first + "=" + p.second;
  20789. }
  20790. res.set_content(r, "text/plain");
  20791. });
  20792. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20793. res.set_content(req.body, req.get_header_value("Content-Type"));
  20794. });
  20795. svr_.Post("/echo-headers",
  20796. [](const httplib::Request &req, httplib::Response &res) {
  20797. std::string r;
  20798. for (const auto &h : req.headers)
  20799. r += h.first + ": " + h.second + "\n";
  20800. res.set_content(r, "text/plain");
  20801. });
  20802. svr_.Post("/echo-params",
  20803. [](const httplib::Request &req, httplib::Response &res) {
  20804. std::string r = "params:";
  20805. for (const auto &p : req.params)
  20806. r += p.first + "=" + p.second + ";";
  20807. res.set_content(r + " body:" + req.body, "text/plain");
  20808. });
  20809. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20810. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20811. });
  20812. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20813. res.set_content("PUT:" + req.body, "text/plain");
  20814. });
  20815. svr_.Patch("/echo",
  20816. [](const httplib::Request &req, httplib::Response &res) {
  20817. res.set_content("PATCH:" + req.body, "text/plain");
  20818. });
  20819. svr_.Delete(
  20820. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20821. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20822. "text/plain");
  20823. });
  20824. svr_.Get("/head-test",
  20825. [](const httplib::Request &, httplib::Response &res) {
  20826. res.set_content("body for HEAD", "text/plain");
  20827. });
  20828. svr_.Options("/options",
  20829. [](const httplib::Request &, httplib::Response &res) {
  20830. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20831. });
  20832. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20833. svr_.wait_until_ready();
  20834. }
  20835. void TearDown() override {
  20836. svr_.stop();
  20837. if (thread_.joinable()) thread_.join();
  20838. }
  20839. httplib::Server svr_;
  20840. std::thread thread_;
  20841. };
  20842. // stream::Get tests
  20843. TEST_F(StreamApiTest, GetBasic) {
  20844. httplib::Client cli(HOST, PORT);
  20845. auto result = httplib::stream::Get(cli, "/hello");
  20846. ASSERT_TRUE(result.is_valid());
  20847. EXPECT_EQ(200, result.status());
  20848. EXPECT_EQ("Hello World!", read_body(result));
  20849. }
  20850. TEST_F(StreamApiTest, GetWithParams) {
  20851. httplib::Client cli(HOST, PORT);
  20852. httplib::Params params{{"foo", "bar"}};
  20853. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20854. ASSERT_TRUE(result.is_valid());
  20855. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20856. }
  20857. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20858. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20859. httplib::Client cli(HOST, PORT);
  20860. cli.set_payload_max_length(0);
  20861. auto result = httplib::stream::Get(cli, "/hello");
  20862. ASSERT_TRUE(result.is_valid());
  20863. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20864. EXPECT_EQ("Hello World!", read_body(result));
  20865. }
  20866. #endif
  20867. TEST_F(StreamApiTest, GetConnectionError) {
  20868. httplib::Client cli(HOST, 9999);
  20869. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20870. }
  20871. TEST_F(StreamApiTest, Get404) {
  20872. httplib::Client cli(HOST, PORT);
  20873. auto result = httplib::stream::Get(cli, "/nonexistent");
  20874. EXPECT_TRUE(result.is_valid());
  20875. EXPECT_EQ(404, result.status());
  20876. }
  20877. // stream::Post tests
  20878. TEST_F(StreamApiTest, PostBasic) {
  20879. httplib::Client cli(HOST, PORT);
  20880. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20881. "application/json");
  20882. ASSERT_TRUE(result.is_valid());
  20883. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20884. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20885. }
  20886. TEST_F(StreamApiTest, PostWithHeaders) {
  20887. httplib::Client cli(HOST, PORT);
  20888. httplib::Headers headers{{"X-Custom", "value"}};
  20889. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20890. "text/plain");
  20891. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20892. }
  20893. TEST_F(StreamApiTest, PostWithParams) {
  20894. httplib::Client cli(HOST, PORT);
  20895. httplib::Params params{{"k", "v"}};
  20896. auto result =
  20897. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20898. auto body = read_body(result);
  20899. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20900. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20901. }
  20902. TEST_F(StreamApiTest, PostLarge) {
  20903. httplib::Client cli(HOST, PORT);
  20904. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20905. size_t total = 0;
  20906. while (result.next()) {
  20907. total += result.size();
  20908. }
  20909. EXPECT_EQ(100u * 1024u, total);
  20910. }
  20911. // stream::Put/Patch tests
  20912. TEST_F(StreamApiTest, PutAndPatch) {
  20913. httplib::Client cli(HOST, PORT);
  20914. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20915. EXPECT_EQ("PUT:test", read_body(put));
  20916. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20917. EXPECT_EQ("PATCH:test", read_body(patch));
  20918. }
  20919. // stream::Delete tests
  20920. TEST_F(StreamApiTest, Delete) {
  20921. httplib::Client cli(HOST, PORT);
  20922. auto del1 = httplib::stream::Delete(cli, "/resource");
  20923. EXPECT_EQ("Deleted", read_body(del1));
  20924. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20925. EXPECT_EQ("Deleted:data", read_body(del2));
  20926. }
  20927. // stream::Head/Options tests
  20928. TEST_F(StreamApiTest, HeadAndOptions) {
  20929. httplib::Client cli(HOST, PORT);
  20930. auto head = httplib::stream::Head(cli, "/head-test");
  20931. EXPECT_TRUE(head.is_valid());
  20932. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20933. auto opts = httplib::stream::Options(cli, "/options");
  20934. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20935. }
  20936. // SSL stream::* tests
  20937. #ifdef CPPHTTPLIB_SSL_ENABLED
  20938. class SSLStreamApiTest : public ::testing::Test {
  20939. protected:
  20940. void SetUp() override {
  20941. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20942. res.set_content("Hello SSL!", "text/plain");
  20943. });
  20944. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20945. res.set_content(req.body, "text/plain");
  20946. });
  20947. port_ = svr_.bind_to_any_port("127.0.0.1");
  20948. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20949. svr_.wait_until_ready();
  20950. }
  20951. void TearDown() override {
  20952. svr_.stop();
  20953. if (thread_.joinable()) thread_.join();
  20954. }
  20955. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20956. std::thread thread_;
  20957. int port_ = 0;
  20958. };
  20959. TEST_F(SSLStreamApiTest, GetAndPost) {
  20960. httplib::SSLClient cli("127.0.0.1", port_);
  20961. cli.enable_server_certificate_verification(false);
  20962. auto get = httplib::stream::Get(cli, "/hello");
  20963. EXPECT_EQ("Hello SSL!", read_body(get));
  20964. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20965. EXPECT_EQ("test", read_body(post));
  20966. }
  20967. #endif
  20968. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20969. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20970. // BodyReader
  20971. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20972. // Test that read timeout during streaming is detected
  20973. // Use a large content-length response where server delays mid-stream
  20974. Server svr;
  20975. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20976. // Send a large response with delay in the middle
  20977. res.set_content_provider(
  20978. 1000, // content_length
  20979. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20980. if (offset < 100) {
  20981. // Send first 100 bytes immediately
  20982. std::string data(100, 'A');
  20983. sink.write(data.c_str(), data.size());
  20984. return true;
  20985. }
  20986. // Then delay longer than client timeout
  20987. std::this_thread::sleep_for(std::chrono::seconds(3));
  20988. std::string data(900, 'B');
  20989. sink.write(data.c_str(), data.size());
  20990. return true;
  20991. });
  20992. });
  20993. auto port = 8091;
  20994. std::thread t([&]() { svr.listen("localhost", port); });
  20995. svr.wait_until_ready();
  20996. Client cli("localhost", port);
  20997. cli.set_read_timeout(1, 0); // 1 second timeout
  20998. auto handle = cli.open_stream("GET", "/slow-stream");
  20999. ASSERT_TRUE(handle.is_valid());
  21000. char buf[256];
  21001. ssize_t total = 0;
  21002. ssize_t n;
  21003. bool got_error = false;
  21004. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21005. total += n;
  21006. }
  21007. if (n < 0) {
  21008. got_error = true;
  21009. // Should be timeout or read error
  21010. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21011. handle.get_read_error() == Error::Read)
  21012. << "Actual error: " << to_string(handle.get_read_error());
  21013. }
  21014. // Either we got an error, or we got less data than expected
  21015. EXPECT_TRUE(got_error || total < 1000)
  21016. << "Expected timeout but got all " << total << " bytes";
  21017. svr.stop();
  21018. t.join();
  21019. }
  21020. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21021. // Test connection closed detection via BodyReader
  21022. Server svr;
  21023. std::atomic<bool> close_now{false};
  21024. svr.Get("/will-close", [&](const Request &, Response &res) {
  21025. res.set_content_provider(
  21026. 10000, // Large content_length that we won't fully send
  21027. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21028. if (offset < 100) {
  21029. std::string data(100, 'X');
  21030. sink.write(data.c_str(), data.size());
  21031. return true;
  21032. }
  21033. // Wait for signal then abort
  21034. while (!close_now) {
  21035. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21036. }
  21037. return false; // Abort - server will close connection
  21038. });
  21039. });
  21040. auto port = 8092;
  21041. std::thread t([&]() { svr.listen("localhost", port); });
  21042. svr.wait_until_ready();
  21043. Client cli("localhost", port);
  21044. auto handle = cli.open_stream("GET", "/will-close");
  21045. ASSERT_TRUE(handle.is_valid());
  21046. char buf[256];
  21047. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21048. EXPECT_GT(n, 0) << "First read should succeed";
  21049. // Signal server to close
  21050. close_now = true;
  21051. // Keep reading until error or EOF
  21052. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21053. // Keep reading
  21054. }
  21055. // Should get an error since content_length wasn't satisfied
  21056. if (n < 0) {
  21057. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21058. handle.get_read_error() == Error::Read)
  21059. << "Actual error: " << to_string(handle.get_read_error());
  21060. }
  21061. svr.stop();
  21062. t.join();
  21063. }
  21064. #ifdef CPPHTTPLIB_SSL_ENABLED
  21065. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21066. // Test that read timeout during SSL streaming is detected
  21067. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21068. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21069. res.set_content_provider(
  21070. 1000, "text/plain",
  21071. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21072. if (offset < 100) {
  21073. std::string data(100, 'A');
  21074. sink.write(data.c_str(), data.size());
  21075. return true;
  21076. }
  21077. std::this_thread::sleep_for(std::chrono::seconds(3));
  21078. std::string data(900, 'B');
  21079. sink.write(data.c_str(), data.size());
  21080. return true;
  21081. });
  21082. });
  21083. auto port = 8093;
  21084. std::thread t([&]() { svr.listen("localhost", port); });
  21085. svr.wait_until_ready();
  21086. SSLClient cli("localhost", port);
  21087. cli.enable_server_certificate_verification(false);
  21088. cli.set_read_timeout(1, 0); // 1 second timeout
  21089. auto handle = cli.open_stream("GET", "/slow-stream");
  21090. ASSERT_TRUE(handle.is_valid());
  21091. char buf[256];
  21092. ssize_t total = 0;
  21093. ssize_t n;
  21094. bool got_error = false;
  21095. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21096. total += n;
  21097. }
  21098. if (n < 0) {
  21099. got_error = true;
  21100. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21101. handle.get_read_error() == Error::Read)
  21102. << "Actual error: " << to_string(handle.get_read_error());
  21103. }
  21104. EXPECT_TRUE(got_error || total < 1000)
  21105. << "Expected timeout but got all " << total << " bytes";
  21106. svr.stop();
  21107. t.join();
  21108. }
  21109. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21110. // Test SSL connection closed detection
  21111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21112. std::atomic<bool> close_now{false};
  21113. svr.Get("/will-close", [&](const Request &, Response &res) {
  21114. res.set_content_provider(
  21115. 10000, "text/plain",
  21116. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21117. if (offset < 100) {
  21118. std::string data(100, 'X');
  21119. sink.write(data.c_str(), data.size());
  21120. return true;
  21121. }
  21122. while (!close_now) {
  21123. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21124. }
  21125. return false;
  21126. });
  21127. });
  21128. auto port = 8094;
  21129. std::thread t([&]() { svr.listen("localhost", port); });
  21130. svr.wait_until_ready();
  21131. SSLClient cli("localhost", port);
  21132. cli.enable_server_certificate_verification(false);
  21133. auto handle = cli.open_stream("GET", "/will-close");
  21134. ASSERT_TRUE(handle.is_valid());
  21135. char buf[256];
  21136. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21137. EXPECT_GT(n, 0);
  21138. // Signal server to close
  21139. close_now = true;
  21140. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21141. // Keep reading
  21142. }
  21143. if (n < 0) {
  21144. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21145. handle.get_read_error() == Error::Read)
  21146. << "Actual error: " << to_string(handle.get_read_error());
  21147. }
  21148. svr.stop();
  21149. t.join();
  21150. }
  21151. #endif
  21152. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21153. using namespace httplib;
  21154. // Create a test file
  21155. const char *fname = "etag_testfile.txt";
  21156. const char *content = "etag-content";
  21157. {
  21158. std::ofstream ofs(fname);
  21159. ofs << content;
  21160. ASSERT_TRUE(ofs.good());
  21161. }
  21162. Server svr;
  21163. svr.set_mount_point("/static", ".");
  21164. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21165. svr.wait_until_ready();
  21166. Client cli(HOST, PORT);
  21167. // First request: should get 200 with ETag header
  21168. auto res1 = cli.Get("/static/etag_testfile.txt");
  21169. ASSERT_TRUE(res1);
  21170. ASSERT_EQ(200, res1->status);
  21171. ASSERT_TRUE(res1->has_header("ETag"));
  21172. std::string etag = res1->get_header_value("ETag");
  21173. EXPECT_FALSE(etag.empty());
  21174. // Verify ETag format: W/"hex-hex"
  21175. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21176. EXPECT_EQ('W', etag[0]);
  21177. EXPECT_EQ('/', etag[1]);
  21178. EXPECT_EQ('"', etag[2]);
  21179. EXPECT_EQ('"', etag.back());
  21180. // Exact match: expect 304 Not Modified
  21181. Headers h2 = {{"If-None-Match", etag}};
  21182. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21183. ASSERT_TRUE(res2);
  21184. EXPECT_EQ(304, res2->status);
  21185. // Wildcard match: expect 304 Not Modified
  21186. Headers h3 = {{"If-None-Match", "*"}};
  21187. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21188. ASSERT_TRUE(res3);
  21189. EXPECT_EQ(304, res3->status);
  21190. // Non-matching ETag: expect 200
  21191. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21192. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21193. ASSERT_TRUE(res4);
  21194. EXPECT_EQ(200, res4->status);
  21195. // Multiple ETags with one matching: expect 304
  21196. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21197. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21198. ASSERT_TRUE(res5);
  21199. EXPECT_EQ(304, res5->status);
  21200. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21201. // that equivalent to the single comma-separated list above, so the match on
  21202. // the second line must still be found.
  21203. Headers h6;
  21204. h6.emplace("If-None-Match", "W/\"other\"");
  21205. h6.emplace("If-None-Match", etag);
  21206. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21207. ASSERT_TRUE(res6);
  21208. EXPECT_EQ(304, res6->status);
  21209. svr.stop();
  21210. t.join();
  21211. std::remove(fname);
  21212. }
  21213. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21214. using namespace httplib;
  21215. Server svr;
  21216. svr.set_mount_point("/static", ".");
  21217. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21218. svr.wait_until_ready();
  21219. Client cli(HOST, PORT);
  21220. // Send If-None-Match: * to a non-existent file
  21221. Headers h = {{"If-None-Match", "*"}};
  21222. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21224. EXPECT_EQ(404, res->status);
  21225. svr.stop();
  21226. t.join();
  21227. }
  21228. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21229. using namespace httplib;
  21230. // Create a test file
  21231. const char *fname = "etag_boundary_testfile.txt";
  21232. const char *content = "boundary-test";
  21233. {
  21234. std::ofstream ofs(fname);
  21235. ofs << content;
  21236. ASSERT_TRUE(ofs.good());
  21237. }
  21238. Server svr;
  21239. svr.set_mount_point("/static", ".");
  21240. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21241. svr.wait_until_ready();
  21242. Client cli(HOST, PORT);
  21243. // Get the actual ETag
  21244. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21245. ASSERT_TRUE(res1);
  21246. ASSERT_EQ(200, res1->status);
  21247. ASSERT_TRUE(res1->has_header("ETag"));
  21248. std::string etag = res1->get_header_value("ETag");
  21249. // Test 1: Very long ETag value (longer than actual ETag)
  21250. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21251. Headers h1 = {{"If-None-Match", "W/"
  21252. "\"very-long-etag-value-that-is-much-longer-"
  21253. "than-the-actual-etag-value\""}};
  21254. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21255. ASSERT_TRUE(res2);
  21256. EXPECT_EQ(200, res2->status); // Should not match
  21257. // Test 2: Long string followed by wildcard
  21258. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21259. // string)
  21260. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21261. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21262. ASSERT_TRUE(res3);
  21263. EXPECT_EQ(304, res3->status); // Should match on "*"
  21264. // Test 3: Wildcard followed by long string
  21265. // Should match on "*" immediately and return 304
  21266. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21267. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21268. ASSERT_TRUE(res4);
  21269. EXPECT_EQ(304, res4->status); // Should match on "*"
  21270. // Test 4: Multiple long non-matching values
  21271. // Should NOT match and return 200 (test that all comparisons are safe)
  21272. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21273. "W/\"second-long-non-matching-value\", "
  21274. "W/\"third-long-non-matching-value\""}};
  21275. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21276. ASSERT_TRUE(res5);
  21277. EXPECT_EQ(200, res5->status); // Should not match
  21278. // Test 5: Single character that is not "*" (edge case)
  21279. Headers h5 = {{"If-None-Match", "X"}};
  21280. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21281. ASSERT_TRUE(res6);
  21282. EXPECT_EQ(200, res6->status); // Should not match
  21283. svr.stop();
  21284. t.join();
  21285. std::remove(fname);
  21286. }
  21287. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21288. using namespace httplib;
  21289. // Create a test file
  21290. const char *fname = "ims_testfile.txt";
  21291. const char *content = "if-modified-since-test";
  21292. {
  21293. std::ofstream ofs(fname);
  21294. ofs << content;
  21295. ASSERT_TRUE(ofs.good());
  21296. }
  21297. Server svr;
  21298. svr.set_mount_point("/static", ".");
  21299. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21300. svr.wait_until_ready();
  21301. Client cli(HOST, PORT);
  21302. // First request: should get 200 with Last-Modified header
  21303. auto res1 = cli.Get("/static/ims_testfile.txt");
  21304. ASSERT_TRUE(res1);
  21305. ASSERT_EQ(200, res1->status);
  21306. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21307. std::string last_modified = res1->get_header_value("Last-Modified");
  21308. EXPECT_FALSE(last_modified.empty());
  21309. // If-Modified-Since with same time: expect 304
  21310. Headers h2 = {{"If-Modified-Since", last_modified}};
  21311. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21312. ASSERT_TRUE(res2);
  21313. EXPECT_EQ(304, res2->status);
  21314. // If-Modified-Since with future time: expect 304
  21315. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21316. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21317. ASSERT_TRUE(res3);
  21318. EXPECT_EQ(304, res3->status);
  21319. // If-Modified-Since with past time: expect 200
  21320. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21321. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21322. ASSERT_TRUE(res4);
  21323. EXPECT_EQ(200, res4->status);
  21324. // If-None-Match takes precedence over If-Modified-Since
  21325. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21326. ASSERT_TRUE(res1->has_header("ETag"));
  21327. std::string etag = res1->get_header_value("ETag");
  21328. Headers h5 = {{"If-None-Match", etag},
  21329. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21330. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21331. ASSERT_TRUE(res5);
  21332. EXPECT_EQ(304, res5->status);
  21333. svr.stop();
  21334. t.join();
  21335. std::remove(fname);
  21336. }
  21337. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21338. using namespace httplib;
  21339. Server svr;
  21340. // Endpoint that returns compressible content
  21341. svr.Get("/compressible", [](const Request &, Response &res) {
  21342. // Return a large enough body to trigger compression
  21343. std::string body(1000, 'a');
  21344. res.set_content(body, "text/plain");
  21345. });
  21346. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21347. svr.wait_until_ready();
  21348. Client cli(HOST, PORT);
  21349. // Request with gzip support: should get Vary header when compressed
  21350. cli.set_compress(true);
  21351. auto res1 = cli.Get("/compressible");
  21352. ASSERT_TRUE(res1);
  21353. EXPECT_EQ(200, res1->status);
  21354. // If Content-Encoding is set, Vary should also be set
  21355. if (res1->has_header("Content-Encoding")) {
  21356. EXPECT_TRUE(res1->has_header("Vary"));
  21357. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21358. }
  21359. // Request without Accept-Encoding header: should not have compression
  21360. Headers h_no_compress;
  21361. auto res2 = cli.Get("/compressible", h_no_compress);
  21362. ASSERT_TRUE(res2);
  21363. EXPECT_EQ(200, res2->status);
  21364. // Verify Vary header is present when compression is applied
  21365. // (the exact behavior depends on server configuration)
  21366. svr.stop();
  21367. t.join();
  21368. }
  21369. TEST(ETagTest, IfRangeWithETag) {
  21370. using namespace httplib;
  21371. // Create a test file with known content
  21372. const char *fname = "if_range_testfile.txt";
  21373. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21374. {
  21375. std::ofstream ofs(fname);
  21376. ofs << content;
  21377. ASSERT_TRUE(ofs.good());
  21378. }
  21379. Server svr;
  21380. svr.set_mount_point("/static", ".");
  21381. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21382. svr.wait_until_ready();
  21383. Client cli(HOST, PORT);
  21384. // First request: get ETag
  21385. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21386. ASSERT_TRUE(res1);
  21387. ASSERT_EQ(200, res1->status);
  21388. ASSERT_TRUE(res1->has_header("ETag"));
  21389. std::string etag = res1->get_header_value("ETag");
  21390. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21391. // Since our server generates weak ETags (W/"..."), If-Range with our
  21392. // ETag should NOT result in partial content - it should return full content.
  21393. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21394. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21395. ASSERT_TRUE(res2);
  21396. // Weak ETag in If-Range -> full content (200), not partial (206)
  21397. EXPECT_EQ(200, res2->status);
  21398. EXPECT_EQ(content, res2->body);
  21399. EXPECT_FALSE(res2->has_header("Content-Range"));
  21400. // Range request with non-matching If-Range (ETag): should get 200 (full
  21401. // content)
  21402. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21403. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21404. ASSERT_TRUE(res3);
  21405. EXPECT_EQ(200, res3->status);
  21406. EXPECT_EQ(content, res3->body);
  21407. EXPECT_FALSE(res3->has_header("Content-Range"));
  21408. // Range request with strong ETag (hypothetical - our server doesn't generate
  21409. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21410. // should return full content)
  21411. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21412. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21413. ASSERT_TRUE(res4);
  21414. EXPECT_EQ(200, res4->status);
  21415. EXPECT_EQ(content, res4->body);
  21416. EXPECT_FALSE(res4->has_header("Content-Range"));
  21417. svr.stop();
  21418. t.join();
  21419. std::remove(fname);
  21420. }
  21421. TEST(ETagTest, IfRangeWithDate) {
  21422. using namespace httplib;
  21423. // Create a test file
  21424. const char *fname = "if_range_date_testfile.txt";
  21425. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21426. {
  21427. std::ofstream ofs(fname);
  21428. ofs << content;
  21429. ASSERT_TRUE(ofs.good());
  21430. }
  21431. Server svr;
  21432. svr.set_mount_point("/static", ".");
  21433. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21434. svr.wait_until_ready();
  21435. Client cli(HOST, PORT);
  21436. // First request: get Last-Modified
  21437. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21438. ASSERT_TRUE(res1);
  21439. ASSERT_EQ(200, res1->status);
  21440. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21441. std::string last_modified = res1->get_header_value("Last-Modified");
  21442. // Range request with matching If-Range (date): should get 206
  21443. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21444. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21445. ASSERT_TRUE(res2);
  21446. EXPECT_EQ(206, res2->status);
  21447. EXPECT_EQ("FGHIJ", res2->body);
  21448. // Range request with old If-Range date: should get 200 (full content)
  21449. Headers h3 = {{"Range", "bytes=5-9"},
  21450. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21451. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21452. ASSERT_TRUE(res3);
  21453. EXPECT_EQ(200, res3->status);
  21454. EXPECT_EQ(content, res3->body);
  21455. // Range request with future If-Range date: should get 206
  21456. Headers h4 = {{"Range", "bytes=0-4"},
  21457. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21458. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21459. ASSERT_TRUE(res4);
  21460. EXPECT_EQ(206, res4->status);
  21461. EXPECT_EQ("ABCDE", res4->body);
  21462. svr.stop();
  21463. t.join();
  21464. std::remove(fname);
  21465. }
  21466. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21467. using namespace httplib;
  21468. const char *fname = "etag_malformed.txt";
  21469. const char *content = "malformed-etag";
  21470. {
  21471. std::ofstream ofs(fname);
  21472. ofs << content;
  21473. ASSERT_TRUE(ofs.good());
  21474. }
  21475. Server svr;
  21476. svr.set_mount_point("/static", ".");
  21477. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21478. svr.wait_until_ready();
  21479. Client cli(HOST, PORT);
  21480. // baseline: should get 200 and an ETag
  21481. auto res1 = cli.Get("/static/etag_malformed.txt");
  21482. ASSERT_TRUE(res1);
  21483. ASSERT_EQ(200, res1->status);
  21484. ASSERT_TRUE(res1->has_header("ETag"));
  21485. // Malformed ETag value (missing quotes) should be treated as non-matching
  21486. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21487. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21488. ASSERT_TRUE(res_bad);
  21489. EXPECT_EQ(200, res_bad->status);
  21490. // Whitespace-only header value should be considered invalid / non-matching
  21491. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21492. "Host: localhost\r\n"
  21493. "If-None-Match: \r\n"
  21494. "Connection: close\r\n"
  21495. "\r\n";
  21496. std::string out;
  21497. ASSERT_TRUE(send_request(5, raw_req, &out));
  21498. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21499. svr.stop();
  21500. t.join();
  21501. std::remove(fname);
  21502. }
  21503. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21504. using namespace httplib;
  21505. const char *fname = "ims_invalid_format.txt";
  21506. const char *content = "ims-bad-format";
  21507. {
  21508. std::ofstream ofs(fname);
  21509. ofs << content;
  21510. ASSERT_TRUE(ofs.good());
  21511. }
  21512. Server svr;
  21513. svr.set_mount_point("/static", ".");
  21514. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21515. svr.wait_until_ready();
  21516. Client cli(HOST, PORT);
  21517. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21518. ASSERT_TRUE(res1);
  21519. ASSERT_EQ(200, res1->status);
  21520. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21521. // If-Modified-Since with invalid format should not result in 304
  21522. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21523. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21524. ASSERT_TRUE(res_bad);
  21525. EXPECT_EQ(200, res_bad->status);
  21526. // If-Range with invalid date format should be treated as mismatch -> full
  21527. // content (200)
  21528. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21529. {"If-Range", "invalid-date"}};
  21530. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21531. ASSERT_TRUE(res_ifrange);
  21532. EXPECT_EQ(200, res_ifrange->status);
  21533. svr.stop();
  21534. t.join();
  21535. std::remove(fname);
  21536. }
  21537. TEST(ETagTest, IfRangeWithMalformedETag) {
  21538. using namespace httplib;
  21539. const char *fname = "ifrange_malformed.txt";
  21540. const std::string content = "0123456789";
  21541. {
  21542. std::ofstream ofs(fname);
  21543. ofs << content;
  21544. ASSERT_TRUE(ofs.good());
  21545. }
  21546. Server svr;
  21547. svr.set_mount_point("/static", ".");
  21548. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21549. svr.wait_until_ready();
  21550. Client cli(HOST, PORT);
  21551. // First request: get ETag
  21552. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21553. ASSERT_TRUE(res1);
  21554. ASSERT_EQ(200, res1->status);
  21555. ASSERT_TRUE(res1->has_header("ETag"));
  21556. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21557. // full content (200)
  21558. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21559. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21560. ASSERT_TRUE(res2);
  21561. EXPECT_EQ(200, res2->status);
  21562. EXPECT_EQ(content, res2->body);
  21563. svr.stop();
  21564. t.join();
  21565. std::remove(fname);
  21566. }
  21567. TEST(ETagTest, ExtremeLargeDateValues) {
  21568. using namespace httplib;
  21569. const char *fname = "ims_extreme_date.txt";
  21570. const char *content = "ims-extreme-date";
  21571. {
  21572. std::ofstream ofs(fname);
  21573. ofs << content;
  21574. ASSERT_TRUE(ofs.good());
  21575. }
  21576. Server svr;
  21577. svr.set_mount_point("/static", ".");
  21578. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21579. svr.wait_until_ready();
  21580. Client cli(HOST, PORT);
  21581. auto res1 = cli.Get(std::string("/static/") + fname);
  21582. ASSERT_TRUE(res1);
  21583. ASSERT_EQ(200, res1->status);
  21584. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21585. // Extremely large year that may overflow date parsing routines.
  21586. Headers h_large_date = {
  21587. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21588. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21589. ASSERT_TRUE(res_bad);
  21590. // Expect server to treat this as invalid/mismatch and return full content
  21591. EXPECT_EQ(200, res_bad->status);
  21592. // If-Range with extremely large date should be treated as mismatch -> full
  21593. // content (200)
  21594. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21595. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21596. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21597. ASSERT_TRUE(res_ifrange);
  21598. EXPECT_EQ(200, res_ifrange->status);
  21599. svr.stop();
  21600. t.join();
  21601. std::remove(fname);
  21602. }
  21603. TEST(ETagTest, NegativeFileModificationTime) {
  21604. using namespace httplib;
  21605. const char *fname = "ims_negative_mtime.txt";
  21606. const std::string content = "negative-mtime";
  21607. {
  21608. std::ofstream ofs(fname);
  21609. ofs << content;
  21610. ASSERT_TRUE(ofs.good());
  21611. }
  21612. // Try to set file mtime to a negative value. This may fail on some
  21613. // platforms/filesystems; if it fails, the test will still verify server
  21614. // behaves safely by performing a regular conditional request.
  21615. #if defined(__APPLE__) || defined(__linux__)
  21616. bool set_negative = false;
  21617. do {
  21618. struct timeval times[2];
  21619. // access time: now
  21620. times[0].tv_sec = time(nullptr);
  21621. times[0].tv_usec = 0;
  21622. // modification time: negative (e.g., -1)
  21623. times[1].tv_sec = -1;
  21624. times[1].tv_usec = 0;
  21625. if (utimes(fname, times) == 0) { set_negative = true; }
  21626. } while (0);
  21627. #else
  21628. bool set_negative = false;
  21629. #endif
  21630. Server svr;
  21631. svr.set_mount_point("/static", ".");
  21632. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21633. svr.wait_until_ready();
  21634. Client cli(HOST, PORT);
  21635. auto res1 = cli.Get(std::string("/static/") + fname);
  21636. ASSERT_TRUE(res1);
  21637. ASSERT_EQ(200, res1->status);
  21638. bool has_last_modified = res1->has_header("Last-Modified");
  21639. std::string last_modified;
  21640. if (has_last_modified) {
  21641. last_modified = res1->get_header_value("Last-Modified");
  21642. }
  21643. if (set_negative) {
  21644. // If we successfully set a negative mtime, ensure server returns a
  21645. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21646. // with an old date and ensure server handles it without crash.
  21647. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21648. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21649. ASSERT_TRUE(res2);
  21650. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21651. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21652. } else {
  21653. // Could not set negative mtime on this platform; fall back to verifying
  21654. // that normal invalid/malformed dates are treated safely (non-304).
  21655. Headers h_bad_date = {
  21656. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21657. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21658. ASSERT_TRUE(res_bad);
  21659. EXPECT_EQ(200, res_bad->status);
  21660. }
  21661. svr.stop();
  21662. t.join();
  21663. std::remove(fname);
  21664. }
  21665. //==============================================================================
  21666. // Integration Tests with Server
  21667. //==============================================================================
  21668. class SSEIntegrationTest : public ::testing::Test {
  21669. protected:
  21670. void SetUp() override {
  21671. stop_server_.store(false);
  21672. events_.clear();
  21673. server_ = httplib::detail::make_unique<Server>();
  21674. setup_server();
  21675. start_server();
  21676. }
  21677. void TearDown() override {
  21678. stop_server_.store(true);
  21679. event_cv_.notify_all();
  21680. server_->stop();
  21681. if (server_thread_.joinable()) { server_thread_.join(); }
  21682. }
  21683. void setup_server() {
  21684. // Simple SSE endpoint
  21685. server_->Get("/events", [this](const Request &req, Response &res) {
  21686. auto last_id = req.get_header_value("Last-Event-ID");
  21687. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21688. res.set_chunked_content_provider(
  21689. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21690. std::unique_lock<std::mutex> lock(event_mutex_);
  21691. if (event_cv_.wait_for(
  21692. lock, std::chrono::milliseconds(200), [this] {
  21693. return !events_.empty() || stop_server_.load();
  21694. })) {
  21695. if (stop_server_.load()) { return false; }
  21696. if (!events_.empty()) {
  21697. std::string event = events_.front();
  21698. events_.erase(events_.begin());
  21699. sink.write(event.data(), event.size());
  21700. return true;
  21701. }
  21702. }
  21703. return !stop_server_.load();
  21704. });
  21705. });
  21706. // Endpoint that returns error
  21707. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21708. res.status = 500;
  21709. res.set_content("Internal Server Error", "text/plain");
  21710. });
  21711. // Endpoint for custom event types
  21712. server_->Get("/custom-events", [](const Request &, Response &res) {
  21713. res.set_chunked_content_provider(
  21714. "text/event-stream", [](size_t offset, DataSink &sink) {
  21715. if (offset == 0) {
  21716. std::string event = "event: update\ndata: updated\n\n"
  21717. "event: delete\ndata: deleted\n\n";
  21718. sink.write(event.data(), event.size());
  21719. }
  21720. return false; // End stream after sending
  21721. });
  21722. });
  21723. }
  21724. void start_server() {
  21725. port_ = server_->bind_to_any_port(HOST);
  21726. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21727. // Wait for server to start
  21728. while (!server_->is_running()) {
  21729. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21730. }
  21731. }
  21732. int get_port() const { return port_; }
  21733. void send_event(const std::string &event) {
  21734. std::lock_guard<std::mutex> lock(event_mutex_);
  21735. events_.push_back(event);
  21736. event_cv_.notify_all();
  21737. }
  21738. std::unique_ptr<Server> server_;
  21739. std::thread server_thread_;
  21740. std::mutex event_mutex_;
  21741. std::condition_variable event_cv_;
  21742. std::vector<std::string> events_;
  21743. std::atomic<bool> stop_server_{false};
  21744. std::string last_received_event_id_;
  21745. int port_ = 0;
  21746. };
  21747. //==============================================================================
  21748. // SSE Parsing Tests
  21749. //==============================================================================
  21750. class SSEParsingTest : public SSEIntegrationTest {
  21751. protected:
  21752. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21753. // A trailing sentinel event tells when the whole stream has been parsed.
  21754. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21755. auto body = stream + "event: end\ndata: end\n\n";
  21756. server_->Get("/parse", [body](const Request &, Response &res) {
  21757. res.set_content(body, "text/event-stream");
  21758. });
  21759. return collect("/parse");
  21760. }
  21761. // Runs SSEClient against path until an "end" event arrives and returns the
  21762. // messages dispatched before it
  21763. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21764. Client client(HOST, get_port());
  21765. sse::SSEClient sse(client, path);
  21766. std::mutex mutex;
  21767. std::condition_variable cv;
  21768. std::vector<sse::SSEMessage> messages;
  21769. auto done = false;
  21770. sse.on_message([&](const sse::SSEMessage &msg) {
  21771. std::lock_guard<std::mutex> lock(mutex);
  21772. // Ignore a replay from a reconnect that races with stop()
  21773. if (!done) { messages.push_back(msg); }
  21774. });
  21775. sse.on_event("end", [&](const sse::SSEMessage &) {
  21776. std::lock_guard<std::mutex> lock(mutex);
  21777. done = true;
  21778. cv.notify_all();
  21779. });
  21780. sse.set_reconnect_interval(100);
  21781. sse.start_async();
  21782. {
  21783. std::unique_lock<std::mutex> lock(mutex);
  21784. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21785. }
  21786. sse.stop();
  21787. EXPECT_TRUE(done);
  21788. return messages;
  21789. }
  21790. };
  21791. TEST_F(SSEParsingTest, SingleLineData) {
  21792. auto msgs = parse("data: hello\n\n");
  21793. ASSERT_EQ(msgs.size(), 1u);
  21794. EXPECT_EQ(msgs[0].data, "hello");
  21795. EXPECT_EQ(msgs[0].event, "message");
  21796. }
  21797. TEST_F(SSEParsingTest, MultiLineData) {
  21798. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21799. ASSERT_EQ(msgs.size(), 1u);
  21800. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21801. }
  21802. TEST_F(SSEParsingTest, CustomEventType) {
  21803. auto msgs = parse("event: update\ndata: payload\n\n");
  21804. ASSERT_EQ(msgs.size(), 1u);
  21805. EXPECT_EQ(msgs[0].event, "update");
  21806. EXPECT_EQ(msgs[0].data, "payload");
  21807. }
  21808. TEST_F(SSEParsingTest, EventIdHandling) {
  21809. auto msgs = parse("id: 12345\ndata: test\n\n");
  21810. ASSERT_EQ(msgs.size(), 1u);
  21811. EXPECT_EQ(msgs[0].id, "12345");
  21812. }
  21813. TEST_F(SSEParsingTest, EmptyEventId) {
  21814. auto msgs = parse("id:\ndata: test\n\n");
  21815. ASSERT_EQ(msgs.size(), 1u);
  21816. EXPECT_EQ(msgs[0].id, "");
  21817. }
  21818. TEST_F(SSEParsingTest, CommentsIgnored) {
  21819. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21820. ASSERT_EQ(msgs.size(), 1u);
  21821. EXPECT_EQ(msgs[0].data, "hello");
  21822. EXPECT_EQ(msgs[0].event, "message");
  21823. }
  21824. TEST_F(SSEParsingTest, ColonInValue) {
  21825. auto msgs = parse("data: hello:world:test\n\n");
  21826. ASSERT_EQ(msgs.size(), 1u);
  21827. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21828. }
  21829. TEST_F(SSEParsingTest, FieldNameOnly) {
  21830. // A line without a colon is a field name with an empty value
  21831. auto msgs = parse("data\n\n");
  21832. ASSERT_EQ(msgs.size(), 1u);
  21833. EXPECT_EQ(msgs[0].data, "");
  21834. }
  21835. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21836. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21837. ASSERT_EQ(msgs.size(), 1u);
  21838. EXPECT_EQ(msgs[0].event, "update");
  21839. EXPECT_EQ(msgs[0].data, "hello");
  21840. }
  21841. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21842. auto msgs = parse("data\r\n\r\n");
  21843. ASSERT_EQ(msgs.size(), 1u);
  21844. EXPECT_EQ(msgs[0].data, "");
  21845. }
  21846. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21847. auto msgs = parse("event: update\rdata: hello\r\r");
  21848. ASSERT_EQ(msgs.size(), 1u);
  21849. EXPECT_EQ(msgs[0].event, "update");
  21850. EXPECT_EQ(msgs[0].data, "hello");
  21851. }
  21852. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21853. // Chunk boundaries fall inside every \r\n and right before the first one
  21854. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21855. "\n\r", "\nevent: end\ndata: end\n\n"};
  21856. server_->Get("/split", [chunks](const Request &, Response &res) {
  21857. auto i = std::make_shared<size_t>(0);
  21858. res.set_chunked_content_provider(
  21859. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21860. if (*i == chunks.size()) {
  21861. sink.done();
  21862. } else {
  21863. sink.write(chunks[*i].data(), chunks[*i].size());
  21864. (*i)++;
  21865. }
  21866. return true;
  21867. });
  21868. });
  21869. auto msgs = collect("/split");
  21870. ASSERT_EQ(msgs.size(), 1u);
  21871. EXPECT_EQ(msgs[0].event, "update");
  21872. EXPECT_EQ(msgs[0].data, "hello");
  21873. }
  21874. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21875. // Only a BOM at the start of the stream is ignored
  21876. auto msgs = parse("\xEF\xBB\xBF"
  21877. "data: first\n\n"
  21878. "\xEF\xBB\xBF"
  21879. "data: second\n\n");
  21880. ASSERT_EQ(msgs.size(), 1u);
  21881. EXPECT_EQ(msgs[0].data, "first");
  21882. }
  21883. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21884. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21885. ASSERT_EQ(msgs.size(), 1u);
  21886. EXPECT_EQ(msgs[0].data, "hello");
  21887. EXPECT_EQ(msgs[0].event, "message");
  21888. }
  21889. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21890. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21891. ASSERT_EQ(msgs.size(), 2u);
  21892. EXPECT_EQ(msgs[0].data, "hello");
  21893. EXPECT_EQ(msgs[1].data, "hello");
  21894. }
  21895. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21896. // An event without data is not dispatched, and its type must not leak
  21897. // into the next event
  21898. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21899. ASSERT_EQ(msgs.size(), 1u);
  21900. EXPECT_EQ(msgs[0].event, "message");
  21901. EXPECT_EQ(msgs[0].data, "hello");
  21902. }
  21903. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21904. // Also when the empty field replaces an earlier type
  21905. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21906. ASSERT_EQ(msgs.size(), 2u);
  21907. EXPECT_EQ(msgs[0].event, "message");
  21908. EXPECT_EQ(msgs[1].event, "message");
  21909. }
  21910. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21911. // The first connection sends only an id; the second echoes back the
  21912. // Last-Event-ID it was reconnected with
  21913. std::atomic<int> connection_count{0};
  21914. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21915. if (connection_count++ == 0) {
  21916. res.set_content("id: 42\n\n", "text/event-stream");
  21917. } else {
  21918. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21919. "\n\nevent: end\ndata: end\n\n",
  21920. "text/event-stream");
  21921. }
  21922. });
  21923. auto msgs = collect("/id-only");
  21924. ASSERT_EQ(msgs.size(), 1u);
  21925. EXPECT_EQ(msgs[0].data, "42");
  21926. }
  21927. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21928. // The first connection sets an id and then clears it with an empty one; the
  21929. // second reports whether it was reconnected with a Last-Event-ID
  21930. std::atomic<int> connection_count{0};
  21931. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21932. if (connection_count++ == 0) {
  21933. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21934. "text/event-stream");
  21935. } else {
  21936. res.set_content(
  21937. std::string("data: ") +
  21938. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21939. "\n\nevent: end\ndata: end\n\n",
  21940. "text/event-stream");
  21941. }
  21942. });
  21943. auto msgs = collect("/id-clear");
  21944. ASSERT_EQ(msgs.size(), 3u);
  21945. EXPECT_EQ(msgs[0].id, "1");
  21946. EXPECT_EQ(msgs[1].id, "");
  21947. EXPECT_EQ(msgs[2].data, "not sent");
  21948. }
  21949. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21950. // The first connection sets an id and then sends ids that cannot be carried
  21951. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21952. // with
  21953. std::atomic<int> connection_count{0};
  21954. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21955. if (connection_count++ == 0) {
  21956. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21957. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21958. "text/event-stream");
  21959. } else {
  21960. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21961. "\n\nevent: end\ndata: end\n\n",
  21962. "text/event-stream");
  21963. }
  21964. });
  21965. auto msgs = collect("/id-unsendable");
  21966. ASSERT_EQ(msgs.size(), 1u);
  21967. EXPECT_EQ(msgs[0].data, "42");
  21968. }
  21969. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21970. auto msgs = parse("event: notification\nid: evt-42\n"
  21971. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21972. ASSERT_EQ(msgs.size(), 1u);
  21973. EXPECT_EQ(msgs[0].event, "notification");
  21974. EXPECT_EQ(msgs[0].id, "evt-42");
  21975. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21976. }
  21977. TEST(SSEMessageTest, Clear) {
  21978. sse::SSEMessage msg;
  21979. msg.event = "custom";
  21980. msg.data = "some data";
  21981. msg.id = "123";
  21982. msg.clear();
  21983. EXPECT_EQ(msg.event, "message");
  21984. EXPECT_EQ(msg.data, "");
  21985. EXPECT_EQ(msg.id, "");
  21986. }
  21987. //==============================================================================
  21988. // SSE Integration Tests
  21989. //==============================================================================
  21990. // Test: Successful connection and on_open callback
  21991. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21992. // Add a simple endpoint that sends one event and closes
  21993. server_->Get("/simple-event", [](const Request &, Response &res) {
  21994. res.set_chunked_content_provider(
  21995. "text/event-stream", [](size_t offset, DataSink &sink) {
  21996. if (offset == 0) {
  21997. std::string event = "data: hello\n\n";
  21998. sink.write(event.data(), event.size());
  21999. }
  22000. return false; // Close stream after sending
  22001. });
  22002. });
  22003. Client client("localhost", get_port());
  22004. sse::SSEClient sse(client, "/simple-event");
  22005. std::atomic<bool> open_called{false};
  22006. std::atomic<bool> message_received{false};
  22007. sse.on_open([&open_called]() { open_called.store(true); });
  22008. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22009. if (msg.data == "hello") { message_received.store(true); }
  22010. });
  22011. sse.set_reconnect_interval(100);
  22012. sse.set_max_reconnect_attempts(1);
  22013. // Start async
  22014. sse.start_async();
  22015. // Wait for message to be processed
  22016. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22017. sse.stop();
  22018. EXPECT_TRUE(open_called.load());
  22019. EXPECT_TRUE(message_received.load());
  22020. }
  22021. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22022. // A data line that never ends.
  22023. server_->Get("/endless-line", [](const Request &, Response &res) {
  22024. res.set_chunked_content_provider(
  22025. "text/event-stream", [](size_t offset, DataSink &sink) {
  22026. if (offset == 0) { sink.write("data: ", 6); }
  22027. std::string chunk(64 * 1024, 'A');
  22028. return sink.write(chunk.data(), chunk.size());
  22029. });
  22030. });
  22031. Client client("localhost", get_port());
  22032. sse::SSEClient sse(client, "/endless-line");
  22033. std::atomic<bool> too_long{false};
  22034. sse.on_error([&](Error err) {
  22035. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22036. });
  22037. sse.set_max_reconnect_attempts(1);
  22038. sse.start_async();
  22039. for (int i = 0; i < 500 && !too_long; i++) {
  22040. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22041. }
  22042. sse.stop();
  22043. EXPECT_TRUE(too_long);
  22044. }
  22045. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22046. // Far more in all than the client's payload limit below.
  22047. server_->Get("/many-events", [](const Request &, Response &res) {
  22048. res.set_chunked_content_provider(
  22049. "text/event-stream", [](size_t offset, DataSink &sink) {
  22050. if (offset == 0) {
  22051. std::string events;
  22052. for (int i = 0; i < 1000; i++) {
  22053. events += "data: message\n\n";
  22054. }
  22055. sink.write(events.data(), events.size());
  22056. }
  22057. return false;
  22058. });
  22059. });
  22060. Client client("localhost", get_port());
  22061. client.set_payload_max_length(1024);
  22062. sse::SSEClient sse(client, "/many-events");
  22063. std::atomic<int> messages{0};
  22064. std::atomic<bool> too_large{false};
  22065. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22066. sse.on_error([&](Error err) {
  22067. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22068. });
  22069. sse.set_max_reconnect_attempts(1);
  22070. sse.start_async();
  22071. for (int i = 0; i < 500 && messages < 1000; i++) {
  22072. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22073. }
  22074. sse.stop();
  22075. EXPECT_GE(messages.load(), 1000);
  22076. EXPECT_FALSE(too_large);
  22077. }
  22078. // Test: on_message callback
  22079. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22080. // Endpoint that sends multiple events then closes
  22081. server_->Get("/multi-event", [](const Request &, Response &res) {
  22082. res.set_chunked_content_provider(
  22083. "text/event-stream", [](size_t offset, DataSink &sink) {
  22084. if (offset == 0) {
  22085. std::string events = "data: message1\n\ndata: message2\n\n";
  22086. sink.write(events.data(), events.size());
  22087. }
  22088. return false;
  22089. });
  22090. });
  22091. Client client("localhost", get_port());
  22092. sse::SSEClient sse(client, "/multi-event");
  22093. std::vector<std::string> received_messages;
  22094. std::mutex messages_mutex;
  22095. sse.on_message([&](const sse::SSEMessage &msg) {
  22096. std::lock_guard<std::mutex> lock(messages_mutex);
  22097. received_messages.push_back(msg.data);
  22098. });
  22099. sse.set_reconnect_interval(100);
  22100. sse.set_max_reconnect_attempts(1);
  22101. sse.start_async();
  22102. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22103. sse.stop();
  22104. std::lock_guard<std::mutex> lock(messages_mutex);
  22105. EXPECT_GE(received_messages.size(), 2u);
  22106. if (received_messages.size() >= 2) {
  22107. EXPECT_EQ(received_messages[0], "message1");
  22108. EXPECT_EQ(received_messages[1], "message2");
  22109. }
  22110. }
  22111. // Test: on_event for specific types
  22112. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22113. Client client("localhost", get_port());
  22114. sse::SSEClient sse(client, "/custom-events");
  22115. std::atomic<bool> update_received{false};
  22116. std::atomic<bool> delete_received{false};
  22117. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22118. if (msg.data == "updated") { update_received.store(true); }
  22119. });
  22120. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22121. if (msg.data == "deleted") { delete_received.store(true); }
  22122. });
  22123. sse.set_max_reconnect_attempts(1);
  22124. sse.start_async();
  22125. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22126. sse.stop();
  22127. EXPECT_TRUE(update_received.load());
  22128. EXPECT_TRUE(delete_received.load());
  22129. }
  22130. // Test: on_error callback on connection failure
  22131. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22132. // Connect to a non-existent port
  22133. Client client("localhost", 59999);
  22134. sse::SSEClient sse(client, "/events");
  22135. std::atomic<bool> error_called{false};
  22136. Error received_error = Error::Success;
  22137. sse.on_error([&](Error err) {
  22138. error_called.store(true);
  22139. received_error = err;
  22140. });
  22141. sse.set_reconnect_interval(50);
  22142. sse.set_max_reconnect_attempts(1);
  22143. sse.start_async();
  22144. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22145. sse.stop();
  22146. EXPECT_TRUE(error_called.load());
  22147. EXPECT_NE(received_error, Error::Success);
  22148. }
  22149. // Test: Last-Event-ID header sent on reconnect
  22150. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22151. // Endpoint that sends event with ID
  22152. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22153. res.set_chunked_content_provider(
  22154. "text/event-stream", [](size_t offset, DataSink &sink) {
  22155. if (offset == 0) {
  22156. std::string event = "id: evt-123\ndata: test\n\n";
  22157. sink.write(event.data(), event.size());
  22158. }
  22159. return false;
  22160. });
  22161. });
  22162. Client client("localhost", get_port());
  22163. sse::SSEClient sse(client, "/event-with-id");
  22164. std::atomic<bool> id_received{false};
  22165. sse.on_message([&](const sse::SSEMessage &msg) {
  22166. if (!msg.id.empty()) { id_received.store(true); }
  22167. });
  22168. sse.set_reconnect_interval(100);
  22169. sse.set_max_reconnect_attempts(1);
  22170. sse.start_async();
  22171. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22172. sse.stop();
  22173. EXPECT_TRUE(id_received.load());
  22174. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22175. }
  22176. // Test: Manual stop
  22177. TEST_F(SSEIntegrationTest, ManualStop) {
  22178. // Endpoint that sends one event and stays open briefly. The server outlives
  22179. // this test body, so the provider uses the fixture's flag, not a local.
  22180. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22181. res.set_chunked_content_provider(
  22182. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22183. if (offset == 0) {
  22184. std::string event = "data: connected\n\n";
  22185. sink.write(event.data(), event.size());
  22186. }
  22187. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22188. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22189. }
  22190. return false;
  22191. });
  22192. });
  22193. Client client("localhost", get_port());
  22194. sse::SSEClient sse(client, "/stay-open");
  22195. std::atomic<bool> connected{false};
  22196. sse.on_open([&connected]() { connected.store(true); });
  22197. sse.set_reconnect_interval(100);
  22198. sse.set_max_reconnect_attempts(1);
  22199. sse.start_async();
  22200. // Wait for connection to establish
  22201. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22202. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22203. }
  22204. EXPECT_TRUE(connected.load());
  22205. EXPECT_TRUE(sse.is_connected());
  22206. // Signal handler to stop
  22207. stop_server_.store(true);
  22208. // Stop SSE client
  22209. sse.stop();
  22210. EXPECT_FALSE(sse.is_connected());
  22211. }
  22212. // Sends one event, then nothing until stop is set
  22213. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22214. return [&stop](const Request &, Response &res) {
  22215. res.set_chunked_content_provider(
  22216. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22217. if (offset == 0) {
  22218. std::string event = "data: hello\n\n";
  22219. sink.write(event.data(), event.size());
  22220. }
  22221. while (!stop.load()) {
  22222. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22223. }
  22224. return false;
  22225. });
  22226. };
  22227. }
  22228. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22229. static void check_stop_interrupts_blocked_read(Client &client) {
  22230. client.set_read_timeout(30, 0);
  22231. for (auto by_destructor : {false, true}) {
  22232. std::atomic<bool> received{false};
  22233. std::chrono::steady_clock::time_point start;
  22234. {
  22235. sse::SSEClient sse(client, "/idle-stream");
  22236. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22237. sse.start_async();
  22238. for (int i = 0; i < 500 && !received.load(); ++i) {
  22239. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22240. }
  22241. ASSERT_TRUE(received.load());
  22242. // Let the client block in the next read
  22243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22244. start = std::chrono::steady_clock::now();
  22245. if (!by_destructor) { sse.stop(); }
  22246. }
  22247. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22248. std::chrono::seconds(2));
  22249. }
  22250. }
  22251. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22252. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22253. Client client("localhost", get_port());
  22254. check_stop_interrupts_blocked_read(client);
  22255. }
  22256. #ifdef CPPHTTPLIB_SSL_ENABLED
  22257. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22258. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22259. std::atomic<bool> done{false};
  22260. svr.Get("/idle-stream", idle_event_stream(done));
  22261. auto port = svr.bind_to_any_port(HOST);
  22262. std::thread t([&] { svr.listen_after_bind(); });
  22263. auto se = detail::scope_exit([&] {
  22264. done.store(true);
  22265. svr.stop();
  22266. t.join();
  22267. });
  22268. svr.wait_until_ready();
  22269. Client client("https://localhost:" + std::to_string(port));
  22270. client.enable_server_certificate_verification(false);
  22271. check_stop_interrupts_blocked_read(client);
  22272. }
  22273. #endif
  22274. // Test: SSEClient with custom headers
  22275. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22276. // Setup a server endpoint that checks for custom header
  22277. std::atomic<bool> header_received{false};
  22278. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22279. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22280. header_received.store(true);
  22281. }
  22282. res.set_chunked_content_provider("text/event-stream",
  22283. [](size_t, DataSink &) { return false; });
  22284. });
  22285. Client client("localhost", get_port());
  22286. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22287. sse::SSEClient sse(client, "/header-check", headers);
  22288. sse.set_max_reconnect_attempts(1);
  22289. sse.start_async();
  22290. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22291. sse.stop();
  22292. EXPECT_TRUE(header_received.load());
  22293. }
  22294. // Test: Reconnect interval configuration
  22295. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22296. Client client("localhost", get_port());
  22297. sse::SSEClient sse(client, "/events");
  22298. auto &result = sse.set_reconnect_interval(500);
  22299. // Builder pattern should return reference to self
  22300. EXPECT_EQ(&result, &sse);
  22301. }
  22302. // Test: Max reconnect attempts
  22303. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22304. // Connect to non-existent port to force reconnects
  22305. Client client("localhost", 59998);
  22306. sse::SSEClient sse(client, "/events");
  22307. std::atomic<int> error_count{0};
  22308. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22309. sse.set_reconnect_interval(50);
  22310. sse.set_max_reconnect_attempts(2);
  22311. auto start = std::chrono::steady_clock::now();
  22312. sse.start(); // Blocking call
  22313. auto end = std::chrono::steady_clock::now();
  22314. // Should have stopped after 2 failed attempts
  22315. EXPECT_GE(error_count.load(), 2);
  22316. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22317. auto duration =
  22318. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22319. #ifdef _WIN32
  22320. // Windows is much slower for socket connection failures
  22321. EXPECT_LT(duration.count(), 7000);
  22322. #else
  22323. EXPECT_LT(duration.count(), 1000);
  22324. #endif
  22325. }
  22326. // Test: Multi-line data in integration
  22327. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22328. // Endpoint with multi-line data
  22329. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22330. res.set_chunked_content_provider(
  22331. "text/event-stream", [](size_t offset, DataSink &sink) {
  22332. if (offset == 0) {
  22333. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22334. sink.write(event.data(), event.size());
  22335. }
  22336. return false;
  22337. });
  22338. });
  22339. Client client("localhost", get_port());
  22340. sse::SSEClient sse(client, "/multiline-data");
  22341. std::string received_data;
  22342. std::mutex data_mutex;
  22343. sse.on_message([&](const sse::SSEMessage &msg) {
  22344. std::lock_guard<std::mutex> lock(data_mutex);
  22345. received_data = msg.data;
  22346. });
  22347. sse.set_reconnect_interval(100);
  22348. sse.set_max_reconnect_attempts(1);
  22349. sse.start_async();
  22350. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22351. sse.stop();
  22352. std::lock_guard<std::mutex> lock(data_mutex);
  22353. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22354. }
  22355. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22356. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22357. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22358. DataSink &sink) {
  22359. if (offset == 0) {
  22360. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22361. sink.write(events.data(), events.size());
  22362. }
  22363. return false;
  22364. });
  22365. });
  22366. Client client("localhost", get_port());
  22367. sse::SSEClient sse(client, "/empty-data-lines");
  22368. std::mutex mutex;
  22369. std::condition_variable cv;
  22370. std::vector<std::string> received;
  22371. sse.on_message([&](const sse::SSEMessage &msg) {
  22372. std::lock_guard<std::mutex> lock(mutex);
  22373. received.push_back(msg.data);
  22374. cv.notify_all();
  22375. });
  22376. sse.set_max_reconnect_attempts(1);
  22377. sse.start_async();
  22378. {
  22379. std::unique_lock<std::mutex> lock(mutex);
  22380. cv.wait_for(lock, std::chrono::seconds(2),
  22381. [&] { return received.size() >= 3; });
  22382. }
  22383. sse.stop();
  22384. ASSERT_GE(received.size(), 3u);
  22385. EXPECT_EQ(received[0], "");
  22386. EXPECT_EQ(received[1], "\nhello");
  22387. EXPECT_EQ(received[2], "");
  22388. }
  22389. // Test: Auto-reconnect after server disconnection
  22390. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22391. std::atomic<int> connection_count{0};
  22392. std::atomic<int> message_count{0};
  22393. // Endpoint that sends one event and closes, forcing reconnect
  22394. server_->Get("/reconnect-test",
  22395. [&connection_count](const Request &, Response &res) {
  22396. connection_count.fetch_add(1);
  22397. res.set_chunked_content_provider(
  22398. "text/event-stream", [](size_t offset, DataSink &sink) {
  22399. if (offset == 0) {
  22400. std::string event = "data: hello\n\n";
  22401. sink.write(event.data(), event.size());
  22402. }
  22403. return false; // Close connection after sending
  22404. });
  22405. });
  22406. Client client("localhost", get_port());
  22407. sse::SSEClient sse(client, "/reconnect-test");
  22408. sse.on_message([&message_count](const sse::SSEMessage &) {
  22409. message_count.fetch_add(1);
  22410. });
  22411. sse.set_reconnect_interval(100);
  22412. sse.set_max_reconnect_attempts(3);
  22413. sse.start_async();
  22414. // Wait long enough for multiple reconnects
  22415. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22416. sse.stop();
  22417. // Should have connected multiple times (initial + reconnects)
  22418. EXPECT_GE(connection_count.load(), 2);
  22419. // Should have received messages from multiple connections
  22420. EXPECT_GE(message_count.load(), 2);
  22421. }
  22422. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22423. std::atomic<int> connection_count{0};
  22424. // Neither Content-Length nor chunked: the close ends the stream
  22425. server_->Get("/close-delimited",
  22426. [&connection_count](const Request &, Response &res) {
  22427. connection_count.fetch_add(1);
  22428. res.set_content_provider(
  22429. "text/event-stream", [](size_t offset, DataSink &sink) {
  22430. if (offset == 0) {
  22431. std::string event = "data: hello\n\n";
  22432. sink.write(event.data(), event.size());
  22433. } else {
  22434. sink.done();
  22435. }
  22436. return true;
  22437. });
  22438. });
  22439. Client client("localhost", get_port());
  22440. sse::SSEClient sse(client, "/close-delimited");
  22441. std::atomic<int> error_count{0};
  22442. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22443. sse.set_reconnect_interval(100);
  22444. sse.start_async();
  22445. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22446. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22447. }
  22448. sse.stop();
  22449. // Reconnects as after any end of the stream, but reports no error
  22450. EXPECT_GE(connection_count.load(), 2);
  22451. EXPECT_EQ(0, error_count.load());
  22452. }
  22453. // Test: A retry field that is not all ASCII digits is ignored
  22454. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22455. std::atomic<int> connection_count{0};
  22456. server_->Get("/bad-retry",
  22457. [&connection_count](const Request &, Response &res) {
  22458. connection_count.fetch_add(1);
  22459. res.set_chunked_content_provider(
  22460. "text/event-stream", [](size_t offset, DataSink &sink) {
  22461. if (offset == 0) {
  22462. std::string event = "retry: -1\ndata: hello\n\n";
  22463. sink.write(event.data(), event.size());
  22464. }
  22465. return false;
  22466. });
  22467. });
  22468. Client client("localhost", get_port());
  22469. sse::SSEClient sse(client, "/bad-retry");
  22470. sse.set_reconnect_interval(10000);
  22471. sse.start_async();
  22472. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22473. sse.stop();
  22474. EXPECT_EQ(connection_count.load(), 1);
  22475. }
  22476. // Test: A retry field of all ASCII digits sets the reconnection time
  22477. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22478. std::mutex mutex;
  22479. std::condition_variable cv;
  22480. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22481. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22482. {
  22483. std::lock_guard<std::mutex> lock(mutex);
  22484. connected_at.push_back(std::chrono::steady_clock::now());
  22485. cv.notify_all();
  22486. }
  22487. res.set_chunked_content_provider(
  22488. "text/event-stream", [](size_t offset, DataSink &sink) {
  22489. if (offset == 0) {
  22490. std::string event = "retry: 0\ndata: hello\n\n";
  22491. sink.write(event.data(), event.size());
  22492. }
  22493. return false;
  22494. });
  22495. });
  22496. Client client("localhost", get_port());
  22497. sse::SSEClient sse(client, "/zero-retry");
  22498. sse.set_reconnect_interval(10000);
  22499. sse.start_async();
  22500. {
  22501. std::unique_lock<std::mutex> lock(mutex);
  22502. cv.wait_for(lock, std::chrono::seconds(5),
  22503. [&] { return connected_at.size() >= 2; });
  22504. }
  22505. sse.stop();
  22506. // The server-supplied interval is applied, but never below 100ms, so
  22507. // "retry: 0" does not cause a busy reconnect loop
  22508. std::lock_guard<std::mutex> lock(mutex);
  22509. ASSERT_GE(connected_at.size(), 2u);
  22510. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22511. connected_at[1] - connected_at[0])
  22512. .count();
  22513. EXPECT_GE(interval_ms, 100);
  22514. }
  22515. // Test: Last-Event-ID sent on reconnect
  22516. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22517. std::atomic<int> connection_count{0};
  22518. std::vector<std::string> received_last_event_ids;
  22519. std::mutex id_mutex;
  22520. // Endpoint that checks Last-Event-ID header and sends event with ID
  22521. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22522. int conn = connection_count.fetch_add(1);
  22523. // Capture the Last-Event-ID header from each connection
  22524. {
  22525. std::lock_guard<std::mutex> lock(id_mutex);
  22526. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22527. }
  22528. res.set_chunked_content_provider(
  22529. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22530. if (offset == 0) {
  22531. std::string event =
  22532. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22533. sink.write(event.data(), event.size());
  22534. }
  22535. return false;
  22536. });
  22537. });
  22538. Client client("localhost", get_port());
  22539. sse::SSEClient sse(client, "/reconnect-with-id");
  22540. sse.set_reconnect_interval(100);
  22541. sse.set_max_reconnect_attempts(3);
  22542. sse.start_async();
  22543. // Wait for at least 2 connections
  22544. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22545. sse.stop();
  22546. // Verify behavior
  22547. std::lock_guard<std::mutex> lock(id_mutex);
  22548. EXPECT_GE(received_last_event_ids.size(), 2u);
  22549. // First connection should have no Last-Event-ID
  22550. if (!received_last_event_ids.empty()) {
  22551. EXPECT_EQ(received_last_event_ids[0], "");
  22552. }
  22553. // Second connection should have Last-Event-ID from first connection
  22554. if (received_last_event_ids.size() >= 2) {
  22555. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22556. }
  22557. }
  22558. // Test: set_headers updates headers used on reconnect
  22559. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22560. std::vector<std::string> received_tokens;
  22561. std::mutex token_mutex;
  22562. // Endpoint that captures Authorization header
  22563. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22564. {
  22565. std::lock_guard<std::mutex> lock(token_mutex);
  22566. received_tokens.push_back(req.get_header_value("Authorization"));
  22567. }
  22568. res.set_chunked_content_provider(
  22569. "text/event-stream", [](size_t offset, DataSink &sink) {
  22570. if (offset == 0) {
  22571. std::string event = "data: hello\n\n";
  22572. sink.write(event.data(), event.size());
  22573. }
  22574. return false; // Close connection to trigger reconnect
  22575. });
  22576. });
  22577. Client client("localhost", get_port());
  22578. Headers headers = {{"Authorization", "Bearer old-token"}};
  22579. sse::SSEClient sse(client, "/auth-check", headers);
  22580. // Update headers on each successful connection
  22581. sse.on_open(
  22582. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22583. sse.set_reconnect_interval(100);
  22584. sse.set_max_reconnect_attempts(3);
  22585. sse.start_async();
  22586. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22587. sse.stop();
  22588. std::lock_guard<std::mutex> lock(token_mutex);
  22589. ASSERT_GE(received_tokens.size(), 2u);
  22590. // First connection uses original header
  22591. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22592. // Second connection uses updated header from set_headers
  22593. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22594. }
  22595. // Test: 401 allows reconnection (so on_error can refresh headers)
  22596. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22597. std::atomic<int> connection_count{0};
  22598. // Endpoint: returns 401 on first attempt, 200 on second
  22599. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22600. int conn = connection_count.fetch_add(1);
  22601. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22602. res.status = StatusCode::Unauthorized_401;
  22603. res.set_content("Unauthorized", "text/plain");
  22604. return;
  22605. }
  22606. res.set_chunked_content_provider(
  22607. "text/event-stream", [](size_t offset, DataSink &sink) {
  22608. if (offset == 0) {
  22609. std::string event = "data: authenticated\n\n";
  22610. sink.write(event.data(), event.size());
  22611. }
  22612. return false;
  22613. });
  22614. });
  22615. Client client("localhost", get_port());
  22616. Headers headers = {{"Authorization", "Bearer expired"}};
  22617. sse::SSEClient sse(client, "/auth-retry", headers);
  22618. std::atomic<bool> message_received{false};
  22619. // Refresh token on error
  22620. sse.on_error(
  22621. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22622. sse.on_message([&](const sse::SSEMessage &msg) {
  22623. if (msg.data == "authenticated") { message_received.store(true); }
  22624. });
  22625. sse.set_reconnect_interval(100);
  22626. sse.set_max_reconnect_attempts(3);
  22627. sse.start_async();
  22628. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22629. sse.stop();
  22630. // Should have reconnected after 401 and succeeded with new token
  22631. EXPECT_GE(connection_count.load(), 2);
  22632. EXPECT_TRUE(message_received.load());
  22633. }
  22634. TEST(Issue2318Test, EmptyHostString) {
  22635. {
  22636. httplib::Client cli_empty("", PORT);
  22637. auto res = cli_empty.Get("/");
  22638. ASSERT_FALSE(res);
  22639. EXPECT_EQ(httplib::Error::Connection, res.error());
  22640. }
  22641. {
  22642. httplib::Client cli(" ", PORT);
  22643. auto res = cli.Get("/");
  22644. ASSERT_FALSE(res);
  22645. EXPECT_EQ(httplib::Error::Connection, res.error());
  22646. }
  22647. }
  22648. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22649. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22650. Server svr;
  22651. // Set a small payload limit (1KB)
  22652. svr.set_payload_max_length(1024);
  22653. svr.Post("/test", [&](const Request &req, Response &res) {
  22654. res.set_content("Body size: " + std::to_string(req.body.size()),
  22655. "text/plain");
  22656. });
  22657. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22658. auto se = detail::scope_exit([&] {
  22659. svr.stop();
  22660. listen_thread.join();
  22661. });
  22662. svr.wait_until_ready();
  22663. // Create data that compresses well but exceeds limit when decompressed
  22664. // 8KB of repeated null bytes compresses to a very small size
  22665. std::string original_data(8 * 1024, '\0');
  22666. // Compress the data using gzip
  22667. std::string compressed_data;
  22668. detail::gzip_compressor compressor;
  22669. compressor.compress(original_data.data(), original_data.size(), true,
  22670. [&](const char *data, size_t size) {
  22671. compressed_data.append(data, size);
  22672. return true;
  22673. });
  22674. // Verify compression worked (compressed should be much smaller)
  22675. ASSERT_LT(compressed_data.size(), original_data.size());
  22676. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22677. // Send compressed data with Content-Encoding: gzip
  22678. Client cli(HOST, PORT);
  22679. Headers headers = {{"Content-Encoding", "gzip"}};
  22680. auto res =
  22681. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22682. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22684. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22685. }
  22686. #endif
  22687. // ============================================================================
  22688. // OpenSSL-Specific Tests
  22689. // ============================================================================
  22690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22691. X509 *readCertificate(const std::string &strFileName) {
  22692. std::ifstream inStream(strFileName);
  22693. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22694. std::istreambuf_iterator<char>());
  22695. if (strCertPEM.empty()) return (nullptr);
  22696. BIO *pbCert = BIO_new(BIO_s_mem());
  22697. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22698. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22699. BIO_free(pbCert);
  22700. return (pCert);
  22701. }
  22702. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22703. std::ifstream inStream(strFileName);
  22704. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22705. std::istreambuf_iterator<char>());
  22706. if (strPrivateKeyPEM.empty()) return (nullptr);
  22707. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22708. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22709. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22710. BIO_free(pbPrivKey);
  22711. return (pPrivateKey);
  22712. }
  22713. TEST(BindServerTest, UpdateCerts) {
  22714. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22715. int port = svr.bind_to_any_port("0.0.0.0");
  22716. ASSERT_TRUE(svr.is_valid());
  22717. ASSERT_TRUE(port > 0);
  22718. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22719. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22720. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22721. ASSERT_TRUE(cert != nullptr);
  22722. ASSERT_TRUE(ca_cert != nullptr);
  22723. ASSERT_TRUE(key != nullptr);
  22724. X509_STORE *cert_store = X509_STORE_new();
  22725. X509_STORE_add_cert(cert_store, ca_cert);
  22726. // svr.update_certs(cert, key, cert_store); // deprecated
  22727. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22728. CLIENT_CA_CERT_FILE);
  22729. ASSERT_TRUE(svr.is_valid());
  22730. svr.stop();
  22731. X509_STORE_free(cert_store);
  22732. X509_free(cert);
  22733. X509_free(ca_cert);
  22734. EVP_PKEY_free(key);
  22735. }
  22736. // Test that update_certs() updates client CA list correctly
  22737. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22738. // Start with file-based constructor
  22739. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22740. ASSERT_TRUE(svr.is_valid());
  22741. // Initially no client CA list should be set
  22742. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22743. ASSERT_TRUE(ssl_ctx != nullptr);
  22744. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22745. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22746. // Now update with client CA (PEM string)
  22747. std::string cert_pem, key_pem, ca_pem;
  22748. read_file(SERVER_CERT_FILE, cert_pem);
  22749. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22750. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22751. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22752. ASSERT_TRUE(svr.is_valid());
  22753. // Now client CA list should be set
  22754. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22755. ASSERT_TRUE(ca_list_after != nullptr);
  22756. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22757. }
  22758. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22759. // Test that the file-path SSLServer constructor properly sets the client CA
  22760. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22761. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22762. ASSERT_TRUE(svr.is_valid());
  22763. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22764. ASSERT_TRUE(ssl_ctx != nullptr);
  22765. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22766. ASSERT_TRUE(ca_list != nullptr);
  22767. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22768. }
  22769. #endif
  22770. // ============================================================================
  22771. // MbedTLS-Specific Tests
  22772. // ============================================================================
  22773. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22774. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22775. using namespace httplib::tls;
  22776. // Track if callback was invoked
  22777. bool callback_invoked = false;
  22778. // The callback receives void* ctx which is actually MbedTlsContext*
  22779. // We can access the mbedtls_ssl_config via the context
  22780. auto setup_callback = [&callback_invoked](void *ctx) {
  22781. callback_invoked = true;
  22782. // Cast to MbedTlsContext* to access the ssl config
  22783. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22784. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22785. // Use static variables to hold certificate data (simplified for test)
  22786. static mbedtls_x509_crt own_cert;
  22787. static mbedtls_pk_context own_key;
  22788. static mbedtls_x509_crt ca_chain;
  22789. static bool initialized = false;
  22790. if (!initialized) {
  22791. mbedtls_x509_crt_init(&own_cert);
  22792. mbedtls_pk_init(&own_key);
  22793. mbedtls_x509_crt_init(&ca_chain);
  22794. // Load server certificate
  22795. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22796. return false;
  22797. }
  22798. // Load server private key.
  22799. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22800. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22801. #if MBEDTLS_VERSION_MAJOR == 3
  22802. ,
  22803. mbedtls_ctr_drbg_random, nullptr
  22804. #endif
  22805. ) != 0) {
  22806. return false;
  22807. }
  22808. // Load CA chain for client verification
  22809. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22810. return false;
  22811. }
  22812. initialized = true;
  22813. }
  22814. // Configure the SSL config
  22815. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22816. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22817. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22818. // Set minimum TLS version using mbedTLS native API
  22819. #if MBEDTLS_VERSION_MAJOR >= 3
  22820. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22821. #else
  22822. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22823. MBEDTLS_SSL_MINOR_VERSION_3);
  22824. #endif
  22825. return true;
  22826. };
  22827. SSLServer svr(setup_callback);
  22828. ASSERT_TRUE(svr.is_valid());
  22829. ASSERT_TRUE(callback_invoked);
  22830. svr.Get("/test", [&](const Request &req, Response &res) {
  22831. res.set_content("test", "text/plain");
  22832. auto cert = req.peer_cert();
  22833. ASSERT_TRUE(static_cast<bool>(cert));
  22834. auto common_name = cert.subject_cn();
  22835. EXPECT_EQ("Common Name", common_name);
  22836. });
  22837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22838. auto se = detail::scope_exit([&] {
  22839. svr.stop();
  22840. t.join();
  22841. ASSERT_FALSE(svr.is_running());
  22842. });
  22843. svr.wait_until_ready();
  22844. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22845. cli.enable_server_certificate_verification(false);
  22846. cli.set_connection_timeout(30);
  22847. auto res = cli.Get("/test");
  22848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22849. ASSERT_EQ(StatusCode::OK_200, res->status);
  22850. }
  22851. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22852. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22853. // keep-alive SSL session, which reads through that config in
  22854. // mbedtls_ssl_close_notify.
  22855. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22856. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22857. ASSERT_TRUE(svr.is_valid());
  22858. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22859. res.set_content("test", "text/plain");
  22860. });
  22861. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22862. auto se = detail::scope_exit([&] {
  22863. svr.stop();
  22864. t.join();
  22865. ASSERT_FALSE(svr.is_running());
  22866. });
  22867. svr.wait_until_ready();
  22868. {
  22869. SSLClient cli(HOST, PORT);
  22870. cli.enable_server_certificate_verification(false);
  22871. cli.set_keep_alive(true);
  22872. auto res = cli.Get("/test");
  22873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22874. ASSERT_EQ(StatusCode::OK_200, res->status);
  22875. // cli is destructed here with the keep-alive SSL session still open.
  22876. }
  22877. }
  22878. #endif
  22879. // WebSocket Tests
  22880. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22881. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22882. // defining the meaning of these bits has been negotiated.
  22883. auto make_frame = [](uint8_t first_byte) {
  22884. std::string frame;
  22885. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22886. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22887. frame += "Hello";
  22888. return frame;
  22889. };
  22890. // RSV1 set (0x40)
  22891. {
  22892. detail::BufferStream strm;
  22893. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22894. ws::Opcode opcode;
  22895. std::string payload;
  22896. bool fin;
  22897. EXPECT_EQ(
  22898. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22899. ws::impl::FrameRead::Fail);
  22900. }
  22901. // RSV2 set (0x20)
  22902. {
  22903. detail::BufferStream strm;
  22904. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22905. ws::Opcode opcode;
  22906. std::string payload;
  22907. bool fin;
  22908. EXPECT_EQ(
  22909. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22910. ws::impl::FrameRead::Fail);
  22911. }
  22912. // RSV3 set (0x10)
  22913. {
  22914. detail::BufferStream strm;
  22915. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22916. ws::Opcode opcode;
  22917. std::string payload;
  22918. bool fin;
  22919. EXPECT_EQ(
  22920. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22921. ws::impl::FrameRead::Fail);
  22922. }
  22923. // No RSV bits set - should succeed
  22924. {
  22925. detail::BufferStream strm;
  22926. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22927. ws::Opcode opcode;
  22928. std::string payload;
  22929. bool fin;
  22930. EXPECT_EQ(
  22931. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22932. ws::impl::FrameRead::Ok);
  22933. EXPECT_EQ(ws::Opcode::Text, opcode);
  22934. EXPECT_EQ("Hello", payload);
  22935. EXPECT_TRUE(fin);
  22936. }
  22937. }
  22938. TEST(WebSocketTest, ControlFrameValidation) {
  22939. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22940. // payload length <= 125.
  22941. // Ping with FIN=0 - must be rejected
  22942. {
  22943. detail::BufferStream strm;
  22944. std::string frame;
  22945. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22946. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22947. strm.write(frame.data(), frame.size());
  22948. ws::Opcode opcode;
  22949. std::string payload;
  22950. bool fin;
  22951. EXPECT_EQ(
  22952. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22953. ws::impl::FrameRead::Fail);
  22954. }
  22955. // Close with FIN=0 - must be rejected
  22956. {
  22957. detail::BufferStream strm;
  22958. std::string frame;
  22959. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22960. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22961. strm.write(frame.data(), frame.size());
  22962. ws::Opcode opcode;
  22963. std::string payload;
  22964. bool fin;
  22965. EXPECT_EQ(
  22966. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22967. ws::impl::FrameRead::Fail);
  22968. }
  22969. // Ping with payload_len=126 (extended length) - must be rejected
  22970. {
  22971. detail::BufferStream strm;
  22972. std::string frame;
  22973. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22974. frame += static_cast<char>(126); // payload_len=126 (>125)
  22975. frame += static_cast<char>(0x00); // extended length high byte
  22976. frame += static_cast<char>(126); // extended length low byte
  22977. frame += std::string(126, 'x');
  22978. strm.write(frame.data(), frame.size());
  22979. ws::Opcode opcode;
  22980. std::string payload;
  22981. bool fin;
  22982. EXPECT_EQ(
  22983. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22984. ws::impl::FrameRead::Fail);
  22985. }
  22986. // Ping with FIN=1 and payload_len=125 - should succeed
  22987. {
  22988. detail::BufferStream strm;
  22989. std::string frame;
  22990. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22991. frame += static_cast<char>(125); // payload_len=125
  22992. frame += std::string(125, 'x');
  22993. strm.write(frame.data(), frame.size());
  22994. ws::Opcode opcode;
  22995. std::string payload;
  22996. bool fin;
  22997. EXPECT_EQ(
  22998. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22999. ws::impl::FrameRead::Ok);
  23000. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23001. EXPECT_EQ(125u, payload.size());
  23002. EXPECT_TRUE(fin);
  23003. }
  23004. }
  23005. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23006. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23007. // length MUST be 0.
  23008. // MSB set - must be rejected
  23009. {
  23010. detail::BufferStream strm;
  23011. std::string frame;
  23012. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23013. frame += static_cast<char>(127); // 64-bit extended length
  23014. frame += static_cast<char>(0x80); // MSB set (invalid)
  23015. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23016. strm.write(frame.data(), frame.size());
  23017. ws::Opcode opcode;
  23018. std::string payload;
  23019. bool fin;
  23020. EXPECT_EQ(
  23021. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23022. ws::impl::FrameRead::Fail);
  23023. }
  23024. // MSB clear - should pass length parsing (will be rejected by max_len,
  23025. // but that's a different check; use a small length to verify)
  23026. {
  23027. detail::BufferStream strm;
  23028. std::string frame;
  23029. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23030. frame += static_cast<char>(127); // 64-bit extended length
  23031. frame += std::string(7, '\0'); // high bytes = 0
  23032. frame += static_cast<char>(0x03); // length = 3
  23033. frame += "abc";
  23034. strm.write(frame.data(), frame.size());
  23035. ws::Opcode opcode;
  23036. std::string payload;
  23037. bool fin;
  23038. EXPECT_EQ(
  23039. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23040. ws::impl::FrameRead::Ok);
  23041. EXPECT_EQ(ws::Opcode::Text, opcode);
  23042. EXPECT_EQ("abc", payload);
  23043. }
  23044. }
  23045. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23046. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23047. // Valid UTF-8
  23048. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23049. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23050. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23051. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23052. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23053. // Invalid UTF-8
  23054. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23055. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23056. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23057. EXPECT_FALSE(
  23058. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23059. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23060. }
  23061. TEST(WebSocketTest, ConnectAndDisconnect) {
  23062. Server svr;
  23063. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23064. std::string msg;
  23065. while (ws.read(msg)) {}
  23066. });
  23067. auto port = svr.bind_to_any_port(HOST);
  23068. std::thread t([&]() { svr.listen_after_bind(); });
  23069. svr.wait_until_ready();
  23070. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23071. auto res = client.connect();
  23072. ASSERT_TRUE(res);
  23073. EXPECT_EQ(Error::Success, res.error());
  23074. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23075. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23076. EXPECT_TRUE(client.is_open());
  23077. client.close();
  23078. EXPECT_FALSE(client.is_open());
  23079. svr.stop();
  23080. t.join();
  23081. }
  23082. TEST(WebSocketTest, ValidURL) {
  23083. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23084. EXPECT_TRUE(ws1.is_valid());
  23085. ws::WebSocketClient ws2("ws://example.com/path");
  23086. EXPECT_TRUE(ws2.is_valid());
  23087. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23088. EXPECT_TRUE(ws3.is_valid());
  23089. #ifdef CPPHTTPLIB_SSL_ENABLED
  23090. ws::WebSocketClient wss1("wss://example.com/path");
  23091. EXPECT_TRUE(wss1.is_valid());
  23092. ws::WebSocketClient wss2("wss://example.com:443/path");
  23093. EXPECT_TRUE(wss2.is_valid());
  23094. #endif
  23095. }
  23096. TEST(WebSocketTest, InvalidURL) {
  23097. // No scheme
  23098. ws::WebSocketClient ws1("localhost:8080/path");
  23099. EXPECT_FALSE(ws1.is_valid());
  23100. // No path
  23101. ws::WebSocketClient ws2("ws://localhost:8080");
  23102. EXPECT_FALSE(ws2.is_valid());
  23103. // Empty string
  23104. ws::WebSocketClient ws3("");
  23105. EXPECT_FALSE(ws3.is_valid());
  23106. // Missing host
  23107. ws::WebSocketClient ws4("ws://:8080/path");
  23108. EXPECT_FALSE(ws4.is_valid());
  23109. // Port number overflow — should not crash
  23110. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23111. EXPECT_FALSE(ws5.is_valid());
  23112. // Port out of range
  23113. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23114. EXPECT_FALSE(ws6.is_valid());
  23115. }
  23116. TEST(WebSocketTest, UnsupportedScheme) {
  23117. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23118. ws::WebSocketClient ws1("http://localhost:8080/path");
  23119. EXPECT_FALSE(ws1.is_valid());
  23120. ws::WebSocketClient ws2("https://localhost:8080/path");
  23121. EXPECT_FALSE(ws2.is_valid());
  23122. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23123. EXPECT_FALSE(ws3.is_valid());
  23124. #else
  23125. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23126. std::invalid_argument);
  23127. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23128. std::invalid_argument);
  23129. #endif
  23130. }
  23131. TEST(WebSocketTest, ConnectWhenInvalid) {
  23132. ws::WebSocketClient ws("not a valid url");
  23133. EXPECT_FALSE(ws.is_valid());
  23134. auto res = ws.connect();
  23135. EXPECT_FALSE(res);
  23136. EXPECT_EQ(Error::Connection, res.error());
  23137. EXPECT_EQ(-1, res.status());
  23138. }
  23139. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23140. // Grab a port that is free, then close it again so nothing listens there
  23141. Server svr;
  23142. auto port = svr.bind_to_any_port(HOST);
  23143. svr.stop();
  23144. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23145. auto res = client.connect();
  23146. ASSERT_FALSE(res);
  23147. EXPECT_EQ(Error::Connection, res.error());
  23148. EXPECT_EQ(-1, res.status());
  23149. }
  23150. TEST(WebSocketTest, DefaultPort) {
  23151. ws::WebSocketClient ws1("ws://example.com/path");
  23152. EXPECT_TRUE(ws1.is_valid());
  23153. // ws:// defaults to port 80 (verified by successful parse)
  23154. #ifdef CPPHTTPLIB_SSL_ENABLED
  23155. ws::WebSocketClient ws2("wss://example.com/path");
  23156. EXPECT_TRUE(ws2.is_valid());
  23157. // wss:// defaults to port 443 (verified by successful parse)
  23158. #endif
  23159. }
  23160. TEST(WebSocketTest, IPv6LiteralAddress) {
  23161. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23162. EXPECT_TRUE(ws1.is_valid());
  23163. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23164. EXPECT_TRUE(ws2.is_valid());
  23165. }
  23166. TEST(WebSocketTest, ComplexPath) {
  23167. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23168. EXPECT_TRUE(ws1.is_valid());
  23169. ws::WebSocketClient ws2("ws://localhost:8080/");
  23170. EXPECT_TRUE(ws2.is_valid());
  23171. }
  23172. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23173. Server svr;
  23174. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23175. std::string msg;
  23176. while (ws.read(msg)) {}
  23177. });
  23178. auto port = svr.bind_to_any_port(HOST);
  23179. std::thread t([&]() { svr.listen_after_bind(); });
  23180. svr.wait_until_ready();
  23181. auto another_host = "example.com";
  23182. auto wrong_ip = "192.0.2.1";
  23183. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23184. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23185. ASSERT_TRUE(client.connect());
  23186. EXPECT_TRUE(client.is_open());
  23187. client.close();
  23188. svr.stop();
  23189. t.join();
  23190. }
  23191. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23192. Server svr;
  23193. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23194. std::string msg;
  23195. while (ws.read(msg)) {}
  23196. });
  23197. auto port = svr.bind_to_any_port(HOST);
  23198. std::thread t([&]() { svr.listen_after_bind(); });
  23199. svr.wait_until_ready();
  23200. auto wrong_ip = "192.0.2.1";
  23201. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23202. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23203. client.set_connection_timeout(1);
  23204. client.set_read_timeout(1);
  23205. client.set_write_timeout(1);
  23206. EXPECT_FALSE(client.connect());
  23207. EXPECT_FALSE(client.is_open());
  23208. svr.stop();
  23209. t.join();
  23210. }
  23211. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23212. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23213. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23214. // (RFC 6761) is only a map key and the Host header value.
  23215. auto host = "target.invalid";
  23216. Server svr;
  23217. std::string received_host;
  23218. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23219. received_host = req.get_header_value("Host");
  23220. std::string msg;
  23221. while (ws.read(msg)) {}
  23222. });
  23223. auto port = svr.bind_to_any_port(HOST);
  23224. std::thread t([&]() { svr.listen_after_bind(); });
  23225. // ASSERT_* below returns from the test body, which would leave t joinable
  23226. // and make ~thread call std::terminate.
  23227. auto se = detail::scope_exit([&] {
  23228. svr.stop();
  23229. if (t.joinable()) { t.join(); }
  23230. });
  23231. svr.wait_until_ready();
  23232. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23233. std::to_string(port) + "/ws");
  23234. client.set_hostname_addr_map({{host, HOST}});
  23235. ASSERT_TRUE(client.connect());
  23236. EXPECT_TRUE(client.is_open());
  23237. client.close();
  23238. svr.stop();
  23239. t.join();
  23240. // The mapping only redirects the connection; the identity stays host_.
  23241. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23242. }
  23243. class WebSocketIntegrationTest : public ::testing::Test {
  23244. protected:
  23245. void SetUp() override {
  23246. server_ = httplib::detail::make_unique<Server>();
  23247. setup_server();
  23248. start_server();
  23249. }
  23250. void TearDown() override {
  23251. server_->stop();
  23252. if (server_thread_.joinable()) { server_thread_.join(); }
  23253. }
  23254. void setup_server() {
  23255. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23256. std::string msg;
  23257. ws::ReadResult ret;
  23258. while ((ret = ws.read(msg))) {
  23259. if (ret == ws::Binary) {
  23260. ws.send(msg.data(), msg.size());
  23261. } else {
  23262. ws.send(msg);
  23263. }
  23264. }
  23265. });
  23266. server_->WebSocket("/ws-echo-string",
  23267. [](const Request &, ws::WebSocket &ws) {
  23268. std::string msg;
  23269. while (ws.read(msg)) {
  23270. ws.send("echo: " + msg);
  23271. }
  23272. });
  23273. server_->WebSocket(
  23274. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23275. // Echo back request metadata
  23276. ws.send("path:" + req.path);
  23277. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23278. std::string msg;
  23279. while (ws.read(msg)) {}
  23280. });
  23281. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23282. std::string msg;
  23283. ws.read(msg); // wait for a message
  23284. ws.close();
  23285. });
  23286. server_->WebSocket("/ws-close-status",
  23287. [](const Request &, ws::WebSocket &ws) {
  23288. std::string msg;
  23289. ws.read(msg); // wait for a message
  23290. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23291. });
  23292. server_->WebSocket(
  23293. "/ws-subprotocol",
  23294. [](const Request &, ws::WebSocket &ws) {
  23295. std::string msg;
  23296. while (ws.read(msg)) {
  23297. ws.send(msg);
  23298. }
  23299. },
  23300. [](const std::vector<std::string> &protocols) -> std::string {
  23301. for (const auto &p : protocols) {
  23302. if (p == "graphql-ws") { return p; }
  23303. }
  23304. return "";
  23305. });
  23306. server_->WebSocket(
  23307. "/ws-subprotocol-unoffered",
  23308. [](const Request &, ws::WebSocket &ws) {
  23309. std::string msg;
  23310. while (ws.read(msg)) {
  23311. ws.send(msg);
  23312. }
  23313. },
  23314. [](const std::vector<std::string> &) -> std::string {
  23315. return "admin";
  23316. });
  23317. }
  23318. void start_server() {
  23319. port_ = server_->bind_to_any_port(HOST);
  23320. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23321. server_->wait_until_ready();
  23322. }
  23323. std::unique_ptr<Server> server_;
  23324. std::thread server_thread_;
  23325. int port_ = 0;
  23326. };
  23327. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23328. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23329. "/ws-echo");
  23330. ASSERT_TRUE(client.connect());
  23331. ASSERT_TRUE(client.is_open());
  23332. ASSERT_TRUE(client.send("Hello WebSocket"));
  23333. std::string msg;
  23334. EXPECT_EQ(ws::Text, client.read(msg));
  23335. EXPECT_EQ("Hello WebSocket", msg);
  23336. client.close();
  23337. }
  23338. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23339. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23340. "/ws-echo");
  23341. ASSERT_TRUE(client.connect());
  23342. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23343. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23344. std::string msg;
  23345. EXPECT_EQ(ws::Binary, client.read(msg));
  23346. EXPECT_EQ(binary_data, msg);
  23347. client.close();
  23348. }
  23349. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23350. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23351. "/ws-echo");
  23352. ASSERT_TRUE(client.connect());
  23353. for (int i = 0; i < 10; i++) {
  23354. auto text = "message " + std::to_string(i);
  23355. ASSERT_TRUE(client.send(text));
  23356. std::string msg;
  23357. ASSERT_TRUE(client.read(msg));
  23358. EXPECT_EQ(text, msg);
  23359. }
  23360. client.close();
  23361. }
  23362. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23363. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23364. "/ws-close");
  23365. ASSERT_TRUE(client.connect());
  23366. // Send a message to trigger the server to close
  23367. ASSERT_TRUE(client.send("trigger close"));
  23368. // The server will close, so read should return false
  23369. std::string msg;
  23370. EXPECT_FALSE(client.read(msg));
  23371. EXPECT_FALSE(client.is_open());
  23372. }
  23373. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23374. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23375. "/ws-echo");
  23376. ASSERT_TRUE(client.connect());
  23377. // 128KB message
  23378. std::string large_data(128 * 1024, 'X');
  23379. ASSERT_TRUE(client.send(large_data));
  23380. std::string msg;
  23381. ASSERT_TRUE(client.read(msg));
  23382. EXPECT_EQ(large_data, msg);
  23383. client.close();
  23384. }
  23385. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23386. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23387. "/ws-echo");
  23388. ASSERT_TRUE(client.connect());
  23389. const int num_threads = 4;
  23390. std::vector<std::thread> threads;
  23391. std::atomic<int> send_count{0};
  23392. for (int t = 0; t < num_threads; t++) {
  23393. threads.emplace_back([&client, &send_count, t]() {
  23394. for (int i = 0; i < 5; i++) {
  23395. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23396. if (client.send(text)) { send_count++; }
  23397. }
  23398. });
  23399. }
  23400. for (auto &th : threads) {
  23401. th.join();
  23402. }
  23403. int received = 0;
  23404. std::string msg;
  23405. while (received < send_count.load()) {
  23406. if (!client.read(msg)) { break; }
  23407. received++;
  23408. }
  23409. EXPECT_EQ(send_count.load(), received);
  23410. client.close();
  23411. }
  23412. TEST_F(WebSocketIntegrationTest, ReadString) {
  23413. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23414. "/ws-echo-string");
  23415. ASSERT_TRUE(client.connect());
  23416. ASSERT_TRUE(client.send("hello"));
  23417. std::string msg;
  23418. ASSERT_TRUE(client.read(msg));
  23419. EXPECT_EQ("echo: hello", msg);
  23420. ASSERT_TRUE(client.send("world"));
  23421. ASSERT_TRUE(client.read(msg));
  23422. EXPECT_EQ("echo: world", msg);
  23423. client.close();
  23424. }
  23425. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23426. Headers headers = {{"X-Test-Header", "test-value"}};
  23427. ws::WebSocketClient client(
  23428. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23429. ASSERT_TRUE(client.connect());
  23430. std::string msg;
  23431. ASSERT_TRUE(client.read(msg));
  23432. EXPECT_EQ("path:/ws-request-info", msg);
  23433. ASSERT_TRUE(client.read(msg));
  23434. EXPECT_EQ("header:test-value", msg);
  23435. client.close();
  23436. }
  23437. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23438. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23439. "/ws-echo");
  23440. client.set_read_timeout(1, 0); // 1 second
  23441. ASSERT_TRUE(client.connect());
  23442. // Don't send anything — server echo handler waits for a message, so read()
  23443. // should time out. The connection survives it: nothing was consumed.
  23444. std::string msg;
  23445. EXPECT_EQ(client.read(msg), ws::Timeout);
  23446. EXPECT_TRUE(client.is_open());
  23447. // And it is still usable afterwards.
  23448. EXPECT_TRUE(client.send("after timeout"));
  23449. EXPECT_EQ(client.read(msg), ws::Text);
  23450. EXPECT_EQ(msg, "after timeout");
  23451. }
  23452. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23453. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23454. "/ws-echo");
  23455. client.set_read_timeout(1, 0);
  23456. ASSERT_TRUE(client.connect());
  23457. ASSERT_TRUE(client.send("first"));
  23458. std::string msg;
  23459. ASSERT_EQ(client.read(msg), ws::Text);
  23460. ASSERT_EQ(msg, "first");
  23461. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23462. // not be used with a read timeout: it would reprocess the previous message.
  23463. EXPECT_EQ(client.read(msg), ws::Timeout);
  23464. EXPECT_EQ(msg, "first");
  23465. }
  23466. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23467. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23468. "/ws-echo");
  23469. ASSERT_TRUE(client.connect());
  23470. // Setting it once the connection is open reaches the live stream, not just
  23471. // the seed for the next connect().
  23472. client.set_read_timeout(1, 0);
  23473. std::string msg;
  23474. EXPECT_EQ(client.read(msg), ws::Timeout);
  23475. EXPECT_TRUE(client.is_open());
  23476. }
  23477. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23478. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23479. "/ws-echo");
  23480. client.set_read_timeout(5, 0);
  23481. ASSERT_TRUE(client.connect());
  23482. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23483. // The server should reject it and close the connection.
  23484. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23485. client.send(oversized);
  23486. // The server's read() should have failed due to payload limit,
  23487. // so our read() should return false (connection closed).
  23488. std::string msg;
  23489. EXPECT_FALSE(client.read(msg));
  23490. }
  23491. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23492. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23493. "/ws-echo");
  23494. client.set_read_timeout(10, 0);
  23495. ASSERT_TRUE(client.connect());
  23496. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23497. // This should succeed.
  23498. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23499. ASSERT_TRUE(client.send(at_limit));
  23500. std::string msg;
  23501. ASSERT_TRUE(client.read(msg));
  23502. EXPECT_EQ(at_limit.size(), msg.size());
  23503. client.close();
  23504. }
  23505. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23506. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23507. "/nonexistent");
  23508. auto res = client.connect();
  23509. EXPECT_FALSE(res);
  23510. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23511. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23512. EXPECT_FALSE(client.is_open());
  23513. }
  23514. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23515. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23516. "/ws-echo");
  23517. ASSERT_TRUE(client.connect());
  23518. ASSERT_TRUE(client.send(""));
  23519. std::string msg;
  23520. EXPECT_EQ(ws::Text, client.read(msg));
  23521. EXPECT_EQ("", msg);
  23522. client.close();
  23523. }
  23524. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23525. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23526. "/ws-echo");
  23527. // First connection
  23528. ASSERT_TRUE(client.connect());
  23529. ASSERT_TRUE(client.send("first"));
  23530. std::string msg;
  23531. ASSERT_TRUE(client.read(msg));
  23532. EXPECT_EQ("first", msg);
  23533. client.close();
  23534. EXPECT_FALSE(client.is_open());
  23535. // Reconnect using the same client object
  23536. ASSERT_TRUE(client.connect());
  23537. ASSERT_TRUE(client.is_open());
  23538. ASSERT_TRUE(client.send("second"));
  23539. ASSERT_TRUE(client.read(msg));
  23540. EXPECT_EQ("second", msg);
  23541. client.close();
  23542. }
  23543. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23544. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23545. "/ws-close-status");
  23546. ASSERT_TRUE(client.connect());
  23547. // Trigger the server to close with GoingAway status
  23548. ASSERT_TRUE(client.send("trigger"));
  23549. // read() should return false after receiving the close frame
  23550. std::string msg;
  23551. EXPECT_FALSE(client.read(msg));
  23552. EXPECT_FALSE(client.is_open());
  23553. }
  23554. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23555. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23556. "/ws-echo");
  23557. ASSERT_TRUE(client.connect());
  23558. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23559. EXPECT_FALSE(client.is_open());
  23560. }
  23561. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23562. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23563. ws::WebSocketClient client(
  23564. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23565. ASSERT_TRUE(client.connect());
  23566. // Server should have selected graphql-ws
  23567. EXPECT_EQ("graphql-ws", client.subprotocol());
  23568. client.close();
  23569. }
  23570. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23571. Headers headers;
  23572. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23573. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23574. ws::WebSocketClient client(
  23575. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23576. ASSERT_TRUE(client.connect());
  23577. // The offer on the second field line counts too, so graphql-ws is selected
  23578. EXPECT_EQ("graphql-ws", client.subprotocol());
  23579. client.close();
  23580. }
  23581. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23582. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23583. ws::WebSocketClient client(
  23584. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23585. ASSERT_TRUE(client.connect());
  23586. // Server should not have selected any subprotocol
  23587. EXPECT_TRUE(client.subprotocol().empty());
  23588. client.close();
  23589. }
  23590. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23591. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23592. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23593. "/ws-subprotocol-unoffered",
  23594. headers);
  23595. ASSERT_TRUE(client.connect());
  23596. EXPECT_TRUE(client.subprotocol().empty());
  23597. client.close();
  23598. }
  23599. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23600. // Connect without requesting any subprotocol
  23601. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23602. "/ws-subprotocol");
  23603. ASSERT_TRUE(client.connect());
  23604. EXPECT_TRUE(client.subprotocol().empty());
  23605. client.close();
  23606. }
  23607. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23608. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23609. "/ws-echo");
  23610. client.set_tcp_nodelay(true);
  23611. client.set_connection_timeout(3, 0);
  23612. bool socket_options_called = false;
  23613. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23614. ASSERT_TRUE(client.connect());
  23615. ASSERT_TRUE(client.is_open());
  23616. EXPECT_TRUE(socket_options_called);
  23617. ASSERT_TRUE(client.send("hello"));
  23618. std::string msg;
  23619. auto result = client.read(msg);
  23620. EXPECT_EQ(result, ws::ReadResult::Text);
  23621. EXPECT_EQ(msg, "hello");
  23622. client.close();
  23623. }
  23624. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23625. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23626. "/ws-echo");
  23627. client.set_connection_timeout(std::chrono::seconds(3));
  23628. client.set_write_timeout(std::chrono::seconds(3));
  23629. // A sub-second remainder exercises the seconds/microseconds split.
  23630. client.set_read_timeout(std::chrono::milliseconds(1500));
  23631. ASSERT_TRUE(client.connect());
  23632. auto start = std::chrono::steady_clock::now();
  23633. std::string msg;
  23634. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23635. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23636. std::chrono::steady_clock::now() - start)
  23637. .count();
  23638. // Above 1s so that dropping the microseconds half of the split fails here.
  23639. // Ignoring the setter altogether would not reach this line at all: a client
  23640. // waits forever by default.
  23641. EXPECT_GE(elapsed, 1400);
  23642. EXPECT_LT(elapsed, 30000);
  23643. }
  23644. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23645. Server svr;
  23646. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23647. if (!req.has_header("Authorization")) {
  23648. res.status = StatusCode::Unauthorized_401;
  23649. res.set_content("Unauthorized", "text/plain");
  23650. return Server::HandlerResponse::Handled;
  23651. }
  23652. return Server::HandlerResponse::Unhandled;
  23653. });
  23654. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23655. std::string msg;
  23656. while (ws.read(msg)) {
  23657. ws.send(msg);
  23658. }
  23659. });
  23660. auto port = svr.bind_to_any_port("localhost");
  23661. std::thread t([&]() { svr.listen_after_bind(); });
  23662. svr.wait_until_ready();
  23663. // Without Authorization header - should be rejected before upgrade
  23664. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23665. EXPECT_FALSE(client1.connect());
  23666. // The rejection is framed like any other HTTP response
  23667. {
  23668. Client cli("localhost", port);
  23669. Headers headers = {{"Upgrade", "websocket"},
  23670. {"Connection", "Upgrade"},
  23671. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23672. {"Sec-WebSocket-Version", "13"}};
  23673. auto res = cli.Get("/ws", headers);
  23674. ASSERT_TRUE(res);
  23675. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23676. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23677. EXPECT_EQ("Unauthorized", res->body);
  23678. }
  23679. // With Authorization header - should succeed
  23680. Headers headers = {{"Authorization", "Bearer token123"}};
  23681. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23682. headers);
  23683. ASSERT_TRUE(client2.connect());
  23684. ASSERT_TRUE(client2.send("hello"));
  23685. std::string msg;
  23686. ASSERT_TRUE(client2.read(msg));
  23687. EXPECT_EQ("hello", msg);
  23688. client2.close();
  23689. svr.stop();
  23690. t.join();
  23691. }
  23692. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23693. Server svr;
  23694. std::atomic<int> pre_routing_calls{0};
  23695. std::atomic<int> pre_request_calls{0};
  23696. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23697. pre_routing_calls++;
  23698. if (req.path == "/handled") {
  23699. res.set_content("handled", "text/plain");
  23700. return Server::HandlerResponse::Handled;
  23701. }
  23702. return Server::HandlerResponse::Unhandled;
  23703. });
  23704. svr.set_pre_request_handler([&](const Request &, Response &) {
  23705. pre_request_calls++;
  23706. return Server::HandlerResponse::Unhandled;
  23707. });
  23708. svr.Get("/http", [](const Request &, Response &res) {
  23709. res.set_content("http", "text/plain");
  23710. });
  23711. svr.WebSocket("/ws",
  23712. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23713. auto port = svr.bind_to_any_port("localhost");
  23714. std::thread t([&]() { svr.listen_after_bind(); });
  23715. auto se = detail::scope_exit([&] {
  23716. svr.stop();
  23717. t.join();
  23718. });
  23719. svr.wait_until_ready();
  23720. Headers upgrade = {{"Upgrade", "websocket"},
  23721. {"Connection", "Upgrade"},
  23722. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23723. {"Sec-WebSocket-Version", "13"}};
  23724. auto get = [&](const char *path) {
  23725. pre_routing_calls = 0;
  23726. return Client("localhost", port).Get(path, upgrade);
  23727. };
  23728. // No WebSocket route, but an HTTP one
  23729. auto res = get("/http");
  23730. ASSERT_TRUE(res);
  23731. EXPECT_EQ(StatusCode::OK_200, res->status);
  23732. EXPECT_EQ("http", res->body);
  23733. EXPECT_EQ(1, pre_routing_calls);
  23734. EXPECT_EQ(1, pre_request_calls);
  23735. // No route at all
  23736. res = get("/none");
  23737. ASSERT_TRUE(res);
  23738. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23739. EXPECT_EQ(1, pre_routing_calls);
  23740. // Answered by the pre-routing handler
  23741. res = get("/handled");
  23742. ASSERT_TRUE(res);
  23743. EXPECT_EQ(StatusCode::OK_200, res->status);
  23744. EXPECT_EQ("handled", res->body);
  23745. EXPECT_EQ(1, pre_routing_calls);
  23746. // A WebSocket route
  23747. pre_routing_calls = 0;
  23748. pre_request_calls = 0;
  23749. {
  23750. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23751. "/ws");
  23752. ASSERT_TRUE(client.connect());
  23753. std::string msg;
  23754. ASSERT_TRUE(client.read(msg));
  23755. EXPECT_EQ("ws", msg);
  23756. client.close();
  23757. }
  23758. EXPECT_EQ(1, pre_routing_calls);
  23759. EXPECT_EQ(1, pre_request_calls);
  23760. }
  23761. // An upgrade request answered by a hook leaves its body unread, so that body
  23762. // must not be served as the next request on the connection.
  23763. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23764. Server svr;
  23765. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23766. if (req.path == "/pre-routing") {
  23767. res.set_content("pre-routing", "text/plain");
  23768. return Server::HandlerResponse::Handled;
  23769. }
  23770. return Server::HandlerResponse::Unhandled;
  23771. });
  23772. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23773. if (req.matched_route == "/pre-request") {
  23774. res.set_content("pre-request", "text/plain");
  23775. return Server::HandlerResponse::Handled;
  23776. }
  23777. return Server::HandlerResponse::Unhandled;
  23778. });
  23779. svr.Get("/smuggled", [](const Request &, Response &res) {
  23780. res.set_content("smuggled", "text/plain");
  23781. });
  23782. svr.WebSocket("/pre-request",
  23783. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23784. auto port = svr.bind_to_any_port(HOST);
  23785. std::thread t([&]() { svr.listen_after_bind(); });
  23786. auto se = detail::scope_exit([&] {
  23787. svr.stop();
  23788. t.join();
  23789. });
  23790. svr.wait_until_ready();
  23791. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23792. for (auto path : {"/pre-routing", "/pre-request"}) {
  23793. std::string req = std::string("GET ") + path +
  23794. " HTTP/1.1\r\n"
  23795. "Host: localhost\r\n"
  23796. "Upgrade: websocket\r\n"
  23797. "Connection: Upgrade\r\n"
  23798. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23799. "Sec-WebSocket-Version: 13\r\n"
  23800. "Content-Length: " +
  23801. std::to_string(body.size()) + "\r\n\r\n" + body;
  23802. std::string res;
  23803. ASSERT_TRUE(send_request(5, req, &res, port));
  23804. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23805. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23806. // Only one response, and the body was not served as a request
  23807. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23808. }
  23809. }
  23810. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23811. Server svr;
  23812. std::atomic<int> pre_request_calls{0};
  23813. std::atomic<bool> route_matched{false};
  23814. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23815. pre_request_calls++;
  23816. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23817. if (req.get_header_value("Authorization") != "Bearer token123") {
  23818. res.status = StatusCode::Unauthorized_401;
  23819. res.set_content("Unauthorized", "text/plain");
  23820. return Server::HandlerResponse::Handled;
  23821. }
  23822. return Server::HandlerResponse::Unhandled;
  23823. });
  23824. std::atomic<bool> handler_called{false};
  23825. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23826. handler_called = true;
  23827. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23828. });
  23829. auto port = svr.bind_to_any_port("localhost");
  23830. std::thread t([&]() { svr.listen_after_bind(); });
  23831. svr.wait_until_ready();
  23832. // Without Authorization header - should be rejected before upgrade
  23833. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23834. "/ws/1");
  23835. EXPECT_FALSE(client1.connect());
  23836. EXPECT_FALSE(handler_called);
  23837. EXPECT_EQ(1, pre_request_calls);
  23838. EXPECT_TRUE(route_matched);
  23839. // The rejection is an ordinary HTTP response, not a protocol switch
  23840. {
  23841. Client cli("localhost", port);
  23842. Headers headers = {{"Upgrade", "websocket"},
  23843. {"Connection", "Upgrade"},
  23844. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23845. {"Sec-WebSocket-Version", "13"}};
  23846. auto res = cli.Get("/ws/1", headers);
  23847. ASSERT_TRUE(res);
  23848. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23849. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23850. EXPECT_EQ("Unauthorized", res->body);
  23851. }
  23852. EXPECT_FALSE(handler_called);
  23853. // With Authorization header - should succeed
  23854. Headers headers = {{"Authorization", "Bearer token123"}};
  23855. ws::WebSocketClient client2(
  23856. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23857. ASSERT_TRUE(client2.connect());
  23858. std::string msg;
  23859. ASSERT_TRUE(client2.read(msg));
  23860. EXPECT_EQ("/ws/:id 2", msg);
  23861. EXPECT_TRUE(handler_called);
  23862. client2.close();
  23863. svr.stop();
  23864. t.join();
  23865. }
  23866. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  23867. static Headers websocket_upgrade_headers() {
  23868. return {{"Upgrade", "websocket"},
  23869. {"Connection", "Upgrade"},
  23870. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23871. {"Sec-WebSocket-Version", "13"},
  23872. {"Sec-WebSocket-Protocol", "chat"}};
  23873. }
  23874. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  23875. Server svr;
  23876. svr.set_pre_routing_handler([](const Request &req, Response &) {
  23877. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  23878. return Server::HandlerResponse::Unhandled;
  23879. });
  23880. svr.set_pre_request_handler([](const Request &req, Response &) {
  23881. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  23882. return Server::HandlerResponse::Unhandled;
  23883. });
  23884. svr.set_exception_handler(
  23885. [](const Request &, Response &res, std::exception_ptr ep) {
  23886. try {
  23887. std::rethrow_exception(ep);
  23888. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  23889. });
  23890. auto handler = [](const Request &, ws::WebSocket &) {};
  23891. svr.WebSocket("/pre-routing", handler);
  23892. svr.WebSocket("/pre-request", handler);
  23893. svr.WebSocket("/sub-protocol", handler,
  23894. [](const std::vector<std::string> &) -> std::string {
  23895. throw std::runtime_error("/sub-protocol");
  23896. });
  23897. auto port = svr.bind_to_any_port(HOST);
  23898. ASSERT_GT(port, 0);
  23899. thread t = thread([&] { svr.listen_after_bind(); });
  23900. auto se = detail::scope_exit([&] {
  23901. svr.stop();
  23902. t.join();
  23903. ASSERT_FALSE(svr.is_running());
  23904. });
  23905. svr.wait_until_ready();
  23906. Client cli(HOST, port);
  23907. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  23908. auto res = cli.Get(path, websocket_upgrade_headers());
  23909. if (!res) {
  23910. ADD_FAILURE() << path << ": " << to_string(res.error());
  23911. continue;
  23912. }
  23913. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  23914. EXPECT_EQ(path, res->body);
  23915. }
  23916. }
  23917. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  23918. Server svr;
  23919. svr.set_pre_routing_handler(
  23920. [](const Request &, Response &) -> Server::HandlerResponse {
  23921. throw std::runtime_error("pre-routing");
  23922. });
  23923. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23924. auto port = svr.bind_to_any_port(HOST);
  23925. ASSERT_GT(port, 0);
  23926. thread t = thread([&] { svr.listen_after_bind(); });
  23927. auto se = detail::scope_exit([&] {
  23928. svr.stop();
  23929. t.join();
  23930. ASSERT_FALSE(svr.is_running());
  23931. });
  23932. svr.wait_until_ready();
  23933. Client cli(HOST, port);
  23934. auto res = cli.Get("/ws", websocket_upgrade_headers());
  23935. ASSERT_TRUE(res) << to_string(res.error());
  23936. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  23937. }
  23938. #endif
  23939. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23940. Server svr;
  23941. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23942. // A read timeout is how a handler gets control back. Without it, a handler
  23943. // parked in read() can never write on the connection it is reading.
  23944. ws.set_read_timeout(std::chrono::milliseconds(100));
  23945. std::string msg;
  23946. while (ws.is_open()) {
  23947. auto r = ws.read(msg);
  23948. if (r == httplib::ws::Timeout) {
  23949. ws.send("tick");
  23950. continue;
  23951. }
  23952. if (r == httplib::ws::Fail) { break; }
  23953. ws.send(msg);
  23954. }
  23955. });
  23956. auto port = svr.bind_to_any_port("localhost");
  23957. std::thread t([&]() { svr.listen_after_bind(); });
  23958. svr.wait_until_ready();
  23959. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23960. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23961. ASSERT_TRUE(client.connect());
  23962. // The client sends nothing, so anything it receives came out of the
  23963. // handler's timeout path.
  23964. std::string msg;
  23965. ASSERT_EQ(client.read(msg), ws::Text);
  23966. EXPECT_EQ("tick", msg);
  23967. client.close();
  23968. svr.stop();
  23969. t.join();
  23970. }
  23971. // Stream::read may return fewer bytes than asked for. This is that contract at
  23972. // its worst -- one byte per call -- which is what a frame header straddling a
  23973. // read buffer's boundary looks like to the frame parser.
  23974. class WsByteAtATimeStream : public Stream {
  23975. public:
  23976. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23977. bool is_readable() const override { return true; }
  23978. bool wait_readable() const override { return true; }
  23979. bool wait_writable() const override { return true; }
  23980. ssize_t read(char *ptr, size_t size) override {
  23981. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23982. *ptr = data_[pos_++];
  23983. return 1;
  23984. }
  23985. ssize_t write(const char *, size_t size) override {
  23986. return static_cast<ssize_t>(size);
  23987. }
  23988. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23989. ip = "127.0.0.1";
  23990. port = 0;
  23991. }
  23992. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23993. ip = "127.0.0.1";
  23994. port = 0;
  23995. }
  23996. socket_t socket() const override { return INVALID_SOCKET; }
  23997. time_t duration() const override { return 0; }
  23998. private:
  23999. std::string data_;
  24000. size_t pos_ = 0;
  24001. };
  24002. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24003. // The payload uses the 16-bit extended length, so the header, the length
  24004. // and the mask key are all multi-byte fields here. Each used to be read
  24005. // with a single read() call, which fails as soon as one is split. The
  24006. // payload is also a little over one read chunk, so it is read in two.
  24007. std::string body;
  24008. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24009. body += static_cast<char>(i % 251);
  24010. }
  24011. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24012. std::string frame;
  24013. frame += static_cast<char>(0x81); // FIN + Text
  24014. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24015. frame += static_cast<char>(body.size() >> 8);
  24016. frame += static_cast<char>(body.size() & 0xff);
  24017. for (size_t i = 0; i < 4; i++) {
  24018. frame += static_cast<char>(mask[i]);
  24019. }
  24020. for (size_t i = 0; i < body.size(); i++) {
  24021. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24022. }
  24023. WsByteAtATimeStream strm(frame);
  24024. ws::Opcode opcode;
  24025. std::string payload;
  24026. bool fin = false;
  24027. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24028. /*expect_masked=*/true, body.size()),
  24029. ws::impl::FrameRead::Ok);
  24030. EXPECT_TRUE(fin);
  24031. EXPECT_EQ(opcode, ws::Opcode::Text);
  24032. EXPECT_EQ(payload, body);
  24033. }
  24034. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24035. std::string body(2000, 'x');
  24036. std::string frame;
  24037. frame += static_cast<char>(0x82); // FIN + Binary
  24038. frame += static_cast<char>(126); // 16-bit length follows
  24039. frame += static_cast<char>(body.size() >> 8);
  24040. frame += static_cast<char>(body.size() & 0xff);
  24041. frame += body;
  24042. detail::BufferStream strm;
  24043. strm.write(frame.data(), frame.size());
  24044. ws::Opcode opcode;
  24045. std::string payload;
  24046. bool fin;
  24047. EXPECT_EQ(
  24048. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24049. ws::impl::FrameRead::Ok);
  24050. EXPECT_EQ(body, payload);
  24051. }
  24052. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24053. // The header announces the largest payload allowed, and only 3 bytes of it
  24054. // ever arrive.
  24055. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24056. std::string frame;
  24057. frame += static_cast<char>(0x82); // FIN + Binary
  24058. frame += static_cast<char>(127); // 64-bit length follows
  24059. for (int shift = 56; shift >= 0; shift -= 8) {
  24060. frame += static_cast<char>((len >> shift) & 0xff);
  24061. }
  24062. frame += "abc";
  24063. detail::BufferStream strm;
  24064. strm.write(frame.data(), frame.size());
  24065. ws::Opcode opcode;
  24066. std::string payload;
  24067. bool fin;
  24068. EXPECT_EQ(
  24069. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24070. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24071. ws::impl::FrameRead::Fail);
  24072. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24073. }
  24074. TEST(WebSocketTest, QueryStringInHandshake) {
  24075. Server svr;
  24076. std::mutex mtx;
  24077. std::string received_target;
  24078. std::string received_token;
  24079. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24080. {
  24081. std::lock_guard<std::mutex> lock(mtx);
  24082. received_target = req.target;
  24083. if (req.has_param("token")) {
  24084. received_token = req.get_param_value("token");
  24085. }
  24086. }
  24087. std::string msg;
  24088. while (ws.read(msg)) {
  24089. ws.send(msg);
  24090. }
  24091. });
  24092. auto port = svr.bind_to_any_port("localhost");
  24093. std::thread t([&]() { svr.listen_after_bind(); });
  24094. svr.wait_until_ready();
  24095. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24096. "/ws?token=ABC&session=123");
  24097. ASSERT_TRUE(client.connect());
  24098. // Round-trip ensures the handler has run and captured the request.
  24099. ASSERT_TRUE(client.send("hello"));
  24100. std::string msg;
  24101. ASSERT_TRUE(client.read(msg));
  24102. EXPECT_EQ("hello", msg);
  24103. client.close();
  24104. {
  24105. std::lock_guard<std::mutex> lock(mtx);
  24106. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24107. EXPECT_EQ("ABC", received_token);
  24108. }
  24109. svr.stop();
  24110. t.join();
  24111. }
  24112. // Run a handshake against a throwaway server and hand the request the server
  24113. // received back to the caller, so tests can assert on the headers the client
  24114. // actually put on the wire.
  24115. static void capture_websocket_handshake_request(
  24116. const Headers &client_headers,
  24117. std::function<void(const Request &, int port)> verify) {
  24118. Server svr;
  24119. std::mutex mtx;
  24120. Request received;
  24121. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24122. {
  24123. std::lock_guard<std::mutex> lock(mtx);
  24124. received = req;
  24125. }
  24126. std::string msg;
  24127. while (ws.read(msg)) {
  24128. ws.send(msg);
  24129. }
  24130. });
  24131. auto port = svr.bind_to_any_port("localhost");
  24132. std::thread t([&]() { svr.listen_after_bind(); });
  24133. auto se = detail::scope_exit([&] {
  24134. svr.stop();
  24135. t.join();
  24136. });
  24137. svr.wait_until_ready();
  24138. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24139. client_headers);
  24140. ASSERT_TRUE(client.connect());
  24141. ASSERT_TRUE(client.send("hello"));
  24142. std::string msg;
  24143. ASSERT_TRUE(client.read(msg));
  24144. client.close();
  24145. {
  24146. std::lock_guard<std::mutex> lock(mtx);
  24147. verify(received, port);
  24148. }
  24149. }
  24150. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24151. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24152. // Non-default port must be present in the Host header. Default ports
  24153. // (80/443) are omitted; that logic is covered by
  24154. // MakeHostAndPortStringTest.
  24155. EXPECT_EQ("localhost:" + std::to_string(port),
  24156. req.get_header_value("Host"));
  24157. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24158. req.get_header_value("User-Agent"));
  24159. EXPECT_FALSE(req.has_header("Accept"));
  24160. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24161. EXPECT_FALSE(req.has_header("Content-Length"));
  24162. });
  24163. }
  24164. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24165. capture_websocket_handshake_request(
  24166. {{"Host", "example.com"},
  24167. {"User-Agent", "custom-agent"},
  24168. {"X-Custom", "value"}},
  24169. [](const Request &req, int) {
  24170. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24171. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24172. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24173. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24174. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24175. });
  24176. }
  24177. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24178. capture_websocket_handshake_request(
  24179. {{"Upgrade", "bogus"},
  24180. {"Connection", "close"},
  24181. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24182. {"Sec-WebSocket-Version", "8"}},
  24183. [](const Request &req, int) {
  24184. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24185. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24186. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24187. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24188. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24189. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24190. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24191. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24192. req.get_header_value("Sec-WebSocket-Key"));
  24193. });
  24194. }
  24195. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24196. // A header the client refuses to send must abort the handshake before any
  24197. // part of it reaches the wire; a lone request line would otherwise sit in
  24198. // the peer's buffer as a truncated request.
  24199. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24200. ASSERT_NE(INVALID_SOCKET, srv);
  24201. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24202. sockaddr_in addr{};
  24203. addr.sin_family = AF_INET;
  24204. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24205. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24206. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24207. ASSERT_EQ(0, ::listen(srv, 1));
  24208. sockaddr_in bound{};
  24209. socklen_t bound_len = sizeof(bound);
  24210. ASSERT_EQ(
  24211. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24212. auto port = ntohs(bound.sin_port);
  24213. ssize_t received = -1;
  24214. std::thread t([&] {
  24215. // Bound every blocking call so a regression fails the test with a bad
  24216. // value instead of hanging the suite.
  24217. fd_set rfds;
  24218. FD_ZERO(&rfds);
  24219. FD_SET(srv, &rfds);
  24220. timeval tv{5, 0};
  24221. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24222. 0) {
  24223. return;
  24224. }
  24225. sockaddr_in cli_addr{};
  24226. socklen_t cli_len = sizeof(cli_addr);
  24227. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24228. if (cli == INVALID_SOCKET) { return; }
  24229. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24230. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24231. char buf[4096];
  24232. received = ::recv(cli, buf, sizeof(buf), 0);
  24233. });
  24234. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24235. // connect() has already shut the socket down by the time it returns false,
  24236. // so the peer sees EOF without waiting for the client to be destroyed.
  24237. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24238. {{"X-Bad", "a\r\nInjected: 1"}});
  24239. EXPECT_FALSE(client.connect());
  24240. t.join();
  24241. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24242. EXPECT_EQ(0, received);
  24243. }
  24244. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24245. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24246. // contains "upgrade" as a substring is a different token and must not
  24247. // start a WebSocket handshake.
  24248. auto make_request = [](const std::vector<std::string> &connection_values) {
  24249. Request req;
  24250. req.method = "GET";
  24251. req.headers.emplace("Upgrade", "websocket");
  24252. for (const auto &value : connection_values) {
  24253. req.headers.emplace("Connection", value);
  24254. }
  24255. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24256. req.headers.emplace("Sec-WebSocket-Version", "13");
  24257. return req;
  24258. };
  24259. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24260. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24261. EXPECT_TRUE(
  24262. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24263. EXPECT_TRUE(
  24264. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24265. EXPECT_TRUE(
  24266. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24267. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24268. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24269. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24270. EXPECT_FALSE(
  24271. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24272. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24273. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24274. }
  24275. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24276. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24277. // asks recipients to match each protocol-name case-insensitively, and RFC
  24278. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24279. // client naming websocket alongside another protocol, or on a second field
  24280. // line, is offering websocket; a value that merely contains "websocket" as a
  24281. // substring is a different protocol name and is not.
  24282. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24283. Request req;
  24284. req.method = "GET";
  24285. for (const auto &value : upgrade_values) {
  24286. req.headers.emplace("Upgrade", value);
  24287. }
  24288. req.headers.emplace("Connection", "Upgrade");
  24289. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24290. req.headers.emplace("Sec-WebSocket-Version", "13");
  24291. return req;
  24292. };
  24293. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24294. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24295. EXPECT_TRUE(
  24296. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24297. EXPECT_TRUE(
  24298. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24299. EXPECT_TRUE(
  24300. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24301. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24302. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24303. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24304. EXPECT_FALSE(
  24305. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24306. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24307. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24308. }
  24309. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24310. Server svr;
  24311. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24312. auto port = svr.bind_to_any_port("localhost");
  24313. std::thread t([&]() { svr.listen_after_bind(); });
  24314. auto se = detail::scope_exit([&] {
  24315. svr.stop();
  24316. t.join();
  24317. });
  24318. svr.wait_until_ready();
  24319. Headers headers = {{"Upgrade", "websocket"},
  24320. {"Connection", "notupgrade"},
  24321. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24322. {"Sec-WebSocket-Version", "13"}};
  24323. Client cli("localhost", port);
  24324. auto res = cli.Get("/ws", headers);
  24325. // The route exists only as a WebSocket route, so a request that fails the
  24326. // handshake check falls through to ordinary routing.
  24327. ASSERT_TRUE(res);
  24328. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24329. }
  24330. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24331. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24332. // Connection value is the only thing left for the client to reject.
  24333. Server svr;
  24334. svr.Get("/ws", [](const Request &req, Response &res) {
  24335. res.status = StatusCode::SwitchingProtocol_101;
  24336. res.set_header("Upgrade", "websocket");
  24337. res.set_header("Connection", "notupgrade");
  24338. res.set_header("Sec-WebSocket-Accept",
  24339. detail::websocket_accept_key(
  24340. req.get_header_value("Sec-WebSocket-Key")));
  24341. });
  24342. auto port = svr.bind_to_any_port("localhost");
  24343. std::thread t([&]() { svr.listen_after_bind(); });
  24344. auto se = detail::scope_exit([&] {
  24345. svr.stop();
  24346. t.join();
  24347. });
  24348. svr.wait_until_ready();
  24349. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24350. auto res = client.connect();
  24351. EXPECT_FALSE(res);
  24352. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24353. EXPECT_FALSE(client.is_open());
  24354. }
  24355. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24356. Server svr;
  24357. svr.Get("/ws", [](const Request &req, Response &res) {
  24358. res.status = StatusCode::SwitchingProtocol_101;
  24359. res.set_header("Upgrade", "websocket");
  24360. res.set_header("Connection", "Upgrade");
  24361. res.set_header("Sec-WebSocket-Accept",
  24362. detail::websocket_accept_key(
  24363. req.get_header_value("Sec-WebSocket-Key")));
  24364. res.set_header("Sec-WebSocket-Protocol", "admin");
  24365. });
  24366. auto port = svr.bind_to_any_port("localhost");
  24367. std::thread t([&]() { svr.listen_after_bind(); });
  24368. auto se = detail::scope_exit([&] {
  24369. svr.stop();
  24370. t.join();
  24371. });
  24372. svr.wait_until_ready();
  24373. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24374. // Server selects a subprotocol the client never offered
  24375. {
  24376. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24377. ws::WebSocketClient client(url, headers);
  24378. auto res = client.connect();
  24379. EXPECT_FALSE(res);
  24380. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24381. EXPECT_FALSE(client.is_open());
  24382. EXPECT_TRUE(client.subprotocol().empty());
  24383. }
  24384. // Client offered none but the server named one anyway
  24385. {
  24386. ws::WebSocketClient client(url);
  24387. auto res = client.connect();
  24388. EXPECT_FALSE(res);
  24389. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24390. EXPECT_FALSE(client.is_open());
  24391. EXPECT_TRUE(client.subprotocol().empty());
  24392. }
  24393. }
  24394. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24395. // The socket path doubles as the URL host, so it must not contain '/'.
  24396. const char *shard = getenv("GTEST_SHARD_INDEX");
  24397. const std::string sock_path =
  24398. shard ? std::string("httplib-ws-") + shard + ".sock"
  24399. : std::string("httplib-ws.sock");
  24400. std::remove(sock_path.c_str());
  24401. Server svr;
  24402. std::mutex mtx;
  24403. std::string received_host;
  24404. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24405. {
  24406. std::lock_guard<std::mutex> lock(mtx);
  24407. received_host = req.get_header_value("Host");
  24408. }
  24409. std::string msg;
  24410. while (ws.read(msg)) {
  24411. ws.send(msg);
  24412. }
  24413. });
  24414. svr.set_address_family(AF_UNIX);
  24415. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24416. auto se = detail::scope_exit([&] {
  24417. svr.stop();
  24418. t.join();
  24419. std::remove(sock_path.c_str());
  24420. });
  24421. svr.wait_until_ready();
  24422. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24423. client.set_address_family(AF_UNIX);
  24424. ASSERT_TRUE(client.connect());
  24425. ASSERT_TRUE(client.send("hello"));
  24426. std::string msg;
  24427. ASSERT_TRUE(client.read(msg));
  24428. client.close();
  24429. {
  24430. std::lock_guard<std::mutex> lock(mtx);
  24431. // There is no host:port for a Unix socket, so the same "localhost"
  24432. // placeholder the HTTP client uses is expected.
  24433. EXPECT_EQ("localhost", received_host);
  24434. }
  24435. }
  24436. // Two threads must never parse WebSocket frames from the same stream.
  24437. // close() used to read the peer's Close reply with its own frame read, so it
  24438. // raced a reader thread that was in the middle of a payload: the payload loop
  24439. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24440. // so bytes taken by close() were replaced with bytes from further along the
  24441. // stream. The message kept its length and silently changed content.
  24442. //
  24443. // The raw peer below sends a frame header plus part of the payload, waits for
  24444. // the handler to call close(), and only then sends the rest. Whichever thread
  24445. // would win the race for those bytes, the message must arrive intact, because
  24446. // close() must not touch the stream while read() owns it.
  24447. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24448. #ifndef _WIN32
  24449. signal(SIGPIPE, SIG_IGN);
  24450. #endif
  24451. const size_t payload_len = 120; // fits the 7-bit length field
  24452. const size_t prefix_len = 8;
  24453. const int attempts = 8;
  24454. std::string expected(payload_len, '\0');
  24455. for (size_t i = 0; i < payload_len; i++) {
  24456. expected[i] = static_cast<char>('a' + i % 26);
  24457. }
  24458. std::atomic<bool> peer_stalled{false};
  24459. std::atomic<bool> handler_done{false};
  24460. std::mutex received_mutex;
  24461. std::vector<std::string> received;
  24462. // Bound every wait, so a regression fails the test instead of hanging the
  24463. // suite.
  24464. auto wait_for = [](const std::atomic<bool> &flag) {
  24465. for (int i = 0; i < 500 && !flag; i++) {
  24466. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24467. }
  24468. };
  24469. Server svr;
  24470. svr.set_websocket_ping_interval(0);
  24471. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24472. std::thread reader([&]() {
  24473. std::string msg;
  24474. while (ws.read(msg)) {
  24475. std::lock_guard<std::mutex> guard(received_mutex);
  24476. received.push_back(msg);
  24477. }
  24478. });
  24479. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24480. // inside read_websocket_frame() when close() runs.
  24481. wait_for(peer_stalled);
  24482. ws.close();
  24483. reader.join();
  24484. handler_done = true;
  24485. });
  24486. auto port = svr.bind_to_any_port("127.0.0.1");
  24487. std::thread t([&]() { svr.listen_after_bind(); });
  24488. auto se = detail::scope_exit([&] {
  24489. svr.stop();
  24490. t.join();
  24491. });
  24492. svr.wait_until_ready();
  24493. auto send_bytes = [](socket_t s, const std::string &data) {
  24494. #ifdef _WIN32
  24495. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24496. #else
  24497. auto n = ::send(s, data.data(), data.size(), 0);
  24498. #endif
  24499. return n == static_cast<decltype(n)>(data.size());
  24500. };
  24501. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24502. // Every length used here fits the 7-bit length field.
  24503. auto masked_header = [](uint8_t first_byte, size_t len) {
  24504. std::string h;
  24505. h += static_cast<char>(first_byte);
  24506. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24507. h.append(4, '\0'); // mask key
  24508. return h;
  24509. };
  24510. for (int attempt = 0; attempt < attempts; attempt++) {
  24511. peer_stalled = false;
  24512. handler_done = false;
  24513. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24514. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24515. auto se_sock = detail::scope_exit([&] {
  24516. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24517. });
  24518. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24519. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24520. sockaddr_in addr{};
  24521. addr.sin_family = AF_INET;
  24522. addr.sin_port = htons(static_cast<uint16_t>(port));
  24523. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24524. ASSERT_EQ(
  24525. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24526. << "attempt " << attempt;
  24527. ASSERT_TRUE(send_bytes(sock,
  24528. "GET /ws HTTP/1.1\r\n"
  24529. "Host: 127.0.0.1\r\n"
  24530. "Upgrade: websocket\r\n"
  24531. "Connection: Upgrade\r\n"
  24532. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24533. "Sec-WebSocket-Version: 13\r\n"
  24534. "\r\n"))
  24535. << "attempt " << attempt;
  24536. std::string response;
  24537. while (response.find("\r\n\r\n") == std::string::npos) {
  24538. char buf[512];
  24539. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24540. if (n <= 0) { break; }
  24541. response.append(buf, static_cast<size_t>(n));
  24542. }
  24543. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24544. << "attempt " << attempt;
  24545. // Send the header of a Binary message but only the first prefix_len bytes
  24546. // of its payload, leaving the reader thread stalled inside the payload.
  24547. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24548. expected.substr(0, prefix_len)))
  24549. << "attempt " << attempt;
  24550. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24551. peer_stalled = true;
  24552. // Let close() send its Close frame and park in its own read before the
  24553. // rest of the payload arrives, so both threads are waiting for it.
  24554. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24555. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24556. close_frame += static_cast<char>(0x03); // status 1000
  24557. close_frame += static_cast<char>(0xE8);
  24558. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24559. << "attempt " << attempt;
  24560. // Closing the peer releases the reader thread even on the buggy path,
  24561. // where it waits for bytes another thread already consumed.
  24562. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24563. detail::close_socket(sock);
  24564. sock = INVALID_SOCKET;
  24565. wait_for(handler_done);
  24566. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24567. }
  24568. std::lock_guard<std::mutex> guard(received_mutex);
  24569. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24570. << "a message in flight when close() ran was dropped";
  24571. for (size_t i = 0; i < received.size(); i++) {
  24572. EXPECT_EQ(expected, received[i]) << "message " << i;
  24573. }
  24574. }
  24575. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24576. // returning the socket, or INVALID_SOCKET.
  24577. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24578. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24579. if (sock == INVALID_SOCKET) { return sock; }
  24580. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24581. sockaddr_in addr{};
  24582. addr.sin_family = AF_INET;
  24583. addr.sin_port = htons(static_cast<uint16_t>(port));
  24584. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24585. std::string req = "GET " + path +
  24586. " HTTP/1.1\r\n"
  24587. "Host: 127.0.0.1\r\n"
  24588. "Upgrade: websocket\r\n"
  24589. "Connection: Upgrade\r\n"
  24590. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24591. "Sec-WebSocket-Version: 13\r\n"
  24592. "\r\n";
  24593. std::string res;
  24594. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24595. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24596. static_cast<ssize_t>(req.size())) {
  24597. char c;
  24598. while (res.find("\r\n\r\n") == std::string::npos &&
  24599. ::recv(sock, &c, 1, 0) == 1) {
  24600. res += c;
  24601. }
  24602. }
  24603. if (res.find(" 101 ") == std::string::npos) {
  24604. detail::close_socket(sock);
  24605. return INVALID_SOCKET;
  24606. }
  24607. return sock;
  24608. }
  24609. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24610. // The payload must fit the 7-bit length field.
  24611. static std::string masked_frame(uint8_t first_byte,
  24612. const std::string &payload) {
  24613. std::string f;
  24614. f += static_cast<char>(first_byte);
  24615. f += static_cast<char>(0x80 | payload.size());
  24616. f.append(4, '\0');
  24617. return f + payload;
  24618. }
  24619. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24620. std::atomic<bool> done{false};
  24621. std::string received;
  24622. Server svr;
  24623. svr.set_websocket_ping_interval(0);
  24624. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24625. std::string msg;
  24626. if (ws.read(msg) == ws::Binary) { received = msg; }
  24627. done = true;
  24628. });
  24629. auto port = svr.bind_to_any_port("127.0.0.1");
  24630. std::thread t([&]() { svr.listen_after_bind(); });
  24631. auto se = detail::scope_exit([&] {
  24632. svr.stop();
  24633. t.join();
  24634. });
  24635. svr.wait_until_ready();
  24636. auto sock = connect_raw_websocket(port, "/ws");
  24637. ASSERT_NE(INVALID_SOCKET, sock);
  24638. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24639. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24640. masked_frame(0x89, "p") + // FIN + Ping
  24641. masked_frame(0x80, "lo"); // FIN + Continuation
  24642. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24643. for (int i = 0; i < 500 && !done; i++) {
  24644. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24645. }
  24646. ASSERT_TRUE(done);
  24647. EXPECT_EQ("Hello", received);
  24648. // The Ping between the fragments is answered with a Pong.
  24649. char pong[3];
  24650. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24651. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24652. }
  24653. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24654. Server svr;
  24655. svr.set_websocket_ping_interval(-1);
  24656. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24657. std::string msg;
  24658. while (ws.read(msg)) {}
  24659. });
  24660. auto port = svr.bind_to_any_port("127.0.0.1");
  24661. std::thread t([&]() { svr.listen_after_bind(); });
  24662. auto se = detail::scope_exit([&] {
  24663. svr.stop();
  24664. t.join();
  24665. });
  24666. svr.wait_until_ready();
  24667. auto sock = connect_raw_websocket(port, "/ws");
  24668. ASSERT_NE(INVALID_SOCKET, sock);
  24669. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24670. // Nothing comes while the client stays quiet.
  24671. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24672. char c;
  24673. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24674. }
  24675. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24676. // and that has to end a read() already waiting on the peer, on every platform.
  24677. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24678. // The peer sends no pings, and its handler never calls read(), which is
  24679. // where pongs are written.
  24680. std::mutex mutex;
  24681. std::condition_variable cv;
  24682. auto release = false;
  24683. svr.set_websocket_ping_interval(0);
  24684. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24685. std::unique_lock<std::mutex> lock(mutex);
  24686. cv.wait(lock, [&] { return release; });
  24687. });
  24688. auto port = svr.bind_to_any_port(HOST);
  24689. std::thread t([&]() { svr.listen_after_bind(); });
  24690. auto se = detail::scope_exit([&] {
  24691. {
  24692. std::lock_guard<std::mutex> lock(mutex);
  24693. release = true;
  24694. }
  24695. cv.notify_all();
  24696. svr.stop();
  24697. t.join();
  24698. });
  24699. svr.wait_until_ready();
  24700. ws::WebSocketClient client(std::string(scheme) +
  24701. "://localhost:" + std::to_string(port) + "/ws");
  24702. #ifdef CPPHTTPLIB_SSL_ENABLED
  24703. client.enable_server_certificate_verification(false);
  24704. #endif
  24705. // A ping a second, given up on after two go unanswered: about 3s
  24706. client.set_websocket_ping_interval(1);
  24707. client.set_websocket_max_missed_pongs(2);
  24708. // Well past that, so that a read the timeout ends instead stands out
  24709. client.set_read_timeout(10);
  24710. ASSERT_TRUE(client.connect());
  24711. auto start = std::chrono::steady_clock::now();
  24712. std::string msg;
  24713. EXPECT_EQ(ws::Fail, client.read(msg));
  24714. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24715. std::chrono::steady_clock::now() - start)
  24716. .count(),
  24717. 6000);
  24718. EXPECT_FALSE(client.is_open());
  24719. }
  24720. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24721. Server svr;
  24722. check_pong_timeout_ends_read(svr, "ws");
  24723. }
  24724. #ifdef CPPHTTPLIB_SSL_ENABLED
  24725. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24726. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24727. ASSERT_TRUE(svr.is_valid());
  24728. check_pong_timeout_ends_read(svr, "wss");
  24729. }
  24730. #endif
  24731. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24732. Server svr;
  24733. svr.set_websocket_ping_interval(0);
  24734. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24735. std::string msg;
  24736. while (ws.read(msg)) {}
  24737. });
  24738. auto port = svr.bind_to_any_port("127.0.0.1");
  24739. std::thread t([&]() { svr.listen_after_bind(); });
  24740. auto se = detail::scope_exit([&] {
  24741. svr.stop();
  24742. t.join();
  24743. });
  24744. svr.wait_until_ready();
  24745. // Each Close payload and the reply it should get: an echo when valid, 1002
  24746. // otherwise.
  24747. std::vector<std::pair<std::string, std::string>> cases = {
  24748. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24749. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24750. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24751. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24752. };
  24753. // Also between the fragments of a message.
  24754. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24755. for (const auto &c : cases) {
  24756. auto sock = connect_raw_websocket(port, "/ws");
  24757. ASSERT_NE(INVALID_SOCKET, sock);
  24758. auto frames = prefix + masked_frame(0x88, c.first);
  24759. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24760. std::string reply;
  24761. char buf[256];
  24762. while (reply.size() < 2 + c.second.size()) {
  24763. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24764. if (n <= 0) { break; }
  24765. reply.append(buf, static_cast<size_t>(n));
  24766. }
  24767. detail::close_socket(sock);
  24768. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24769. c.second,
  24770. reply);
  24771. }
  24772. }
  24773. }
  24774. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24775. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24776. protected:
  24777. void SetUp() override {
  24778. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24779. SERVER_PRIVATE_KEY_FILE);
  24780. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24781. std::string msg;
  24782. ws::ReadResult ret;
  24783. while ((ret = ws.read(msg))) {
  24784. if (ret == ws::Binary) {
  24785. ws.send(msg.data(), msg.size());
  24786. } else {
  24787. ws.send(msg);
  24788. }
  24789. }
  24790. });
  24791. port_ = server_->bind_to_any_port(HOST);
  24792. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24793. server_->wait_until_ready();
  24794. }
  24795. void TearDown() override {
  24796. server_->stop();
  24797. if (server_thread_.joinable()) { server_thread_.join(); }
  24798. }
  24799. std::unique_ptr<SSLServer> server_;
  24800. std::thread server_thread_;
  24801. int port_ = 0;
  24802. };
  24803. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24804. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24805. {
  24806. ws::WebSocketClient client(url);
  24807. client.enable_server_certificate_verification(false);
  24808. auto calls = 0;
  24809. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24810. calls++;
  24811. return false;
  24812. });
  24813. EXPECT_FALSE(client.connect());
  24814. EXPECT_GT(calls, 0);
  24815. }
  24816. {
  24817. ws::WebSocketClient client(url);
  24818. client.enable_server_certificate_verification(false);
  24819. client.set_session_verifier([](tls::session_t) {
  24820. return SSLVerifierResponse::CertificateRejected;
  24821. });
  24822. EXPECT_FALSE(client.connect());
  24823. }
  24824. {
  24825. ws::WebSocketClient client(url);
  24826. client.enable_server_certificate_verification(false);
  24827. client.set_session_verifier([](tls::session_t) {
  24828. return SSLVerifierResponse::CertificateAccepted;
  24829. });
  24830. EXPECT_TRUE(client.connect());
  24831. }
  24832. }
  24833. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24834. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24835. "/ws-echo");
  24836. client.enable_server_certificate_verification(false);
  24837. ASSERT_TRUE(client.connect());
  24838. ASSERT_TRUE(client.is_open());
  24839. ASSERT_TRUE(client.send("Hello WSS"));
  24840. std::string msg;
  24841. EXPECT_EQ(ws::Text, client.read(msg));
  24842. EXPECT_EQ("Hello WSS", msg);
  24843. client.close();
  24844. }
  24845. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24846. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24847. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24848. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24849. // client (without calling close() first) is the only path that runs
  24850. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24851. // bug exactly.
  24852. //
  24853. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24854. // when linked against an instrumented libssl; run under Valgrind to catch it
  24855. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24856. // suite (the freed session otherwise stalls on the close handshake) — this test
  24857. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24858. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24859. {
  24860. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24861. "/ws-echo");
  24862. client.enable_server_certificate_verification(false);
  24863. client.set_read_timeout(2, 0);
  24864. client.set_write_timeout(2, 0);
  24865. ASSERT_TRUE(client.connect());
  24866. ASSERT_TRUE(client.is_open());
  24867. ASSERT_TRUE(client.send("still open"));
  24868. // Intentionally do NOT call client.close(): leaving scope runs
  24869. // shutdown_and_close() with the WebSocket still open, which must send the
  24870. // close frame while the TLS session is still alive.
  24871. }
  24872. }
  24873. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24874. // shutdown_and_close() at the start of connect(), reproducing the same
  24875. // use-after-free within the test body rather than at scope exit. The second
  24876. // connect must succeed and echo, proving the close handshake ran over a live
  24877. // session. See the note above about memory-tool requirements.
  24878. TEST_F(WebSocketSSLIntegrationTest,
  24879. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24880. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24881. "/ws-echo");
  24882. client.enable_server_certificate_verification(false);
  24883. client.set_read_timeout(2, 0);
  24884. client.set_write_timeout(2, 0);
  24885. ASSERT_TRUE(client.connect());
  24886. ASSERT_TRUE(client.is_open());
  24887. ASSERT_TRUE(client.send("still open"));
  24888. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24889. // the still-open connection, which must not touch a freed TLS session.
  24890. ASSERT_TRUE(client.connect());
  24891. ASSERT_TRUE(client.is_open());
  24892. ASSERT_TRUE(client.send("after reconnect"));
  24893. std::string msg;
  24894. EXPECT_EQ(ws::Text, client.read(msg));
  24895. EXPECT_EQ("after reconnect", msg);
  24896. client.close();
  24897. }
  24898. #endif
  24899. #ifdef CPPHTTPLIB_SSL_ENABLED
  24900. class WebSocketSSLCATest : public ::testing::Test {
  24901. protected:
  24902. void SetUp() override {
  24903. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24904. SERVER_PRIVATE_KEY_FILE);
  24905. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24906. std::string msg;
  24907. while (ws.read(msg)) {
  24908. ws.send(msg);
  24909. }
  24910. });
  24911. port_ = server_->bind_to_any_port("127.0.0.1");
  24912. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24913. server_->wait_until_ready();
  24914. }
  24915. void TearDown() override {
  24916. server_->stop();
  24917. if (server_thread_.joinable()) { server_thread_.join(); }
  24918. }
  24919. std::string url() const {
  24920. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24921. }
  24922. std::unique_ptr<SSLServer> server_;
  24923. std::thread server_thread_;
  24924. int port_ = 0;
  24925. };
  24926. // A custom CA loaded as PEM verifies the server with full certificate
  24927. // verification enabled
  24928. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24929. ws::WebSocketClient client(url());
  24930. std::string cert;
  24931. read_file(SERVER_CERT2_FILE, cert);
  24932. client.load_ca_cert_store(cert.c_str(), cert.size());
  24933. ASSERT_TRUE(client.connect());
  24934. ASSERT_TRUE(client.send("hello"));
  24935. std::string msg;
  24936. EXPECT_EQ(ws::Text, client.read(msg));
  24937. EXPECT_EQ("hello", msg);
  24938. client.close();
  24939. }
  24940. // A custom CA that does not cover the server must fail verification (the
  24941. // custom CA is exclusive; system certs are not loaded alongside it)
  24942. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24943. ws::WebSocketClient client(url());
  24944. std::string cert;
  24945. read_file(CLIENT_CA_CERT_FILE, cert);
  24946. client.load_ca_cert_store(cert.c_str(), cert.size());
  24947. auto res = client.connect();
  24948. ASSERT_FALSE(res);
  24949. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24950. EXPECT_EQ(-1, res.status());
  24951. EXPECT_NE(0u, res.ssl_backend_error());
  24952. }
  24953. // The same CA as a file path rather than PEM in memory
  24954. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24955. ws::WebSocketClient client(url());
  24956. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24957. ASSERT_TRUE(client.connect());
  24958. ASSERT_TRUE(client.send("hello"));
  24959. std::string msg;
  24960. EXPECT_EQ(ws::Text, client.read(msg));
  24961. EXPECT_EQ("hello", msg);
  24962. client.close();
  24963. }
  24964. // ...and a CA file that does not cover the server still fails, so it is the
  24965. // path above that decides the outcome
  24966. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24967. ws::WebSocketClient client(url());
  24968. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24969. ASSERT_FALSE(client.connect());
  24970. }
  24971. // Regression test: reconnecting with a native custom CA store used to reuse
  24972. // a store handle the previous TLS context had already freed (use-after-free
  24973. // under the OpenSSL backend). The context now lives as long as the client.
  24974. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24975. ws::WebSocketClient client(url());
  24976. std::string cert;
  24977. read_file(SERVER_CERT2_FILE, cert);
  24978. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24979. ASSERT_TRUE(client.connect());
  24980. client.close();
  24981. ASSERT_TRUE(client.connect());
  24982. ASSERT_TRUE(client.send("again"));
  24983. std::string msg;
  24984. EXPECT_EQ(ws::Text, client.read(msg));
  24985. EXPECT_EQ("again", msg);
  24986. client.close();
  24987. }
  24988. // Regression test: a certificate with a trusted chain but no identity match
  24989. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24990. // verification entirely for IP hosts, so this connection succeeded there.
  24991. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24992. // chain verification while the identity check must still fail.
  24993. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24994. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24995. ASSERT_TRUE(svr.is_valid());
  24996. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24997. std::string msg;
  24998. while (ws.read(msg)) {
  24999. ws.send(msg);
  25000. }
  25001. });
  25002. auto port = svr.bind_to_any_port("127.0.0.1");
  25003. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25004. auto se = detail::scope_exit([&] {
  25005. svr.stop();
  25006. t.join();
  25007. });
  25008. svr.wait_until_ready();
  25009. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25010. "/echo");
  25011. std::string cert;
  25012. read_file(SERVER_CERT_FILE, cert);
  25013. client.load_ca_cert_store(cert.c_str(), cert.size());
  25014. ASSERT_FALSE(client.connect());
  25015. }
  25016. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25017. // SNI, so nothing binds the host name to the TLS session. These bind the
  25018. // server to "localhost" instead, the only shape that exercises the SNI and
  25019. // hostname-verification path with certificate verification left enabled.
  25020. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25021. protected:
  25022. void Start(const char *cert_file) {
  25023. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25024. SERVER_PRIVATE_KEY_FILE);
  25025. ASSERT_TRUE(server_->is_valid());
  25026. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25027. std::string msg;
  25028. while (ws.read(msg)) {
  25029. ws.send(msg);
  25030. }
  25031. });
  25032. port_ = server_->bind_to_any_port("localhost");
  25033. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25034. server_->wait_until_ready();
  25035. }
  25036. void TearDown() override {
  25037. if (server_) { server_->stop(); }
  25038. if (server_thread_.joinable()) { server_thread_.join(); }
  25039. }
  25040. std::string url() const {
  25041. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25042. }
  25043. std::unique_ptr<SSLServer> server_;
  25044. std::thread server_thread_;
  25045. int port_ = 0;
  25046. };
  25047. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25048. // out and the connection is usable
  25049. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25050. Start(SERVER_CERT2_FILE);
  25051. ws::WebSocketClient client(url());
  25052. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25053. ASSERT_TRUE(client.connect());
  25054. ASSERT_TRUE(client.send("hello"));
  25055. std::string msg;
  25056. EXPECT_EQ(ws::Text, client.read(msg));
  25057. EXPECT_EQ("hello", msg);
  25058. client.close();
  25059. }
  25060. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25061. // while the identity check must still reject "localhost"
  25062. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25063. Start(SERVER_CERT_FILE);
  25064. ws::WebSocketClient client(url());
  25065. client.set_ca_cert_path(SERVER_CERT_FILE);
  25066. auto res = client.connect();
  25067. ASSERT_FALSE(res);
  25068. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25069. EXPECT_EQ(-1, res.status());
  25070. }
  25071. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25072. // disabled: the chain is still checked, only the identity check is skipped
  25073. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25074. Start(SERVER_CERT_FILE);
  25075. ws::WebSocketClient client(url());
  25076. client.set_ca_cert_path(SERVER_CERT_FILE);
  25077. client.enable_server_hostname_verification(false);
  25078. ASSERT_TRUE(client.connect());
  25079. ASSERT_TRUE(client.send("hello"));
  25080. std::string msg;
  25081. EXPECT_EQ(ws::Text, client.read(msg));
  25082. EXPECT_EQ("hello", msg);
  25083. client.close();
  25084. }
  25085. // A CA that did not sign the server certificate fails the chain, even though
  25086. // the name would match
  25087. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25088. Start(SERVER_CERT2_FILE);
  25089. ws::WebSocketClient client(url());
  25090. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25091. ASSERT_FALSE(client.connect());
  25092. }
  25093. // With verification disabled, neither the chain nor the name is checked
  25094. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25095. Start(SERVER_CERT_FILE);
  25096. ws::WebSocketClient client(url());
  25097. client.enable_server_certificate_verification(false);
  25098. ASSERT_TRUE(client.connect());
  25099. ASSERT_TRUE(client.send("hello"));
  25100. std::string msg;
  25101. EXPECT_EQ(ws::Text, client.read(msg));
  25102. EXPECT_EQ("hello", msg);
  25103. client.close();
  25104. }
  25105. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25106. protected:
  25107. void SetUp() override {
  25108. server_ = httplib::detail::make_unique<SSLServer>(
  25109. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25110. ASSERT_TRUE(server_->is_valid());
  25111. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25112. std::string msg;
  25113. while (ws.read(msg)) {
  25114. ws.send(msg);
  25115. }
  25116. });
  25117. port_ = server_->bind_to_any_port("localhost");
  25118. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25119. server_->wait_until_ready();
  25120. }
  25121. void TearDown() override {
  25122. server_->stop();
  25123. if (server_thread_.joinable()) { server_thread_.join(); }
  25124. }
  25125. std::string url() const {
  25126. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25127. }
  25128. void ConnectWithClientCert(const std::string &client_cert_file,
  25129. const std::string &client_private_key_file,
  25130. const char *private_key_password) {
  25131. std::string cert_pem, key_pem;
  25132. read_file(client_cert_file, cert_pem);
  25133. read_file(client_private_key_file, key_pem);
  25134. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25135. key_pem.c_str(), key_pem.size(),
  25136. private_key_password};
  25137. ConnectWithPem(pem);
  25138. }
  25139. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25140. ws::WebSocketClient client(url(), pem);
  25141. ASSERT_TRUE(client.is_valid());
  25142. client.enable_server_certificate_verification(false);
  25143. ASSERT_TRUE(client.connect());
  25144. ASSERT_TRUE(client.send("hello"));
  25145. std::string msg;
  25146. EXPECT_EQ(ws::Text, client.read(msg));
  25147. EXPECT_EQ("hello", msg);
  25148. client.close();
  25149. }
  25150. std::unique_ptr<SSLServer> server_;
  25151. std::thread server_thread_;
  25152. int port_ = 0;
  25153. };
  25154. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25155. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25156. }
  25157. // Control for the tests above: the fixture's server really does require a
  25158. // client certificate, so it is the PEM the constructor installed that decides
  25159. // the outcome.
  25160. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25161. ws::WebSocketClient client(url());
  25162. ASSERT_TRUE(client.is_valid());
  25163. client.enable_server_certificate_verification(false);
  25164. EXPECT_FALSE(client.connect());
  25165. }
  25166. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25167. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25168. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25169. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25170. }
  25171. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25172. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25173. std::string cert_pem, key_pem;
  25174. read_file(CLIENT_CERT_FILE, cert_pem);
  25175. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25176. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25177. std::vector<char> key(key_pem.begin(), key_pem.end());
  25178. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25179. key.size(), nullptr};
  25180. ConnectWithPem(pem);
  25181. }
  25182. #endif
  25183. #if !defined(_WIN32)
  25184. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25185. auto secret_dir = std::string("./symlink_test_secret");
  25186. auto served_dir = std::string("./symlink_test_served");
  25187. auto secret_file = secret_dir + "/secret.txt";
  25188. auto symlink_path = served_dir + "/escape";
  25189. // Setup: create directories and files
  25190. mkdir(secret_dir.c_str(), 0755);
  25191. mkdir(served_dir.c_str(), 0755);
  25192. {
  25193. std::ofstream ofs(secret_file);
  25194. ofs << "SECRET_DATA";
  25195. }
  25196. // Create symlink using absolute path so it resolves correctly
  25197. #ifdef PATH_MAX
  25198. char abs_secret[PATH_MAX];
  25199. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25200. #else
  25201. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25202. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25203. ASSERT_NE(nullptr, abs_secret);
  25204. #endif
  25205. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25206. auto se = detail::scope_exit([&] {
  25207. unlink(symlink_path.c_str());
  25208. unlink(secret_file.c_str());
  25209. rmdir(served_dir.c_str());
  25210. rmdir(secret_dir.c_str());
  25211. });
  25212. Server svr;
  25213. svr.set_mount_point("/", served_dir);
  25214. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25215. auto se2 = detail::scope_exit([&] {
  25216. svr.stop();
  25217. listen_thread.join();
  25218. });
  25219. svr.wait_until_ready();
  25220. Client cli("localhost", PORT);
  25221. // Symlink pointing outside base dir should be blocked
  25222. auto res = cli.Get("/escape/secret.txt");
  25223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25224. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25225. }
  25226. #endif
  25227. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25228. // "GET /smuggled" request), reads the first response, and only then sends the
  25229. // embedded request as the body. Returns how many times /smuggled ran.
  25230. //
  25231. // The body is sent AFTER receiving the first response (as in the original
  25232. // PoC) so that the stream_line_reader cannot buffer it together with the
  25233. // headers of the first request.
  25234. static int count_smuggled_requests(const std::string &outer_head,
  25235. std::string &first_response) {
  25236. Server svr;
  25237. svr.set_mount_point("/", "./www");
  25238. std::atomic<int> smuggled_count(0);
  25239. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25240. smuggled_count++;
  25241. res.set_content("oops", "text/plain");
  25242. });
  25243. svr.Post("/post", [&](const Request &req, Response &res) {
  25244. res.set_content(req.body, "text/plain");
  25245. });
  25246. auto port = svr.bind_to_any_port("localhost");
  25247. thread t = thread([&] { svr.listen_after_bind(); });
  25248. auto se = detail::scope_exit([&] {
  25249. svr.stop();
  25250. t.join();
  25251. });
  25252. svr.wait_until_ready();
  25253. auto error = Error::Success;
  25254. auto sock = detail::create_client_socket(
  25255. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25256. /*connection_timeout_sec=*/2, 0,
  25257. /*read_timeout_sec=*/2, 0,
  25258. /*write_timeout_sec=*/2, 0, std::string(), error);
  25259. EXPECT_NE(INVALID_SOCKET, sock);
  25260. if (sock == INVALID_SOCKET) { return -1; }
  25261. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25262. // The "smuggled" request will be sent as the body of the outer request
  25263. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25264. "Host: localhost\r\n"
  25265. "Connection: close\r\n"
  25266. "\r\n";
  25267. auto head = outer_head;
  25268. auto len = std::to_string(smuggled.size());
  25269. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25270. pos = head.find("{len}", pos + len.size())) {
  25271. head.replace(pos, 5, len);
  25272. }
  25273. // Step 1: Send only the outer request headers (no body yet)
  25274. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25275. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25276. // Step 2: Read the first response
  25277. char buf[4096];
  25278. for (;;) {
  25279. auto n = recv(sock, buf, sizeof(buf), 0);
  25280. if (n <= 0) break;
  25281. first_response.append(buf, static_cast<size_t>(n));
  25282. // Stop once we have a complete response (headers + body)
  25283. auto hdr_end = first_response.find("\r\n\r\n");
  25284. if (hdr_end != std::string::npos) {
  25285. // Check for Content-Length to know when the body is complete
  25286. auto cl_pos = first_response.find("Content-Length:");
  25287. if (cl_pos != std::string::npos) {
  25288. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25289. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25290. auto cl = std::stoul(
  25291. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25292. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25293. } else {
  25294. break; // No Content-Length, assume headers-only response
  25295. }
  25296. }
  25297. }
  25298. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25299. // vulnerable server the keep-alive loop reads this as a second request. The
  25300. // server may already have closed the connection, so the result is ignored.
  25301. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25302. // Half-close so that a server which drained the body sees EOF and closes,
  25303. // instead of the read below waiting for the read timeout.
  25304. #ifdef _WIN32
  25305. ::shutdown(sock, SD_SEND);
  25306. #else
  25307. ::shutdown(sock, SHUT_WR);
  25308. #endif
  25309. // Step 4: Read until the server closes the connection
  25310. for (;;) {
  25311. auto n = recv(sock, buf, sizeof(buf), 0);
  25312. if (n <= 0) break;
  25313. }
  25314. return smuggled_count.load();
  25315. }
  25316. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25317. // A GET request with Content-Length to a static file handler must have its
  25318. // body drained before the keep-alive connection is reused. Otherwise the
  25319. // unread body bytes are interpreted as the next HTTP request.
  25320. std::string first_response;
  25321. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25322. "Host: localhost\r\n"
  25323. "Content-Length: {len}\r\n"
  25324. "\r\n",
  25325. first_response));
  25326. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25327. }
  25328. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25329. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25330. // be answered with 400 and the connection closed. Treating it as "no body"
  25331. // leaves the body to be parsed as the next request.
  25332. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25333. const char *targets[] = {
  25334. "GET /file", // handler that never reads the body
  25335. "GET /not-found", // no handler matches (404)
  25336. "POST /post", // handler that reads the body
  25337. };
  25338. for (auto target : targets) {
  25339. for (auto value : values) {
  25340. std::string first_response;
  25341. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25342. " HTTP/1.1\r\n"
  25343. "Host: localhost\r\n"
  25344. "Content-Length: " +
  25345. value + "\r\n\r\n",
  25346. first_response))
  25347. << target << " with Content-Length: " << value;
  25348. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25349. << target << " with Content-Length: " << value;
  25350. }
  25351. }
  25352. }
  25353. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25354. // A 400 for an unparseable request line leaves the rest of the message
  25355. // unread, so the connection must be closed rather than reused.
  25356. std::string first_response;
  25357. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25358. "Host: localhost\r\n"
  25359. "Content-Length: {len}\r\n"
  25360. "\r\n",
  25361. first_response));
  25362. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25363. }
  25364. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25365. // Same as above for a header block that fails to parse.
  25366. std::string first_response;
  25367. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25368. "Host: localhost\r\n"
  25369. "Bad Header\r\n"
  25370. "Content-Length: {len}\r\n"
  25371. "\r\n",
  25372. first_response));
  25373. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25374. }
  25375. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25376. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25377. // server must not read another request on that connection, even when the
  25378. // request had no body to drain.
  25379. std::string first_response;
  25380. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25381. "Host: localhost\r\n"
  25382. "\r\n",
  25383. first_response));
  25384. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25385. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25386. }
  25387. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25388. // A content reader that stops early leaves the stream inside the body.
  25389. // Draining the whole Content-Length from there, or reading the body again,
  25390. // reads into the next request, and whatever follows is parsed as a request
  25391. // of its own.
  25392. Server svr;
  25393. std::atomic<int> smuggled_count(0);
  25394. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25395. svr.Post("/upload", [](const Request &req, Response &res,
  25396. const ContentReader &content_reader) {
  25397. // Stop at the last chunk, so the whole body has been read however it
  25398. // arrives.
  25399. auto length = req.get_header_value_u64("Content-Length");
  25400. size_t total = 0;
  25401. auto consumed = content_reader([&](const char *, size_t n) {
  25402. total += n;
  25403. return total < length;
  25404. });
  25405. EXPECT_FALSE(consumed);
  25406. if (req.has_param("retry")) {
  25407. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25408. }
  25409. // Replace the 400 the aborted read set, which would close the connection.
  25410. res.set_redirect("/done");
  25411. });
  25412. auto port = svr.bind_to_any_port(HOST);
  25413. thread t = thread([&] { svr.listen_after_bind(); });
  25414. auto se = detail::scope_exit([&] {
  25415. svr.stop();
  25416. t.join();
  25417. });
  25418. svr.wait_until_ready();
  25419. // A front end sees the second request as a POST whose body is the GET. The
  25420. // first body is as long as the POST's headers, so draining it again reads
  25421. // exactly those and leaves the GET to be parsed next.
  25422. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25423. "Host: localhost\r\n"
  25424. "\r\n";
  25425. std::string second_head = "POST /post HTTP/1.1\r\n"
  25426. "Host: localhost\r\n"
  25427. "Content-Length: " +
  25428. std::to_string(inner.size()) +
  25429. "\r\n"
  25430. "\r\n";
  25431. for (auto target : {"/upload", "/upload?retry"}) {
  25432. smuggled_count = 0;
  25433. std::string request = "POST " + std::string(target) +
  25434. " HTTP/1.1\r\n"
  25435. "Host: localhost\r\n"
  25436. "Content-Length: " +
  25437. std::to_string(second_head.size()) +
  25438. "\r\n"
  25439. "\r\n" +
  25440. std::string(second_head.size(), 'A') + second_head +
  25441. inner;
  25442. std::string response;
  25443. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25444. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25445. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25446. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25447. EXPECT_EQ(0, smuggled_count.load()) << target;
  25448. }
  25449. }
  25450. // An error response closes the connection anyway, so the body is left unread
  25451. // with a redirect, such as one to a login page.
  25452. static void serve_redirects(Server &svr,
  25453. const std::function<void(int)> &client) {
  25454. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25455. res.set_redirect("/login");
  25456. return Server::HandlerResponse::Handled;
  25457. });
  25458. auto port = svr.bind_to_any_port(HOST);
  25459. ASSERT_GT(port, 0);
  25460. thread t = thread([&] { svr.listen_after_bind(); });
  25461. auto se = detail::scope_exit([&] {
  25462. svr.stop();
  25463. t.join();
  25464. ASSERT_FALSE(svr.is_running());
  25465. });
  25466. svr.wait_until_ready();
  25467. client(port);
  25468. }
  25469. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25470. Server svr;
  25471. serve_redirects(svr, [](int port) {
  25472. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25473. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25474. std::to_string(body.size()) + "\r\n\r\n" + body +
  25475. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25476. std::string resp;
  25477. ASSERT_TRUE(send_request(1, req, &resp, port));
  25478. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25479. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25480. });
  25481. }
  25482. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25483. Server svr;
  25484. svr.set_read_timeout(0, 200000);
  25485. serve_redirects(svr, [](int port) {
  25486. // A byte every 100 ms keeps each read within the read timeout, but not the
  25487. // body as a whole, so the server closes and the bytes sent after that fail.
  25488. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25489. "Content-Length: 10\r\n\r\n"};
  25490. parts.resize(11, "x");
  25491. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25492. });
  25493. }
  25494. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25495. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25496. // must be rejected with 400 Bad Request.
  25497. Server svr;
  25498. svr.Post("/test", [&](const Request &, Response &res) {
  25499. res.set_content("ok", "text/plain");
  25500. });
  25501. thread t = thread([&] { svr.listen(HOST, PORT); });
  25502. auto se = detail::scope_exit([&] {
  25503. svr.stop();
  25504. t.join();
  25505. ASSERT_FALSE(svr.is_running());
  25506. });
  25507. svr.wait_until_ready();
  25508. // Exact "chunked"
  25509. {
  25510. auto req = "POST /test HTTP/1.1\r\n"
  25511. "Host: localhost\r\n"
  25512. "Content-Length: 5\r\n"
  25513. "Transfer-Encoding: chunked\r\n"
  25514. "Connection: close\r\n"
  25515. "\r\n"
  25516. "hello";
  25517. std::string response;
  25518. ASSERT_TRUE(send_request(1, req, &response));
  25519. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25520. response.substr(0, response.find("\r\n")));
  25521. }
  25522. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25523. {
  25524. auto req = "POST /test HTTP/1.1\r\n"
  25525. "Host: localhost\r\n"
  25526. "Content-Length: 5\r\n"
  25527. "Transfer-Encoding: gzip, chunked\r\n"
  25528. "Connection: close\r\n"
  25529. "\r\n"
  25530. "hello";
  25531. std::string response;
  25532. ASSERT_TRUE(send_request(1, req, &response));
  25533. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25534. response.substr(0, response.find("\r\n")));
  25535. }
  25536. }
  25537. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25538. Server svr;
  25539. svr.Post("/test", [&](const Request &, Response &res) {
  25540. res.set_content("ok", "text/plain");
  25541. });
  25542. thread t = thread([&] { svr.listen(HOST, PORT); });
  25543. auto se = detail::scope_exit([&] {
  25544. svr.stop();
  25545. t.join();
  25546. ASSERT_FALSE(svr.is_running());
  25547. });
  25548. svr.wait_until_ready();
  25549. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25550. // length cannot be determined, so the server must answer 400 and close
  25551. // rather than treat the request as bodyless and leave the body in the
  25552. // socket for the next request to pick up.
  25553. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25554. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25555. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25556. std::string response;
  25557. ASSERT_TRUE(send_request(1, req, &response));
  25558. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25559. response.substr(0, response.find("\r\n")))
  25560. << transfer_encoding;
  25561. }
  25562. // RFC 9110 5.3: the codings may also be split across several
  25563. // Transfer-Encoding lines, which combine in the order they were received.
  25564. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25565. // just like the single-line "chunked, gzip" above.
  25566. {
  25567. auto req = "POST /test HTTP/1.1\r\n"
  25568. "Host: localhost\r\n"
  25569. "Transfer-Encoding: chunked\r\n"
  25570. "Transfer-Encoding: gzip\r\n"
  25571. "\r\n"
  25572. "0\r\n\r\n";
  25573. std::string response;
  25574. ASSERT_TRUE(send_request(1, req, &response));
  25575. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25576. response.substr(0, response.find("\r\n")));
  25577. }
  25578. }
  25579. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25580. Server svr;
  25581. svr.Post("/test", [&](const Request &, Response &res) {
  25582. res.set_content("ok", "text/plain");
  25583. });
  25584. auto port = svr.bind_to_any_port(HOST);
  25585. ASSERT_GT(port, 0);
  25586. thread t = thread([&] { svr.listen_after_bind(); });
  25587. auto se = detail::scope_exit([&] {
  25588. svr.stop();
  25589. t.join();
  25590. ASSERT_FALSE(svr.is_running());
  25591. });
  25592. svr.wait_until_ready();
  25593. for (auto transfer_encoding :
  25594. {"Transfer-Encoding: gzip, chunked\r\n",
  25595. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25596. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25597. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25598. transfer_encoding + "\r\n0\r\n\r\n";
  25599. std::string response;
  25600. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25601. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25602. response.substr(0, response.find("\r\n")))
  25603. << transfer_encoding;
  25604. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25605. << transfer_encoding;
  25606. }
  25607. }
  25608. // Regression for issue #2450: a DELETE without Content-Length on a
  25609. // keep-alive connection must not let the post-response drain consume the
  25610. // next request's bytes.
  25611. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25612. Server svr;
  25613. std::atomic<int> delete_count(0);
  25614. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25615. delete_count++;
  25616. res.status = StatusCode::NoContent_204;
  25617. });
  25618. auto port = svr.bind_to_any_port(HOST);
  25619. thread t = thread([&] { svr.listen_after_bind(); });
  25620. auto se = detail::scope_exit([&] {
  25621. svr.stop();
  25622. t.join();
  25623. });
  25624. svr.wait_until_ready();
  25625. auto error = Error::Success;
  25626. auto sock = detail::create_client_socket(
  25627. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25628. /*connection_timeout_sec=*/2, 0,
  25629. /*read_timeout_sec=*/2, 0,
  25630. /*write_timeout_sec=*/2, 0, std::string(), error);
  25631. ASSERT_NE(INVALID_SOCKET, sock);
  25632. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25633. auto send_request_and_read_response = [&](const std::string &req,
  25634. std::string &out) -> bool {
  25635. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25636. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25637. char buf[4096];
  25638. for (;;) {
  25639. auto n = recv(sock, buf, sizeof(buf), 0);
  25640. if (n <= 0) { return !out.empty(); }
  25641. out.append(buf, static_cast<size_t>(n));
  25642. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25643. }
  25644. };
  25645. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25646. "Host: localhost\r\n"
  25647. "\r\n";
  25648. std::string resp1;
  25649. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25650. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25651. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25652. "Host: localhost\r\n"
  25653. "Connection: close\r\n"
  25654. "\r\n";
  25655. std::string resp2;
  25656. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25657. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25658. EXPECT_EQ(2, delete_count.load());
  25659. }
  25660. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25661. Server svr;
  25662. svr.Post("/ingest", [&](const Request &, Response &res,
  25663. const ContentReader &content_reader) {
  25664. auto consumed = content_reader([](const char *, size_t) { return false; });
  25665. EXPECT_FALSE(consumed);
  25666. res.status = StatusCode::Conflict_409;
  25667. res.set_header("Connection", "close");
  25668. });
  25669. auto port = svr.bind_to_any_port(HOST);
  25670. thread t = thread([&] { svr.listen_after_bind(); });
  25671. auto se = detail::scope_exit([&] {
  25672. svr.stop();
  25673. t.join();
  25674. });
  25675. svr.wait_until_ready();
  25676. auto error = Error::Success;
  25677. auto sock = detail::create_client_socket(
  25678. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25679. /*connection_timeout_sec=*/2, 0,
  25680. /*read_timeout_sec=*/1, 0,
  25681. /*write_timeout_sec=*/2, 0, std::string(), error);
  25682. ASSERT_NE(INVALID_SOCKET, sock);
  25683. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25684. std::string request = "POST /ingest HTTP/1.1\r\n"
  25685. "Host: localhost\r\n"
  25686. "Transfer-Encoding: chunked\r\n"
  25687. "\r\n"
  25688. "4\r\n"
  25689. "data\r\n";
  25690. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25691. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25692. std::string response;
  25693. ssize_t received = 0;
  25694. do {
  25695. char buf[4096];
  25696. received = recv(sock, buf, sizeof(buf), 0);
  25697. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25698. } while (received > 0);
  25699. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25700. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25701. EXPECT_EQ(0, received);
  25702. }
  25703. namespace no_proxy_test {
  25704. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25705. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25706. // calling listen().
  25707. class ScopedServer {
  25708. public:
  25709. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25710. ~ScopedServer() {
  25711. svr_.stop();
  25712. if (th_.joinable()) { th_.join(); }
  25713. }
  25714. Server &svr() { return svr_; }
  25715. int port() const { return port_; }
  25716. void listen() {
  25717. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25718. svr_.wait_until_ready();
  25719. }
  25720. private:
  25721. Server svr_;
  25722. std::thread th_;
  25723. int port_ = 0;
  25724. };
  25725. class ProxyAndTargetServers {
  25726. public:
  25727. ProxyAndTargetServers() {
  25728. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25729. proxy_hits_++;
  25730. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25731. res.set_content("via-proxy", "text/plain");
  25732. });
  25733. target_.Get(".*", [this](const Request &req, Response &res) {
  25734. target_hits_++;
  25735. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25736. res.set_content("direct", "text/plain");
  25737. });
  25738. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25739. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25740. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25741. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25742. proxy_mock_.wait_until_ready();
  25743. target_.wait_until_ready();
  25744. }
  25745. ~ProxyAndTargetServers() {
  25746. proxy_mock_.stop();
  25747. target_.stop();
  25748. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25749. if (target_thread_.joinable()) { target_thread_.join(); }
  25750. }
  25751. Server &proxy_mock() { return proxy_mock_; }
  25752. Server &target() { return target_; }
  25753. int proxy_port() const { return proxy_port_; }
  25754. int target_port() const { return target_port_; }
  25755. int proxy_hits() const { return proxy_hits_.load(); }
  25756. int target_hits() const { return target_hits_.load(); }
  25757. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25758. void reset_counters() {
  25759. proxy_hits_ = 0;
  25760. target_hits_ = 0;
  25761. last_had_proxy_authz_ = false;
  25762. }
  25763. private:
  25764. Server proxy_mock_;
  25765. Server target_;
  25766. std::thread proxy_thread_;
  25767. std::thread target_thread_;
  25768. int proxy_port_ = 0;
  25769. int target_port_ = 0;
  25770. std::atomic<int> proxy_hits_{0};
  25771. std::atomic<int> target_hits_{0};
  25772. std::atomic<bool> last_had_proxy_authz_{false};
  25773. };
  25774. inline std::unique_ptr<Client> make_client(const std::string &host,
  25775. ProxyAndTargetServers &s) {
  25776. auto cli = detail::make_unique<Client>(host, s.target_port());
  25777. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25778. cli->set_proxy("127.0.0.1", s.proxy_port());
  25779. return cli;
  25780. }
  25781. } // namespace no_proxy_test
  25782. using no_proxy_test::make_client;
  25783. using no_proxy_test::ProxyAndTargetServers;
  25784. // A stream request carries the credentials a buffered request does
  25785. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25786. no_proxy_test::ScopedServer origin;
  25787. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25788. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25789. });
  25790. origin.listen();
  25791. Client cli("127.0.0.1", origin.port());
  25792. cli.set_basic_auth("user", "pass");
  25793. auto handle = cli.open_stream("GET", "/x");
  25794. ASSERT_TRUE(handle.is_valid());
  25795. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25796. Client bearer("127.0.0.1", origin.port());
  25797. bearer.set_bearer_token_auth("tok");
  25798. auto handle2 = bearer.open_stream("GET", "/x");
  25799. ASSERT_TRUE(handle2.is_valid());
  25800. EXPECT_EQ("Bearer tok", read_all(handle2));
  25801. }
  25802. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25803. // takes its own credentials, as for a buffered request
  25804. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25805. std::string target, authz, proxy_authz;
  25806. no_proxy_test::ScopedServer proxy;
  25807. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25808. target = req.target;
  25809. authz = req.get_header_value("Authorization");
  25810. proxy_authz = req.get_header_value("Proxy-Authorization");
  25811. res.set_content("ok", "text/plain");
  25812. });
  25813. proxy.listen();
  25814. Client cli("origin.example", 8080);
  25815. cli.set_proxy("127.0.0.1", proxy.port());
  25816. cli.set_proxy_basic_auth("puser", "ppass");
  25817. cli.set_basic_auth("user", "pass");
  25818. auto handle = cli.open_stream("GET", "/x");
  25819. ASSERT_TRUE(handle.is_valid());
  25820. EXPECT_EQ("ok", read_all(handle));
  25821. EXPECT_EQ("http://origin.example:8080/x", target);
  25822. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25823. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25824. }
  25825. // In absolute-form the path follows the authority, so a path that does not
  25826. // begin with '/' would make the proxy connect to another host
  25827. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  25828. std::vector<std::string> targets;
  25829. no_proxy_test::ScopedServer proxy;
  25830. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25831. targets.push_back(req.target);
  25832. res.set_content("ok", "text/plain");
  25833. });
  25834. proxy.listen();
  25835. Client cli("origin.example", 8080);
  25836. cli.set_proxy("127.0.0.1", proxy.port());
  25837. cli.set_basic_auth("user", "pass");
  25838. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  25839. auto res = cli.Get(path);
  25840. EXPECT_FALSE(res) << path;
  25841. auto handle = cli.open_stream("GET", path);
  25842. EXPECT_FALSE(handle.is_valid()) << path;
  25843. }
  25844. EXPECT_TRUE(targets.empty());
  25845. auto res = cli.Get("/x");
  25846. ASSERT_TRUE(res);
  25847. ASSERT_EQ(1u, targets.size());
  25848. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  25849. }
  25850. TEST(NoProxyTest, ExactHostnameBypasses) {
  25851. ProxyAndTargetServers s;
  25852. auto cli = make_client("example.com", s);
  25853. cli->set_no_proxy({"example.com"});
  25854. auto res = cli->Get("/");
  25855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25856. EXPECT_EQ(0, s.proxy_hits());
  25857. EXPECT_EQ(1, s.target_hits());
  25858. }
  25859. TEST(NoProxyTest, SubdomainBypasses) {
  25860. ProxyAndTargetServers s;
  25861. auto cli = make_client("foo.example.com", s);
  25862. cli->set_no_proxy({"example.com"});
  25863. auto res = cli->Get("/");
  25864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25865. EXPECT_EQ(0, s.proxy_hits());
  25866. EXPECT_EQ(1, s.target_hits());
  25867. }
  25868. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25869. // Regression guard: "evilexample.com" must not be considered a subdomain
  25870. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25871. // check would let traffic bypass the proxy and leak credentials direct
  25872. // to the attacker host.
  25873. ProxyAndTargetServers s;
  25874. auto cli = make_client("evilexample.com", s);
  25875. cli->set_no_proxy({"example.com"});
  25876. auto res = cli->Get("/");
  25877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25878. EXPECT_GE(s.proxy_hits(), 1);
  25879. EXPECT_EQ(0, s.target_hits());
  25880. }
  25881. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25882. ProxyAndTargetServers s;
  25883. auto cli = make_client("example.com.evil.com", s);
  25884. cli->set_no_proxy({"example.com"});
  25885. auto res = cli->Get("/");
  25886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25887. EXPECT_GE(s.proxy_hits(), 1);
  25888. EXPECT_EQ(0, s.target_hits());
  25889. }
  25890. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25891. ProxyAndTargetServers s;
  25892. auto cli = make_client("example.com", s);
  25893. cli->set_no_proxy({".example.com"});
  25894. auto res = cli->Get("/");
  25895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25896. EXPECT_EQ(0, s.proxy_hits());
  25897. EXPECT_EQ(1, s.target_hits());
  25898. }
  25899. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25900. ProxyAndTargetServers s;
  25901. auto cli = make_client("Example.COM", s);
  25902. cli->set_no_proxy({"EXAMPLE.com"});
  25903. auto res = cli->Get("/");
  25904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25905. EXPECT_EQ(0, s.proxy_hits());
  25906. EXPECT_EQ(1, s.target_hits());
  25907. }
  25908. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25909. ProxyAndTargetServers s;
  25910. auto cli = make_client("example.com.", s);
  25911. cli->set_no_proxy({"example.com"});
  25912. auto res = cli->Get("/");
  25913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25914. EXPECT_EQ(0, s.proxy_hits());
  25915. EXPECT_EQ(1, s.target_hits());
  25916. }
  25917. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25918. // Trailing dots must be normalized on BOTH sides — host and entry.
  25919. // An implementation that only strips the host-side trailing dot would
  25920. // fail to match host "example.com" against entry "example.com." because
  25921. // a literal substring search would compare 11 chars against 12.
  25922. ProxyAndTargetServers s;
  25923. auto cli = make_client("example.com", s);
  25924. cli->set_no_proxy({"example.com."});
  25925. auto res = cli->Get("/");
  25926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25927. EXPECT_EQ(0, s.proxy_hits());
  25928. EXPECT_EQ(1, s.target_hits());
  25929. }
  25930. TEST(NoProxyTest, WildcardBypassesEverything) {
  25931. ProxyAndTargetServers s;
  25932. auto cli = make_client("anything.invalid.test", s);
  25933. cli->set_no_proxy({"*"});
  25934. auto res = cli->Get("/");
  25935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25936. EXPECT_EQ(0, s.proxy_hits());
  25937. EXPECT_EQ(1, s.target_hits());
  25938. }
  25939. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25940. ProxyAndTargetServers s;
  25941. Client cli("127.0.0.1", s.target_port());
  25942. cli.set_proxy("127.0.0.1", s.proxy_port());
  25943. cli.set_no_proxy({"127.0.0.1"});
  25944. auto res = cli.Get("/");
  25945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25946. EXPECT_EQ(0, s.proxy_hits());
  25947. EXPECT_EQ(1, s.target_hits());
  25948. }
  25949. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25950. ProxyAndTargetServers s;
  25951. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25952. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25953. cli.set_proxy("127.0.0.1", s.proxy_port());
  25954. cli.set_no_proxy({"::1"});
  25955. auto res = cli.Get("/");
  25956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25957. EXPECT_EQ(0, s.proxy_hits());
  25958. EXPECT_EQ(1, s.target_hits());
  25959. }
  25960. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25961. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25962. // must still be recognized as IPv6 for CIDR matching. Implementations
  25963. // that detect IPv6 only when the host begins with '[' would parse the
  25964. // host as a hostname and miss the match.
  25965. ProxyAndTargetServers s;
  25966. Client cli("fe80::1", s.target_port());
  25967. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25968. cli.set_proxy("127.0.0.1", s.proxy_port());
  25969. cli.set_no_proxy({"fe80::/10"});
  25970. auto res = cli.Get("/");
  25971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25972. EXPECT_EQ(0, s.proxy_hits());
  25973. EXPECT_EQ(1, s.target_hits());
  25974. }
  25975. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25976. ProxyAndTargetServers s;
  25977. Client cli("::1", s.target_port());
  25978. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25979. cli.set_proxy("127.0.0.1", s.proxy_port());
  25980. cli.set_no_proxy({"[::1]"});
  25981. auto res = cli.Get("/");
  25982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25983. EXPECT_EQ(0, s.proxy_hits());
  25984. EXPECT_EQ(1, s.target_hits());
  25985. }
  25986. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25987. ProxyAndTargetServers s;
  25988. Client cli("fe80::1", s.target_port());
  25989. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25990. cli.set_proxy("127.0.0.1", s.proxy_port());
  25991. cli.set_no_proxy({"[fe80::]/10"});
  25992. auto res = cli.Get("/");
  25993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25994. EXPECT_EQ(0, s.proxy_hits());
  25995. EXPECT_EQ(1, s.target_hits());
  25996. }
  25997. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25998. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25999. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26000. // tricks via address-family conversion.
  26001. ProxyAndTargetServers s;
  26002. Client cli("::ffff:127.0.0.1", s.target_port());
  26003. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26004. cli.set_proxy("127.0.0.1", s.proxy_port());
  26005. cli.set_no_proxy({"127.0.0.1"});
  26006. auto res = cli.Get("/");
  26007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26008. EXPECT_GE(s.proxy_hits(), 1);
  26009. EXPECT_EQ(0, s.target_hits());
  26010. }
  26011. TEST(NoProxyTest, IPv4CidrMatch) {
  26012. ProxyAndTargetServers s;
  26013. Client cli("127.0.0.1", s.target_port());
  26014. cli.set_proxy("127.0.0.1", s.proxy_port());
  26015. cli.set_no_proxy({"127.0.0.0/8"});
  26016. auto res = cli.Get("/");
  26017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26018. EXPECT_EQ(0, s.proxy_hits());
  26019. EXPECT_EQ(1, s.target_hits());
  26020. }
  26021. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26022. ProxyAndTargetServers s;
  26023. Client cli("127.0.0.1", s.target_port());
  26024. cli.set_proxy("127.0.0.1", s.proxy_port());
  26025. cli.set_no_proxy({"10.0.0.0/8"});
  26026. auto res = cli.Get("/");
  26027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26028. EXPECT_GE(s.proxy_hits(), 1);
  26029. EXPECT_EQ(0, s.target_hits());
  26030. }
  26031. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26032. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26033. // IPv4 target matches.
  26034. ProxyAndTargetServers s;
  26035. Client cli("127.0.0.1", s.target_port());
  26036. cli.set_proxy("127.0.0.1", s.proxy_port());
  26037. cli.set_no_proxy({"0.0.0.0/0"});
  26038. auto res = cli.Get("/");
  26039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26040. EXPECT_EQ(0, s.proxy_hits());
  26041. EXPECT_EQ(1, s.target_hits());
  26042. }
  26043. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26044. ProxyAndTargetServers s;
  26045. Client cli("127.0.0.1", s.target_port());
  26046. cli.set_proxy("127.0.0.1", s.proxy_port());
  26047. cli.set_no_proxy({"127.0.0.1"});
  26048. auto res = cli.Get("/");
  26049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26050. EXPECT_EQ(0, s.proxy_hits());
  26051. EXPECT_EQ(1, s.target_hits());
  26052. }
  26053. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26054. ProxyAndTargetServers s;
  26055. Client cli("127.0.0.1", s.target_port());
  26056. cli.set_proxy("127.0.0.1", s.proxy_port());
  26057. cli.set_no_proxy({"127.0.0.0/33"});
  26058. auto res = cli.Get("/");
  26059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26060. EXPECT_GE(s.proxy_hits(), 1);
  26061. EXPECT_EQ(0, s.target_hits());
  26062. }
  26063. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26064. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26065. ProxyAndTargetServers s;
  26066. Client cli("127.0.0.1", s.target_port());
  26067. cli.set_proxy("127.0.0.1", s.proxy_port());
  26068. cli.set_no_proxy({"127.0.0.1/"});
  26069. auto res = cli.Get("/");
  26070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26071. EXPECT_GE(s.proxy_hits(), 1);
  26072. EXPECT_EQ(0, s.target_hits());
  26073. }
  26074. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26075. ProxyAndTargetServers s;
  26076. auto cli = make_client("internal.corp", s);
  26077. cli->set_proxy_basic_auth("u", "p");
  26078. cli->set_no_proxy({"internal.corp"});
  26079. auto res = cli->Get("/");
  26080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26081. EXPECT_EQ(1, s.target_hits());
  26082. EXPECT_EQ(0, s.proxy_hits());
  26083. EXPECT_FALSE(s.last_had_proxy_authz())
  26084. << "Proxy-Authorization must not be sent direct to the target";
  26085. }
  26086. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26087. ProxyAndTargetServers s;
  26088. auto cli = make_client("public.example", s);
  26089. cli->set_proxy_basic_auth("u", "p");
  26090. cli->set_no_proxy({"internal.corp"}); // does not match
  26091. auto res = cli->Get("/");
  26092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26093. EXPECT_GE(s.proxy_hits(), 1);
  26094. EXPECT_TRUE(s.last_had_proxy_authz());
  26095. }
  26096. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26097. std::atomic<int> hits{0};
  26098. std::atomic<int> hits_with_authz{0};
  26099. no_proxy_test::ScopedServer proxy_mock;
  26100. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26101. hits++;
  26102. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26103. if (req.target.find("/redir") != std::string::npos) {
  26104. res.set_redirect("http://other.example/landed");
  26105. } else {
  26106. res.set_content("via-proxy", "text/plain");
  26107. }
  26108. });
  26109. proxy_mock.listen();
  26110. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26111. hits = 0;
  26112. hits_with_authz = 0;
  26113. Client cli("public.example", 80);
  26114. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26115. cli.set_proxy_basic_auth(c.first, c.second);
  26116. cli.set_follow_location(true);
  26117. // The redirect to another host goes through the proxy as well
  26118. auto res = cli.Get("/redir");
  26119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26120. EXPECT_EQ(2, hits.load());
  26121. EXPECT_EQ(2, hits_with_authz.load());
  26122. }
  26123. }
  26124. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26125. ProxyAndTargetServers s;
  26126. auto cli = make_client("anything.test", s);
  26127. auto res = cli->Get("/");
  26128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26129. EXPECT_GE(s.proxy_hits(), 1);
  26130. EXPECT_EQ(0, s.target_hits());
  26131. }
  26132. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26133. ProxyAndTargetServers s;
  26134. auto cli = make_client("example.com", s);
  26135. cli->set_no_proxy({"example.com:8080"});
  26136. auto res = cli->Get("/");
  26137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26138. EXPECT_GE(s.proxy_hits(), 1);
  26139. EXPECT_EQ(0, s.target_hits());
  26140. }
  26141. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26142. ProxyAndTargetServers s;
  26143. auto cli = make_client("anything.test", s);
  26144. cli->set_no_proxy({"", " ", "\t"});
  26145. auto res = cli->Get("/");
  26146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26147. EXPECT_GE(s.proxy_hits(), 1);
  26148. EXPECT_EQ(0, s.target_hits());
  26149. }
  26150. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26151. // An entry with leading/trailing whitespace must still match — env-style
  26152. // values are commonly pasted with stray spaces and an implementation
  26153. // that feeds the raw token directly to inet_pton would fail to match
  26154. // valid CIDRs because of the spaces.
  26155. ProxyAndTargetServers s;
  26156. Client cli("127.0.0.1", s.target_port());
  26157. cli.set_proxy("127.0.0.1", s.proxy_port());
  26158. cli.set_no_proxy({" 127.0.0.0/8 "});
  26159. auto res = cli.Get("/");
  26160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26161. EXPECT_EQ(0, s.proxy_hits());
  26162. EXPECT_EQ(1, s.target_hits());
  26163. }
  26164. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26165. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26166. // go direct and must NOT carry Proxy-Authorization.
  26167. std::atomic<int> proxy_hits{0};
  26168. std::atomic<int> target_hits{0};
  26169. std::atomic<bool> target_saw_authz{false};
  26170. no_proxy_test::ScopedServer proxy_mock, target;
  26171. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26172. proxy_hits++;
  26173. res.status = 302;
  26174. res.set_header("Location", "http://127.0.0.1:" +
  26175. std::to_string(target.port()) + "/landed");
  26176. });
  26177. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26178. target_hits++;
  26179. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26180. res.set_content("direct", "text/plain");
  26181. });
  26182. proxy_mock.listen();
  26183. target.listen();
  26184. Client cli("public.example", target.port());
  26185. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26186. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26187. cli.set_proxy_basic_auth("u", "p");
  26188. cli.set_no_proxy({"127.0.0.1"});
  26189. cli.set_follow_location(true);
  26190. auto res = cli.Get("/redir");
  26191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26192. EXPECT_GE(proxy_hits.load(), 1);
  26193. EXPECT_GE(target_hits.load(), 1);
  26194. EXPECT_FALSE(target_saw_authz.load());
  26195. }
  26196. #ifdef CPPHTTPLIB_SSL_ENABLED
  26197. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26198. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26199. // proxy creds would be sent to the (possibly hostile) origin.
  26200. std::atomic<int> target_hits{0};
  26201. std::atomic<bool> target_saw_proxy_authz{false};
  26202. no_proxy_test::ScopedServer target;
  26203. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26204. target_hits++;
  26205. if (req.has_header("Proxy-Authorization")) {
  26206. target_saw_proxy_authz = true;
  26207. }
  26208. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26209. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26210. "nonce=\"abc\", algorithm=MD5");
  26211. });
  26212. target.listen();
  26213. // The proxy address is set to the target's port: the bypass MUST kick in;
  26214. // if it doesn't, the test still routes "via proxy" to the same server and
  26215. // the Proxy-Authorization assertion below catches the leak.
  26216. Client cli("evil.example", target.port());
  26217. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26218. cli.set_proxy("127.0.0.1", target.port());
  26219. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26220. cli.set_no_proxy({"evil.example"});
  26221. auto res = cli.Get("/x");
  26222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26223. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26224. EXPECT_EQ(1, target_hits.load());
  26225. EXPECT_FALSE(target_saw_proxy_authz.load());
  26226. }
  26227. #endif
  26228. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26229. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26230. std::atomic<int> proxy_hits{0};
  26231. std::atomic<int> bypass_hits{0};
  26232. std::atomic<bool> proxy_saw_c_url{false};
  26233. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26234. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26235. proxy_hits++;
  26236. if (req.path.find("/start") != std::string::npos) {
  26237. res.status = 302;
  26238. res.set_header("Location", "http://127.0.0.1:" +
  26239. std::to_string(bypass_server.port()) +
  26240. "/middle");
  26241. return;
  26242. }
  26243. if (req.path.find("/end") != std::string::npos) {
  26244. proxy_saw_c_url = true;
  26245. res.set_content("c-via-proxy", "text/plain");
  26246. return;
  26247. }
  26248. res.set_content("unexpected", "text/plain");
  26249. });
  26250. // public.example's "advertised" port is arbitrary (the request never lands
  26251. // there — it goes through the proxy), but use a dynamic value to stay
  26252. // friendly with sharded parallel runs.
  26253. int public_port = bypass_server.port();
  26254. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26255. bypass_hits++;
  26256. res.status = 302;
  26257. res.set_header("Location", "http://public.example:" +
  26258. std::to_string(public_port) + "/end");
  26259. });
  26260. proxy_mock.listen();
  26261. bypass_server.listen();
  26262. Client cli("public.example", public_port);
  26263. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26264. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26265. cli.set_no_proxy({"127.0.0.1"});
  26266. cli.set_follow_location(true);
  26267. auto res = cli.Get("/start");
  26268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26269. EXPECT_EQ(StatusCode::OK_200, res->status);
  26270. EXPECT_EQ("c-via-proxy", res->body);
  26271. EXPECT_GE(proxy_hits.load(), 2);
  26272. EXPECT_GE(bypass_hits.load(), 1);
  26273. EXPECT_TRUE(proxy_saw_c_url.load());
  26274. }
  26275. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26276. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26277. // request reconnects to the correct endpoint.
  26278. std::atomic<int> proxy_hits{0};
  26279. std::atomic<int> target_hits{0};
  26280. no_proxy_test::ScopedServer proxy_mock, target;
  26281. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26282. proxy_hits++;
  26283. res.set_content("via-proxy", "text/plain");
  26284. });
  26285. target.svr().Get(".*", [&](const Request &, Response &res) {
  26286. target_hits++;
  26287. res.set_content("direct", "text/plain");
  26288. });
  26289. proxy_mock.listen();
  26290. target.listen();
  26291. Client cli("public.example", target.port());
  26292. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26293. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26294. cli.set_keep_alive(true);
  26295. auto res1 = cli.Get("/a");
  26296. ASSERT_TRUE(res1);
  26297. EXPECT_EQ("via-proxy", res1->body);
  26298. EXPECT_EQ(1, proxy_hits.load());
  26299. EXPECT_EQ(0, target_hits.load());
  26300. cli.set_no_proxy({"public.example"});
  26301. auto res2 = cli.Get("/b");
  26302. ASSERT_TRUE(res2);
  26303. EXPECT_EQ("direct", res2->body);
  26304. EXPECT_EQ(1, proxy_hits.load());
  26305. EXPECT_EQ(1, target_hits.load());
  26306. }
  26307. // Forward declarations (see the base64_encode note).
  26308. namespace httplib {
  26309. namespace detail {
  26310. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26311. int shutdown_socket(socket_t sock) noexcept;
  26312. } // namespace detail
  26313. } // namespace httplib
  26314. namespace proxy_tunnel_test {
  26315. const char *const kTunnelEstablished =
  26316. "HTTP/1.1 200 Connection established\r\n\r\n";
  26317. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26318. using ConnectReply = std::function<std::string(const std::string &head)>;
  26319. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26320. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26321. class ScopedConnectProxy {
  26322. public:
  26323. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26324. : forward_port_(forward_port), reply_(std::move(reply)) {
  26325. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26326. if (listen_sock_ == INVALID_SOCKET) { return; }
  26327. auto a = loopback(0);
  26328. auto addr = reinterpret_cast<sockaddr *>(&a);
  26329. socklen_t alen = sizeof(a);
  26330. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26331. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26332. ::listen(listen_sock_, 4) != 0) {
  26333. return;
  26334. }
  26335. port_ = ntohs(a.sin_port);
  26336. th_ = std::thread([this] { run(); });
  26337. }
  26338. ~ScopedConnectProxy() {
  26339. if (th_.joinable()) {
  26340. stop_ = true;
  26341. auto wake = connect_to(port_);
  26342. th_.join();
  26343. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26344. }
  26345. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26346. }
  26347. int port() const { return port_; }
  26348. int connect_hits() const { return connect_hits_.load(); }
  26349. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26350. std::string connect_request() const {
  26351. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26352. return connect_request_;
  26353. }
  26354. private:
  26355. static sockaddr_in loopback(int port) {
  26356. sockaddr_in a{};
  26357. a.sin_family = AF_INET;
  26358. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26359. a.sin_port = htons(static_cast<unsigned short>(port));
  26360. return a;
  26361. }
  26362. static socket_t connect_to(int port) {
  26363. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26364. if (sock == INVALID_SOCKET) { return sock; }
  26365. auto a = loopback(port);
  26366. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26367. detail::close_socket(sock);
  26368. return INVALID_SOCKET;
  26369. }
  26370. return sock;
  26371. }
  26372. static bool send_all(socket_t sock, const char *data, size_t size) {
  26373. while (size > 0) {
  26374. auto n = detail::send_socket(sock, data, size, 0);
  26375. if (n <= 0) { return false; }
  26376. data += n;
  26377. size -= static_cast<size_t>(n);
  26378. }
  26379. return true;
  26380. }
  26381. void run() {
  26382. for (;;) {
  26383. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26384. if (stop_) {
  26385. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26386. return;
  26387. }
  26388. if (client == INVALID_SOCKET) { continue; }
  26389. serve(client);
  26390. detail::close_socket(client);
  26391. }
  26392. }
  26393. void serve(socket_t client) {
  26394. std::string head;
  26395. char buf[2048];
  26396. while (head.find("\r\n\r\n") == std::string::npos) {
  26397. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26398. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26399. if (n <= 0) { return; }
  26400. head.append(buf, static_cast<size_t>(n));
  26401. }
  26402. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26403. connect_hits_++;
  26404. {
  26405. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26406. connect_request_ = head;
  26407. }
  26408. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26409. if (!send_all(client, res.data(), res.size()) ||
  26410. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26411. return;
  26412. }
  26413. auto origin = connect_to(forward_port_);
  26414. if (origin == INVALID_SOCKET) { return; }
  26415. // When either side stops, shut both down so the other pump returns too.
  26416. auto pump = [&](socket_t from, socket_t to) {
  26417. char b[8192];
  26418. for (;;) {
  26419. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26420. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26421. }
  26422. detail::shutdown_socket(client);
  26423. detail::shutdown_socket(origin);
  26424. };
  26425. std::thread up([&] { pump(client, origin); });
  26426. pump(origin, client);
  26427. up.join();
  26428. detail::close_socket(origin);
  26429. }
  26430. int forward_port_;
  26431. ConnectReply reply_;
  26432. socket_t listen_sock_ = INVALID_SOCKET;
  26433. int port_ = 0;
  26434. std::thread th_;
  26435. std::atomic<bool> stop_{false};
  26436. std::atomic<int> connect_hits_{0};
  26437. mutable std::mutex connect_request_mutex_;
  26438. std::string connect_request_;
  26439. };
  26440. } // namespace proxy_tunnel_test
  26441. #ifdef CPPHTTPLIB_SSL_ENABLED
  26442. namespace proxy_tunnel_test {
  26443. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26444. class ScopedSSLServer {
  26445. public:
  26446. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26447. port_ = svr_.bind_to_any_port("127.0.0.1");
  26448. }
  26449. ~ScopedSSLServer() {
  26450. svr_.stop();
  26451. if (th_.joinable()) { th_.join(); }
  26452. }
  26453. SSLServer &svr() { return svr_; }
  26454. int port() const { return port_; }
  26455. void listen() {
  26456. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26457. svr_.wait_until_ready();
  26458. }
  26459. private:
  26460. SSLServer svr_;
  26461. std::thread th_;
  26462. int port_ = 0;
  26463. };
  26464. // Sends one request through the CONNECT proxy to the TLS origin with a
  26465. // credential configured for each hop, and checks that each credential reaches
  26466. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26467. // origin's (every header in origin_headers) on the tunnelled request.
  26468. void CredentialsStayWithTheirHop(
  26469. const std::function<void(SSLClient &)> &set_credentials,
  26470. const std::string &scheme,
  26471. const std::vector<std::string> &origin_headers = {"Authorization"},
  26472. bool stream = false) {
  26473. std::atomic<int> origin_hits{0};
  26474. std::atomic<bool> origin_saw_proxy_authz{false};
  26475. std::atomic<bool> origin_saw_headers{false};
  26476. ScopedSSLServer origin;
  26477. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26478. origin_hits++;
  26479. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26480. origin_saw_headers =
  26481. std::all_of(origin_headers.begin(), origin_headers.end(),
  26482. [&](const std::string &h) { return req.has_header(h); });
  26483. res.set_content("ok", "text/plain");
  26484. });
  26485. origin.listen();
  26486. ScopedConnectProxy proxy(origin.port());
  26487. ASSERT_NE(0, proxy.port());
  26488. // Pinned to 127.0.0.1 for the same reason as the test below.
  26489. SSLClient cli("127.0.0.1", origin.port());
  26490. cli.enable_server_certificate_verification(false);
  26491. cli.set_proxy("127.0.0.1", proxy.port());
  26492. set_credentials(cli);
  26493. if (stream) {
  26494. auto handle = cli.open_stream("GET", "/x");
  26495. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26496. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26497. } else {
  26498. auto res = cli.Get("/x");
  26499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26500. EXPECT_EQ(StatusCode::OK_200, res->status);
  26501. }
  26502. EXPECT_EQ(1, origin_hits.load());
  26503. EXPECT_EQ(1, proxy.connect_hits());
  26504. EXPECT_TRUE(origin_saw_headers.load());
  26505. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26506. << "Proxy-Authorization must not be sent inside the tunnel";
  26507. auto connect_req = proxy.connect_request();
  26508. EXPECT_NE(std::string::npos,
  26509. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26510. for (const auto &h : origin_headers) {
  26511. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26512. << h << " must not be sent to the proxy on CONNECT";
  26513. }
  26514. }
  26515. } // namespace proxy_tunnel_test
  26516. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26517. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26518. [](SSLClient &cli) {
  26519. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26520. cli.set_basic_auth("origin-user", "origin-pass");
  26521. },
  26522. "Basic");
  26523. }
  26524. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26525. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26526. [](SSLClient &cli) {
  26527. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26528. cli.set_basic_auth("origin-user", "origin-pass");
  26529. },
  26530. "Basic", {"Authorization"}, true);
  26531. }
  26532. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26533. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26534. [](SSLClient &cli) {
  26535. cli.set_proxy_bearer_token_auth("proxy-token");
  26536. cli.set_bearer_token_auth("origin-token");
  26537. },
  26538. "Bearer");
  26539. }
  26540. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26541. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26542. [](SSLClient &cli) {
  26543. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26544. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26545. {"Cookie", "sid=origin-session"},
  26546. {"X-Api-Key", "origin-key"}});
  26547. },
  26548. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26549. }
  26550. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26551. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26552. // retry; otherwise proxy creds would be sent to the origin.
  26553. std::atomic<int> origin_hits{0};
  26554. std::atomic<bool> origin_saw_proxy_authz{false};
  26555. proxy_tunnel_test::ScopedSSLServer origin;
  26556. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26557. origin_hits++;
  26558. if (req.has_header("Proxy-Authorization")) {
  26559. origin_saw_proxy_authz = true;
  26560. }
  26561. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26562. res.set_header("Proxy-Authenticate",
  26563. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26564. "algorithm=MD5");
  26565. });
  26566. origin.listen();
  26567. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26568. ASSERT_NE(0, proxy.port());
  26569. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26570. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26571. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26572. // and answer with its own status, making this test flaky.
  26573. SSLClient cli("127.0.0.1", origin.port());
  26574. cli.enable_server_certificate_verification(false);
  26575. cli.set_proxy("127.0.0.1", proxy.port());
  26576. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26577. auto res = cli.Get("/x");
  26578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26579. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26580. EXPECT_EQ(1, origin_hits.load());
  26581. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26582. EXPECT_EQ(1, proxy.connect_hits());
  26583. }
  26584. #endif
  26585. namespace proxy_tunnel_test {
  26586. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26587. // anything else gets a 407 with `challenge`.
  26588. ConnectReply require_proxy_auth(const std::string &expected,
  26589. const std::string &challenge) {
  26590. return [=](const std::string &head) -> std::string {
  26591. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26592. std::string::npos) {
  26593. return kTunnelEstablished;
  26594. }
  26595. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26596. "Proxy-Authenticate: " +
  26597. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26598. };
  26599. }
  26600. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26601. // request, then echoes.
  26602. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26603. ws.send(
  26604. "authorization:" + req.get_header_value("Authorization") +
  26605. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26606. std::string msg;
  26607. while (ws.read(msg)) {
  26608. ws.send(msg);
  26609. }
  26610. }
  26611. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26612. class ScopedWebSocketOrigin {
  26613. public:
  26614. ScopedWebSocketOrigin() {
  26615. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26616. server_.listen();
  26617. }
  26618. int port() const { return server_.port(); }
  26619. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26620. std::string url() const {
  26621. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26622. }
  26623. private:
  26624. no_proxy_test::ScopedServer server_;
  26625. };
  26626. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26627. // passed as a constructor header, and checks that each reaches only its hop.
  26628. void WebSocketCredentialsStayWithTheirHop(
  26629. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26630. const std::string &proxy_authz, const std::string &origin_authz) {
  26631. ScopedWebSocketOrigin origin;
  26632. ScopedConnectProxy proxy(
  26633. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26634. ASSERT_NE(0, proxy.port());
  26635. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26636. client.set_proxy("127.0.0.1", proxy.port());
  26637. set_proxy_credentials(client);
  26638. auto res = client.connect();
  26639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26640. std::string msg;
  26641. ASSERT_TRUE(client.read(msg));
  26642. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26643. client.close();
  26644. EXPECT_EQ(1, proxy.connect_hits());
  26645. EXPECT_EQ(std::string::npos,
  26646. proxy.connect_request().find("\r\nAuthorization: "))
  26647. << "origin credentials must not be sent to the proxy";
  26648. }
  26649. } // namespace proxy_tunnel_test
  26650. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26651. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26652. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26653. ASSERT_NE(0, proxy.port());
  26654. ws::WebSocketClient client(origin.url());
  26655. client.set_proxy("127.0.0.1", proxy.port());
  26656. auto res = client.connect();
  26657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26658. std::string msg;
  26659. ASSERT_TRUE(client.read(msg));
  26660. ASSERT_TRUE(client.send("hello"));
  26661. ASSERT_TRUE(client.read(msg));
  26662. EXPECT_EQ("hello", msg);
  26663. client.close();
  26664. EXPECT_EQ(1, proxy.connect_hits());
  26665. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26666. auto connect_req = proxy.connect_request();
  26667. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26668. EXPECT_NE(std::string::npos,
  26669. connect_req.find("\r\nHost: " + target + "\r\n"));
  26670. }
  26671. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26672. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26673. [](ws::WebSocketClient &cli) {
  26674. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26675. },
  26676. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26677. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26678. }
  26679. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26680. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26681. [](ws::WebSocketClient &cli) {
  26682. cli.set_proxy_bearer_token_auth("proxy-token");
  26683. },
  26684. "Bearer proxy-token", "Bearer origin-token");
  26685. }
  26686. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26687. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26688. proxy_tunnel_test::ScopedConnectProxy proxy(
  26689. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26690. "Basic " + detail::base64_encode("proxy-user:"),
  26691. "Basic realm=\"proxy\""));
  26692. ASSERT_NE(0, proxy.port());
  26693. ws::WebSocketClient client(origin.url());
  26694. client.set_proxy("127.0.0.1", proxy.port());
  26695. client.set_proxy_basic_auth("proxy-user", "");
  26696. auto res = client.connect();
  26697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26698. client.close();
  26699. EXPECT_EQ(1, proxy.connect_hits());
  26700. }
  26701. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26702. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26703. proxy_tunnel_test::ScopedConnectProxy proxy(
  26704. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26705. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26706. ASSERT_NE(0, proxy.port());
  26707. ws::WebSocketClient client(origin.url());
  26708. client.set_proxy("127.0.0.1", proxy.port());
  26709. auto res = client.connect();
  26710. EXPECT_FALSE(res);
  26711. EXPECT_EQ(Error::ProxyConnection, res.error());
  26712. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26713. EXPECT_EQ("Basic realm=\"proxy\"",
  26714. res.get_header_value("Proxy-Authenticate"));
  26715. EXPECT_FALSE(client.is_open());
  26716. }
  26717. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26718. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26719. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26720. ASSERT_NE(0, proxy.port());
  26721. ws::WebSocketClient client(origin.url());
  26722. client.set_proxy("127.0.0.1", proxy.port());
  26723. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26724. client.set_no_proxy({"127.0.0.1"});
  26725. auto res = client.connect();
  26726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26727. std::string msg;
  26728. ASSERT_TRUE(client.read(msg));
  26729. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26730. << "proxy credentials must not reach a bypassed origin";
  26731. client.close();
  26732. EXPECT_EQ(0, proxy.connect_hits());
  26733. }
  26734. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26735. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26736. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26737. ASSERT_NE(0, proxy.port());
  26738. ws::WebSocketClient client(origin.url());
  26739. client.set_proxy("127.0.0.1", proxy.port());
  26740. ASSERT_TRUE(client.connect());
  26741. ASSERT_TRUE(client.connect());
  26742. client.close();
  26743. EXPECT_EQ(2, proxy.connect_hits());
  26744. }
  26745. #ifdef CPPHTTPLIB_SSL_ENABLED
  26746. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26747. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26748. proxy_tunnel_test::ScopedConnectProxy proxy(
  26749. origin.port(), [](const std::string &head) -> std::string {
  26750. if (head.find(
  26751. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26752. std::string::npos) {
  26753. return proxy_tunnel_test::kTunnelEstablished;
  26754. }
  26755. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26756. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26757. "nonce=\"abc\", algorithm=MD5\r\n"
  26758. "Content-Length: 0\r\n\r\n";
  26759. });
  26760. ASSERT_NE(0, proxy.port());
  26761. ws::WebSocketClient client(origin.url());
  26762. client.set_proxy("127.0.0.1", proxy.port());
  26763. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26764. auto res = client.connect();
  26765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26766. std::string msg;
  26767. ASSERT_TRUE(client.read(msg));
  26768. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26769. client.close();
  26770. EXPECT_EQ(2, proxy.connect_hits());
  26771. }
  26772. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26773. proxy_tunnel_test::ScopedSSLServer origin;
  26774. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26775. origin.listen();
  26776. proxy_tunnel_test::ScopedConnectProxy proxy(
  26777. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26778. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26779. ASSERT_NE(0, proxy.port());
  26780. ws::WebSocketClient client(
  26781. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26782. client.enable_server_certificate_verification(false);
  26783. client.set_proxy("127.0.0.1", proxy.port());
  26784. client.set_proxy_bearer_token_auth("proxy-token");
  26785. auto res = client.connect();
  26786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26787. std::string msg;
  26788. ASSERT_TRUE(client.read(msg));
  26789. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26790. << "Proxy-Authorization must not be sent inside the tunnel";
  26791. client.close();
  26792. EXPECT_EQ(1, proxy.connect_hits());
  26793. }
  26794. #endif