test.cc 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. #ifdef CPPHTTPLIB_SSL_ENABLED
  492. bool match_hostname(const std::string &pattern, const std::string &hostname);
  493. #endif
  494. } // namespace detail
  495. } // namespace httplib
  496. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  497. struct {
  498. const char *line;
  499. const char *version;
  500. int status;
  501. const char *reason;
  502. } cases[] = {
  503. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  504. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  505. // The reason phrase may be empty, or left out along with its space.
  506. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  507. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  508. };
  509. for (const auto &c : cases) {
  510. std::string version;
  511. int status = 0;
  512. std::string reason = "unset";
  513. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  514. << c.line;
  515. EXPECT_EQ(c.version, version);
  516. EXPECT_EQ(c.status, status);
  517. EXPECT_EQ(c.reason, reason);
  518. }
  519. }
  520. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  521. const char *lines[] = {
  522. "HTTP/2 200 OK\r\n",
  523. "HTTP/1.2 200 OK\r\n",
  524. "HTTP/1.1 20 OK\r\n",
  525. "HTTP/1.1 2000 OK\r\n",
  526. "HTTP/1.1 2x0 OK\r\n",
  527. "HTTP/1.1 200 OK\r\n",
  528. "HTTP/1.1 200OK\r\n",
  529. "HTTP/1.1 200 O\rK\r\n",
  530. "HTTP/1.1 200 OK",
  531. "HTTP/1.1 200 OK\r\nX",
  532. "",
  533. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  534. "HTTP/1.1 200 OK\n",
  535. #endif
  536. };
  537. for (auto line : lines) {
  538. std::string version;
  539. int status = 0;
  540. std::string reason;
  541. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  542. << line;
  543. }
  544. }
  545. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  546. // Long enough to overflow the stack when matched with std::regex.
  547. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  548. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  549. std::string version;
  550. int status = 0;
  551. std::string reason;
  552. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  553. EXPECT_EQ(200, status);
  554. EXPECT_EQ(long_reason, reason);
  555. }
  556. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  557. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  558. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  559. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  560. EXPECT_EQ("", detail::file_extension("noext"));
  561. EXPECT_EQ("", detail::file_extension("a."));
  562. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  563. EXPECT_EQ("", detail::file_extension("a.b-c"));
  564. // Long enough to overflow the stack when matched with std::regex.
  565. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  566. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  567. }
  568. #ifdef CPPHTTPLIB_SSL_ENABLED
  569. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  570. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  573. // A wildcard needs two labels after it, in the leftmost label only
  574. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  575. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  576. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  577. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  578. EXPECT_FALSE(
  579. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  580. // No name may have an empty label
  581. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  582. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  583. }
  584. #endif
  585. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  586. detail::case_ignore::hash hash;
  587. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  588. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  589. // Long enough to overflow the stack if hashed one call per character.
  590. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  591. }
  592. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  593. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  594. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  595. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  596. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  597. // Same 26-bit hash as html, svg and js.
  598. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  601. }
  602. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  603. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  604. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  605. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  606. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  607. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  608. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  609. // Same 26-bit hash as application/json.
  610. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  611. }
  612. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  613. Request req;
  614. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  615. EXPECT_TRUE(req.is_multipart_form_data());
  616. std::string boundary;
  617. EXPECT_TRUE(detail::parse_multipart_boundary(
  618. req.get_header_value("Content-Type"), boundary));
  619. EXPECT_EQ("x", boundary);
  620. }
  621. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  622. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  623. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  624. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  625. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  626. // Same 26-bit hash as REMOTE_ADDR.
  627. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  628. }
  629. // Forward declaration: in split builds split.py strips `inline` and moves the
  630. // definition into httplib.cc, so detail::base64_encode is not visible from the
  631. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  632. // in both header-only and split builds.
  633. namespace httplib {
  634. namespace detail {
  635. std::string base64_encode(const std::string &in);
  636. } // namespace detail
  637. } // namespace httplib
  638. TEST(Base64EncodeTest, KnownAnswers) {
  639. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  640. // where the accumulator's top bit is already set before the next shift.
  641. EXPECT_EQ("", detail::base64_encode(""));
  642. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  643. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  644. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  645. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  646. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  647. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  648. // High bytes keep the top bit set across several rounds.
  649. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  650. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  651. }
  652. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  653. string unescapedCharacters = "-_.!~*'()";
  654. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  655. }
  656. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  657. string reservedCharacters = ";,/?:@&=+$";
  658. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  659. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  660. }
  661. TEST(ClientQueryOrder, PreserveOrder) {
  662. // This test reproduces Issue #2259: client may reorder query parameters
  663. // when sending a GET request. The expected behavior is that the client
  664. // preserves the original query string order when the caller supplied it
  665. // as part of the path.
  666. Server svr;
  667. svr.Get("/", [&](const Request &req, Response &res) {
  668. // Echo back the raw target so the test can assert ordering
  669. res.set_content(req.target, "text/plain");
  670. });
  671. std::thread t{[&] { svr.listen(HOST, PORT); }};
  672. auto se = detail::scope_exit([&] {
  673. svr.stop();
  674. t.join();
  675. ASSERT_FALSE(svr.is_running());
  676. });
  677. svr.wait_until_ready();
  678. Client cli(HOST, PORT);
  679. ASSERT_TRUE(cli.is_valid());
  680. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  681. auto res = cli.Get(original);
  682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  683. // Expect the echoed target to exactly match the original path (order
  684. // preserved)
  685. EXPECT_EQ(res->body, original);
  686. }
  687. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  688. string chineseCharacters = U8("中国語");
  689. string russianCharacters = U8("дом");
  690. string brazilianCharacters = U8("óculos");
  691. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  692. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  693. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  694. "%D0%B4%D0%BE%D0%BC");
  695. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  696. }
  697. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  698. string unescapedCharacters = "-_.!~*'()";
  699. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  700. }
  701. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  702. string reservedCharacters = ";,/?:@&=+$";
  703. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  704. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  705. }
  706. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  707. string chineseCharacters = U8("中国語");
  708. string russianCharacters = U8("дом");
  709. string brazilianCharacters = U8("óculos");
  710. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  711. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  712. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  713. "%D0%B4%D0%BE%D0%BC");
  714. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  715. }
  716. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  717. // Issue #2082 use case: encoding path component with ampersand
  718. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  719. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  720. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  721. }
  722. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  723. string unescapedCharacters = "-_.!~*'()";
  724. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  725. }
  726. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  727. string reservedCharacters = ";,/?:@&=+$#";
  728. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  729. }
  730. TEST(EncodeUriTest, TestUTF8Characters) {
  731. string chineseCharacters = U8("中国語");
  732. string russianCharacters = U8("дом");
  733. string brazilianCharacters = U8("óculos");
  734. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  735. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  736. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  737. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  738. }
  739. TEST(EncodeUriTest, TestCompleteUri) {
  740. string uri =
  741. "https://example.com/path/to/resource?query=value&param=test#fragment";
  742. EXPECT_EQ(
  743. httplib::encode_uri(uri),
  744. "https://example.com/path/to/resource?query=value&param=test#fragment");
  745. }
  746. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  747. string uri =
  748. "https://example.com/path with spaces/file name.html?q=hello world";
  749. EXPECT_EQ(httplib::encode_uri(uri),
  750. "https://example.com/path%20with%20spaces/"
  751. "file%20name.html?q=hello%20world");
  752. }
  753. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  754. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  755. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  756. }
  757. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  758. string unescapedCharacters = "-_.!~*'()";
  759. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  760. }
  761. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  762. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  763. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  764. string encodedBrazilian = "%C3%B3culos";
  765. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  767. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  768. }
  769. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  770. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  772. "Piri Tommy Villiers - on & on");
  773. }
  774. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  775. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  776. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  777. }
  778. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  779. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  780. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  781. }
  782. TEST(DecodeUriTest, TestUTF8Characters) {
  783. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  784. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  785. string encodedBrazilian = "%C3%B3culos";
  786. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  787. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  788. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  789. }
  790. TEST(DecodeUriTest, TestCompleteUri) {
  791. string encodedUri = "https://example.com/path%20with%20spaces/"
  792. "file%20name.html?q=hello%20world";
  793. EXPECT_EQ(
  794. httplib::decode_uri(encodedUri),
  795. "https://example.com/path with spaces/file name.html?q=hello world");
  796. }
  797. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  798. string original =
  799. "https://example.com/path with spaces/file name.html?q=hello world";
  800. string encoded = httplib::encode_uri(original);
  801. string decoded = httplib::decode_uri(encoded);
  802. EXPECT_EQ(decoded, original);
  803. }
  804. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  805. // decode_uri is the inverse of encode_uri: an escaped reserved character
  806. // stays encoded so it is not promoted into a real delimiter, while
  807. // non-reserved escapes still decode (like JS decodeURI).
  808. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  809. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  810. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  811. "%3F%3A%40%26%3D%2B%24%2C%3B");
  812. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  813. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  814. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  815. "http://example.com/a%2Fb");
  816. // decode_uri_component still decodes the reserved character.
  817. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  818. }
  819. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  820. string original = "Piri Tommy Villiers - on & on";
  821. string encoded = httplib::encode_uri_component(original);
  822. string decoded = httplib::decode_uri_component(encoded);
  823. EXPECT_EQ(decoded, original);
  824. }
  825. TEST(TrimTests, TrimStringTests) {
  826. EXPECT_EQ("abc", detail::trim_copy("abc"));
  827. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  828. EXPECT_TRUE(detail::trim_copy("").empty());
  829. }
  830. TEST(AsciiTest, LocaleIndependentClassification) {
  831. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  832. // which consult the global C locale: std::isalnum(0xC5) can return true
  833. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  834. // helpers must classify every byte by the ASCII grammar alone.
  835. for (int i = 0; i < 256; i++) {
  836. auto c = static_cast<char>(i);
  837. auto is_digit = i >= '0' && i <= '9';
  838. auto is_upper = i >= 'A' && i <= 'Z';
  839. auto is_lower = i >= 'a' && i <= 'z';
  840. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  841. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  842. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  843. << "byte " << i;
  844. }
  845. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  846. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  847. // Non-ASCII bytes must be percent-encoded, never passed through as
  848. // alphanumeric.
  849. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  850. }
  851. TEST(FromCharsTest, Double) {
  852. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  853. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  854. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  855. auto parse = [](const std::string &s, double &v) {
  856. return detail::from_chars(s.data(), s.data() + s.size(), v);
  857. };
  858. double v = -1.0;
  859. // Representative quality values.
  860. EXPECT_EQ(parse("0", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.0);
  862. EXPECT_EQ(parse("1", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 1.0);
  864. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.8);
  866. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.001);
  868. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. // A missing integer or fractional part is tolerated.
  871. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.5);
  873. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 5.0);
  875. // Values outside [0, 1] still parse; the caller range-checks them.
  876. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  877. EXPECT_DOUBLE_EQ(v, 123.456);
  878. // Stops at the first byte that is not part of the number and reports where.
  879. std::string trailing = "0.9, text/html";
  880. auto r = parse(trailing, v);
  881. EXPECT_EQ(r.ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 0.9);
  883. EXPECT_EQ(*r.ptr, ',');
  884. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  885. // outright, and an 'e'/'E' simply ends the number.
  886. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  888. std::string exp_input = "1.5e3";
  889. r = parse(exp_input, v);
  890. EXPECT_EQ(r.ec, std::errc{});
  891. EXPECT_DOUBLE_EQ(v, 1.5);
  892. EXPECT_EQ(*r.ptr, 'e');
  893. // Invalid inputs.
  894. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  898. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  899. // Pathological but well-formed inputs must stay bounded (no overflow, no
  900. // out-of-bounds table access) and stay within [0, 1] for the caller.
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  902. std::errc{});
  903. EXPECT_DOUBLE_EQ(v, 0.0);
  904. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  905. std::errc{});
  906. EXPECT_GE(v, 0.0);
  907. EXPECT_LE(v, 1.0);
  908. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  909. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  910. }
  911. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  912. // Simple case without quality values
  913. std::vector<std::string> result1;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html,application/json,text/plain", result1));
  916. EXPECT_EQ(result1.size(), 3U);
  917. EXPECT_EQ(result1[0], "text/html");
  918. EXPECT_EQ(result1[1], "application/json");
  919. EXPECT_EQ(result1[2], "text/plain");
  920. // With quality values
  921. std::vector<std::string> result2;
  922. EXPECT_TRUE(detail::parse_accept_header(
  923. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  924. EXPECT_EQ(result2.size(), 3U);
  925. EXPECT_EQ(result2[0], "application/json"); // highest q value
  926. EXPECT_EQ(result2[1], "text/html");
  927. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  928. }
  929. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  930. // Mixed with and without quality values
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(
  933. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  934. EXPECT_EQ(result.size(), 3U);
  935. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  936. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  937. EXPECT_EQ(result[2], "application/json"); // q=0.5
  938. }
  939. TEST(ParseAcceptHeaderTest, EdgeCases) {
  940. // Empty header
  941. std::vector<std::string> empty_result;
  942. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  943. EXPECT_TRUE(empty_result.empty());
  944. // Single type
  945. std::vector<std::string> single_result;
  946. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  947. EXPECT_EQ(single_result.size(), 1U);
  948. EXPECT_EQ(single_result[0], "application/json");
  949. // Wildcard types
  950. std::vector<std::string> wildcard_result;
  951. EXPECT_TRUE(detail::parse_accept_header(
  952. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  953. EXPECT_EQ(wildcard_result.size(), 3U);
  954. EXPECT_EQ(wildcard_result[0], "application/json");
  955. EXPECT_EQ(wildcard_result[1], "text/*");
  956. EXPECT_EQ(wildcard_result[2], "*/*");
  957. }
  958. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  959. // Common browser Accept header
  960. std::vector<std::string> browser_result;
  961. EXPECT_TRUE(
  962. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  963. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  964. browser_result));
  965. EXPECT_EQ(browser_result.size(), 6U);
  966. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  970. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  971. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  972. // API client header
  973. std::vector<std::string> api_result;
  974. EXPECT_TRUE(detail::parse_accept_header(
  975. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  976. api_result));
  977. EXPECT_EQ(api_result.size(), 3U);
  978. EXPECT_EQ(api_result[0], "application/json");
  979. EXPECT_EQ(api_result[1], "application/xml");
  980. EXPECT_EQ(api_result[2], "text/plain");
  981. }
  982. TEST(ParseAcceptHeaderTest, SpecialCases) {
  983. // Quality value with 3 decimal places
  984. std::vector<std::string> decimal_result;
  985. EXPECT_TRUE(detail::parse_accept_header(
  986. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  987. EXPECT_EQ(decimal_result.size(), 2U);
  988. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  989. EXPECT_EQ(decimal_result[1], "text/html");
  990. // Zero quality (should still be included but with lowest priority)
  991. std::vector<std::string> zero_q_result;
  992. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  993. zero_q_result));
  994. EXPECT_EQ(zero_q_result.size(), 2U);
  995. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  996. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  997. // No spaces around commas
  998. std::vector<std::string> no_space_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1001. no_space_result));
  1002. EXPECT_EQ(no_space_result.size(), 3U);
  1003. EXPECT_EQ(no_space_result[0], "text/html");
  1004. EXPECT_EQ(no_space_result[1], "application/json");
  1005. EXPECT_EQ(no_space_result[2], "text/plain");
  1006. }
  1007. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1008. // Quality values always use '.' as the decimal separator, so parsing must
  1009. // not depend on the process locale. An embedding application may have
  1010. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1011. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1012. std::string saved = cur ? cur : "C";
  1013. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1014. "fr_FR.UTF-8"};
  1015. bool switched = false;
  1016. for (const auto loc : comma_locales) {
  1017. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1018. std::localeconv()->decimal_point[0] == ',') {
  1019. switched = true;
  1020. break;
  1021. }
  1022. }
  1023. if (!switched) {
  1024. std::setlocale(LC_NUMERIC, saved.c_str());
  1025. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1026. }
  1027. // The higher-weighted type appears later in the list, so a correct parse
  1028. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1029. // sensitive parse reads both weights as 0 and leaves the original order.
  1030. std::vector<std::string> result;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "application/json;q=0.1,text/html;q=0.9", result));
  1033. ASSERT_EQ(result.size(), 2U);
  1034. EXPECT_EQ(result[0], "text/html");
  1035. EXPECT_EQ(result[1], "application/json");
  1036. std::setlocale(LC_NUMERIC, saved.c_str());
  1037. }
  1038. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1039. std::vector<std::string> result;
  1040. // Invalid quality value (> 1.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1043. // Invalid quality value (< 0.0)
  1044. EXPECT_FALSE(
  1045. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1046. // Invalid quality value (not a number)
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=invalid,application/json", result));
  1049. // A valid numeric prefix does not make the entire quality value valid.
  1050. EXPECT_FALSE(detail::parse_accept_header(
  1051. "text/html;q=0.5junk,application/json", result));
  1052. // Empty quality value
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("text/html;q=,application/json", result));
  1055. // Invalid media type format (no slash and not wildcard)
  1056. EXPECT_FALSE(
  1057. detail::parse_accept_header("invalidtype,application/json", result));
  1058. // Valid cases should still work
  1059. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*/*");
  1062. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "*");
  1065. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "text/*");
  1068. }
  1069. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1070. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1071. // and must not be answered with 400 Bad Request.
  1072. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1073. struct {
  1074. const char *value;
  1075. std::vector<std::string> expected;
  1076. } cases[] = {
  1077. {",application/json", {"application/json"}},
  1078. {"text/html,", {"text/html"}},
  1079. {"text/html,,*/*", {"text/html", "*/*"}},
  1080. // An empty element may be spelled with whitespace in it
  1081. {"text/html, , application/json", {"text/html", "application/json"}},
  1082. // Nothing but empty elements is an empty list, which means the same
  1083. // thing as no Accept header at all
  1084. {",,,", {}},
  1085. // Quality values still apply across ignored empty elements
  1086. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1087. };
  1088. for (const auto &c : cases) {
  1089. std::vector<std::string> result;
  1090. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1091. << "value: " << c.value;
  1092. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1093. }
  1094. // An invalid entry is still rejected when empty elements surround it
  1095. std::vector<std::string> result;
  1096. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1097. }
  1098. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1099. // or ';' inside one does not end the list element or the parameter. Section
  1100. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1101. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1102. struct {
  1103. const char *value;
  1104. std::vector<std::string> expected;
  1105. } cases[] = {
  1106. {"text/html;profile=\"a,b\",application/json",
  1107. {"text/html", "application/json"}},
  1108. // A "q=" inside a quoted value is not the weight
  1109. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1110. {"text/html", "application/json"}},
  1111. // The weight after a quoted value still applies
  1112. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1113. {"application/json", "text/html"}},
  1114. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1115. {"application/json", "text/html"}},
  1116. {"text/html;profile=\"a\\\"b\",application/json",
  1117. {"text/html", "application/json"}},
  1118. // An escaped backslash does not escape the '"' after it
  1119. {"text/html;profile=\"a\\\\\",application/json",
  1120. {"text/html", "application/json"}},
  1121. };
  1122. for (const auto &c : cases) {
  1123. std::vector<std::string> result;
  1124. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1125. << "value: " << c.value;
  1126. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1127. }
  1128. }
  1129. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1130. Server svr;
  1131. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1132. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1133. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1134. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1135. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1136. res.set_content("ok", "text/plain");
  1137. });
  1138. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1139. EXPECT_TRUE(false);
  1140. res.set_content("bad request", "text/plain");
  1141. });
  1142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1143. auto se = detail::scope_exit([&] {
  1144. svr.stop();
  1145. listen_thread.join();
  1146. ASSERT_FALSE(svr.is_running());
  1147. });
  1148. svr.wait_until_ready();
  1149. Client cli("localhost", PORT);
  1150. {
  1151. auto res = cli.Get(
  1152. "/accept_ok",
  1153. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. auto res = cli.Get("/accept_bad_request",
  1159. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1162. }
  1163. }
  1164. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1165. Server svr;
  1166. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1167. res.set_content("ok", "text/plain");
  1168. });
  1169. std::atomic<int> start_count{0};
  1170. std::atomic<bool> running_when_called{false};
  1171. svr.set_start_handler([&]() {
  1172. running_when_called = svr.is_running();
  1173. start_count++;
  1174. });
  1175. auto port = svr.bind_to_any_port(HOST);
  1176. std::thread t([&]() { svr.listen_after_bind(); });
  1177. auto se = detail::scope_exit([&] {
  1178. svr.stop();
  1179. t.join();
  1180. ASSERT_FALSE(svr.is_running());
  1181. });
  1182. svr.wait_until_ready();
  1183. // A successful request proves the accept loop is running, which the start
  1184. // handler precedes; so by now the handler must have run exactly once.
  1185. Client cli(HOST, port);
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. auto res = cli.Get("/");
  1188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. EXPECT_EQ(1, start_count.load());
  1191. EXPECT_TRUE(running_when_called.load());
  1192. }
  1193. TEST(DivideTest, DivideStringTests) {
  1194. auto divide = [](const std::string &str, char d) {
  1195. std::string lhs;
  1196. std::string rhs;
  1197. detail::divide(str, d,
  1198. [&](const char *lhs_data, std::size_t lhs_size,
  1199. const char *rhs_data, std::size_t rhs_size) {
  1200. lhs.assign(lhs_data, lhs_size);
  1201. rhs.assign(rhs_data, rhs_size);
  1202. });
  1203. return std::make_pair(std::move(lhs), std::move(rhs));
  1204. };
  1205. {
  1206. const auto res = divide("", '=');
  1207. EXPECT_EQ(res.first, "");
  1208. EXPECT_EQ(res.second, "");
  1209. }
  1210. {
  1211. const auto res = divide("=", '=');
  1212. EXPECT_EQ(res.first, "");
  1213. EXPECT_EQ(res.second, "");
  1214. }
  1215. {
  1216. const auto res = divide(" ", '=');
  1217. EXPECT_EQ(res.first, " ");
  1218. EXPECT_EQ(res.second, "");
  1219. }
  1220. {
  1221. const auto res = divide("a", '=');
  1222. EXPECT_EQ(res.first, "a");
  1223. EXPECT_EQ(res.second, "");
  1224. }
  1225. {
  1226. const auto res = divide("a=", '=');
  1227. EXPECT_EQ(res.first, "a");
  1228. EXPECT_EQ(res.second, "");
  1229. }
  1230. {
  1231. const auto res = divide("=b", '=');
  1232. EXPECT_EQ(res.first, "");
  1233. EXPECT_EQ(res.second, "b");
  1234. }
  1235. {
  1236. const auto res = divide("a=b", '=');
  1237. EXPECT_EQ(res.first, "a");
  1238. EXPECT_EQ(res.second, "b");
  1239. }
  1240. {
  1241. const auto res = divide("a=b=", '=');
  1242. EXPECT_EQ(res.first, "a");
  1243. EXPECT_EQ(res.second, "b=");
  1244. }
  1245. {
  1246. const auto res = divide("a=b=c", '=');
  1247. EXPECT_EQ(res.first, "a");
  1248. EXPECT_EQ(res.second, "b=c");
  1249. }
  1250. }
  1251. TEST(SplitTest, ParseQueryString) {
  1252. string s = "key1=val1&key2=val2&key3=val3";
  1253. Params dic;
  1254. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1255. [&](const char *b, const char *e) {
  1256. string key, val;
  1257. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1258. if (key.empty()) {
  1259. key.assign(b2, e2);
  1260. } else {
  1261. val.assign(b2, e2);
  1262. }
  1263. });
  1264. dic.emplace(key, val);
  1265. });
  1266. EXPECT_EQ("val1", dic.find("key1")->second);
  1267. EXPECT_EQ("val2", dic.find("key2")->second);
  1268. EXPECT_EQ("val3", dic.find("key3")->second);
  1269. }
  1270. TEST(SplitTest, ParseInvalidQueryTests) {
  1271. {
  1272. string s = " ";
  1273. Params dict;
  1274. detail::parse_query_text(s, dict);
  1275. EXPECT_TRUE(dict.empty());
  1276. }
  1277. {
  1278. string s = " = =";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. }
  1284. TEST(ParseQueryTest, ParseQueryString) {
  1285. {
  1286. std::string s = "key1=val1&key2=val2&key3=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("val1", dic.find("key1")->second);
  1290. EXPECT_EQ("val2", dic.find("key2")->second);
  1291. EXPECT_EQ("val3", dic.find("key3")->second);
  1292. }
  1293. {
  1294. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1295. Params dic;
  1296. detail::parse_query_text(s, dic);
  1297. EXPECT_EQ("", dic.find("key1")->second);
  1298. EXPECT_EQ("val1", dic.find("key2")->second);
  1299. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1300. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1301. }
  1302. }
  1303. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1304. Params dic;
  1305. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1306. dic.emplace("key1", "val1");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1308. dic.emplace("key2", "val2");
  1309. dic.emplace("key3", "val3");
  1310. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1311. }
  1312. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1313. Params params;
  1314. params.emplace("a", "1");
  1315. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1316. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1317. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1318. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1319. // Long enough to overflow the stack when matched with std::regex.
  1320. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1321. EXPECT_EQ("/p?" + long_query + "&a=1",
  1322. append_query_params("/p?" + long_query, params));
  1323. }
  1324. // Joins every entry of a Headers or Params into "key=value " so a whole
  1325. // traversal can be compared in one assertion. Both are instantiations of the
  1326. // same insertion-ordered container, so one helper serves both.
  1327. template <typename Map> static std::string entries_to_string(const Map &m) {
  1328. std::string s;
  1329. for (const auto &entry : m) {
  1330. s += entry.first + "=" + entry.second + " ";
  1331. }
  1332. return s;
  1333. }
  1334. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1335. // Params used to be a std::multimap, which sorted by name and handed the
  1336. // caller's query back alphabetised. A client signing its query string could
  1337. // not reproduce the order it asked for.
  1338. Params dic;
  1339. dic.emplace("zulu", "1");
  1340. dic.emplace("alpha", "2");
  1341. dic.emplace("mike", "3");
  1342. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1343. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1344. }
  1345. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1346. Params dic;
  1347. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1349. }
  1350. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1351. Request req;
  1352. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1353. req.params);
  1354. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag"));
  1356. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1357. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1358. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1359. EXPECT_EQ("", req.get_param_value("tag", 3));
  1360. }
  1361. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1362. // Params shares its container with Headers, which matches field names
  1363. // case-insensitively. Parameter names must not pick that up.
  1364. Params dic;
  1365. dic.emplace("Key", "upper");
  1366. dic.emplace("key", "lower");
  1367. EXPECT_EQ(2U, dic.size());
  1368. EXPECT_EQ(1U, dic.count("Key"));
  1369. EXPECT_EQ(1U, dic.count("key"));
  1370. EXPECT_EQ("upper", dic.find("Key")->second);
  1371. EXPECT_EQ("lower", dic.find("key")->second);
  1372. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1373. }
  1374. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1375. Server svr;
  1376. std::string order;
  1377. svr.Get("/order", [&](const Request &req, Response &res) {
  1378. order = entries_to_string(req.params);
  1379. res.set_content("ok", "text/plain");
  1380. });
  1381. auto port = svr.bind_to_any_port(HOST);
  1382. thread t = thread([&] { svr.listen_after_bind(); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. t.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, port);
  1390. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1391. ASSERT_TRUE(res);
  1392. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1393. }
  1394. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1395. Server svr;
  1396. std::string field_order, file_order;
  1397. svr.Post("/order", [&](const Request &req, Response &res) {
  1398. for (const auto &field : req.form.fields) {
  1399. field_order += field.first + "=" + field.second.content + " ";
  1400. }
  1401. for (const auto &file : req.form.files) {
  1402. file_order += file.first + "=" + file.second.filename + " ";
  1403. }
  1404. res.set_content("ok", "text/plain");
  1405. });
  1406. auto port = svr.bind_to_any_port(HOST);
  1407. thread t = thread([&] { svr.listen_after_bind(); });
  1408. auto se = detail::scope_exit([&] {
  1409. svr.stop();
  1410. t.join();
  1411. ASSERT_FALSE(svr.is_running());
  1412. });
  1413. svr.wait_until_ready();
  1414. UploadFormDataItems items = {
  1415. {"zulu", "1", "", ""},
  1416. {"alpha", "2", "", ""},
  1417. {"mike", "3", "", ""},
  1418. {"zebra", "z", "z.txt", "text/plain"},
  1419. {"apple", "a", "a.txt", "text/plain"},
  1420. };
  1421. Client cli(HOST, port);
  1422. auto res = cli.Post("/order", items);
  1423. ASSERT_TRUE(res);
  1424. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1425. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1426. }
  1427. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1428. Server svr;
  1429. std::vector<std::string> values;
  1430. std::string first, second, out_of_range, order;
  1431. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1432. values = req.form.get_fields("tag");
  1433. first = req.form.get_field("tag", 0);
  1434. second = req.form.get_field("tag", 1);
  1435. out_of_range = req.form.get_field("tag", 2);
  1436. for (const auto &field : req.form.fields) {
  1437. order += field.first + "=" + field.second.content + " ";
  1438. }
  1439. res.set_content("ok", "text/plain");
  1440. });
  1441. auto port = svr.bind_to_any_port(HOST);
  1442. thread t = thread([&] { svr.listen_after_bind(); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. t.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1450. // not adjacent in the container.
  1451. UploadFormDataItems items = {
  1452. {"tag", "first", "", ""},
  1453. {"other", "x", "", ""},
  1454. {"tag", "second", "", ""},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/repeated", items);
  1458. ASSERT_TRUE(res);
  1459. ASSERT_EQ(2U, values.size());
  1460. EXPECT_EQ("first", values[0]);
  1461. EXPECT_EQ("second", values[1]);
  1462. EXPECT_EQ("first", first);
  1463. EXPECT_EQ("second", second);
  1464. // std::multimap already kept entries sharing a name in insertion order, so
  1465. // everything above passes without this change too. The whole traversal is
  1466. // what tells the two apart: sorting by name would hoist "other" to the front
  1467. // and the two "tag" parts would end up adjacent.
  1468. EXPECT_EQ("tag=first other=x tag=second ", order);
  1469. // Advancing past the last entry of a name used to run off the container;
  1470. // the container's saturating increment makes it return the default instead.
  1471. EXPECT_EQ("", out_of_range);
  1472. }
  1473. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1474. Server svr;
  1475. std::string file_names;
  1476. svr.Post("/upload", [&](const Request &req, Response &res) {
  1477. for (const auto &file : req.form.files) {
  1478. file_names += file.first + "|" + file.second.filename + " ";
  1479. }
  1480. res.set_content("ok", "text/plain");
  1481. });
  1482. auto port = svr.bind_to_any_port(HOST);
  1483. thread t = thread([&] { svr.listen_after_bind(); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. t.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. // A trailing backslash would otherwise escape the closing quote.
  1491. UploadFormDataItems items = {
  1492. {"dir\\", "x", "a.txt", "text/plain"},
  1493. {"b", "y", "a\\\\b.txt", "text/plain"},
  1494. };
  1495. Client cli(HOST, port);
  1496. auto res = cli.Post("/upload", items);
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1499. }
  1500. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1501. // Server::read_content() keeps a FormFields::iterator alive across the
  1502. // content callbacks that fill the part it points at. The container is
  1503. // vector-backed, so a later emplace can reallocate and invalidate an older
  1504. // iterator; 64 parts grow the vector through seven reallocations, which
  1505. // checks that every part's content still lands in its own entry.
  1506. const size_t part_count = 64;
  1507. // One formula for both the parts sent and the values expected back, so the
  1508. // two cannot drift apart.
  1509. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1510. auto content_of = [](size_t i) {
  1511. return std::string(64, static_cast<char>('a' + (i % 26)));
  1512. };
  1513. Server svr;
  1514. std::vector<std::pair<std::string, std::string>> received;
  1515. svr.Post("/many", [&](const Request &req, Response &res) {
  1516. for (const auto &field : req.form.fields) {
  1517. received.emplace_back(field.first, field.second.content);
  1518. }
  1519. res.set_content("ok", "text/plain");
  1520. });
  1521. auto port = svr.bind_to_any_port(HOST);
  1522. thread t = thread([&] { svr.listen_after_bind(); });
  1523. auto se = detail::scope_exit([&] {
  1524. svr.stop();
  1525. t.join();
  1526. ASSERT_FALSE(svr.is_running());
  1527. });
  1528. svr.wait_until_ready();
  1529. UploadFormDataItems items;
  1530. for (size_t i = 0; i < part_count; i++) {
  1531. items.push_back({name_of(i), content_of(i), "", ""});
  1532. }
  1533. Client cli(HOST, port);
  1534. auto res = cli.Post("/many", items);
  1535. ASSERT_TRUE(res);
  1536. ASSERT_EQ(part_count, received.size());
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1539. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1540. }
  1541. }
  1542. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1543. string content_type = "multipart/form-data; boundary=something";
  1544. string boundary;
  1545. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(boundary, "something");
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1550. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1557. string content_type =
  1558. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1559. string boundary;
  1560. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1561. EXPECT_TRUE(ret);
  1562. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1565. string content_type =
  1566. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1567. string boundary;
  1568. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1569. EXPECT_TRUE(ret);
  1570. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1571. }
  1572. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1573. const string boundary(70, 'a');
  1574. string content_type = "multipart/form-data; boundary=" + boundary;
  1575. string parsed;
  1576. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1577. EXPECT_TRUE(ret);
  1578. EXPECT_EQ(parsed, boundary);
  1579. }
  1580. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1581. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1582. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1583. string parsed;
  1584. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1585. EXPECT_FALSE(ret);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1588. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1589. // is 72 characters on the wire and still valid.
  1590. const string boundary(70, 'a');
  1591. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1592. string parsed;
  1593. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1594. EXPECT_EQ(parsed, boundary);
  1595. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1596. parsed.clear();
  1597. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1598. }
  1599. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1600. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1601. // The parameter parser must not treat that '=' as the key/value separator.
  1602. string content_type =
  1603. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1604. "charset=UTF-8";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1608. }
  1609. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1610. // A ';' inside the quoted-string is part of the value, not a parameter
  1611. // separator, so it must not truncate the boundary.
  1612. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1613. string parsed;
  1614. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1615. EXPECT_EQ(parsed, "a;b");
  1616. }
  1617. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1621. EXPECT_EQ("a\\b", parsed);
  1622. EXPECT_TRUE(detail::parse_multipart_boundary(
  1623. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1624. EXPECT_EQ("a\"b", parsed);
  1625. }
  1626. TEST(ParseDispositionParamsTest, QuotedValues) {
  1627. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1628. // ';' and '=' are ordinary characters inside one.
  1629. struct {
  1630. const char *value;
  1631. std::vector<std::pair<const char *, const char *>> expected;
  1632. } cases[] = {
  1633. {"name=\"file1\"; filename=\"a.txt\"",
  1634. {{"name", "file1"}, {"filename", "a.txt"}}},
  1635. // Whitespace around '=' and ';' is still trimmed
  1636. {"name=\"file2\" ;filename = \"a.html\"",
  1637. {{"name", "file2"}, {"filename", "a.html"}}},
  1638. // '=' inside the value used to leave only the text after the last one
  1639. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1640. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1641. {"name=\"x=y\"", {{"name", "x=y"}}},
  1642. // ';' inside the value used to truncate the pair and leave a bogus one
  1643. {"name=\"file3\"; filename=\"a;b.txt\"",
  1644. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1645. // An unquoted value keeps working, and so does filename*
  1646. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1647. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1648. // A parameter with no key is dropped rather than turned into one whose
  1649. // key is the value
  1650. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1651. // An escaped quote does not end the value
  1652. {"name=\"a\\\"; filename=evil.php\"",
  1653. {{"name", "a\"; filename=evil.php"}}},
  1654. // Other backslashes, as in a Windows path, are kept
  1655. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1656. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1657. };
  1658. for (const auto &c : cases) {
  1659. Params params;
  1660. detail::parse_disposition_params(c.value, params);
  1661. for (const auto &kv : c.expected) {
  1662. auto it = params.find(kv.first);
  1663. ASSERT_NE(it, params.end())
  1664. << "value: " << c.value << ", key: " << kv.first;
  1665. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1666. }
  1667. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1668. }
  1669. }
  1670. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1671. Server svr;
  1672. std::string filename;
  1673. std::string content;
  1674. svr.Post("/upload", [&](const Request &req, Response &) {
  1675. const auto &file = req.form.get_file("file");
  1676. filename = file.filename;
  1677. content = file.content;
  1678. });
  1679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1680. auto se = detail::scope_exit([&] {
  1681. svr.stop();
  1682. thread.join();
  1683. ASSERT_FALSE(svr.is_running());
  1684. });
  1685. svr.wait_until_ready();
  1686. std::string body = "--B\r\n"
  1687. "Content-Disposition: form-data; name=\"file\"; "
  1688. "filename=\"a.txt\"\r\n"
  1689. "Content-Type: text/plain\r\n"
  1690. "\r\n"
  1691. "hello\r\n"
  1692. "--B--\r\n";
  1693. Client cli(HOST, PORT);
  1694. auto res = cli.Post(
  1695. "/upload",
  1696. [&](size_t offset, DataSink &sink) {
  1697. if (offset < body.size()) {
  1698. sink.write(&body[offset], 1);
  1699. } else {
  1700. sink.done();
  1701. }
  1702. return true;
  1703. },
  1704. "multipart/form-data; boundary=B");
  1705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1706. EXPECT_EQ(StatusCode::OK_200, res->status);
  1707. EXPECT_EQ("a.txt", filename);
  1708. EXPECT_EQ("hello", content);
  1709. }
  1710. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1711. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1712. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1713. Server svr;
  1714. std::string field_value, file_name, file_filename;
  1715. bool has_field = false, has_file = false;
  1716. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1717. has_field = req.form.has_field("x=y");
  1718. field_value = req.form.get_field("x=y");
  1719. has_file = req.form.has_file("file1");
  1720. const auto &file = req.form.get_file("file1");
  1721. file_name = file.name;
  1722. file_filename = file.filename;
  1723. res.set_content("ok", "text/plain");
  1724. });
  1725. auto port = svr.bind_to_any_port(HOST);
  1726. thread t = thread([&] { svr.listen_after_bind(); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. t.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. UploadFormDataItems items = {
  1734. {"x=y", "field-value", "", ""},
  1735. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1736. };
  1737. Client cli(HOST, port);
  1738. auto res = cli.Post("/quoted", items);
  1739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1740. ASSERT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_TRUE(has_field);
  1742. EXPECT_EQ("field-value", field_value);
  1743. EXPECT_TRUE(has_file);
  1744. EXPECT_EQ("file1", file_name);
  1745. EXPECT_EQ("a;b=report.pdf", file_filename);
  1746. }
  1747. TEST(GetHeaderValueTest, DefaultValue) {
  1748. Headers headers = {{"Dummy", "Dummy"}};
  1749. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1750. EXPECT_STREQ("text/plain", val);
  1751. }
  1752. TEST(GetHeaderValueTest, DefaultValueInt) {
  1753. Headers headers = {{"Dummy", "Dummy"}};
  1754. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1755. EXPECT_EQ(100ull, val);
  1756. }
  1757. TEST(GetHeaderValueTest, RegularValue) {
  1758. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1759. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1760. EXPECT_STREQ("text/html", val);
  1761. }
  1762. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1763. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1764. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1765. EXPECT_STREQ("text/html", val);
  1766. }
  1767. TEST(GetHeaderValueTest, SetContent) {
  1768. Response res;
  1769. res.set_content("html", "text/html");
  1770. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1771. res.set_content("text", "text/plain");
  1772. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1773. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueInt) {
  1776. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1778. EXPECT_EQ(100ull, val);
  1779. }
  1780. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1781. Headers headers = {{"Content-Length", "x"}};
  1782. auto is_invalid_value = false;
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1784. is_invalid_value);
  1785. EXPECT_EQ(0ull, val);
  1786. EXPECT_TRUE(is_invalid_value);
  1787. }
  1788. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1789. // An all-digit value that overflows size_t must be reported as invalid, not
  1790. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1791. // a large length to a small one on 32-bit builds, leaving the framing length
  1792. // wrong while is_invalid_value stayed false.
  1793. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1794. auto is_invalid_value = false;
  1795. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1796. is_invalid_value);
  1797. EXPECT_TRUE(is_invalid_value);
  1798. // A well-formed length is unaffected.
  1799. Headers ok = {{"Content-Length", "1234"}};
  1800. is_invalid_value = false;
  1801. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_EQ(1234ull, val);
  1804. EXPECT_FALSE(is_invalid_value);
  1805. }
  1806. TEST(GetHeaderValueTest, Range) {
  1807. {
  1808. Headers headers = {make_range_header({{1, -1}})};
  1809. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1810. EXPECT_STREQ("bytes=1-", val);
  1811. }
  1812. {
  1813. Headers headers = {make_range_header({{-1, 1}})};
  1814. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1815. EXPECT_STREQ("bytes=-1", val);
  1816. }
  1817. {
  1818. Headers headers = {make_range_header({{1, 10}})};
  1819. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1820. EXPECT_STREQ("bytes=1-10", val);
  1821. }
  1822. {
  1823. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1824. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1825. EXPECT_STREQ("bytes=1-10, 100-", val);
  1826. }
  1827. {
  1828. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1829. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1830. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1831. }
  1832. {
  1833. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1834. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1835. EXPECT_STREQ("bytes=0-0, -1", val);
  1836. }
  1837. }
  1838. TEST(BearerTokenAuthTest, SchemeValidation) {
  1839. // A value shorter than "Bearer " must not throw from the fixed-length
  1840. // substr, and a non-Bearer scheme must not be reported as a token.
  1841. struct {
  1842. const char *value;
  1843. const char *expected;
  1844. } cases[] = {
  1845. {"x", ""},
  1846. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1847. {"Bearer abc123", "abc123"},
  1848. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1849. };
  1850. for (const auto &c : cases) {
  1851. Request req;
  1852. req.set_header("Authorization", c.value);
  1853. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1854. }
  1855. }
  1856. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1857. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1858. // to depend on the standard library (libstdc++ handed back duplicates in
  1859. // reverse insertion order, libc++ in insertion order).
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "gzip");
  1862. req.set_header("Accept-Encoding", "deflate");
  1863. req.set_header("Accept-Encoding", "br");
  1864. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1866. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1867. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1868. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1869. }
  1870. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1871. Request req;
  1872. req.set_header("X-Test", "only");
  1873. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1875. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1876. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1877. }
  1878. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1879. Request req;
  1880. req.set_header("X-First", "1");
  1881. req.set_header("X-Test", "2");
  1882. req.params.emplace("first", "1");
  1883. req.params.emplace("test", "2");
  1884. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1885. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1886. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1887. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1888. // The second one is negative when read as a signed value
  1889. const auto max_id = (std::numeric_limits<size_t>::max)();
  1890. for (auto id : {max_id / 2, max_id}) {
  1891. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1892. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1893. EXPECT_EQ("", req.get_param_value("test", id));
  1894. EXPECT_EQ("", req.form.get_field("test", id));
  1895. EXPECT_EQ("", req.form.get_file("test", id).content);
  1896. }
  1897. }
  1898. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1899. Headers headers;
  1900. headers.emplace("Host", "example.com");
  1901. headers.emplace("Accept-Encoding", "gzip");
  1902. headers.emplace("User-Agent", "test");
  1903. headers.emplace("Accept-Encoding", "deflate");
  1904. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1905. "Accept-Encoding=deflate ",
  1906. entries_to_string(headers));
  1907. }
  1908. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1909. Headers headers = {{"Content-Type", "text/html"},
  1910. {"CONTENT-TYPE", "text/xml"}};
  1911. EXPECT_EQ(2U, headers.count("content-type"));
  1912. auto it = headers.find("content-type");
  1913. ASSERT_TRUE(it != headers.end());
  1914. EXPECT_EQ("text/html", it->second);
  1915. }
  1916. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1917. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1918. // drop only those fields and leave everything positioned between them.
  1919. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1920. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1921. auto rng = headers.equal_range("a");
  1922. headers.erase(rng.first, rng.second);
  1923. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1924. }
  1925. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1926. Headers headers = {
  1927. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1928. EXPECT_EQ(3U, headers.erase("A"));
  1929. EXPECT_EQ(0U, headers.count("A"));
  1930. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1933. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1934. headers.emplace_front("Host", "example.com");
  1935. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1936. entries_to_string(headers));
  1937. }
  1938. TEST(ParseHeaderValueTest, Range) {
  1939. {
  1940. Ranges ranges;
  1941. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1944. }
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1960. EXPECT_FALSE(ret);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1965. EXPECT_TRUE(ret);
  1966. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret =
  1971. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1990. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1991. EXPECT_FALSE(
  1992. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1993. EXPECT_TRUE(ranges.empty());
  1994. }
  1995. {
  1996. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1997. // remainder of the representation, so it stays accepted.
  1998. Ranges ranges;
  1999. auto ret =
  2000. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2001. EXPECT_TRUE(ret);
  2002. ASSERT_EQ(1u, ranges.size());
  2003. EXPECT_EQ(0, ranges[0].first);
  2004. EXPECT_EQ(-1, ranges[0].second);
  2005. }
  2006. // RFC 9110 14.1: range unit names are case-insensitive.
  2007. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2008. Ranges ranges;
  2009. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2010. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2011. }
  2012. }
  2013. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding", "gzip");
  2016. Response res;
  2017. res.set_header("Content-Type", "text/plain");
  2018. auto ret = detail::encoding_type(req, res);
  2019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2020. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2021. #else
  2022. EXPECT_TRUE(ret == detail::EncodingType::None);
  2023. #endif
  2024. }
  2025. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2033. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2034. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2035. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2036. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2037. #else
  2038. EXPECT_TRUE(ret == detail::EncodingType::None);
  2039. #endif
  2040. }
  2041. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2042. Request req;
  2043. req.set_header("Accept-Encoding",
  2044. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2045. Response res;
  2046. res.set_header("Content-Type", "text/plain");
  2047. auto ret = detail::encoding_type(req, res);
  2048. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2050. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2052. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2053. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2054. #else
  2055. EXPECT_TRUE(ret == detail::EncodingType::None);
  2056. #endif
  2057. }
  2058. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2059. // All supported encodings rejected with q=0 should return None
  2060. Request req;
  2061. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2062. Response res;
  2063. res.set_header("Content-Type", "text/plain");
  2064. auto ret = detail::encoding_type(req, res);
  2065. EXPECT_TRUE(ret == detail::EncodingType::None);
  2066. }
  2067. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2068. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2069. Request req;
  2070. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2071. Response res;
  2072. res.set_header("Content-Type", "text/plain");
  2073. auto ret = detail::encoding_type(req, res);
  2074. EXPECT_TRUE(ret == detail::EncodingType::None);
  2075. }
  2076. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2077. Request req;
  2078. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2079. Response res;
  2080. res.set_header("Content-Type", "text/plain");
  2081. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2082. }
  2083. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2084. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2085. Request req;
  2086. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2087. Response res;
  2088. res.set_header("Content-Type", "text/plain");
  2089. auto ret = detail::encoding_type(req, res);
  2090. EXPECT_TRUE(ret == detail::EncodingType::None);
  2091. }
  2092. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2093. // RFC 7231: Accept-Encoding values are case-insensitive
  2094. Request req;
  2095. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2096. Response res;
  2097. res.set_header("Content-Type", "text/plain");
  2098. auto ret = detail::encoding_type(req, res);
  2099. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2100. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2101. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2102. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2103. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2104. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2105. #else
  2106. EXPECT_TRUE(ret == detail::EncodingType::None);
  2107. #endif
  2108. }
  2109. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2110. // q value should determine priority, not hardcoded order
  2111. Request req;
  2112. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2113. Response res;
  2114. res.set_header("Content-Type", "text/plain");
  2115. auto ret = detail::encoding_type(req, res);
  2116. // gzip has highest q=1.0, so it should be selected even though
  2117. // br and zstd are also supported
  2118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2120. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2121. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2122. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2123. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2124. #else
  2125. EXPECT_TRUE(ret == detail::EncodingType::None);
  2126. #endif
  2127. }
  2128. TEST(BufferStreamTest, read) {
  2129. detail::BufferStream strm1;
  2130. Stream &strm = strm1;
  2131. EXPECT_EQ(5, strm.write("hello"));
  2132. char buf[512];
  2133. EXPECT_EQ(2, strm.read(buf, 2));
  2134. EXPECT_EQ('h', buf[0]);
  2135. EXPECT_EQ('e', buf[1]);
  2136. EXPECT_EQ(2, strm.read(buf, 2));
  2137. EXPECT_EQ('l', buf[0]);
  2138. EXPECT_EQ('l', buf[1]);
  2139. EXPECT_EQ(1, strm.read(buf, 1));
  2140. EXPECT_EQ('o', buf[0]);
  2141. EXPECT_EQ(0, strm.read(buf, 1));
  2142. }
  2143. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2144. auto host = "www.httpwatch.com";
  2145. auto ip = hosted_at(host);
  2146. EXPECT_EQ("23.96.13.243", ip);
  2147. std::vector<std::string> addrs;
  2148. hosted_at(host, addrs);
  2149. EXPECT_EQ(1u, addrs.size());
  2150. }
  2151. #if 0 // It depends on each test environment...
  2152. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2153. auto host = "www.youtube.com";
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(20u, addrs.size());
  2157. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2158. EXPECT_TRUE(it != addrs.end());
  2159. }
  2160. #endif
  2161. class ChunkedEncodingTest : public ::testing::Test {
  2162. protected:
  2163. ChunkedEncodingTest()
  2164. : cli_(HOST, PORT)
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. ,
  2167. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2168. #endif
  2169. {
  2170. cli_.set_connection_timeout(2);
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. cli_.enable_server_certificate_verification(false);
  2173. #endif
  2174. }
  2175. virtual void SetUp() {
  2176. read_file("./image.jpg", image_data_);
  2177. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2178. res.set_content("Hello World!", "text/plain");
  2179. });
  2180. svr_.Get(
  2181. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2182. res.set_chunked_content_provider(
  2183. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2184. size_t remaining = image_data_.size() - offset;
  2185. if (remaining == 0) {
  2186. sink.done();
  2187. } else {
  2188. constexpr size_t CHUNK_SIZE = 1024;
  2189. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2190. sink.write(&image_data_[offset], send_size);
  2191. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2192. }
  2193. return true;
  2194. });
  2195. });
  2196. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2197. svr_.wait_until_ready();
  2198. }
  2199. virtual void TearDown() {
  2200. svr_.stop();
  2201. if (!request_threads_.empty()) {
  2202. std::this_thread::sleep_for(std::chrono::seconds(1));
  2203. for (auto &t : request_threads_) {
  2204. t.join();
  2205. }
  2206. }
  2207. t_.join();
  2208. }
  2209. #ifdef CPPHTTPLIB_SSL_ENABLED
  2210. SSLClient cli_;
  2211. SSLServer svr_;
  2212. #else
  2213. Client cli_;
  2214. Server svr_;
  2215. #endif
  2216. thread t_;
  2217. std::vector<thread> request_threads_;
  2218. std::string image_data_;
  2219. };
  2220. TEST_F(ChunkedEncodingTest, NormalGet) {
  2221. auto res = cli_.Get("/chunked");
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. std::string out;
  2224. read_file("./image.jpg", out);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(out, res->body);
  2227. }
  2228. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2229. std::string body;
  2230. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2231. body.append(data, data_length);
  2232. return true;
  2233. });
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get(
  2243. "/chunked",
  2244. [&](const Response &response) {
  2245. EXPECT_EQ(StatusCode::OK_200, response.status);
  2246. return true;
  2247. },
  2248. [&](const char *data, size_t data_length) {
  2249. body.append(data, data_length);
  2250. return true;
  2251. });
  2252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2253. std::string out;
  2254. read_file("./image.jpg", out);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. EXPECT_EQ(out, body);
  2257. }
  2258. TEST(RangeTest, FromHTTPBin_Online) {
  2259. auto host = "httpbingo.org";
  2260. auto path = std::string{"/range/32"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(5);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. }
  2275. {
  2276. Headers headers = {make_range_header({{1, -1}})};
  2277. auto res = cli.Get(path, headers);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, 10}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijk", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2290. // entire resource, while the original httpbin returned 200. Both are
  2291. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2292. {
  2293. Headers headers = {make_range_header({{0, 31}})};
  2294. auto res = cli.Get(path, headers);
  2295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2296. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2297. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2298. res->status == StatusCode::PartialContent_206);
  2299. }
  2300. {
  2301. Headers headers = {make_range_header({{0, -1}})};
  2302. auto res = cli.Get(path, headers);
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2306. res->status == StatusCode::PartialContent_206);
  2307. }
  2308. // go-httpbin returns 206 with clamped range for over-range requests,
  2309. // while the original httpbin returned 416. Both behaviors are observed
  2310. // in real servers, so we only verify the request succeeds.
  2311. {
  2312. Headers headers = {make_range_header({{0, 32}})};
  2313. auto res = cli.Get(path, headers);
  2314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2315. }
  2316. }
  2317. TEST(RangeTest, IgnoredForPost) {
  2318. Server svr;
  2319. svr.Post("/", [](const Request &, Response &res) {
  2320. res.set_content("abcdefg", "text/plain");
  2321. });
  2322. auto port = svr.bind_to_any_port(HOST);
  2323. ASSERT_GT(port, 0);
  2324. thread t = thread([&] { svr.listen_after_bind(); });
  2325. auto se = detail::scope_exit([&] {
  2326. svr.stop();
  2327. t.join();
  2328. ASSERT_FALSE(svr.is_running());
  2329. });
  2330. svr.wait_until_ready();
  2331. Client cli(HOST, port);
  2332. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2333. auto res = cli.Post("/", Headers{{"Range", range}});
  2334. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2335. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2336. EXPECT_EQ("abcdefg", res->body) << range;
  2337. }
  2338. }
  2339. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2340. auto host = "unresolvableaddress.local";
  2341. auto path = std::string{"/"};
  2342. #ifdef CPPHTTPLIB_SSL_ENABLED
  2343. auto port = 443;
  2344. SSLClient cli(host, port);
  2345. #else
  2346. auto port = 80;
  2347. Client cli(host, port);
  2348. #endif
  2349. cli.set_connection_timeout(1);
  2350. {
  2351. auto res = cli.Get(path);
  2352. ASSERT_FALSE(res);
  2353. }
  2354. std::this_thread::sleep_for(std::chrono::seconds(8));
  2355. }
  2356. #if defined(__linux__) && defined(__GLIBC__) && \
  2357. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2358. // Forward declaration: in split builds split.py strips `inline` and moves the
  2359. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2360. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2361. // against the symbol in both header-only and split builds.
  2362. namespace httplib {
  2363. namespace detail {
  2364. int getaddrinfo_with_timeout(const char *node, const char *service,
  2365. const struct addrinfo *hints,
  2366. struct addrinfo **res, time_t timeout_sec);
  2367. } // namespace detail
  2368. } // namespace httplib
  2369. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2370. //
  2371. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2372. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2373. // gai_suspend() call hits the connection timeout the function calls
  2374. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2375. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2376. // still alive and still references the now-destroyed stack frame.
  2377. //
  2378. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2379. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2380. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2381. // and runs them in a container.
  2382. namespace {
  2383. bool should_run_issue_2431_tests() {
  2384. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2385. return v && *v && std::string(v) != "0";
  2386. }
  2387. std::string unique_unresolvable_host(int n) {
  2388. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2389. // glibc still asks the configured nameserver — which is exactly the path
  2390. // we want to exercise. A unique label per call avoids the resolver cache.
  2391. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2392. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2393. std::to_string(n) + ".invalid";
  2394. }
  2395. } // namespace
  2396. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2397. if (!should_run_issue_2431_tests()) {
  2398. GTEST_SKIP()
  2399. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2400. }
  2401. for (int i = 0; i < 8; ++i) {
  2402. struct addrinfo hints;
  2403. memset(&hints, 0, sizeof(hints));
  2404. hints.ai_family = AF_UNSPEC;
  2405. hints.ai_socktype = SOCK_STREAM;
  2406. auto host = unique_unresolvable_host(i);
  2407. struct addrinfo *result = nullptr;
  2408. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2409. &result, /*timeout_sec=*/1);
  2410. if (rc == 0 && result) { freeaddrinfo(result); }
  2411. }
  2412. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2413. // stack region they still believe holds their gaicb.
  2414. std::this_thread::sleep_for(std::chrono::seconds(3));
  2415. }
  2416. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2417. if (!should_run_issue_2431_tests()) {
  2418. GTEST_SKIP()
  2419. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2420. }
  2421. std::atomic<bool> stop{false};
  2422. std::vector<std::thread> threads;
  2423. for (int t = 0; t < 8; ++t) {
  2424. threads.emplace_back([t, &stop] {
  2425. int i = 0;
  2426. while (!stop.load(std::memory_order_relaxed)) {
  2427. struct addrinfo hints;
  2428. memset(&hints, 0, sizeof(hints));
  2429. hints.ai_family = AF_UNSPEC;
  2430. hints.ai_socktype = SOCK_STREAM;
  2431. auto host = unique_unresolvable_host(t * 100000 + i++);
  2432. struct addrinfo *result = nullptr;
  2433. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2434. &result, /*timeout_sec=*/1);
  2435. if (rc == 0 && result) { freeaddrinfo(result); }
  2436. }
  2437. });
  2438. }
  2439. std::this_thread::sleep_for(std::chrono::seconds(8));
  2440. stop.store(true, std::memory_order_relaxed);
  2441. for (auto &th : threads) {
  2442. th.join();
  2443. }
  2444. std::this_thread::sleep_for(std::chrono::seconds(3));
  2445. }
  2446. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2447. if (!should_run_issue_2431_tests()) {
  2448. GTEST_SKIP()
  2449. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2450. }
  2451. std::atomic<bool> stop{false};
  2452. std::vector<std::thread> threads;
  2453. for (int t = 0; t < 8; ++t) {
  2454. threads.emplace_back([t, &stop] {
  2455. int i = 0;
  2456. while (!stop.load(std::memory_order_relaxed)) {
  2457. auto host = unique_unresolvable_host(t * 100000 + i++);
  2458. Client cli(host, 80);
  2459. cli.set_connection_timeout(1, 0);
  2460. cli.set_read_timeout(1, 0);
  2461. cli.set_write_timeout(1, 0);
  2462. (void)cli.Get("/");
  2463. }
  2464. });
  2465. }
  2466. std::this_thread::sleep_for(std::chrono::seconds(8));
  2467. stop.store(true, std::memory_order_relaxed);
  2468. for (auto &th : threads) {
  2469. th.join();
  2470. }
  2471. std::this_thread::sleep_for(std::chrono::seconds(3));
  2472. }
  2473. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2474. TEST(ConnectionErrorTest, InvalidHost) {
  2475. auto host = "-abcde.com";
  2476. #ifdef CPPHTTPLIB_SSL_ENABLED
  2477. auto port = 443;
  2478. SSLClient cli(host, port);
  2479. #else
  2480. auto port = 80;
  2481. Client cli(host, port);
  2482. #endif
  2483. cli.set_connection_timeout(std::chrono::seconds(2));
  2484. auto res = cli.Get("/");
  2485. ASSERT_TRUE(!res);
  2486. EXPECT_EQ(Error::Connection, res.error());
  2487. }
  2488. TEST(ConnectionErrorTest, InvalidHost2) {
  2489. auto host = "httpcan.org/";
  2490. #ifdef CPPHTTPLIB_SSL_ENABLED
  2491. SSLClient cli(host);
  2492. #else
  2493. Client cli(host);
  2494. #endif
  2495. cli.set_connection_timeout(std::chrono::seconds(2));
  2496. auto res = cli.Get("/");
  2497. ASSERT_TRUE(!res);
  2498. EXPECT_EQ(Error::Connection, res.error());
  2499. }
  2500. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2501. auto host = "httpcan.org/";
  2502. #ifdef CPPHTTPLIB_SSL_ENABLED
  2503. SSLClient cli(host);
  2504. #else
  2505. Client cli(host);
  2506. #endif
  2507. cli.set_connection_timeout(std::chrono::seconds(2));
  2508. auto res = cli.Get("/");
  2509. ASSERT_TRUE(!res);
  2510. stringstream s;
  2511. s << "error code: " << res.error();
  2512. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2513. }
  2514. TEST(ConnectionErrorTest, InvalidPort) {
  2515. auto host = "localhost";
  2516. auto port = 44380;
  2517. #ifdef CPPHTTPLIB_SSL_ENABLED
  2518. SSLClient cli(host, port);
  2519. #else
  2520. Client cli(host, port);
  2521. #endif
  2522. cli.set_connection_timeout(std::chrono::seconds(2));
  2523. auto res = cli.Get("/");
  2524. ASSERT_TRUE(!res);
  2525. EXPECT_TRUE(Error::Connection == res.error() ||
  2526. Error::ConnectionTimeout == res.error());
  2527. }
  2528. TEST(ConnectionErrorTest, Timeout_Online) {
  2529. auto host = "google.com";
  2530. #ifdef CPPHTTPLIB_SSL_ENABLED
  2531. auto port = 44380;
  2532. SSLClient cli(host, port);
  2533. #else
  2534. auto port = 8080;
  2535. Client cli(host, port);
  2536. #endif
  2537. cli.set_connection_timeout(std::chrono::seconds(2));
  2538. // only probe one address type so that the error reason
  2539. // correlates to the timed-out IPv4, not the unsupported
  2540. // IPv6 connection attempt
  2541. cli.set_address_family(AF_INET);
  2542. auto res = cli.Get("/");
  2543. ASSERT_TRUE(!res);
  2544. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2545. }
  2546. TEST(CancelTest, NoCancel_Online) {
  2547. auto host = "httpbingo.org";
  2548. auto path = std::string{"/range/32"};
  2549. #ifdef CPPHTTPLIB_SSL_ENABLED
  2550. auto port = 443;
  2551. SSLClient cli(host, port);
  2552. #else
  2553. auto port = 80;
  2554. Client cli(host, port);
  2555. #endif
  2556. cli.set_connection_timeout(std::chrono::seconds(5));
  2557. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2559. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2560. EXPECT_EQ(StatusCode::OK_200, res->status);
  2561. }
  2562. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2563. // Use /bytes with a large payload so that the DownloadProgress callback
  2564. // (which only fires for Content-Length responses) is invoked before the
  2565. // entire body is received, giving cancellation a chance to fire.
  2566. auto host = "httpbingo.org";
  2567. auto path = std::string{"/bytes/524288"};
  2568. #ifdef CPPHTTPLIB_SSL_ENABLED
  2569. auto port = 443;
  2570. SSLClient cli(host, port);
  2571. #else
  2572. auto port = 80;
  2573. Client cli(host, port);
  2574. #endif
  2575. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2576. cli.set_connection_timeout(std::chrono::seconds(5));
  2577. ASSERT_TRUE(!res);
  2578. EXPECT_EQ(Error::Canceled, res.error());
  2579. }
  2580. TEST(CancelTest, WithCancelLargePayload_Online) {
  2581. auto host = "httpbingo.org";
  2582. auto path = std::string{"/bytes/524288"};
  2583. #ifdef CPPHTTPLIB_SSL_ENABLED
  2584. auto port = 443;
  2585. SSLClient cli(host, port);
  2586. #else
  2587. auto port = 80;
  2588. Client cli(host, port);
  2589. #endif
  2590. cli.set_connection_timeout(std::chrono::seconds(5));
  2591. uint32_t count = 0;
  2592. auto res =
  2593. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2594. ASSERT_TRUE(!res);
  2595. EXPECT_EQ(Error::Canceled, res.error());
  2596. }
  2597. TEST(CancelTest, NoCancelPost) {
  2598. Server svr;
  2599. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2600. res.set_content("Hello World!", "text/plain");
  2601. });
  2602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2603. auto se = detail::scope_exit([&] {
  2604. svr.stop();
  2605. thread.join();
  2606. ASSERT_FALSE(svr.is_running());
  2607. });
  2608. svr.wait_until_ready();
  2609. Client cli(HOST, PORT);
  2610. cli.set_connection_timeout(std::chrono::seconds(5));
  2611. auto res =
  2612. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2613. "application/json", [](uint64_t, uint64_t) { return true; });
  2614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2615. EXPECT_EQ("Hello World!", res->body);
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. }
  2618. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2619. Server svr;
  2620. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2621. res.set_content("Hello World!", "text/plain");
  2622. });
  2623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, PORT);
  2631. cli.set_connection_timeout(std::chrono::seconds(5));
  2632. auto res =
  2633. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2634. "application/json", [](uint64_t, uint64_t) { return false; });
  2635. ASSERT_TRUE(!res);
  2636. EXPECT_EQ(Error::Canceled, res.error());
  2637. }
  2638. TEST(CancelTest, WithCancelLargePayloadPost) {
  2639. Server svr;
  2640. svr.set_payload_max_length(200 * 1024 * 1024);
  2641. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2642. res.set_content(LARGE_DATA, "text/plain");
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. cli.set_payload_max_length(200 * 1024 * 1024);
  2653. cli.set_connection_timeout(std::chrono::seconds(5));
  2654. auto res =
  2655. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2656. "application/json", [](uint64_t, uint64_t) { return false; });
  2657. ASSERT_TRUE(!res);
  2658. EXPECT_EQ(Error::Canceled, res.error());
  2659. }
  2660. TEST(CancelTest, NoCancelPut) {
  2661. Server svr;
  2662. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2663. res.set_content("Hello World!", "text/plain");
  2664. });
  2665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2666. auto se = detail::scope_exit([&] {
  2667. svr.stop();
  2668. thread.join();
  2669. ASSERT_FALSE(svr.is_running());
  2670. });
  2671. svr.wait_until_ready();
  2672. Client cli(HOST, PORT);
  2673. cli.set_connection_timeout(std::chrono::seconds(5));
  2674. auto res =
  2675. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2676. "application/json", [](uint64_t, uint64_t) { return true; });
  2677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2678. EXPECT_EQ("Hello World!", res->body);
  2679. EXPECT_EQ(StatusCode::OK_200, res->status);
  2680. }
  2681. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2682. Server svr;
  2683. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2684. res.set_content("Hello World!", "text/plain");
  2685. });
  2686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2687. auto se = detail::scope_exit([&] {
  2688. svr.stop();
  2689. thread.join();
  2690. ASSERT_FALSE(svr.is_running());
  2691. });
  2692. svr.wait_until_ready();
  2693. Client cli(HOST, PORT);
  2694. cli.set_connection_timeout(std::chrono::seconds(5));
  2695. auto res =
  2696. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2697. "application/json", [](uint64_t, uint64_t) { return false; });
  2698. ASSERT_TRUE(!res);
  2699. EXPECT_EQ(Error::Canceled, res.error());
  2700. }
  2701. TEST(CancelTest, WithCancelLargePayloadPut) {
  2702. Server svr;
  2703. svr.set_payload_max_length(200 * 1024 * 1024);
  2704. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2705. res.set_content(LARGE_DATA, "text/plain");
  2706. });
  2707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2708. auto se = detail::scope_exit([&] {
  2709. svr.stop();
  2710. thread.join();
  2711. ASSERT_FALSE(svr.is_running());
  2712. });
  2713. svr.wait_until_ready();
  2714. Client cli(HOST, PORT);
  2715. cli.set_payload_max_length(200 * 1024 * 1024);
  2716. cli.set_connection_timeout(std::chrono::seconds(5));
  2717. auto res =
  2718. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2719. "application/json", [](uint64_t, uint64_t) { return false; });
  2720. ASSERT_TRUE(!res);
  2721. EXPECT_EQ(Error::Canceled, res.error());
  2722. }
  2723. TEST(CancelTest, NoCancelPatch) {
  2724. Server svr;
  2725. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2726. res.set_content("Hello World!", "text/plain");
  2727. });
  2728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2729. auto se = detail::scope_exit([&] {
  2730. svr.stop();
  2731. thread.join();
  2732. ASSERT_FALSE(svr.is_running());
  2733. });
  2734. svr.wait_until_ready();
  2735. Client cli(HOST, PORT);
  2736. cli.set_connection_timeout(std::chrono::seconds(5));
  2737. auto res =
  2738. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2739. "application/json", [](uint64_t, uint64_t) { return true; });
  2740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2741. EXPECT_EQ("Hello World!", res->body);
  2742. EXPECT_EQ(StatusCode::OK_200, res->status);
  2743. }
  2744. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2745. Server svr;
  2746. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2747. res.set_content("Hello World!", "text/plain");
  2748. });
  2749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2750. auto se = detail::scope_exit([&] {
  2751. svr.stop();
  2752. thread.join();
  2753. ASSERT_FALSE(svr.is_running());
  2754. });
  2755. svr.wait_until_ready();
  2756. Client cli(HOST, PORT);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. auto res =
  2759. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2760. "application/json", [](uint64_t, uint64_t) { return false; });
  2761. ASSERT_TRUE(!res);
  2762. EXPECT_EQ(Error::Canceled, res.error());
  2763. }
  2764. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2765. Server svr;
  2766. svr.set_payload_max_length(200 * 1024 * 1024);
  2767. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2768. res.set_content(LARGE_DATA, "text/plain");
  2769. });
  2770. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2771. auto se = detail::scope_exit([&] {
  2772. svr.stop();
  2773. thread.join();
  2774. ASSERT_FALSE(svr.is_running());
  2775. });
  2776. svr.wait_until_ready();
  2777. Client cli(HOST, PORT);
  2778. cli.set_payload_max_length(200 * 1024 * 1024);
  2779. cli.set_connection_timeout(std::chrono::seconds(5));
  2780. auto res =
  2781. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2782. "application/json", [](uint64_t, uint64_t) { return false; });
  2783. ASSERT_TRUE(!res);
  2784. EXPECT_EQ(Error::Canceled, res.error());
  2785. }
  2786. TEST(CancelTest, NoCancelDelete) {
  2787. Server svr;
  2788. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2789. res.set_content("Hello World!", "text/plain");
  2790. });
  2791. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2792. auto se = detail::scope_exit([&] {
  2793. svr.stop();
  2794. thread.join();
  2795. ASSERT_FALSE(svr.is_running());
  2796. });
  2797. svr.wait_until_ready();
  2798. Client cli(HOST, PORT);
  2799. cli.set_connection_timeout(std::chrono::seconds(5));
  2800. auto res =
  2801. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2802. "application/json", [](uint64_t, uint64_t) { return true; });
  2803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2804. EXPECT_EQ("Hello World!", res->body);
  2805. EXPECT_EQ(StatusCode::OK_200, res->status);
  2806. }
  2807. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2808. Server svr;
  2809. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2810. res.set_content("Hello World!", "text/plain");
  2811. });
  2812. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2813. auto se = detail::scope_exit([&] {
  2814. svr.stop();
  2815. thread.join();
  2816. ASSERT_FALSE(svr.is_running());
  2817. });
  2818. svr.wait_until_ready();
  2819. Client cli(HOST, PORT);
  2820. cli.set_connection_timeout(std::chrono::seconds(5));
  2821. auto res =
  2822. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2823. "application/json", [](uint64_t, uint64_t) { return false; });
  2824. ASSERT_TRUE(!res);
  2825. EXPECT_EQ(Error::Canceled, res.error());
  2826. }
  2827. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2828. Server svr;
  2829. svr.set_payload_max_length(200 * 1024 * 1024);
  2830. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2831. res.set_content(LARGE_DATA, "text/plain");
  2832. });
  2833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2834. auto se = detail::scope_exit([&] {
  2835. svr.stop();
  2836. thread.join();
  2837. ASSERT_FALSE(svr.is_running());
  2838. });
  2839. svr.wait_until_ready();
  2840. Client cli(HOST, PORT);
  2841. cli.set_payload_max_length(200 * 1024 * 1024);
  2842. cli.set_connection_timeout(std::chrono::seconds(5));
  2843. auto res =
  2844. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2845. "application/json", [](uint64_t, uint64_t) { return false; });
  2846. ASSERT_TRUE(!res);
  2847. EXPECT_EQ(Error::Canceled, res.error());
  2848. }
  2849. static std::string remove_whitespace(const std::string &input) {
  2850. std::string output;
  2851. output.reserve(input.size());
  2852. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2853. [](unsigned char c) { return !std::isspace(c); });
  2854. return output;
  2855. }
  2856. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2857. auto host = "httpbingo.org";
  2858. auto path = std::string{"/basic-auth/hello/world"};
  2859. #ifdef CPPHTTPLIB_SSL_ENABLED
  2860. auto port = 443;
  2861. SSLClient cli(host, port);
  2862. #else
  2863. auto port = 80;
  2864. Client cli(host, port);
  2865. #endif
  2866. {
  2867. auto res = cli.Get(path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2870. }
  2871. {
  2872. auto res = cli.Get(
  2873. path, Headers{make_basic_authentication_header("hello", "world")});
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. auto body = remove_whitespace(res->body);
  2876. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2877. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. {
  2881. cli.set_basic_auth("hello", "world");
  2882. auto res = cli.Get(path);
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. auto body = remove_whitespace(res->body);
  2885. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2886. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2887. EXPECT_EQ(StatusCode::OK_200, res->status);
  2888. }
  2889. {
  2890. cli.set_basic_auth("hello", "bad");
  2891. auto res = cli.Get(path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. cli.set_basic_auth("bad", "world");
  2897. auto res = cli.Get(path);
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2900. }
  2901. }
  2902. #ifdef CPPHTTPLIB_SSL_ENABLED
  2903. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2904. auto host = "httpbingo.org";
  2905. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2906. auto paths = std::vector<std::string>{
  2907. "/digest-auth/auth/hello/world/MD5",
  2908. "/digest-auth/auth/hello/world/SHA-256",
  2909. };
  2910. auto port = 443;
  2911. SSLClient cli(host, port);
  2912. {
  2913. auto res = cli.Get(unauth_path);
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2916. }
  2917. {
  2918. cli.set_digest_auth("hello", "world");
  2919. for (const auto &path : paths) {
  2920. auto res = cli.Get(path.c_str());
  2921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2922. auto body = remove_whitespace(res->body);
  2923. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2924. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2925. EXPECT_EQ(StatusCode::OK_200, res->status);
  2926. }
  2927. cli.set_digest_auth("hello", "bad");
  2928. for (const auto &path : paths) {
  2929. auto res = cli.Get(path.c_str());
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2932. }
  2933. }
  2934. }
  2935. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2936. // comma-separated list of challenges, and each challenge may itself carry a
  2937. // comma-separated auth-param list, so a server can legally offer Basic
  2938. // before Digest, either as two field lines or packed into one. Runs one 401
  2939. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2940. // value() joins them in receipt order) and checks that the retry carries a
  2941. // well-formed Digest Authorization header naming expected_realm.
  2942. static void
  2943. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2944. const std::string &expected_realm) {
  2945. std::atomic<int> hits{0};
  2946. Server svr;
  2947. svr.Get("/x", [&](const Request &req, Response &res) {
  2948. if (++hits == 1) {
  2949. res.status = StatusCode::Unauthorized_401;
  2950. for (const auto &challenge : challenges) {
  2951. res.set_header("WWW-Authenticate", challenge);
  2952. }
  2953. } else {
  2954. auto authorization = req.get_header_value("Authorization");
  2955. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2956. EXPECT_NE(std::string::npos,
  2957. authorization.find("realm=\"" + expected_realm + "\""));
  2958. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2959. res.set_content("ok", "text/plain");
  2960. }
  2961. });
  2962. auto port = svr.bind_to_any_port(HOST);
  2963. std::thread t([&]() { svr.listen_after_bind(); });
  2964. auto se = detail::scope_exit([&] {
  2965. svr.stop();
  2966. t.join();
  2967. });
  2968. svr.wait_until_ready();
  2969. Client cli(HOST, port);
  2970. cli.set_digest_auth("hello", "world");
  2971. auto res = cli.Get("/x");
  2972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2973. EXPECT_EQ(2, hits.load());
  2974. }
  2975. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2976. static const char *kDigestChallenge =
  2977. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2978. "algorithm=MD5";
  2979. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2980. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2981. "testrealm");
  2982. }
  2983. // Same challenge list with the schemes in the opposite order, to make sure
  2984. // the fix above didn't just special-case "Basic first".
  2985. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2986. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2987. "testrealm");
  2988. }
  2989. // A comma inside a quoted auth-param value must not be mistaken for the
  2990. // separator between two challenges (or two auth-params).
  2991. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2992. run_digest_challenge_list_test(
  2993. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2994. "algorithm=MD5"},
  2995. "test,realm");
  2996. }
  2997. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2998. // the params and leaves out the fragment.
  2999. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3000. Server svr;
  3001. std::string uri, target;
  3002. svr.Get("/a b", [&](const Request &req, Response &res) {
  3003. auto auth = req.get_header_value("Authorization");
  3004. if (auth.empty()) {
  3005. res.status = StatusCode::Unauthorized_401;
  3006. res.set_header("WWW-Authenticate",
  3007. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3008. return;
  3009. }
  3010. auto b = auth.find("uri=\"") + 5;
  3011. uri = auth.substr(b, auth.find('"', b) - b);
  3012. target = req.target;
  3013. });
  3014. auto port = svr.bind_to_any_port(HOST);
  3015. std::thread t([&]() { svr.listen_after_bind(); });
  3016. auto se = detail::scope_exit([&] {
  3017. svr.stop();
  3018. t.join();
  3019. });
  3020. svr.wait_until_ready();
  3021. Client cli(HOST, port);
  3022. cli.set_digest_auth("hello", "world");
  3023. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3025. EXPECT_EQ("/a%20b?x=1", target);
  3026. EXPECT_EQ(target, uri);
  3027. }
  3028. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3029. // make_digest_authentication_header() dereferences both unconditionally, so
  3030. // a server sending a challenge missing either one must not be treated as
  3031. // usable -- doing so used to crash the client with std::out_of_range.
  3032. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3033. Server svr;
  3034. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3035. res.status = StatusCode::Unauthorized_401;
  3036. res.set_header("WWW-Authenticate", challenge);
  3037. });
  3038. auto port = svr.bind_to_any_port(HOST);
  3039. std::thread t([&]() { svr.listen_after_bind(); });
  3040. auto se = detail::scope_exit([&] {
  3041. svr.stop();
  3042. t.join();
  3043. });
  3044. svr.wait_until_ready();
  3045. Client cli(HOST, port);
  3046. cli.set_digest_auth("hello", "world");
  3047. auto res = cli.Get("/x");
  3048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3049. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3050. }
  3051. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3052. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3053. }
  3054. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3055. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3056. }
  3057. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3058. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3059. }
  3060. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3061. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3062. // when storing the values, so the header builder has to re-escape them (and
  3063. // keep algorithm a bare token); otherwise the value breaks out of its
  3064. // quoted-string and injects extra auth-params into the client's Authorization.
  3065. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3066. std::atomic<int> hits{0};
  3067. std::string authorization;
  3068. Server svr;
  3069. svr.Get("/x", [&](const Request &req, Response &res) {
  3070. if (++hits == 1) {
  3071. res.status = StatusCode::Unauthorized_401;
  3072. // On the wire the quotes embedded in the values are backslash-escaped.
  3073. res.set_header("WWW-Authenticate",
  3074. "Digest realm=\"testrealm\", "
  3075. "nonce=\"n\\\"; injected=\\\"x\", "
  3076. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3077. } else {
  3078. authorization = req.get_header_value("Authorization");
  3079. res.set_content("ok", "text/plain");
  3080. }
  3081. });
  3082. auto port = svr.bind_to_any_port(HOST);
  3083. std::thread t([&]() { svr.listen_after_bind(); });
  3084. auto se = detail::scope_exit([&] {
  3085. svr.stop();
  3086. t.join();
  3087. });
  3088. svr.wait_until_ready();
  3089. Client cli(HOST, port);
  3090. cli.set_digest_auth("hello", "world");
  3091. auto res = cli.Get("/x");
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. EXPECT_EQ(2, hits.load());
  3094. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3095. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3096. // inside its quoted-string rather than starting an "injected" auth-param.
  3097. EXPECT_NE(std::string::npos,
  3098. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3099. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3100. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3101. }
  3102. #endif
  3103. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3104. auto host = "google.com";
  3105. auto another_host = "example.com";
  3106. auto wrong_ip = "0.0.0.0";
  3107. #ifdef CPPHTTPLIB_SSL_ENABLED
  3108. SSLClient cli(host);
  3109. #else
  3110. Client cli(host);
  3111. #endif
  3112. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3113. auto res = cli.Get("/");
  3114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3115. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3116. }
  3117. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3118. auto host = "google.com";
  3119. auto wrong_ip = "0.0.0.0";
  3120. #ifdef CPPHTTPLIB_SSL_ENABLED
  3121. SSLClient cli(host);
  3122. #else
  3123. Client cli(host);
  3124. #endif
  3125. cli.set_hostname_addr_map({{host, wrong_ip}});
  3126. auto res = cli.Get("/");
  3127. ASSERT_TRUE(!res);
  3128. EXPECT_EQ(Error::Connection, res.error());
  3129. }
  3130. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3131. // A mapped value that is not an IP literal must be resolved. "localhost"
  3132. // resolves from the hosts file, so this test needs no external DNS.
  3133. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3134. auto host = "target.invalid";
  3135. Server svr;
  3136. std::string received_host;
  3137. svr.Get("/hi", [&](const Request &req, Response &res) {
  3138. received_host = req.get_header_value("Host");
  3139. res.set_content("Hello World!", "text/plain");
  3140. });
  3141. auto port = svr.bind_to_any_port(HOST);
  3142. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. thread.join();
  3146. ASSERT_FALSE(svr.is_running());
  3147. });
  3148. svr.wait_until_ready();
  3149. Client cli(host, port);
  3150. cli.set_hostname_addr_map({{host, HOST}});
  3151. auto res = cli.Get("/hi");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. // The mapping only redirects the connection; the identity stays host_.
  3155. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3156. }
  3157. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3158. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3159. auto host = "target.invalid";
  3160. Server svr;
  3161. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3162. res.set_content("Hello World!", "text/plain");
  3163. });
  3164. auto port = svr.bind_to_any_port("127.0.0.1");
  3165. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3166. auto se = detail::scope_exit([&] {
  3167. svr.stop();
  3168. thread.join();
  3169. ASSERT_FALSE(svr.is_running());
  3170. });
  3171. svr.wait_until_ready();
  3172. Client cli(host, port);
  3173. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3174. auto res = cli.Get("/hi");
  3175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3176. EXPECT_EQ(StatusCode::OK_200, res->status);
  3177. }
  3178. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3179. // An empty mapped value must leave host_ as the connection target. Without
  3180. // that guard the empty value would become the host argument, getaddrinfo
  3181. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3182. // loopback - silently connecting somewhere the caller never asked for.
  3183. // The server listens on loopback, so such a fallback would succeed and is
  3184. // therefore observable as a failure of this test.
  3185. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3186. Server svr;
  3187. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3188. res.set_content("Hello World!", "text/plain");
  3189. });
  3190. auto port = svr.bind_to_any_port(HOST);
  3191. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3192. auto se = detail::scope_exit([&] {
  3193. svr.stop();
  3194. thread.join();
  3195. ASSERT_FALSE(svr.is_running());
  3196. });
  3197. svr.wait_until_ready();
  3198. Client cli(blackhole, port);
  3199. cli.set_hostname_addr_map({{blackhole, ""}});
  3200. cli.set_connection_timeout(1);
  3201. auto res = cli.Get("/hi");
  3202. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3203. }
  3204. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3205. auto host = "httpbingo.org";
  3206. auto path = std::string{"/absolute-redirect/3"};
  3207. #ifdef CPPHTTPLIB_SSL_ENABLED
  3208. SSLClient cli(host);
  3209. #else
  3210. Client cli(host);
  3211. #endif
  3212. cli.set_follow_location(true);
  3213. auto res = cli.Get(path);
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. }
  3217. TEST(RedirectTest, Redirect_Online) {
  3218. auto host = "httpbingo.org";
  3219. auto path = std::string{"/redirect/3"};
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(host);
  3222. #else
  3223. Client cli(host);
  3224. #endif
  3225. cli.set_follow_location(true);
  3226. auto res = cli.Get(path);
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. }
  3230. TEST(RelativeRedirectTest, Redirect_Online) {
  3231. auto host = "httpbingo.org";
  3232. auto path = std::string{"/relative-redirect/3"};
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. SSLClient cli(host);
  3235. #else
  3236. Client cli(host);
  3237. #endif
  3238. cli.set_follow_location(true);
  3239. auto res = cli.Get(path);
  3240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. }
  3243. TEST(TooManyRedirectTest, Redirect_Online) {
  3244. auto host = "httpbingo.org";
  3245. auto path = std::string{"/redirect/21"};
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. SSLClient cli(host);
  3248. #else
  3249. Client cli(host);
  3250. #endif
  3251. cli.set_follow_location(true);
  3252. auto res = cli.Get(path);
  3253. ASSERT_TRUE(!res);
  3254. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3255. }
  3256. #ifdef CPPHTTPLIB_SSL_ENABLED
  3257. TEST(YahooRedirectTest, Redirect_Online) {
  3258. Client cli("yahoo.com");
  3259. auto res = cli.Get("/");
  3260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3261. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3262. cli.set_follow_location(true);
  3263. res = cli.Get("/");
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3267. }
  3268. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3269. #define REDIR_HOST "httpbingo.org"
  3270. #define REDIR_PATH "/redirect-to"
  3271. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3272. SSLClient cli(REDIR_HOST);
  3273. cli.set_follow_location(true);
  3274. auto res =
  3275. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. }
  3279. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3280. SSLClient cli(REDIR_HOST);
  3281. cli.set_follow_location(true);
  3282. Params params;
  3283. params.emplace("url", "http://example.com");
  3284. params.emplace("status_code", "302");
  3285. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3290. SSLClient cli(REDIR_HOST);
  3291. cli.set_follow_location(true);
  3292. Params params;
  3293. params.emplace("url", "http://example.com");
  3294. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. TEST(UrlWithSpace, Redirect_Online) {
  3299. SSLClient cli("edge.forgecdn.net");
  3300. cli.set_follow_location(true);
  3301. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. EXPECT_EQ(StatusCode::OK_200, res->status);
  3304. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3305. }
  3306. #endif
  3307. #if !defined(_WIN32) && !defined(_WIN64)
  3308. TEST(ReceiveSignals, Signal) {
  3309. auto setupSignalHandlers = []() {
  3310. struct sigaction act;
  3311. sigemptyset(&act.sa_mask);
  3312. act.sa_flags = SA_SIGINFO;
  3313. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3314. switch (sig) {
  3315. case SIGINT:
  3316. default: break;
  3317. }
  3318. };
  3319. ::sigaction(SIGINT, &act, nullptr);
  3320. };
  3321. Server svr;
  3322. int port = 0;
  3323. auto thread = std::thread([&]() {
  3324. setupSignalHandlers();
  3325. port = svr.bind_to_any_port(HOST);
  3326. svr.listen_after_bind();
  3327. });
  3328. auto se = detail::scope_exit([&] {
  3329. svr.stop();
  3330. thread.join();
  3331. ASSERT_FALSE(svr.is_running());
  3332. });
  3333. svr.wait_until_ready();
  3334. ASSERT_TRUE(svr.is_running());
  3335. pthread_kill(thread.native_handle(), SIGINT);
  3336. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3337. ASSERT_TRUE(svr.is_running());
  3338. }
  3339. #endif
  3340. TEST(RedirectToDifferentPort, Redirect) {
  3341. Server svr1;
  3342. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3343. res.set_content("Hello World!", "text/plain");
  3344. });
  3345. int svr1_port = 0;
  3346. auto thread1 = std::thread([&]() {
  3347. svr1_port = svr1.bind_to_any_port(HOST);
  3348. svr1.listen_after_bind();
  3349. });
  3350. Server svr2;
  3351. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3352. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3353. });
  3354. int svr2_port = 0;
  3355. auto thread2 = std::thread([&]() {
  3356. svr2_port = svr2.bind_to_any_port(HOST);
  3357. svr2.listen_after_bind();
  3358. });
  3359. auto se = detail::scope_exit([&] {
  3360. svr2.stop();
  3361. thread2.join();
  3362. svr1.stop();
  3363. thread1.join();
  3364. ASSERT_FALSE(svr2.is_running());
  3365. ASSERT_FALSE(svr1.is_running());
  3366. });
  3367. svr1.wait_until_ready();
  3368. svr2.wait_until_ready();
  3369. Client cli("localhost", svr2_port);
  3370. cli.set_follow_location(true);
  3371. auto res = cli.Get("/2");
  3372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3373. EXPECT_EQ(StatusCode::OK_200, res->status);
  3374. EXPECT_EQ("Hello World!", res->body);
  3375. }
  3376. // GET /redir on one server redirects to /target on another port, so the
  3377. // client follows it with a new client.
  3378. static Result
  3379. GetThroughRedirectToDifferentPort(Server::Handler target,
  3380. const std::function<void(Client &)> &setup,
  3381. const Headers &headers = Headers()) {
  3382. Server target_svr;
  3383. target_svr.Get("/target", target);
  3384. int target_port = 0;
  3385. auto target_thread = std::thread([&]() {
  3386. target_port = target_svr.bind_to_any_port(HOST);
  3387. target_svr.listen_after_bind();
  3388. });
  3389. Server origin_svr;
  3390. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3391. res.set_redirect(
  3392. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3393. });
  3394. int origin_port = 0;
  3395. auto origin_thread = std::thread([&]() {
  3396. origin_port = origin_svr.bind_to_any_port(HOST);
  3397. origin_svr.listen_after_bind();
  3398. });
  3399. auto se = detail::scope_exit([&] {
  3400. origin_svr.stop();
  3401. origin_thread.join();
  3402. target_svr.stop();
  3403. target_thread.join();
  3404. });
  3405. target_svr.wait_until_ready();
  3406. origin_svr.wait_until_ready();
  3407. Client cli("localhost", origin_port);
  3408. cli.set_follow_location(true);
  3409. setup(cli);
  3410. return cli.Get("/redir", headers);
  3411. }
  3412. static void
  3413. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3414. std::string captured_authorization;
  3415. auto result = GetThroughRedirectToDifferentPort(
  3416. [&](const Request &req, Response &res) {
  3417. captured_authorization = req.get_header_value("Authorization");
  3418. res.set_content("OK", "text/plain");
  3419. },
  3420. set_auth);
  3421. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3422. EXPECT_EQ(StatusCode::OK_200, result->status);
  3423. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3424. EXPECT_TRUE(captured_authorization.empty());
  3425. }
  3426. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3427. TestDoNotForwardCredentialsOnRedirect(
  3428. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3429. }
  3430. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3431. TestDoNotForwardCredentialsOnRedirect(
  3432. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3433. }
  3434. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3435. std::string captured_cookie;
  3436. auto result = GetThroughRedirectToDifferentPort(
  3437. [&](const Request &req, Response &res) {
  3438. captured_cookie = req.get_header_value("Cookie");
  3439. res.set_content("OK", "text/plain");
  3440. },
  3441. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3442. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3443. EXPECT_EQ(StatusCode::OK_200, result->status);
  3444. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3445. EXPECT_TRUE(captured_cookie.empty());
  3446. }
  3447. TEST(RedirectToSamePort, ForwardCookie) {
  3448. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3449. // header so that ordinary session flows keep working.
  3450. Server svr;
  3451. std::string captured_cookie;
  3452. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3453. res.set_redirect("/target", 302);
  3454. });
  3455. svr.Get("/target", [&](const Request &req, Response &res) {
  3456. captured_cookie = req.get_header_value("Cookie");
  3457. res.set_content("OK", "text/plain");
  3458. });
  3459. auto port = svr.bind_to_any_port(HOST);
  3460. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3461. auto se = detail::scope_exit([&] {
  3462. svr.stop();
  3463. thread.join();
  3464. ASSERT_FALSE(svr.is_running());
  3465. });
  3466. svr.wait_until_ready();
  3467. Client cli(HOST, port);
  3468. cli.set_follow_location(true);
  3469. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3470. auto res = cli.Get("/redir", headers);
  3471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3472. EXPECT_EQ(StatusCode::OK_200, res->status);
  3473. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3474. }
  3475. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3476. std::string authorization;
  3477. std::string trace_id;
  3478. auto result = GetThroughRedirectToDifferentPort(
  3479. [&](const Request &req, Response &res) {
  3480. authorization = req.get_header_value("Authorization");
  3481. trace_id = req.get_header_value("X-Trace-Id");
  3482. res.set_content("OK", "text/plain");
  3483. },
  3484. [](Client &cli) {
  3485. cli.set_default_headers(
  3486. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3487. });
  3488. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3489. EXPECT_EQ(StatusCode::OK_200, result->status);
  3490. // Like a header given with the request, a default one goes along unless it
  3491. // carries credentials (RFC 9110 15.4).
  3492. EXPECT_TRUE(authorization.empty());
  3493. EXPECT_EQ("42", trace_id);
  3494. }
  3495. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3496. auto result = GetThroughRedirectToDifferentPort(
  3497. [](const Request &, Response &res) {
  3498. res.set_content(std::string(2048, 'x'), "text/plain");
  3499. },
  3500. [](Client &cli) { cli.set_payload_max_length(1024); });
  3501. EXPECT_FALSE(result);
  3502. }
  3503. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3504. auto result = GetThroughRedirectToDifferentPort(
  3505. [](const Request &req, Response &res) {
  3506. // Answer after a second, or once the client gives up.
  3507. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3508. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3509. }
  3510. res.set_content("late", "text/plain");
  3511. },
  3512. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3513. ASSERT_FALSE(result);
  3514. EXPECT_EQ(Error::Read, result.error());
  3515. }
  3516. #ifdef CPPHTTPLIB_SSL_ENABLED
  3517. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3518. auto result = GetThroughRedirectToDifferentPort(
  3519. [](const Request &, Response &res) {
  3520. res.status = StatusCode::Unauthorized_401;
  3521. res.set_header("WWW-Authenticate",
  3522. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3523. },
  3524. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3525. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3526. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3527. }
  3528. #endif
  3529. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3530. Server svr;
  3531. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3532. // Port number that overflows int — should not crash
  3533. res.set_redirect("http://localhost:99999999999999999999/target");
  3534. });
  3535. auto port = svr.bind_to_any_port(HOST);
  3536. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3537. auto se = detail::scope_exit([&] {
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. });
  3542. svr.wait_until_ready();
  3543. Client cli(HOST, port);
  3544. cli.set_follow_location(true);
  3545. auto res = cli.Get("/redir");
  3546. // Should fail gracefully, not crash (no valid response due to bad port)
  3547. EXPECT_FALSE(res);
  3548. }
  3549. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3550. Server svr;
  3551. auto port = svr.bind_to_any_port(HOST);
  3552. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3553. // The server's own port followed by junk must not be followed
  3554. res.set_redirect("http://" + std::string(HOST) + ":" +
  3555. std::to_string(port) + "junk/target");
  3556. });
  3557. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3558. res.set_content("target", "text/plain");
  3559. });
  3560. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3561. auto se = detail::scope_exit([&] {
  3562. svr.stop();
  3563. thread.join();
  3564. ASSERT_FALSE(svr.is_running());
  3565. });
  3566. svr.wait_until_ready();
  3567. Client cli(HOST, port);
  3568. cli.set_follow_location(true);
  3569. auto res = cli.Get("/redir");
  3570. EXPECT_FALSE(res);
  3571. }
  3572. TEST(RedirectFromPageWithContent, Redirect) {
  3573. Server svr;
  3574. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3575. res.set_content("___", "text/plain");
  3576. res.set_redirect("/2");
  3577. });
  3578. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3579. res.set_content("Hello World!", "text/plain");
  3580. });
  3581. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3582. auto se = detail::scope_exit([&] {
  3583. svr.stop();
  3584. th.join();
  3585. ASSERT_FALSE(svr.is_running());
  3586. });
  3587. svr.wait_until_ready();
  3588. {
  3589. Client cli("localhost", PORT);
  3590. cli.set_follow_location(true);
  3591. std::string body;
  3592. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3593. body.append(data, data_length);
  3594. return true;
  3595. });
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ(StatusCode::OK_200, res->status);
  3598. EXPECT_EQ("Hello World!", body);
  3599. }
  3600. {
  3601. Client cli("localhost", PORT);
  3602. std::string body;
  3603. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3604. body.append(data, data_length);
  3605. return true;
  3606. });
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ(StatusCode::Found_302, res->status);
  3609. EXPECT_EQ("___", body);
  3610. }
  3611. }
  3612. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3613. Server svr;
  3614. auto port_str = std::to_string(PORT);
  3615. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3616. auto expected_host = "[::1]:" + port_str;
  3617. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3618. res.set_content("___", "text/plain");
  3619. // res.set_redirect("/2");
  3620. res.set_redirect(redirect_url);
  3621. });
  3622. svr.Get("/2", [&](const Request &req, Response &res) {
  3623. auto host_header = req.headers.find("Host");
  3624. ASSERT_TRUE(host_header != req.headers.end());
  3625. EXPECT_EQ(expected_host, host_header->second);
  3626. res.set_content("Hello World!", "text/plain");
  3627. });
  3628. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3629. auto se = detail::scope_exit([&] {
  3630. svr.stop();
  3631. th.join();
  3632. ASSERT_FALSE(svr.is_running());
  3633. });
  3634. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3635. // actually starts anything, so the condition !svr.is_running() will
  3636. // always remain true, and the loop never stops.
  3637. // This basically counts how many milliseconds have passed since the
  3638. // call to svr.listen(), and if after 5 seconds nothing started yet
  3639. // aborts the test.
  3640. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3641. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3642. ASSERT_LT(milliseconds, 5000U);
  3643. }
  3644. {
  3645. Client cli("::1", PORT);
  3646. cli.set_follow_location(true);
  3647. std::string body;
  3648. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3649. body.append(data, data_length);
  3650. return true;
  3651. });
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::OK_200, res->status);
  3654. EXPECT_EQ("Hello World!", body);
  3655. }
  3656. {
  3657. Client cli("::1", PORT);
  3658. std::string body;
  3659. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3660. body.append(data, data_length);
  3661. return true;
  3662. });
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::Found_302, res->status);
  3665. EXPECT_EQ("___", body);
  3666. }
  3667. }
  3668. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3669. Server svr;
  3670. svr.Get("/foo", [](const Request &req, Response &res) {
  3671. auto a = req.params.find("a");
  3672. if (a != req.params.end()) {
  3673. res.set_content((*a).second, "text/plain");
  3674. res.status = StatusCode::OK_200;
  3675. } else {
  3676. res.status = StatusCode::BadRequest_400;
  3677. }
  3678. });
  3679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3680. auto se = detail::scope_exit([&] {
  3681. svr.stop();
  3682. thread.join();
  3683. ASSERT_FALSE(svr.is_running());
  3684. });
  3685. svr.wait_until_ready();
  3686. {
  3687. Client cli(HOST, PORT);
  3688. cli.set_path_encode(false);
  3689. auto res = cli.Get("/foo?a=explicitly+encoded");
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. // This expects it back with a space, as the `+` won't have been
  3693. // url-encoded, and server-side the params get decoded turning `+`
  3694. // into spaces.
  3695. EXPECT_EQ("explicitly encoded", res->body);
  3696. }
  3697. }
  3698. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3699. // When path encoding is disabled the client must transmit the supplied
  3700. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3701. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3702. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3703. // than a space (0x20). Assert on the raw wire target to catch this.
  3704. Server svr;
  3705. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3706. svr.Get("/foo", [&](const Request &req, Response &res) {
  3707. EXPECT_EQ(expected_target, req.target);
  3708. res.status = StatusCode::OK_200;
  3709. });
  3710. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3711. auto se = detail::scope_exit([&] {
  3712. svr.stop();
  3713. thread.join();
  3714. ASSERT_FALSE(svr.is_running());
  3715. });
  3716. svr.wait_until_ready();
  3717. {
  3718. Client cli(HOST, PORT);
  3719. cli.set_path_encode(false);
  3720. auto res = cli.Get(expected_target.c_str());
  3721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3722. EXPECT_EQ(StatusCode::OK_200, res->status);
  3723. }
  3724. }
  3725. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3726. // `open_stream()` used to skip the path encoding that the buffered send
  3727. // path applies, so the same `path` produced different bytes in the request
  3728. // line depending on which API was used. Assert the two agree.
  3729. Server svr;
  3730. std::string target;
  3731. svr.Get(".*", [&](const Request &req, Response &res) {
  3732. target = req.target;
  3733. res.status = StatusCode::OK_200;
  3734. });
  3735. auto port = svr.bind_to_any_port(HOST);
  3736. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3737. auto se = detail::scope_exit([&] {
  3738. svr.stop();
  3739. thread.join();
  3740. ASSERT_FALSE(svr.is_running());
  3741. });
  3742. svr.wait_until_ready();
  3743. struct {
  3744. const char *path;
  3745. const char *expected;
  3746. } cases[] = {
  3747. {"/a b?x=1", "/a%20b?x=1"},
  3748. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3749. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3750. };
  3751. for (const auto &c : cases) {
  3752. Client cli(HOST, port);
  3753. target.clear();
  3754. auto res = cli.Get(c.path);
  3755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3756. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3757. auto buffered_target = target;
  3758. target.clear();
  3759. auto handle = cli.open_stream("GET", c.path);
  3760. EXPECT_TRUE(handle.is_valid())
  3761. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3762. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3763. }
  3764. }
  3765. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3766. // The `set_path_encode(false)` contract — transmit the supplied target
  3767. // verbatim — must hold for the streaming API too.
  3768. Server svr;
  3769. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3770. std::string target;
  3771. svr.Get("/foo", [&](const Request &req, Response &res) {
  3772. target = req.target;
  3773. res.status = StatusCode::OK_200;
  3774. });
  3775. auto port = svr.bind_to_any_port(HOST);
  3776. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3777. auto se = detail::scope_exit([&] {
  3778. svr.stop();
  3779. thread.join();
  3780. ASSERT_FALSE(svr.is_running());
  3781. });
  3782. svr.wait_until_ready();
  3783. {
  3784. Client cli(HOST, port);
  3785. cli.set_path_encode(false);
  3786. auto handle = cli.open_stream("GET", expected_target);
  3787. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3788. EXPECT_EQ(expected_target, target);
  3789. }
  3790. }
  3791. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3792. // With path encoding enabled a CR/LF in the target is percent-encoded
  3793. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3794. // write_request_line still backstops `set_path_encode(false)`, which is
  3795. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3796. Server svr;
  3797. // Captured before routing: the decoded path contains a newline, which a
  3798. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3799. std::string target;
  3800. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3801. target = req.target;
  3802. res.status = StatusCode::OK_200;
  3803. return Server::HandlerResponse::Handled;
  3804. });
  3805. auto port = svr.bind_to_any_port(HOST);
  3806. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3807. auto se = detail::scope_exit([&] {
  3808. svr.stop();
  3809. thread.join();
  3810. ASSERT_FALSE(svr.is_running());
  3811. });
  3812. svr.wait_until_ready();
  3813. {
  3814. Client cli(HOST, port);
  3815. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3816. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3817. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3818. }
  3819. }
  3820. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3821. // Every control character is percent-encoded, not just CR/LF, so the target
  3822. // passes the request-target check in write_request_line.
  3823. Server svr;
  3824. std::string target;
  3825. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3826. target = req.target;
  3827. res.status = StatusCode::OK_200;
  3828. return Server::HandlerResponse::Handled;
  3829. });
  3830. auto port = svr.bind_to_any_port(HOST);
  3831. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3832. auto se = detail::scope_exit([&] {
  3833. svr.stop();
  3834. thread.join();
  3835. ASSERT_FALSE(svr.is_running());
  3836. });
  3837. svr.wait_until_ready();
  3838. {
  3839. Client cli(HOST, port);
  3840. auto res = cli.Get("/a\tb\x1b\x7f");
  3841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3842. EXPECT_EQ("/a%09b%1B%7F", target);
  3843. }
  3844. }
  3845. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3846. // Nothing may reach the wire: a raw CR/LF target would split the request
  3847. // line and inject headers.
  3848. Server svr;
  3849. // Pre-routing so that "not called" means nothing reached the server at all,
  3850. // rather than merely failing to match a handler pattern.
  3851. auto handler_called = false;
  3852. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3853. handler_called = true;
  3854. res.status = StatusCode::OK_200;
  3855. return Server::HandlerResponse::Handled;
  3856. });
  3857. auto port = svr.bind_to_any_port(HOST);
  3858. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3859. auto se = detail::scope_exit([&] {
  3860. svr.stop();
  3861. thread.join();
  3862. ASSERT_FALSE(svr.is_running());
  3863. });
  3864. svr.wait_until_ready();
  3865. {
  3866. Client cli(HOST, port);
  3867. cli.set_path_encode(false);
  3868. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3869. EXPECT_FALSE(handle.is_valid());
  3870. EXPECT_EQ(Error::Write, handle.error);
  3871. EXPECT_FALSE(handler_called);
  3872. }
  3873. }
  3874. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3875. // Which of the two branches runs is decided by whether the query component
  3876. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3877. // an empty query and must still fall back to building one from
  3878. // `req.params`, while a non-empty query must win over `req.params`.
  3879. Server svr;
  3880. std::string target;
  3881. svr.Get("/foo", [&](const Request &req, Response &res) {
  3882. target = req.target;
  3883. res.status = StatusCode::OK_200;
  3884. });
  3885. auto port = svr.bind_to_any_port(HOST);
  3886. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3887. auto se = detail::scope_exit([&] {
  3888. svr.stop();
  3889. thread.join();
  3890. ASSERT_FALSE(svr.is_running());
  3891. });
  3892. svr.wait_until_ready();
  3893. {
  3894. // Trailing `?` -> empty query component -> `req.params` is used.
  3895. Client cli(HOST, port);
  3896. Request req;
  3897. req.method = "GET";
  3898. req.path = "/foo?";
  3899. req.params.emplace("a", "1");
  3900. target.clear();
  3901. auto res = cli.send(req);
  3902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3903. EXPECT_EQ("/foo?a=1", target);
  3904. }
  3905. {
  3906. // Non-empty query in `req.path` -> `req.params` is not appended.
  3907. Client cli(HOST, port);
  3908. Request req;
  3909. req.method = "GET";
  3910. req.path = "/foo?b=2";
  3911. req.params.emplace("a", "1");
  3912. target.clear();
  3913. auto res = cli.send(req);
  3914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3915. EXPECT_EQ("/foo?b=2", target);
  3916. }
  3917. }
  3918. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3919. Server svr;
  3920. svr.Get("/", [](const Request &req, Response &) {
  3921. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3922. });
  3923. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3924. auto se = detail::scope_exit([&] {
  3925. svr.stop();
  3926. thread.join();
  3927. ASSERT_FALSE(svr.is_running());
  3928. });
  3929. svr.wait_until_ready();
  3930. {
  3931. Client cli(HOST, PORT);
  3932. cli.set_path_encode(false);
  3933. auto res = cli.Get("/?something=%0A");
  3934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3935. EXPECT_EQ(StatusCode::OK_200, res->status);
  3936. }
  3937. }
  3938. TEST(BindServerTest, BindDualStack) {
  3939. Server svr;
  3940. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3941. res.set_content("Hello World!", "text/plain");
  3942. });
  3943. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3944. auto se = detail::scope_exit([&] {
  3945. svr.stop();
  3946. thread.join();
  3947. ASSERT_FALSE(svr.is_running());
  3948. });
  3949. svr.wait_until_ready();
  3950. {
  3951. Client cli("127.0.0.1", PORT);
  3952. auto res = cli.Get("/1");
  3953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. {
  3958. Client cli("::1", PORT);
  3959. auto res = cli.Get("/1");
  3960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3961. EXPECT_EQ(StatusCode::OK_200, res->status);
  3962. EXPECT_EQ("Hello World!", res->body);
  3963. }
  3964. }
  3965. TEST(BindServerTest, BindAndListenSeparately) {
  3966. Server svr;
  3967. int port = svr.bind_to_any_port("0.0.0.0");
  3968. ASSERT_TRUE(svr.is_valid());
  3969. ASSERT_TRUE(port > 0);
  3970. svr.stop();
  3971. }
  3972. // Reports whether anything is still listening on a loopback port. A plain
  3973. // connect() is used instead of a Client request because a socket left bound by
  3974. // mistake accepts the connection into its backlog and never answers, which
  3975. // would hang the test instead of failing it.
  3976. static bool is_loopback_port_accepting(int port) {
  3977. sockaddr_in addr{};
  3978. addr.sin_family = AF_INET;
  3979. addr.sin_port = htons(static_cast<uint16_t>(port));
  3980. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3981. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3982. EXPECT_NE(sock, INVALID_SOCKET);
  3983. if (sock == INVALID_SOCKET) { return false; }
  3984. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3985. static_cast<socklen_t>(sizeof(addr)));
  3986. detail::close_socket(sock);
  3987. return ret == 0;
  3988. }
  3989. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3990. Server svr;
  3991. auto port = svr.bind_to_any_port("127.0.0.1");
  3992. ASSERT_TRUE(port > 0);
  3993. svr.stop();
  3994. // bind_to_any_port() already called listen(2), so until stop() closed the
  3995. // descriptor the port kept accepting connections into the backlog. ASSERT
  3996. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3997. // below blocks forever in the accept loop.
  3998. ASSERT_FALSE(is_loopback_port_accepting(port));
  3999. // Nothing is left to accept on, so listen_after_bind() must report failure
  4000. // instead of returning success without ever serving.
  4001. EXPECT_FALSE(svr.listen_after_bind());
  4002. // The failed listen marks the server decommissioned, so a waiter returns
  4003. // instead of spinning forever.
  4004. svr.wait_until_ready();
  4005. }
  4006. #ifdef CPPHTTPLIB_SSL_ENABLED
  4007. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4009. CLIENT_CA_CERT_DIR);
  4010. int port = svr.bind_to_any_port("0.0.0.0");
  4011. ASSERT_TRUE(svr.is_valid());
  4012. ASSERT_TRUE(port > 0);
  4013. svr.stop();
  4014. }
  4015. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4016. // or a rejected CustomRoute() registration would not stop the server binding.
  4017. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4019. CLIENT_CA_CERT_DIR);
  4020. ASSERT_TRUE(svr.is_valid());
  4021. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4022. EXPECT_FALSE(svr.is_valid());
  4023. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4024. }
  4025. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4026. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4027. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4028. int port = svr.bind_to_any_port("0.0.0.0");
  4029. ASSERT_TRUE(svr.is_valid());
  4030. ASSERT_TRUE(port > 0);
  4031. svr.stop();
  4032. }
  4033. TEST(BindServerTest, UpdateCertsPem) {
  4034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4035. int port = svr.bind_to_any_port("0.0.0.0");
  4036. ASSERT_TRUE(svr.is_valid());
  4037. ASSERT_TRUE(port > 0);
  4038. // Read PEM files
  4039. std::string cert_pem, key_pem, ca_pem;
  4040. read_file(SERVER_CERT_FILE, cert_pem);
  4041. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4042. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4043. // Update server certificates using PEM API
  4044. ASSERT_TRUE(
  4045. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4046. ASSERT_TRUE(svr.is_valid());
  4047. svr.stop();
  4048. }
  4049. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4050. // Start server with client CA (enables client auth)
  4051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4052. ASSERT_TRUE(svr.is_valid());
  4053. bool handler_called = false;
  4054. svr.Get("/test", [&](const Request &req, Response &res) {
  4055. handler_called = true;
  4056. // Verify client certificate is present
  4057. auto cert = req.peer_cert();
  4058. EXPECT_TRUE(static_cast<bool>(cert));
  4059. res.set_content("ok", "text/plain");
  4060. });
  4061. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4062. auto se = detail::scope_exit([&] {
  4063. svr.stop();
  4064. t.join();
  4065. ASSERT_FALSE(svr.is_running());
  4066. });
  4067. svr.wait_until_ready();
  4068. // Read PEM files
  4069. std::string cert_pem, key_pem, ca_pem;
  4070. read_file(SERVER_CERT_FILE, cert_pem);
  4071. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4072. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4073. // Update server certificates and client CA using PEM API while server running
  4074. ASSERT_TRUE(
  4075. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4076. // Connect with client certificate
  4077. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4078. cli.enable_server_certificate_verification(false);
  4079. cli.set_connection_timeout(30);
  4080. auto res = cli.Get("/test");
  4081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4082. ASSERT_EQ(StatusCode::OK_200, res->status);
  4083. ASSERT_TRUE(handler_called);
  4084. EXPECT_EQ("ok", res->body);
  4085. }
  4086. // Puts a CA that did not sign the client's certificate in the old one's place.
  4087. static bool replace_client_ca(SSLServer &svr) {
  4088. std::string cert_pem, key_pem, ca_pem;
  4089. read_file(SERVER_CERT_FILE, cert_pem);
  4090. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4091. read_file(SERVER_CERT2_FILE, ca_pem);
  4092. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4093. ca_pem.c_str());
  4094. }
  4095. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4097. ASSERT_TRUE(svr.is_valid());
  4098. svr.Get("/test", [](const Request &, Response &res) {
  4099. res.set_content("ok", "text/plain");
  4100. });
  4101. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4102. auto se = detail::scope_exit([&] {
  4103. svr.stop();
  4104. t.join();
  4105. ASSERT_FALSE(svr.is_running());
  4106. });
  4107. svr.wait_until_ready();
  4108. auto get = [] {
  4109. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4110. cli.enable_server_certificate_verification(false);
  4111. return cli.Get("/test");
  4112. };
  4113. ASSERT_TRUE(get());
  4114. ASSERT_TRUE(replace_client_ca(svr));
  4115. EXPECT_FALSE(get());
  4116. }
  4117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4118. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4120. ASSERT_TRUE(svr.is_valid());
  4121. tls::set_verify_callback(svr.tls_context(),
  4122. [](const tls::VerifyContext &) -> bool {
  4123. throw std::runtime_error("verify");
  4124. });
  4125. svr.Get("/test", [](const Request &, Response &res) {
  4126. res.set_content("ok", "text/plain");
  4127. });
  4128. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4129. auto se = detail::scope_exit([&] {
  4130. svr.stop();
  4131. t.join();
  4132. ASSERT_FALSE(svr.is_running());
  4133. });
  4134. svr.wait_until_ready();
  4135. auto get = [] {
  4136. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4137. cli.enable_server_certificate_verification(false);
  4138. return cli.Get("/test");
  4139. };
  4140. EXPECT_FALSE(get());
  4141. // The handshake is over, so an update does not wait for it.
  4142. std::string cert_pem, key_pem;
  4143. read_file(SERVER_CERT_FILE, cert_pem);
  4144. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4145. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4146. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4147. return v.preverify_ok;
  4148. });
  4149. auto res = get();
  4150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4151. EXPECT_EQ("ok", res->body);
  4152. }
  4153. #endif
  4154. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4155. // Sends each request over a new connection with a client certificate,
  4156. // resuming the session of the one before when there is one.
  4157. class ResumingClient {
  4158. public:
  4159. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4160. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4161. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4162. SSL_FILETYPE_PEM);
  4163. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4164. // callback, not through SSL_get1_session().
  4165. SSL_CTX_set_app_data(ctx_, this);
  4166. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4167. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4168. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4169. auto self = static_cast<ResumingClient *>(
  4170. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4171. SSL_SESSION_free(self->session_);
  4172. self->session_ = session;
  4173. return 1; // Keeps the reference
  4174. });
  4175. }
  4176. ~ResumingClient() {
  4177. SSL_SESSION_free(session_);
  4178. SSL_CTX_free(ctx_);
  4179. }
  4180. // Tells whether the request was answered.
  4181. bool get() {
  4182. auto error = Error::Success;
  4183. auto sock = detail::create_client_socket(
  4184. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4185. /*connection_timeout_sec=*/5, 0,
  4186. /*read_timeout_sec=*/5, 0,
  4187. /*write_timeout_sec=*/5, 0, std::string(), error);
  4188. if (sock == INVALID_SOCKET) { return false; }
  4189. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4190. auto ssl = SSL_new(ctx_);
  4191. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4192. SSL_set_fd(ssl, static_cast<int>(sock));
  4193. if (session_) { SSL_set_session(ssl, session_); }
  4194. if (SSL_connect(ssl) != 1) { return false; }
  4195. reused_ = SSL_session_reused(ssl) == 1;
  4196. // Reading the response also takes in a TLS 1.3 session ticket.
  4197. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4198. "Connection: close\r\n\r\n";
  4199. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4200. std::string res;
  4201. char buf[256];
  4202. int n;
  4203. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4204. res.append(buf, static_cast<size_t>(n));
  4205. }
  4206. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4207. SSL_shutdown(ssl);
  4208. return res.find("200 OK") != std::string::npos;
  4209. }
  4210. // Whether the last connection resumed a session
  4211. bool reused() const { return reused_; }
  4212. private:
  4213. SSL_CTX *ctx_;
  4214. SSL_SESSION *session_ = nullptr;
  4215. bool reused_ = false;
  4216. };
  4217. // A client that resumes its session gets through, but not once the client CA
  4218. // has changed, as a resumed session does not show the certificate again.
  4219. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4221. ASSERT_TRUE(svr.is_valid());
  4222. svr.Get("/test", [](const Request &, Response &res) {
  4223. res.set_content("ok", "text/plain");
  4224. });
  4225. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4226. auto se = detail::scope_exit([&] {
  4227. svr.stop();
  4228. t.join();
  4229. ASSERT_FALSE(svr.is_running());
  4230. });
  4231. svr.wait_until_ready();
  4232. ResumingClient cli;
  4233. ASSERT_TRUE(cli.get());
  4234. ASSERT_TRUE(cli.get());
  4235. EXPECT_TRUE(cli.reused());
  4236. ASSERT_TRUE(replace_client_ca(svr));
  4237. EXPECT_FALSE(cli.get());
  4238. }
  4239. // A resumed session does not show the certificate again, so the server does
  4240. // not resume one with a verify callback to run on it.
  4241. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4242. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4243. ASSERT_TRUE(svr.is_valid());
  4244. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4245. return v.preverify_ok;
  4246. });
  4247. svr.Get("/test", [](const Request &, Response &res) {
  4248. res.set_content("ok", "text/plain");
  4249. });
  4250. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4251. auto se = detail::scope_exit([&] {
  4252. svr.stop();
  4253. t.join();
  4254. ASSERT_FALSE(svr.is_running());
  4255. });
  4256. svr.wait_until_ready();
  4257. ResumingClient cli;
  4258. ASSERT_TRUE(cli.get());
  4259. ASSERT_TRUE(cli.get());
  4260. EXPECT_FALSE(cli.reused());
  4261. }
  4262. #endif
  4263. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4264. // wolfSSL shares its session cache between contexts, so a resumed session
  4265. // could carry a client certificate checked against another server's CA, or
  4266. // against a client CA since replaced.
  4267. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4269. ASSERT_TRUE(svr.is_valid());
  4270. // Trusts a CA that did not sign the client's certificate.
  4271. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4272. ASSERT_TRUE(other.is_valid());
  4273. for (auto s : {&svr, &other}) {
  4274. s->Get("/test", [](const Request &, Response &res) {
  4275. res.set_content("ok", "text/plain");
  4276. });
  4277. }
  4278. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4279. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4280. auto se = detail::scope_exit([&] {
  4281. other.stop();
  4282. svr.stop();
  4283. t2.join();
  4284. t.join();
  4285. });
  4286. svr.wait_until_ready();
  4287. other.wait_until_ready();
  4288. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4289. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4290. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4291. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4292. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4293. ASSERT_EQ(WOLFSSL_SUCCESS,
  4294. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4295. WOLFSSL_FILETYPE_PEM));
  4296. WOLFSSL_SESSION *session = nullptr;
  4297. auto session_se = detail::scope_exit([&] {
  4298. if (session) { wolfSSL_SESSION_free(session); }
  4299. });
  4300. // A request over a new connection, resuming `session` when there is one and
  4301. // keeping the connection's own in its place. Tells whether it was answered.
  4302. auto get = [&](int port) {
  4303. auto error = Error::Success;
  4304. auto sock = detail::create_client_socket(
  4305. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4306. /*connection_timeout_sec=*/5, 0,
  4307. /*read_timeout_sec=*/5, 0,
  4308. /*write_timeout_sec=*/5, 0, std::string(), error);
  4309. if (sock == INVALID_SOCKET) { return false; }
  4310. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4311. auto ssl = wolfSSL_new(ctx);
  4312. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4313. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4314. if (session) { wolfSSL_set_session(ssl, session); }
  4315. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4316. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4317. "Connection: close\r\n\r\n";
  4318. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4319. std::string res;
  4320. char buf[256];
  4321. int n;
  4322. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4323. res.append(buf, static_cast<size_t>(n));
  4324. }
  4325. wolfSSL_shutdown(ssl);
  4326. if (session) { wolfSSL_SESSION_free(session); }
  4327. session = wolfSSL_get1_session(ssl);
  4328. return res.find("200 OK") != std::string::npos;
  4329. };
  4330. ASSERT_TRUE(get(PORT));
  4331. EXPECT_FALSE(get(PORT + 1));
  4332. ASSERT_TRUE(get(PORT));
  4333. ASSERT_TRUE(replace_client_ca(svr));
  4334. EXPECT_FALSE(get(PORT));
  4335. }
  4336. #endif
  4337. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4339. ASSERT_TRUE(svr.is_valid());
  4340. svr.Get("/test", [](const Request &, Response &res) {
  4341. res.set_content("ok", "text/plain");
  4342. });
  4343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4344. auto se = detail::scope_exit([&] {
  4345. svr.stop();
  4346. t.join();
  4347. ASSERT_FALSE(svr.is_running());
  4348. });
  4349. svr.wait_until_ready();
  4350. // A connection that sends no ClientHello keeps its handshake in progress,
  4351. // once the server has had a moment to start it.
  4352. auto error = Error::Success;
  4353. auto sock = detail::create_client_socket(
  4354. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4355. /*connection_timeout_sec=*/5, 0,
  4356. /*read_timeout_sec=*/5, 0,
  4357. /*write_timeout_sec=*/5, 0, std::string(), error);
  4358. ASSERT_NE(INVALID_SOCKET, sock);
  4359. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4360. std::string cert_pem, key_pem;
  4361. read_file(SERVER_CERT_FILE, cert_pem);
  4362. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4363. auto update = std::async(std::launch::async, [&]() {
  4364. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4365. });
  4366. EXPECT_EQ(std::future_status::timeout,
  4367. update.wait_for(std::chrono::milliseconds(200)));
  4368. detail::close_socket(sock);
  4369. EXPECT_TRUE(update.get());
  4370. SSLClient cli(HOST, PORT);
  4371. cli.enable_server_certificate_verification(false);
  4372. auto res = cli.Get("/test");
  4373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4374. EXPECT_EQ(StatusCode::OK_200, res->status);
  4375. }
  4376. #endif
  4377. TEST(ErrorHandlerTest, ContentLength) {
  4378. Server svr;
  4379. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4380. res.status = StatusCode::OK_200;
  4381. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4382. "text/html"); // <= Content-Length still 13
  4383. });
  4384. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4385. res.set_content("Hello World!\n", "text/plain");
  4386. res.status = 524;
  4387. });
  4388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4389. auto se = detail::scope_exit([&] {
  4390. svr.stop();
  4391. thread.join();
  4392. ASSERT_FALSE(svr.is_running());
  4393. });
  4394. svr.wait_until_ready();
  4395. {
  4396. Client cli(HOST, PORT);
  4397. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4399. EXPECT_EQ(StatusCode::OK_200, res->status);
  4400. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4401. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4402. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4403. }
  4404. }
  4405. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4406. TEST(ExceptionTest, WithoutExceptionHandler) {
  4407. Server svr;
  4408. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4409. throw std::runtime_error("exception...");
  4410. });
  4411. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4412. throw std::runtime_error("exception\r\n...");
  4413. });
  4414. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4415. auto se = detail::scope_exit([&] {
  4416. svr.stop();
  4417. listen_thread.join();
  4418. ASSERT_FALSE(svr.is_running());
  4419. });
  4420. svr.wait_until_ready();
  4421. Client cli("localhost", PORT);
  4422. {
  4423. auto res = cli.Get("/exception");
  4424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4425. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4426. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4427. }
  4428. {
  4429. auto res = cli.Get("/unknown");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4432. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4433. }
  4434. }
  4435. TEST(ExceptionTest, WithExceptionHandler) {
  4436. Server svr;
  4437. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4438. std::exception_ptr ep) {
  4439. EXPECT_FALSE(ep == nullptr);
  4440. try {
  4441. std::rethrow_exception(ep);
  4442. } catch (std::exception &e) {
  4443. EXPECT_EQ("abc", std::string(e.what()));
  4444. } catch (...) {}
  4445. res.status = StatusCode::InternalServerError_500;
  4446. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4447. "text/html"); // <= Content-Length still 13 at this point
  4448. });
  4449. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4450. res.set_content("Hello World!\n", "text/plain");
  4451. throw std::runtime_error("abc");
  4452. });
  4453. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4454. auto se = detail::scope_exit([&] {
  4455. svr.stop();
  4456. thread.join();
  4457. ASSERT_FALSE(svr.is_running());
  4458. });
  4459. svr.wait_until_ready();
  4460. for (size_t i = 0; i < 10; i++) {
  4461. Client cli(HOST, PORT);
  4462. for (size_t j = 0; j < 100; j++) {
  4463. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4465. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4466. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4467. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4468. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4469. }
  4470. cli.set_keep_alive(true);
  4471. for (size_t j = 0; j < 100; j++) {
  4472. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4474. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4475. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4476. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4477. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4478. }
  4479. }
  4480. }
  4481. TEST(ExceptionTest, AndErrorHandler) {
  4482. Server svr;
  4483. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4484. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4485. });
  4486. svr.set_exception_handler(
  4487. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4488. EXPECT_FALSE(ep == nullptr);
  4489. try {
  4490. std::rethrow_exception(ep);
  4491. } catch (std::exception &e) {
  4492. res.set_content(e.what(), "text/html");
  4493. } catch (...) {}
  4494. res.status = StatusCode::InternalServerError_500;
  4495. });
  4496. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4497. throw std::runtime_error("EXCEPTION");
  4498. });
  4499. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4500. res.set_content("ERROR", "text/html");
  4501. res.status = StatusCode::InternalServerError_500;
  4502. });
  4503. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4504. auto se = detail::scope_exit([&] {
  4505. svr.stop();
  4506. thread.join();
  4507. ASSERT_FALSE(svr.is_running());
  4508. });
  4509. svr.wait_until_ready();
  4510. Client cli(HOST, PORT);
  4511. {
  4512. auto res = cli.Get("/exception");
  4513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4514. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4515. EXPECT_EQ("EXCEPTION", res->body);
  4516. }
  4517. {
  4518. auto res = cli.Get("/error");
  4519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4520. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4521. EXPECT_EQ("ERROR", res->body);
  4522. }
  4523. {
  4524. auto res = cli.Get("/invalid");
  4525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4527. EXPECT_EQ("NOT_FOUND", res->body);
  4528. }
  4529. }
  4530. #endif
  4531. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4532. // process_request() wraps only routing() in a try/catch, so an exception from
  4533. // any other user callback used to unwind into the task queue - which does not
  4534. // catch - and terminate the process. Each test below runs the server on a
  4535. // single worker thread: a guard that catches the exception but still loses the
  4536. // thread would otherwise be hidden by a spare worker serving the follow-up
  4537. // request. Note that a regression here aborts the whole test binary rather
  4538. // than failing one test.
  4539. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4540. Server svr;
  4541. svr.new_task_queue = [] { return new ThreadPool(1); };
  4542. std::atomic<int> reported{0};
  4543. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4544. if (err == Error::UserCallbackException) { reported++; }
  4545. });
  4546. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4547. res.set_content_provider(
  4548. 1024, "text/plain",
  4549. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4550. sink.write("hello", 5);
  4551. throw std::runtime_error("from the content provider");
  4552. });
  4553. });
  4554. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4555. res.set_content("ok", "text/plain");
  4556. });
  4557. auto port = svr.bind_to_any_port(HOST);
  4558. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4559. auto se = detail::scope_exit([&] {
  4560. svr.stop();
  4561. listen_thread.join();
  4562. ASSERT_FALSE(svr.is_running());
  4563. });
  4564. svr.wait_until_ready();
  4565. {
  4566. Client cli(HOST, port);
  4567. cli.set_read_timeout(5, 0);
  4568. EXPECT_FALSE(cli.Get("/throw"));
  4569. }
  4570. EXPECT_TRUE(svr.is_running());
  4571. EXPECT_EQ(1, reported.load());
  4572. // A request on a fresh connection is still served.
  4573. {
  4574. Client cli(HOST, port);
  4575. auto res = cli.Get("/ok");
  4576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. EXPECT_EQ("ok", res->body);
  4579. }
  4580. }
  4581. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4582. Server svr;
  4583. svr.new_task_queue = [] { return new ThreadPool(1); };
  4584. std::atomic<bool> should_throw{true};
  4585. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4586. res.set_content("hi", "text/plain");
  4587. });
  4588. svr.set_post_routing_handler(
  4589. [&](const Request & /*req*/, Response & /*res*/) {
  4590. if (should_throw) {
  4591. throw std::runtime_error("from the post-routing handler");
  4592. }
  4593. });
  4594. auto port = svr.bind_to_any_port(HOST);
  4595. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4596. auto se = detail::scope_exit([&] {
  4597. svr.stop();
  4598. listen_thread.join();
  4599. ASSERT_FALSE(svr.is_running());
  4600. });
  4601. svr.wait_until_ready();
  4602. {
  4603. Client cli(HOST, port);
  4604. cli.set_read_timeout(5, 0);
  4605. EXPECT_FALSE(cli.Get("/hi"));
  4606. }
  4607. EXPECT_TRUE(svr.is_running());
  4608. should_throw = false;
  4609. {
  4610. Client cli(HOST, port);
  4611. auto res = cli.Get("/hi");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("hi", res->body);
  4615. }
  4616. }
  4617. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4618. // The guard reports the caught exception through the error logger, which is
  4619. // a user callback too. A logger that throws has to be contained as well, or
  4620. // the process would terminate from inside the catch.
  4621. Server svr;
  4622. svr.new_task_queue = [] { return new ThreadPool(1); };
  4623. std::atomic<int> reported{0};
  4624. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4625. if (err == Error::UserCallbackException) {
  4626. reported++;
  4627. throw std::runtime_error("from the error logger");
  4628. }
  4629. });
  4630. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4631. res.set_content_provider(
  4632. 1024, "text/plain",
  4633. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4634. sink.write("hello", 5);
  4635. throw std::runtime_error("from the content provider");
  4636. });
  4637. });
  4638. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4639. res.set_content("ok", "text/plain");
  4640. });
  4641. auto port = svr.bind_to_any_port(HOST);
  4642. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4643. auto se = detail::scope_exit([&] {
  4644. svr.stop();
  4645. listen_thread.join();
  4646. ASSERT_FALSE(svr.is_running());
  4647. });
  4648. svr.wait_until_ready();
  4649. {
  4650. Client cli(HOST, port);
  4651. cli.set_read_timeout(5, 0);
  4652. EXPECT_FALSE(cli.Get("/throw"));
  4653. }
  4654. EXPECT_TRUE(svr.is_running());
  4655. EXPECT_EQ(1, reported.load());
  4656. {
  4657. Client cli(HOST, port);
  4658. auto res = cli.Get("/ok");
  4659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4660. EXPECT_EQ(StatusCode::OK_200, res->status);
  4661. EXPECT_EQ("ok", res->body);
  4662. }
  4663. }
  4664. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4665. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4666. // so the exception unwinds through the ws::WebSocket object on its way to
  4667. // the guard. None of the HTTP cases above cross that.
  4668. Server svr;
  4669. svr.new_task_queue = [] { return new ThreadPool(1); };
  4670. std::atomic<int> reported{0};
  4671. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4672. if (err == Error::UserCallbackException) { reported++; }
  4673. });
  4674. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4675. throw std::runtime_error("from the WebSocket handler");
  4676. });
  4677. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4678. res.set_content("ok", "text/plain");
  4679. });
  4680. auto port = svr.bind_to_any_port(HOST);
  4681. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4682. auto se = detail::scope_exit([&] {
  4683. svr.stop();
  4684. listen_thread.join();
  4685. ASSERT_FALSE(svr.is_running());
  4686. });
  4687. svr.wait_until_ready();
  4688. {
  4689. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4690. "/ws");
  4691. auto res = client.connect();
  4692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4693. // The server dropped the connection instead of dying.
  4694. std::string msg;
  4695. EXPECT_FALSE(client.read(msg));
  4696. client.close();
  4697. }
  4698. EXPECT_TRUE(svr.is_running());
  4699. EXPECT_EQ(1, reported.load());
  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. #ifdef CPPHTTPLIB_SSL_ENABLED
  4709. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4710. // SSLServer::process_and_close_socket() is a separate overload with its own
  4711. // guard, so it is exercised on its own.
  4712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4713. ASSERT_TRUE(svr.is_valid());
  4714. svr.new_task_queue = [] { return new ThreadPool(1); };
  4715. std::atomic<int> reported{0};
  4716. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4717. if (err == Error::UserCallbackException) { reported++; }
  4718. });
  4719. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4720. res.set_content_provider(
  4721. 1024, "text/plain",
  4722. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4723. sink.write("hello", 5);
  4724. throw std::runtime_error("from the content provider");
  4725. });
  4726. });
  4727. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4728. res.set_content("ok", "text/plain");
  4729. });
  4730. auto port = svr.bind_to_any_port(HOST);
  4731. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4732. auto se = detail::scope_exit([&] {
  4733. svr.stop();
  4734. listen_thread.join();
  4735. ASSERT_FALSE(svr.is_running());
  4736. });
  4737. svr.wait_until_ready();
  4738. {
  4739. SSLClient cli(HOST, port);
  4740. cli.enable_server_certificate_verification(false);
  4741. cli.set_read_timeout(5, 0);
  4742. EXPECT_FALSE(cli.Get("/throw"));
  4743. }
  4744. EXPECT_TRUE(svr.is_running());
  4745. EXPECT_EQ(1, reported.load());
  4746. {
  4747. SSLClient cli(HOST, port);
  4748. cli.enable_server_certificate_verification(false);
  4749. auto res = cli.Get("/ok");
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::OK_200, res->status);
  4752. EXPECT_EQ("ok", res->body);
  4753. }
  4754. }
  4755. #endif
  4756. #endif
  4757. TEST(NoContentTest, ContentLength) {
  4758. Server svr;
  4759. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4760. res.status = StatusCode::NoContent_204;
  4761. });
  4762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4763. auto se = detail::scope_exit([&] {
  4764. svr.stop();
  4765. thread.join();
  4766. ASSERT_FALSE(svr.is_running());
  4767. });
  4768. svr.wait_until_ready();
  4769. {
  4770. Client cli(HOST, PORT);
  4771. auto res = cli.Get("/hi");
  4772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4773. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4774. // RFC 9110 8.6: none in a 204 response
  4775. EXPECT_FALSE(res->has_header("Content-Length"));
  4776. }
  4777. }
  4778. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4779. Server svr;
  4780. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4781. res.set_header("Content-Length", "5");
  4782. res.set_content("hello world", "text/plain");
  4783. });
  4784. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4785. // A body that reads as the last chunk, were it taken as chunked
  4786. res.set_header("Transfer-Encoding", "chunked");
  4787. res.set_content("0\r\n\r\n", "text/plain");
  4788. });
  4789. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4790. res.set_header("Content-Length", "2");
  4791. res.set_content_provider(5, "text/plain",
  4792. [](size_t offset, size_t length, DataSink &sink) {
  4793. sink.write(&"hello"[offset], length);
  4794. return true;
  4795. });
  4796. });
  4797. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4798. res.set_header("Content-Length", "1234");
  4799. });
  4800. thread t = thread([&] { svr.listen(HOST, PORT); });
  4801. auto se = detail::scope_exit([&] {
  4802. svr.stop();
  4803. t.join();
  4804. ASSERT_FALSE(svr.is_running());
  4805. });
  4806. svr.wait_until_ready();
  4807. Client cli(HOST, PORT);
  4808. cli.set_read_timeout(1, 0);
  4809. auto expect_body = [&](const Result &res, const std::string &body) {
  4810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4811. EXPECT_EQ(body, res->body);
  4812. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4813. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4814. };
  4815. Headers identity{{"Accept-Encoding", ""}};
  4816. expect_body(cli.Get("/body", identity), "hello world");
  4817. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4818. expect_body(cli.Get("/body",
  4819. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4820. "he");
  4821. expect_body(cli.Get("/provider", identity), "hello");
  4822. expect_body(cli.Get("/empty", identity), "");
  4823. // A HEAD response may give the length of the body a GET would get.
  4824. auto res = cli.Head("/empty");
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4827. }
  4828. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4829. Server svr;
  4830. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4831. res.set_content("short", "text/plain");
  4832. });
  4833. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4834. res.body += " with a footer";
  4835. res.set_header("Transfer-Encoding", "chunked");
  4836. });
  4837. thread t = thread([&] { svr.listen(HOST, PORT); });
  4838. auto se = detail::scope_exit([&] {
  4839. svr.stop();
  4840. t.join();
  4841. ASSERT_FALSE(svr.is_running());
  4842. });
  4843. svr.wait_until_ready();
  4844. Client cli(HOST, PORT);
  4845. cli.set_read_timeout(1, 0);
  4846. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4848. EXPECT_EQ("short with a footer", res->body);
  4849. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4850. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4851. }
  4852. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4853. Server svr;
  4854. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4855. res.set_header("Content-Length", "3");
  4856. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4857. sink.write("abc", 3);
  4858. sink.done();
  4859. return true;
  4860. });
  4861. });
  4862. thread t = thread([&] { svr.listen(HOST, PORT); });
  4863. auto se = detail::scope_exit([&] {
  4864. svr.stop();
  4865. t.join();
  4866. ASSERT_FALSE(svr.is_running());
  4867. });
  4868. svr.wait_until_ready();
  4869. Client cli(HOST, PORT);
  4870. cli.set_keep_alive(true);
  4871. auto res = cli.Get("/");
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. EXPECT_EQ("abc", res->body);
  4874. EXPECT_FALSE(res->has_header("Content-Length"));
  4875. EXPECT_EQ("close", res->get_header_value("Connection"));
  4876. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4877. // No body to delimit
  4878. auto head = cli.Head("/");
  4879. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4880. EXPECT_FALSE(head->has_header("Connection"));
  4881. }
  4882. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4883. #ifdef CPPHTTPLIB_SSL_ENABLED
  4884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4885. ASSERT_TRUE(svr.is_valid());
  4886. #else
  4887. Server svr;
  4888. #endif
  4889. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4890. if (req.path == "/routing_handler") {
  4891. res.set_header("PRE_ROUTING", "on");
  4892. res.set_content("Routing Handler", "text/plain");
  4893. return httplib::Server::HandlerResponse::Handled;
  4894. }
  4895. return httplib::Server::HandlerResponse::Unhandled;
  4896. });
  4897. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4898. res.set_content("Error", "text/html");
  4899. });
  4900. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4901. if (req.path == "/routing_handler") {
  4902. res.set_header("POST_ROUTING", "on");
  4903. }
  4904. });
  4905. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4906. res.set_content("Hello World!\n", "text/plain");
  4907. });
  4908. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4909. auto se = detail::scope_exit([&] {
  4910. svr.stop();
  4911. thread.join();
  4912. ASSERT_FALSE(svr.is_running());
  4913. });
  4914. svr.wait_until_ready();
  4915. {
  4916. #ifdef CPPHTTPLIB_SSL_ENABLED
  4917. SSLClient cli(HOST, PORT);
  4918. cli.enable_server_certificate_verification(false);
  4919. #else
  4920. Client cli(HOST, PORT);
  4921. #endif
  4922. auto res = cli.Get("/routing_handler");
  4923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4924. EXPECT_EQ(StatusCode::OK_200, res->status);
  4925. EXPECT_EQ("Routing Handler", res->body);
  4926. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4927. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4928. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4929. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4930. }
  4931. {
  4932. #ifdef CPPHTTPLIB_SSL_ENABLED
  4933. SSLClient cli(HOST, PORT);
  4934. cli.enable_server_certificate_verification(false);
  4935. #else
  4936. Client cli(HOST, PORT);
  4937. #endif
  4938. auto res = cli.Get("/hi");
  4939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. EXPECT_EQ("Hello World!\n", res->body);
  4942. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4943. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4944. }
  4945. {
  4946. #ifdef CPPHTTPLIB_SSL_ENABLED
  4947. SSLClient cli(HOST, PORT);
  4948. cli.enable_server_certificate_verification(false);
  4949. #else
  4950. Client cli(HOST, PORT);
  4951. #endif
  4952. auto res = cli.Get("/aaa");
  4953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4954. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4955. EXPECT_EQ("Error", res->body);
  4956. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4957. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4958. }
  4959. }
  4960. TEST(RequestHandlerTest, PreRequestHandler) {
  4961. auto route_path = "/user/:user";
  4962. Server svr;
  4963. svr.Get("/hi", [](const Request &, Response &res) {
  4964. res.set_content("hi", "text/plain");
  4965. });
  4966. svr.Get(route_path, [](const Request &req, Response &res) {
  4967. res.set_content(req.path_params.at("user"), "text/plain");
  4968. });
  4969. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4970. if (req.matched_route == route_path) {
  4971. auto user = req.path_params.at("user");
  4972. if (user != "john") {
  4973. res.status = StatusCode::Forbidden_403;
  4974. res.set_content("error", "text/html");
  4975. return Server::HandlerResponse::Handled;
  4976. }
  4977. }
  4978. return Server::HandlerResponse::Unhandled;
  4979. });
  4980. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4981. auto se = detail::scope_exit([&] {
  4982. svr.stop();
  4983. thread.join();
  4984. ASSERT_FALSE(svr.is_running());
  4985. });
  4986. svr.wait_until_ready();
  4987. Client cli(HOST, PORT);
  4988. {
  4989. auto res = cli.Get("/hi");
  4990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4991. EXPECT_EQ(StatusCode::OK_200, res->status);
  4992. EXPECT_EQ("hi", res->body);
  4993. }
  4994. {
  4995. auto res = cli.Get("/user/john");
  4996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4997. EXPECT_EQ(StatusCode::OK_200, res->status);
  4998. EXPECT_EQ("john", res->body);
  4999. }
  5000. {
  5001. auto res = cli.Get("/user/invalid-user");
  5002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5003. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5004. EXPECT_EQ("error", res->body);
  5005. }
  5006. }
  5007. // The pre-request handler must run before the request body is read, so a
  5008. // rejected request never forces the server to buffer a (potentially large)
  5009. // body. Here the posted body is larger than the payload limit: if the body
  5010. // were read first the server would answer 413, but because the pre-request
  5011. // handler runs first it answers 403 and the body is never read.
  5012. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5013. Server svr;
  5014. svr.set_payload_max_length(8);
  5015. auto handler_ran = false;
  5016. svr.Post("/reject", [&](const Request &req, Response &res) {
  5017. handler_ran = true;
  5018. res.set_content(req.body, "text/plain");
  5019. });
  5020. svr.Post("/accept", [](const Request &req, Response &res) {
  5021. res.set_content(req.body, "text/plain");
  5022. });
  5023. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5024. if (req.matched_route == "/reject") {
  5025. res.status = StatusCode::Forbidden_403;
  5026. res.set_content("denied", "text/plain");
  5027. return Server::HandlerResponse::Handled;
  5028. }
  5029. return Server::HandlerResponse::Unhandled;
  5030. });
  5031. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5032. auto se = detail::scope_exit([&] {
  5033. svr.stop();
  5034. thread.join();
  5035. ASSERT_FALSE(svr.is_running());
  5036. });
  5037. svr.wait_until_ready();
  5038. Client cli(HOST, PORT);
  5039. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5040. // rejects with 403 before the body is read, so 413 is never reached.
  5041. {
  5042. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5044. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5045. EXPECT_EQ("denied", res->body);
  5046. EXPECT_FALSE(handler_ran);
  5047. }
  5048. // An approved route still reads the body and enforces the payload limit.
  5049. {
  5050. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5052. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5053. }
  5054. }
  5055. TEST(UserDataTest, BasicOperations) {
  5056. httplib::UserData ud;
  5057. // Initially empty
  5058. EXPECT_FALSE(ud.has("key"));
  5059. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5060. // set and get
  5061. ud.set("key", 42);
  5062. EXPECT_TRUE(ud.has("key"));
  5063. auto *p = ud.get<int>("key");
  5064. ASSERT_NE(nullptr, p);
  5065. EXPECT_EQ(42, *p);
  5066. // Type mismatch → nullptr
  5067. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5068. // Overwrite with different type
  5069. ud.set("key", std::string("hello"));
  5070. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5071. auto *s = ud.get<std::string>("key");
  5072. ASSERT_NE(nullptr, s);
  5073. EXPECT_EQ("hello", *s);
  5074. // erase
  5075. ud.erase("key");
  5076. EXPECT_FALSE(ud.has("key"));
  5077. // clear
  5078. ud.set("a", 1);
  5079. ud.set("b", 2);
  5080. ud.clear();
  5081. EXPECT_FALSE(ud.has("a"));
  5082. EXPECT_FALSE(ud.has("b"));
  5083. }
  5084. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5085. struct AuthCtx {
  5086. std::string user_id;
  5087. };
  5088. Server svr;
  5089. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5090. res.user_data.set("auth", AuthCtx{"alice"});
  5091. return Server::HandlerResponse::Unhandled;
  5092. });
  5093. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5094. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5095. ASSERT_NE(nullptr, ctx);
  5096. res.set_content("Hello " + ctx->user_id, "text/plain");
  5097. });
  5098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5099. auto se = detail::scope_exit([&] {
  5100. svr.stop();
  5101. thread.join();
  5102. ASSERT_FALSE(svr.is_running());
  5103. });
  5104. svr.wait_until_ready();
  5105. Client cli(HOST, PORT);
  5106. auto res = cli.Get("/me");
  5107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5108. EXPECT_EQ(StatusCode::OK_200, res->status);
  5109. EXPECT_EQ("Hello alice", res->body);
  5110. }
  5111. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5112. struct RoleCtx {
  5113. std::string role;
  5114. };
  5115. Server svr;
  5116. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5117. res.user_data.set("role", RoleCtx{"admin"});
  5118. return Server::HandlerResponse::Unhandled;
  5119. });
  5120. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5121. auto *ctx = res.user_data.get<RoleCtx>("role");
  5122. ASSERT_NE(nullptr, ctx);
  5123. res.set_content(ctx->role, "text/plain");
  5124. });
  5125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5126. auto se = detail::scope_exit([&] {
  5127. svr.stop();
  5128. thread.join();
  5129. ASSERT_FALSE(svr.is_running());
  5130. });
  5131. svr.wait_until_ready();
  5132. Client cli(HOST, PORT);
  5133. auto res = cli.Get("/role");
  5134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5135. EXPECT_EQ(StatusCode::OK_200, res->status);
  5136. EXPECT_EQ("admin", res->body);
  5137. }
  5138. TEST(InvalidFormatTest, StatusCode) {
  5139. Server svr;
  5140. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5141. res.set_content("Hello World!\n", "text/plain");
  5142. res.status = 9999; // Status should be a three-digit code...
  5143. });
  5144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5145. auto se = detail::scope_exit([&] {
  5146. svr.stop();
  5147. thread.join();
  5148. ASSERT_FALSE(svr.is_running());
  5149. });
  5150. svr.wait_until_ready();
  5151. {
  5152. Client cli(HOST, PORT);
  5153. auto res = cli.Get("/hi");
  5154. ASSERT_FALSE(res);
  5155. }
  5156. }
  5157. TEST(URLFragmentTest, WithFragment) {
  5158. Server svr;
  5159. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5160. EXPECT_TRUE(req.target == "/hi");
  5161. });
  5162. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5163. auto se = detail::scope_exit([&] {
  5164. svr.stop();
  5165. thread.join();
  5166. ASSERT_FALSE(svr.is_running());
  5167. });
  5168. svr.wait_until_ready();
  5169. {
  5170. Client cli(HOST, PORT);
  5171. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5172. EXPECT_TRUE(res);
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. res = cli.Get("/hi%23key1=val1=key2=val2");
  5175. EXPECT_TRUE(res);
  5176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5177. }
  5178. }
  5179. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5180. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5181. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5182. Server svr;
  5183. std::vector<std::string> targets;
  5184. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5185. targets.push_back(req.target);
  5186. });
  5187. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5188. auto se = detail::scope_exit([&] {
  5189. svr.stop();
  5190. thread.join();
  5191. ASSERT_FALSE(svr.is_running());
  5192. });
  5193. svr.wait_until_ready();
  5194. Client cli(HOST, PORT);
  5195. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5196. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5197. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5198. // A '?' after the '#' belongs to the fragment, not to the query.
  5199. Request req;
  5200. req.method = "GET";
  5201. req.path = "/hi#f?x=1";
  5202. req.params.emplace("a", "1");
  5203. Response res;
  5204. auto error = Error::Success;
  5205. EXPECT_TRUE(cli.send(req, res, error));
  5206. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5207. "/hi?a=1"}),
  5208. targets);
  5209. }
  5210. TEST(HeaderWriter, SetHeaderWriter) {
  5211. Server svr;
  5212. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5213. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5214. return detail::write_headers(strm, hdrs);
  5215. });
  5216. svr.Get("/hi", [](const Request &req, Response &res) {
  5217. auto it = req.headers.find("CustomClientHeader");
  5218. EXPECT_TRUE(it != req.headers.end());
  5219. EXPECT_EQ(it->second, "CustomClientValue");
  5220. res.set_content("Hello World!\n", "text/plain");
  5221. });
  5222. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5223. auto se = detail::scope_exit([&] {
  5224. svr.stop();
  5225. thread.join();
  5226. ASSERT_FALSE(svr.is_running());
  5227. });
  5228. svr.wait_until_ready();
  5229. {
  5230. Client cli(HOST, PORT);
  5231. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5232. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5233. return detail::write_headers(strm, hdrs);
  5234. });
  5235. auto res = cli.Get("/hi");
  5236. EXPECT_TRUE(res);
  5237. EXPECT_EQ(StatusCode::OK_200, res->status);
  5238. auto it = res->headers.find("CustomServerHeader");
  5239. EXPECT_TRUE(it != res->headers.end());
  5240. EXPECT_EQ(it->second, "CustomServerValue");
  5241. }
  5242. }
  5243. class ServerTest : public ::testing::Test {
  5244. protected:
  5245. ServerTest()
  5246. : cli_(HOST, PORT)
  5247. #ifdef CPPHTTPLIB_SSL_ENABLED
  5248. ,
  5249. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5250. #endif
  5251. {
  5252. #ifdef CPPHTTPLIB_SSL_ENABLED
  5253. cli_.enable_server_certificate_verification(false);
  5254. #endif
  5255. // Allow LARGE_DATA (100MB) responses
  5256. cli_.set_payload_max_length(200 * 1024 * 1024);
  5257. }
  5258. virtual void SetUp() {
  5259. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5260. svr_.set_payload_max_length(200 * 1024 * 1024);
  5261. svr_.set_mount_point("/", "./www");
  5262. svr_.set_mount_point("/mount", "./www2");
  5263. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5264. svr_.Get("/hi",
  5265. [&](const Request & /*req*/, Response &res) {
  5266. res.set_content("Hello World!", "text/plain");
  5267. })
  5268. .Get("/file_content",
  5269. [&](const Request & /*req*/, Response &res) {
  5270. res.set_file_content("./www/dir/test.html");
  5271. })
  5272. .Get("/file_content_with_content_type",
  5273. [&](const Request & /*req*/, Response &res) {
  5274. res.set_file_content("./www/file", "text/plain");
  5275. })
  5276. .Get("/invalid_file_content",
  5277. [&](const Request & /*req*/, Response &res) {
  5278. res.set_file_content("./www/dir/invalid_file_path");
  5279. })
  5280. .Get("/http_response_splitting",
  5281. [&](const Request & /*req*/, Response &res) {
  5282. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5283. EXPECT_EQ(0U, res.headers.size());
  5284. EXPECT_FALSE(res.has_header("a"));
  5285. res.set_header("a", "1\nSet-Cookie: a=1");
  5286. EXPECT_EQ(0U, res.headers.size());
  5287. EXPECT_FALSE(res.has_header("a"));
  5288. res.set_header("a", "1\rSet-Cookie: a=1");
  5289. EXPECT_EQ(0U, res.headers.size());
  5290. EXPECT_FALSE(res.has_header("a"));
  5291. res.set_header("a\r\nb", "0");
  5292. EXPECT_EQ(0U, res.headers.size());
  5293. EXPECT_FALSE(res.has_header("a"));
  5294. res.set_header("a\rb", "0");
  5295. EXPECT_EQ(0U, res.headers.size());
  5296. EXPECT_FALSE(res.has_header("a"));
  5297. res.set_header("a\nb", "0");
  5298. EXPECT_EQ(0U, res.headers.size());
  5299. EXPECT_FALSE(res.has_header("a"));
  5300. res.set_redirect("1\r\nSet-Cookie: a=1");
  5301. EXPECT_EQ(0U, res.headers.size());
  5302. EXPECT_FALSE(res.has_header("Location"));
  5303. })
  5304. .Get("/slow",
  5305. [&](const Request & /*req*/, Response &res) {
  5306. std::this_thread::sleep_for(std::chrono::seconds(4));
  5307. res.set_content("slow", "text/plain");
  5308. })
  5309. #if 0
  5310. .Post("/slowpost",
  5311. [&](const Request & /*req*/, Response &res) {
  5312. std::this_thread::sleep_for(std::chrono::seconds(2));
  5313. res.set_content("slow", "text/plain");
  5314. })
  5315. #endif
  5316. .Get("/remote_addr",
  5317. [&](const Request &req, Response &res) {
  5318. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5319. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5320. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5321. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5322. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5323. #endif
  5324. res.set_content(req.remote_addr, "text/plain");
  5325. })
  5326. .Get("/local_addr",
  5327. [&](const Request &req, Response &res) {
  5328. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5329. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5330. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5331. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5332. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5333. #endif
  5334. auto local_addr = req.local_addr;
  5335. auto local_port = std::to_string(req.local_port);
  5336. res.set_content(local_addr.append(":").append(local_port),
  5337. "text/plain");
  5338. })
  5339. .Get("/endwith%",
  5340. [&](const Request & /*req*/, Response &res) {
  5341. res.set_content("Hello World!", "text/plain");
  5342. })
  5343. .Get("/a\\+\\+b",
  5344. [&](const Request &req, Response &res) {
  5345. ASSERT_TRUE(req.has_param("a +b"));
  5346. auto val = req.get_param_value("a +b");
  5347. res.set_content(val, "text/plain");
  5348. })
  5349. .Get("/", [&](const Request & /*req*/,
  5350. Response &res) { res.set_redirect("/hi"); })
  5351. .Post("/1",
  5352. [](const Request & /*req*/, Response &res) {
  5353. res.set_redirect("/2", StatusCode::SeeOther_303);
  5354. })
  5355. .Get("/2",
  5356. [](const Request & /*req*/, Response &res) {
  5357. res.set_content("redirected.", "text/plain");
  5358. res.status = StatusCode::OK_200;
  5359. })
  5360. .Post("/person",
  5361. [&](const Request &req, Response &res) {
  5362. if (req.has_param("name") && req.has_param("note")) {
  5363. persons_[req.get_param_value("name")] =
  5364. req.get_param_value("note");
  5365. } else {
  5366. res.status = StatusCode::BadRequest_400;
  5367. }
  5368. })
  5369. .Put("/person",
  5370. [&](const Request &req, Response &res) {
  5371. if (req.has_param("name") && req.has_param("note")) {
  5372. persons_[req.get_param_value("name")] =
  5373. req.get_param_value("note");
  5374. } else {
  5375. res.status = StatusCode::BadRequest_400;
  5376. }
  5377. })
  5378. .Get("/person/(.*)",
  5379. [&](const Request &req, Response &res) {
  5380. string name = req.matches[1];
  5381. if (persons_.find(name) != persons_.end()) {
  5382. auto note = persons_[name];
  5383. res.set_content(note, "text/plain");
  5384. } else {
  5385. res.status = StatusCode::NotFound_404;
  5386. }
  5387. })
  5388. .Delete("/person",
  5389. [&](const Request &req, Response &res) {
  5390. if (req.has_param("name")) {
  5391. string name = req.get_param_value("name");
  5392. if (persons_.find(name) != persons_.end()) {
  5393. persons_.erase(name);
  5394. res.set_content("DELETED", "text/plain");
  5395. } else {
  5396. res.status = StatusCode::NotFound_404;
  5397. }
  5398. } else {
  5399. res.status = StatusCode::BadRequest_400;
  5400. }
  5401. })
  5402. .Post("/x-www-form-urlencoded-json",
  5403. [&](const Request &req, Response &res) {
  5404. auto json = req.get_param_value("json");
  5405. ASSERT_EQ(JSON_DATA, json);
  5406. res.set_content(json, "appliation/json");
  5407. res.status = StatusCode::OK_200;
  5408. })
  5409. .Get("/streamed-chunked",
  5410. [&](const Request & /*req*/, Response &res) {
  5411. res.set_chunked_content_provider(
  5412. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5413. sink.os << "123";
  5414. sink.os << "456";
  5415. sink.os << "789";
  5416. sink.done();
  5417. return true;
  5418. });
  5419. })
  5420. .Get("/streamed-chunked-with-prohibited-trailer",
  5421. [&](const Request & /*req*/, Response &res) {
  5422. auto i = new int(0);
  5423. // Declare both a prohibited trailer (Content-Length) and an
  5424. // allowed one
  5425. res.set_header("Trailer", "Content-Length, X-Allowed");
  5426. res.set_chunked_content_provider(
  5427. "text/plain",
  5428. [i](size_t /*offset*/, DataSink &sink) {
  5429. switch (*i) {
  5430. case 0: sink.os << "123"; break;
  5431. case 1: sink.os << "456"; break;
  5432. case 2: sink.os << "789"; break;
  5433. case 3: {
  5434. sink.done_with_trailer(
  5435. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5436. } break;
  5437. }
  5438. (*i)++;
  5439. return true;
  5440. },
  5441. [i](bool success) {
  5442. EXPECT_TRUE(success);
  5443. delete i;
  5444. });
  5445. })
  5446. .Get("/streamed-chunked2",
  5447. [&](const Request & /*req*/, Response &res) {
  5448. auto i = new int(0);
  5449. res.set_chunked_content_provider(
  5450. "text/plain",
  5451. [i](size_t /*offset*/, DataSink &sink) {
  5452. switch (*i) {
  5453. case 0: sink.os << "123"; break;
  5454. case 1: sink.os << "456"; break;
  5455. case 2: sink.os << "789"; break;
  5456. case 3: sink.done(); break;
  5457. }
  5458. (*i)++;
  5459. return true;
  5460. },
  5461. [i](bool success) {
  5462. EXPECT_TRUE(success);
  5463. delete i;
  5464. });
  5465. })
  5466. .Get("/streamed-chunked-with-trailer",
  5467. [&](const Request & /*req*/, Response &res) {
  5468. auto i = new int(0);
  5469. res.set_header("Trailer", "Dummy1, Dummy2");
  5470. res.set_chunked_content_provider(
  5471. "text/plain",
  5472. [i](size_t /*offset*/, DataSink &sink) {
  5473. switch (*i) {
  5474. case 0: sink.os << "123"; break;
  5475. case 1: sink.os << "456"; break;
  5476. case 2: sink.os << "789"; break;
  5477. case 3: {
  5478. sink.done_with_trailer(
  5479. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5480. } break;
  5481. }
  5482. (*i)++;
  5483. return true;
  5484. },
  5485. [i](bool success) {
  5486. EXPECT_TRUE(success);
  5487. delete i;
  5488. });
  5489. })
  5490. .Get("/streamed",
  5491. [&](const Request & /*req*/, Response &res) {
  5492. res.set_content_provider(
  5493. 6, "text/plain",
  5494. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5495. sink.os << (offset < 3 ? "a" : "b");
  5496. return true;
  5497. });
  5498. })
  5499. .Get("/streamed-without-length",
  5500. [&](const Request & /*req*/, Response &res) {
  5501. auto data = new std::string("abcdefg");
  5502. res.set_content_provider(
  5503. "text/plain",
  5504. [data](size_t offset, DataSink &sink) {
  5505. if (offset < data->size()) {
  5506. sink.os << data->substr(offset);
  5507. }
  5508. sink.done();
  5509. return true;
  5510. },
  5511. [data](bool success) {
  5512. EXPECT_TRUE(success);
  5513. delete data;
  5514. });
  5515. })
  5516. .Get("/streamed-with-range",
  5517. [&](const Request &req, Response &res) {
  5518. auto data = new std::string("abcdefg");
  5519. // An explicit status keeps the server from picking the 206 it
  5520. // would otherwise choose for a ranged request, so the response
  5521. // is not a partial representation.
  5522. auto status = req.get_param_value("status");
  5523. if (status == "200") {
  5524. res.status = StatusCode::OK_200;
  5525. } else if (status == "403") {
  5526. res.status = StatusCode::Forbidden_403;
  5527. }
  5528. res.set_content_provider(
  5529. data->size(), "text/plain",
  5530. [data](size_t offset, size_t length, DataSink &sink) {
  5531. size_t DATA_CHUNK_SIZE = 4;
  5532. const auto &d = *data;
  5533. auto out_len =
  5534. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5535. auto ret =
  5536. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5537. EXPECT_TRUE(ret);
  5538. return true;
  5539. },
  5540. [data, &req](bool success) {
  5541. EXPECT_EQ(success, !req.has_param("error"));
  5542. delete data;
  5543. });
  5544. })
  5545. .Get("/streamed-cancel",
  5546. [&](const Request & /*req*/, Response &res) {
  5547. res.set_content_provider(
  5548. size_t(-1), "text/plain",
  5549. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5550. sink.os << "data_chunk";
  5551. return true;
  5552. });
  5553. })
  5554. .Get("/regex-with-delimiter",
  5555. [&](const Request &req, Response & /*res*/) {
  5556. ASSERT_TRUE(req.has_param("key"));
  5557. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5558. })
  5559. .Get("/with-range",
  5560. [&](const Request & /*req*/, Response &res) {
  5561. res.set_content("abcdefg", "text/plain");
  5562. })
  5563. .Get("/test-start-time",
  5564. [&](const Request &req, Response & /*res*/) {
  5565. EXPECT_NE(req.start_time_,
  5566. std::chrono::steady_clock::time_point::min());
  5567. })
  5568. .Get("/with-range-customized-response",
  5569. [&](const Request & /*req*/, Response &res) {
  5570. res.status = StatusCode::BadRequest_400;
  5571. res.set_content(JSON_DATA, "application/json");
  5572. })
  5573. .Post("/chunked",
  5574. [&](const Request &req, Response & /*res*/) {
  5575. EXPECT_EQ(req.body, "dechunked post body");
  5576. })
  5577. .Post("/large-chunked",
  5578. [&](const Request &req, Response & /*res*/) {
  5579. std::string expected(6 * 30 * 1024u, 'a');
  5580. EXPECT_EQ(req.body, expected);
  5581. })
  5582. .Post("/multipart",
  5583. [&](const Request &req, Response & /*res*/) {
  5584. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5585. req.form.get_field_count("text2") +
  5586. req.form.get_field_count("file3") +
  5587. req.form.get_field_count("file4"));
  5588. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5589. req.form.get_file_count("file2"));
  5590. ASSERT_TRUE(!req.form.has_file("???"));
  5591. ASSERT_TRUE(!req.form.has_field("???"));
  5592. ASSERT_TRUE(req.body.empty());
  5593. {
  5594. const auto &text = req.form.get_field("text1");
  5595. EXPECT_EQ("text default", text);
  5596. }
  5597. {
  5598. const auto &text = req.form.get_field("text2");
  5599. EXPECT_EQ("aωb", text);
  5600. }
  5601. {
  5602. const auto &file = req.form.get_file("file1");
  5603. EXPECT_EQ("hello.txt", file.filename);
  5604. EXPECT_EQ("text/plain", file.content_type);
  5605. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5606. }
  5607. {
  5608. const auto &file = req.form.get_file("file2");
  5609. EXPECT_EQ("world.json", file.filename);
  5610. EXPECT_EQ("application/json", file.content_type);
  5611. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5612. }
  5613. {
  5614. const auto &text = req.form.get_field("file3");
  5615. EXPECT_EQ(0u, text.size());
  5616. }
  5617. {
  5618. const auto &text = req.form.get_field("file4");
  5619. EXPECT_EQ(0u, text.size());
  5620. }
  5621. })
  5622. .Post("/multipart/multi_file_values",
  5623. [&](const Request &req, Response & /*res*/) {
  5624. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5625. req.form.get_field_count("multi_text1"));
  5626. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5627. ASSERT_TRUE(!req.form.has_file("???"));
  5628. ASSERT_TRUE(!req.form.has_field("???"));
  5629. ASSERT_TRUE(req.body.empty());
  5630. {
  5631. const auto &text = req.form.get_field("text");
  5632. EXPECT_EQ("default text", text);
  5633. }
  5634. {
  5635. const auto &text1_values = req.form.get_fields("multi_text1");
  5636. EXPECT_EQ(2u, text1_values.size());
  5637. EXPECT_EQ("aaaaa", text1_values[0]);
  5638. EXPECT_EQ("bbbbb", text1_values[1]);
  5639. }
  5640. {
  5641. const auto &file1_values = req.form.get_files("multi_file1");
  5642. EXPECT_EQ(2u, file1_values.size());
  5643. auto file1 = file1_values[0];
  5644. EXPECT_EQ(file1.filename, "hello.txt");
  5645. EXPECT_EQ(file1.content_type, "text/plain");
  5646. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5647. auto file2 = file1_values[1];
  5648. EXPECT_EQ(file2.filename, "world.json");
  5649. EXPECT_EQ(file2.content_type, "application/json");
  5650. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5651. }
  5652. })
  5653. .Post("/empty",
  5654. [&](const Request &req, Response &res) {
  5655. EXPECT_EQ(req.body, "");
  5656. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5657. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5658. res.set_content("empty", "text/plain");
  5659. })
  5660. .Post("/empty-no-content-type",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(req.body, "");
  5663. EXPECT_FALSE(req.has_header("Content-Type"));
  5664. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5665. res.set_content("empty-no-content-type", "text/plain");
  5666. })
  5667. .Post("/path-only",
  5668. [&](const Request &req, Response &res) {
  5669. EXPECT_EQ(req.body, "");
  5670. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5671. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5672. res.set_content("path-only", "text/plain");
  5673. })
  5674. .Post("/path-headers-only",
  5675. [&](const Request &req, Response &res) {
  5676. EXPECT_EQ(req.body, "");
  5677. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5678. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5679. EXPECT_EQ("world", req.get_header_value("hello"));
  5680. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5681. res.set_content("path-headers-only", "text/plain");
  5682. })
  5683. .Post("/post-large",
  5684. [&](const Request &req, Response &res) {
  5685. EXPECT_EQ(req.body, LARGE_DATA);
  5686. res.set_content(req.body, "text/plain");
  5687. })
  5688. .Post("/post-loopback",
  5689. [&](const Request &, Response &res,
  5690. ContentReader const &content_reader) {
  5691. std::string body;
  5692. content_reader([&](const char *data, size_t data_length) {
  5693. body.append(data, data_length);
  5694. return true;
  5695. });
  5696. res.set_content(body, "text/plain");
  5697. })
  5698. .Put("/put-loopback",
  5699. [&](const Request &, Response &res,
  5700. ContentReader const &content_reader) {
  5701. std::string body;
  5702. content_reader([&](const char *data, size_t data_length) {
  5703. body.append(data, data_length);
  5704. return true;
  5705. });
  5706. res.set_content(body, "text/plain");
  5707. })
  5708. .Patch("/patch-loopback",
  5709. [&](const Request &, Response &res,
  5710. ContentReader const &content_reader) {
  5711. std::string body;
  5712. content_reader([&](const char *data, size_t data_length) {
  5713. body.append(data, data_length);
  5714. return true;
  5715. });
  5716. res.set_content(body, "text/plain");
  5717. })
  5718. .Put("/empty-no-content-type",
  5719. [&](const Request &req, Response &res) {
  5720. EXPECT_EQ(req.body, "");
  5721. EXPECT_FALSE(req.has_header("Content-Type"));
  5722. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5723. res.set_content("empty-no-content-type", "text/plain");
  5724. })
  5725. .Put("/put",
  5726. [&](const Request &req, Response &res) {
  5727. EXPECT_EQ(req.body, "PUT");
  5728. res.set_content(req.body, "text/plain");
  5729. })
  5730. .Put("/put-large",
  5731. [&](const Request &req, Response &res) {
  5732. EXPECT_EQ(req.body, LARGE_DATA);
  5733. res.set_content(req.body, "text/plain");
  5734. })
  5735. .Patch("/patch",
  5736. [&](const Request &req, Response &res) {
  5737. EXPECT_EQ(req.body, "PATCH");
  5738. res.set_content(req.body, "text/plain");
  5739. })
  5740. .Delete("/delete",
  5741. [&](const Request & /*req*/, Response &res) {
  5742. res.set_content("DELETE", "text/plain");
  5743. })
  5744. .Delete("/delete-body",
  5745. [&](const Request &req, Response &res) {
  5746. EXPECT_EQ(req.body, "content");
  5747. res.set_content(req.body, "text/plain");
  5748. })
  5749. .Options(R"(\*)",
  5750. [&](const Request & /*req*/, Response &res) {
  5751. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5752. })
  5753. .CustomRoute("PROPFIND", "/dav/:id",
  5754. [&](const Request &req, Response &res) {
  5755. res.set_header("x-body-size",
  5756. std::to_string(req.body.size()));
  5757. res.set_header("x-matched-route", req.matched_route);
  5758. res.set_header("x-dav-id", req.path_params.at("id"));
  5759. res.status = StatusCode::MultiStatus_207;
  5760. res.set_content(req.body, "application/xml");
  5761. })
  5762. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5763. [&](const Request &req, Response &res) {
  5764. res.set_header("x-dav-match", req.matches[1]);
  5765. res.status = StatusCode::MultiStatus_207;
  5766. })
  5767. .CustomRoute("MKCOL", "/dav-mkcol",
  5768. [&](const Request &req, Response &res) {
  5769. EXPECT_TRUE(req.body.empty());
  5770. res.status = StatusCode::Created_201;
  5771. })
  5772. .CustomRoute(
  5773. "REPORT", "/dav-report",
  5774. [&](const Request & /*req*/, Response &res,
  5775. const ContentReader &content_reader) {
  5776. std::string body;
  5777. content_reader([&](const char *data, size_t data_length) {
  5778. body.append(data, data_length);
  5779. return true;
  5780. });
  5781. res.set_header("x-body-size", std::to_string(body.size()));
  5782. res.status = StatusCode::MultiStatus_207;
  5783. res.set_content(body, "application/xml");
  5784. })
  5785. .Get("/request-target",
  5786. [&](const Request &req, Response & /*res*/) {
  5787. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5788. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5789. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5790. })
  5791. .Get("/long-query-value",
  5792. [&](const Request &req, Response & /*res*/) {
  5793. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5794. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5795. })
  5796. .Get("/too-long-query-value",
  5797. [&](const Request &req, Response & /*res*/) {
  5798. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5799. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5800. })
  5801. .Get("/array-param",
  5802. [&](const Request &req, Response & /*res*/) {
  5803. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5804. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5805. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5806. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5807. })
  5808. .Get("/array-param-values",
  5809. [&](const Request &req, Response & /*res*/) {
  5810. auto values = req.get_param_values("array");
  5811. EXPECT_EQ(3u, values.size());
  5812. EXPECT_EQ("value1", values[0]);
  5813. EXPECT_EQ("value2", values[1]);
  5814. EXPECT_EQ("value3", values[2]);
  5815. auto empty = req.get_param_values("nonexistent");
  5816. EXPECT_TRUE(empty.empty());
  5817. })
  5818. .Post("/validate-no-multiple-headers",
  5819. [&](const Request &req, Response & /*res*/) {
  5820. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5821. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5822. })
  5823. .Post("/content_receiver",
  5824. [&](const Request &req, Response &res,
  5825. const ContentReader &content_reader) {
  5826. if (req.is_multipart_form_data()) {
  5827. std::vector<FormData> items;
  5828. content_reader(
  5829. [&](const FormData &file) {
  5830. items.push_back(file);
  5831. return true;
  5832. },
  5833. [&](const char *data, size_t data_length) {
  5834. items.back().content.append(data, data_length);
  5835. return true;
  5836. });
  5837. EXPECT_EQ(5u, items.size());
  5838. {
  5839. const auto &file = get_file_value(items, "text1");
  5840. EXPECT_TRUE(file.filename.empty());
  5841. EXPECT_EQ("text default", file.content);
  5842. }
  5843. {
  5844. const auto &file = get_file_value(items, "text2");
  5845. EXPECT_TRUE(file.filename.empty());
  5846. EXPECT_EQ("aωb", file.content);
  5847. }
  5848. {
  5849. const auto &file = get_file_value(items, "file1");
  5850. EXPECT_EQ("hello.txt", file.filename);
  5851. EXPECT_EQ("text/plain", file.content_type);
  5852. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5853. }
  5854. {
  5855. const auto &file = get_file_value(items, "file2");
  5856. EXPECT_EQ("world.json", file.filename);
  5857. EXPECT_EQ("application/json", file.content_type);
  5858. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5859. }
  5860. {
  5861. const auto &file = get_file_value(items, "file3");
  5862. EXPECT_TRUE(file.filename.empty());
  5863. EXPECT_EQ("application/octet-stream", file.content_type);
  5864. EXPECT_EQ(0u, file.content.size());
  5865. }
  5866. } else {
  5867. std::string body;
  5868. content_reader([&](const char *data, size_t data_length) {
  5869. EXPECT_EQ(7U, data_length);
  5870. body.append(data, data_length);
  5871. return true;
  5872. });
  5873. EXPECT_EQ(body, "content");
  5874. res.set_content(body, "text/plain");
  5875. }
  5876. })
  5877. .Put("/content_receiver",
  5878. [&](const Request & /*req*/, Response &res,
  5879. const ContentReader &content_reader) {
  5880. std::string body;
  5881. content_reader([&](const char *data, size_t data_length) {
  5882. body.append(data, data_length);
  5883. return true;
  5884. });
  5885. EXPECT_EQ(body, "content");
  5886. res.set_content(body, "text/plain");
  5887. })
  5888. .Patch("/content_receiver",
  5889. [&](const Request & /*req*/, Response &res,
  5890. const ContentReader &content_reader) {
  5891. std::string body;
  5892. content_reader([&](const char *data, size_t data_length) {
  5893. body.append(data, data_length);
  5894. return true;
  5895. });
  5896. EXPECT_EQ(body, "content");
  5897. res.set_content(body, "text/plain");
  5898. })
  5899. .Post("/query-string-and-body",
  5900. [&](const Request &req, Response & /*res*/) {
  5901. ASSERT_TRUE(req.has_param("key"));
  5902. EXPECT_EQ(req.get_param_value("key"), "value");
  5903. EXPECT_EQ(req.body, "content");
  5904. })
  5905. .Get("/last-request",
  5906. [&](const Request &req, Response & /*res*/) {
  5907. EXPECT_EQ("close", req.get_header_value("Connection"));
  5908. })
  5909. .Get(R"(/redirect/(\d+))",
  5910. [&](const Request &req, Response &res) {
  5911. auto num = std::stoi(req.matches[1]) + 1;
  5912. std::string url = "/redirect/" + std::to_string(num);
  5913. res.set_redirect(url);
  5914. })
  5915. .Post("/binary",
  5916. [&](const Request &req, Response &res) {
  5917. EXPECT_EQ(4U, req.body.size());
  5918. EXPECT_EQ("application/octet-stream",
  5919. req.get_header_value("Content-Type"));
  5920. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5921. res.set_content(req.body, "application/octet-stream");
  5922. })
  5923. .Put("/binary",
  5924. [&](const Request &req, Response &res) {
  5925. EXPECT_EQ(4U, req.body.size());
  5926. EXPECT_EQ("application/octet-stream",
  5927. req.get_header_value("Content-Type"));
  5928. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5929. res.set_content(req.body, "application/octet-stream");
  5930. })
  5931. .Patch("/binary",
  5932. [&](const Request &req, Response &res) {
  5933. EXPECT_EQ(4U, req.body.size());
  5934. EXPECT_EQ("application/octet-stream",
  5935. req.get_header_value("Content-Type"));
  5936. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5937. res.set_content(req.body, "application/octet-stream");
  5938. })
  5939. .Delete("/binary",
  5940. [&](const Request &req, Response &res) {
  5941. EXPECT_EQ(4U, req.body.size());
  5942. EXPECT_EQ("application/octet-stream",
  5943. req.get_header_value("Content-Type"));
  5944. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5945. res.set_content(req.body, "application/octet-stream");
  5946. })
  5947. .Get("/issue1772",
  5948. [&](const Request & /*req*/, Response &res) {
  5949. res.status = 401;
  5950. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5951. })
  5952. .Delete("/issue609",
  5953. [](const httplib::Request &, httplib::Response &res,
  5954. const httplib::ContentReader &) {
  5955. res.set_content("ok", "text/plain");
  5956. })
  5957. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5958. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5959. .Get("/compress",
  5960. [&](const Request & /*req*/, Response &res) {
  5961. res.set_content(
  5962. "12345678901234567890123456789012345678901234567890123456789"
  5963. "01234567890123456789012345678901234567890",
  5964. "text/plain");
  5965. })
  5966. .Get("/compress-with-charset",
  5967. [&](const Request & /*req*/, Response &res) {
  5968. res.set_content(
  5969. "12345678901234567890123456789012345678901234567890123456789"
  5970. "01234567890123456789012345678901234567890",
  5971. "application/json; charset=utf-8");
  5972. })
  5973. .Get("/nocompress",
  5974. [&](const Request & /*req*/, Response &res) {
  5975. res.set_content(
  5976. "12345678901234567890123456789012345678901234567890123456789"
  5977. "01234567890123456789012345678901234567890",
  5978. "application/octet-stream");
  5979. })
  5980. .Post("/compress-multipart",
  5981. [&](const Request &req, Response & /*res*/) {
  5982. EXPECT_EQ(2u, req.form.fields.size());
  5983. ASSERT_TRUE(!req.form.has_field("???"));
  5984. {
  5985. const auto &text = req.form.get_field("key1");
  5986. EXPECT_EQ("test", text);
  5987. }
  5988. {
  5989. const auto &text = req.form.get_field("key2");
  5990. EXPECT_EQ("--abcdefg123", text);
  5991. }
  5992. })
  5993. #endif
  5994. ;
  5995. persons_["john"] = "programmer";
  5996. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5997. svr_.wait_until_ready();
  5998. }
  5999. virtual void TearDown() {
  6000. svr_.stop();
  6001. if (!request_threads_.empty()) {
  6002. std::this_thread::sleep_for(std::chrono::seconds(1));
  6003. for (auto &t : request_threads_) {
  6004. t.join();
  6005. }
  6006. }
  6007. t_.join();
  6008. }
  6009. map<string, string> persons_;
  6010. #ifdef CPPHTTPLIB_SSL_ENABLED
  6011. SSLClient cli_;
  6012. SSLServer svr_;
  6013. #else
  6014. Client cli_;
  6015. Server svr_;
  6016. #endif
  6017. thread t_;
  6018. std::vector<thread> request_threads_;
  6019. };
  6020. TEST_F(ServerTest, GetMethod200) {
  6021. auto res = cli_.Get("/hi");
  6022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6023. EXPECT_EQ("HTTP/1.1", res->version);
  6024. EXPECT_EQ(StatusCode::OK_200, res->status);
  6025. EXPECT_EQ("OK", res->reason);
  6026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6027. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6028. EXPECT_EQ("Hello World!", res->body);
  6029. }
  6030. TEST_F(ServerTest, GetEmptyFile) {
  6031. auto res = cli_.Get("/empty_file");
  6032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6033. EXPECT_EQ(StatusCode::OK_200, res->status);
  6034. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6035. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6036. EXPECT_EQ("", res->body);
  6037. }
  6038. TEST_F(ServerTest, GetFileContent) {
  6039. auto res = cli_.Get("/file_content");
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ(StatusCode::OK_200, res->status);
  6042. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6043. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6044. EXPECT_EQ("test.html", res->body);
  6045. }
  6046. TEST_F(ServerTest, GetFileContentWithRange) {
  6047. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6050. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6051. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6052. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6053. EXPECT_EQ("est", res->body);
  6054. }
  6055. TEST_F(ServerTest, GetFileContentWithContentType) {
  6056. auto res = cli_.Get("/file_content_with_content_type");
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. EXPECT_EQ(StatusCode::OK_200, res->status);
  6059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6060. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6061. EXPECT_EQ("file\n", res->body);
  6062. }
  6063. TEST_F(ServerTest, GetInvalidFileContent) {
  6064. auto res = cli_.Get("/invalid_file_content");
  6065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6066. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6067. }
  6068. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6069. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ("HTTP/1.1", res->version);
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6074. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6075. EXPECT_EQ("Hello World!", res->body);
  6076. }
  6077. TEST_F(ServerTest, GetMethod302) {
  6078. auto res = cli_.Get("/");
  6079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6080. EXPECT_EQ(StatusCode::Found_302, res->status);
  6081. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6082. }
  6083. TEST_F(ServerTest, GetMethod302Redirect) {
  6084. cli_.set_follow_location(true);
  6085. auto res = cli_.Get("/");
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::OK_200, res->status);
  6088. EXPECT_EQ("Hello World!", res->body);
  6089. EXPECT_EQ("/hi", res->location);
  6090. }
  6091. TEST_F(ServerTest, GetMethod404) {
  6092. auto res = cli_.Get("/invalid");
  6093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6094. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6095. }
  6096. TEST_F(ServerTest, HeadMethod200) {
  6097. auto res = cli_.Head("/hi");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6101. EXPECT_TRUE(res->body.empty());
  6102. }
  6103. TEST_F(ServerTest, HeadMethod200Static) {
  6104. auto res = cli_.Head("/mount/dir/index.html");
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6108. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6109. EXPECT_TRUE(res->body.empty());
  6110. }
  6111. TEST_F(ServerTest, HeadMethod404) {
  6112. auto res = cli_.Head("/invalid");
  6113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6114. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6115. EXPECT_TRUE(res->body.empty());
  6116. }
  6117. TEST_F(ServerTest, GetMethodPersonJohn) {
  6118. auto res = cli_.Get("/person/john");
  6119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6120. EXPECT_EQ(StatusCode::OK_200, res->status);
  6121. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6122. EXPECT_EQ("programmer", res->body);
  6123. }
  6124. TEST_F(ServerTest, PostMethod1) {
  6125. auto res = cli_.Get("/person/john1");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6128. res = cli_.Post("/person", "name=john1&note=coder",
  6129. "application/x-www-form-urlencoded");
  6130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6131. ASSERT_EQ(StatusCode::OK_200, res->status);
  6132. res = cli_.Get("/person/john1");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. ASSERT_EQ(StatusCode::OK_200, res->status);
  6135. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6136. ASSERT_EQ("coder", res->body);
  6137. }
  6138. TEST_F(ServerTest, PostMethod2) {
  6139. auto res = cli_.Get("/person/john2");
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6142. Params params;
  6143. params.emplace("name", "john2");
  6144. params.emplace("note", "coder");
  6145. res = cli_.Post("/person", params);
  6146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6147. ASSERT_EQ(StatusCode::OK_200, res->status);
  6148. res = cli_.Get("/person/john2");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. ASSERT_EQ(StatusCode::OK_200, res->status);
  6151. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6152. ASSERT_EQ("coder", res->body);
  6153. }
  6154. TEST_F(ServerTest, PutMethod3) {
  6155. auto res = cli_.Get("/person/john3");
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6158. Params params;
  6159. params.emplace("name", "john3");
  6160. params.emplace("note", "coder");
  6161. res = cli_.Put("/person", params);
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. ASSERT_EQ(StatusCode::OK_200, res->status);
  6164. res = cli_.Get("/person/john3");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. ASSERT_EQ(StatusCode::OK_200, res->status);
  6167. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6168. ASSERT_EQ("coder", res->body);
  6169. }
  6170. TEST_F(ServerTest, DeleteMethod1) {
  6171. auto res = cli_.Get("/person/john4");
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6174. Params params;
  6175. params.emplace("name", "john4");
  6176. params.emplace("note", "coder");
  6177. res = cli_.Post("/person", params);
  6178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6179. ASSERT_EQ(StatusCode::OK_200, res->status);
  6180. res = cli_.Get("/person/john4");
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. ASSERT_EQ(StatusCode::OK_200, res->status);
  6183. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6184. ASSERT_EQ("coder", res->body);
  6185. Params delete_params;
  6186. delete_params.emplace("name", "john4");
  6187. res = cli_.Delete("/person", delete_params);
  6188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6189. ASSERT_EQ(StatusCode::OK_200, res->status);
  6190. ASSERT_EQ("DELETED", res->body);
  6191. res = cli_.Get("/person/john4");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6194. }
  6195. TEST_F(ServerTest, DeleteMethod2) {
  6196. auto res = cli_.Get("/person/john5");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6199. Params params;
  6200. params.emplace("name", "john5");
  6201. params.emplace("note", "developer");
  6202. res = cli_.Post("/person", params);
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. ASSERT_EQ(StatusCode::OK_200, res->status);
  6205. res = cli_.Get("/person/john5");
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. ASSERT_EQ(StatusCode::OK_200, res->status);
  6208. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6209. ASSERT_EQ("developer", res->body);
  6210. Params delete_params;
  6211. delete_params.emplace("name", "john5");
  6212. Headers headers;
  6213. headers.emplace("Custom-Header", "test-value");
  6214. res = cli_.Delete("/person", headers, delete_params);
  6215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6216. ASSERT_EQ(StatusCode::OK_200, res->status);
  6217. ASSERT_EQ("DELETED", res->body);
  6218. res = cli_.Get("/person/john5");
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6221. }
  6222. TEST_F(ServerTest, DeleteMethod3) {
  6223. auto res = cli_.Get("/person/john6");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6226. Params params;
  6227. params.emplace("name", "john6");
  6228. params.emplace("note", "tester");
  6229. res = cli_.Post("/person", params);
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::OK_200, res->status);
  6232. res = cli_.Get("/person/john6");
  6233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6234. ASSERT_EQ(StatusCode::OK_200, res->status);
  6235. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6236. ASSERT_EQ("tester", res->body);
  6237. Params delete_params;
  6238. delete_params.emplace("name", "john6");
  6239. Headers headers;
  6240. headers.emplace("Custom-Header", "test-value");
  6241. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. ASSERT_EQ(StatusCode::OK_200, res->status);
  6244. ASSERT_EQ("DELETED", res->body);
  6245. res = cli_.Get("/person/john6");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6248. }
  6249. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6250. Params params;
  6251. params.emplace("json", JSON_DATA);
  6252. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. ASSERT_EQ(StatusCode::OK_200, res->status);
  6255. ASSERT_EQ(JSON_DATA, res->body);
  6256. }
  6257. TEST_F(ServerTest, PostEmptyContent) {
  6258. auto res = cli_.Post("/empty", "", "text/plain");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. ASSERT_EQ(StatusCode::OK_200, res->status);
  6261. ASSERT_EQ("empty", res->body);
  6262. }
  6263. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6264. auto res = cli_.Post("/empty-no-content-type");
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. ASSERT_EQ(StatusCode::OK_200, res->status);
  6267. ASSERT_EQ("empty-no-content-type", res->body);
  6268. }
  6269. TEST_F(ServerTest, PostPathOnly) {
  6270. auto res = cli_.Post("/path-only");
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. ASSERT_EQ(StatusCode::OK_200, res->status);
  6273. ASSERT_EQ("path-only", res->body);
  6274. }
  6275. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6276. auto res = cli_.Post("/path-headers-only",
  6277. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. ASSERT_EQ(StatusCode::OK_200, res->status);
  6280. ASSERT_EQ("path-headers-only", res->body);
  6281. }
  6282. TEST_F(ServerTest, PostLarge) {
  6283. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. ASSERT_EQ(StatusCode::OK_200, res->status);
  6286. EXPECT_EQ(LARGE_DATA, res->body);
  6287. }
  6288. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6289. auto res = cli_.Put("/empty-no-content-type");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. ASSERT_EQ(StatusCode::OK_200, res->status);
  6292. ASSERT_EQ("empty-no-content-type", res->body);
  6293. }
  6294. TEST_F(ServerTest, GetMethodDir) {
  6295. auto res = cli_.Get("/dir/");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::OK_200, res->status);
  6298. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6299. auto body = R"(<html>
  6300. <head>
  6301. </head>
  6302. <body>
  6303. <a href="/dir/test.html">Test</a>
  6304. <a href="/hi">hi</a>
  6305. </body>
  6306. </html>
  6307. )";
  6308. EXPECT_EQ(body, res->body);
  6309. }
  6310. TEST_F(ServerTest, GetMethodDirTest) {
  6311. auto res = cli_.Get("/dir/test.html");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6315. EXPECT_EQ("test.html", res->body);
  6316. }
  6317. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6318. auto res = cli_.Get("/dir/../dir/test.html");
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6321. }
  6322. TEST_F(ServerTest, GetMethodInvalidPath) {
  6323. auto res = cli_.Get("/dir/../test.html");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6326. }
  6327. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6328. auto res = cli_.Get("/../www/dir/test.html");
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6331. }
  6332. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6333. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6336. }
  6337. TEST_F(ServerTest, GetMethodDirMountTest) {
  6338. auto res = cli_.Get("/mount/dir/test.html");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::OK_200, res->status);
  6341. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6342. EXPECT_EQ("test.html", res->body);
  6343. }
  6344. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6345. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6347. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6348. }
  6349. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6350. auto res = cli_.Get("/mount/dir/../test.html");
  6351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6353. }
  6354. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6355. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6358. }
  6359. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6360. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6362. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6363. }
  6364. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6365. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6368. }
  6369. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6370. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6373. }
  6374. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6375. auto res = cli_.Get("/mount/dir");
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6378. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6379. }
  6380. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6381. auto res = cli_.Get("//dir");
  6382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6383. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6384. EXPECT_FALSE(res->has_header("Location"));
  6385. }
  6386. TEST_F(ServerTest, PostMethod303) {
  6387. auto res = cli_.Post("/1", "body", "text/plain");
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6390. EXPECT_EQ("/2", res->get_header_value("Location"));
  6391. }
  6392. TEST_F(ServerTest, PostMethod303Redirect) {
  6393. cli_.set_follow_location(true);
  6394. auto res = cli_.Post("/1", "body", "text/plain");
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. EXPECT_EQ(StatusCode::OK_200, res->status);
  6397. EXPECT_EQ("redirected.", res->body);
  6398. EXPECT_EQ("/2", res->location);
  6399. }
  6400. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6401. auto res = cli_.Get("/dir/test.abcde");
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::OK_200, res->status);
  6404. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6405. EXPECT_EQ("abcde", res->body);
  6406. }
  6407. TEST_F(ServerTest, StaticFileRange) {
  6408. auto res =
  6409. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6412. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6413. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6414. EXPECT_EQ(true, res->has_header("Content-Range"));
  6415. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6416. EXPECT_EQ(std::string("cd"), res->body);
  6417. }
  6418. TEST_F(ServerTest, StaticFileRanges) {
  6419. auto res = cli_.Get("/dir/test.abcde",
  6420. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6423. EXPECT_TRUE(
  6424. res->get_header_value("Content-Type")
  6425. .find(
  6426. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6427. 0);
  6428. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6429. }
  6430. TEST_F(ServerTest, StaticFileRangeHead) {
  6431. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6433. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6434. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6435. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6436. EXPECT_EQ(true, res->has_header("Content-Range"));
  6437. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6438. }
  6439. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6440. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6443. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6444. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6445. EXPECT_EQ(true, res->has_header("Content-Range"));
  6446. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6447. res->get_header_value("Content-Range"));
  6448. EXPECT_EQ("LAST\n", res->body);
  6449. }
  6450. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6451. auto res =
  6452. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6456. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6457. EXPECT_EQ(true, res->has_header("Content-Range"));
  6458. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6459. }
  6460. TEST_F(ServerTest, StaticFileBigFile) {
  6461. auto res = cli_.Get("/dir/1MB.txt");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::OK_200, res->status);
  6464. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6465. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6466. }
  6467. TEST_F(ServerTest, InvalidBaseDirMount) {
  6468. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6469. }
  6470. TEST_F(ServerTest, Binary) {
  6471. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6472. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6473. "application/octet-stream");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::OK_200, res->status);
  6476. ASSERT_EQ(4U, res->body.size());
  6477. res = cli_.Put("/binary", binary.data(), binary.size(),
  6478. "application/octet-stream");
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. ASSERT_EQ(StatusCode::OK_200, res->status);
  6481. ASSERT_EQ(4U, res->body.size());
  6482. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6483. "application/octet-stream");
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. ASSERT_EQ(StatusCode::OK_200, res->status);
  6486. ASSERT_EQ(4U, res->body.size());
  6487. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6488. "application/octet-stream");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. ASSERT_EQ(StatusCode::OK_200, res->status);
  6491. ASSERT_EQ(4U, res->body.size());
  6492. }
  6493. TEST_F(ServerTest, BinaryString) {
  6494. auto binary = std::string("\x00\x01\x02\x03", 4);
  6495. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6497. ASSERT_EQ(StatusCode::OK_200, res->status);
  6498. ASSERT_EQ(4U, res->body.size());
  6499. res = cli_.Put("/binary", binary, "application/octet-stream");
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. ASSERT_EQ(StatusCode::OK_200, res->status);
  6502. ASSERT_EQ(4U, res->body.size());
  6503. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. ASSERT_EQ(StatusCode::OK_200, res->status);
  6506. ASSERT_EQ(4U, res->body.size());
  6507. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. ASSERT_EQ(StatusCode::OK_200, res->status);
  6510. ASSERT_EQ(4U, res->body.size());
  6511. }
  6512. TEST_F(ServerTest, EmptyRequest) {
  6513. auto res = cli_.Get("");
  6514. ASSERT_TRUE(!res);
  6515. EXPECT_EQ(Error::Connection, res.error());
  6516. }
  6517. TEST_F(ServerTest, LongRequest) {
  6518. std::string request;
  6519. for (size_t i = 0; i < 545; i++) {
  6520. request += "/TooLongRequest";
  6521. }
  6522. request += "OK";
  6523. auto res = cli_.Get(request.c_str());
  6524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6526. }
  6527. TEST_F(ServerTest, TooLongRequest) {
  6528. std::string request;
  6529. for (size_t i = 0; i < 546; i++) {
  6530. request += "/TooLongRequest";
  6531. }
  6532. request += "_NG";
  6533. auto start = std::chrono::high_resolution_clock::now();
  6534. cli_.set_keep_alive(true);
  6535. auto res = cli_.Get(request.c_str());
  6536. auto end = std::chrono::high_resolution_clock::now();
  6537. auto elapsed =
  6538. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6539. .count();
  6540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6541. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6542. EXPECT_LE(elapsed, 1000);
  6543. EXPECT_EQ("close", res->get_header_value("Connection"));
  6544. EXPECT_FALSE(cli_.is_socket_open());
  6545. }
  6546. TEST_F(ServerTest, AlmostTooLongRequest) {
  6547. // test for #2046 - URI length check shouldn't include other content on req
  6548. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6549. // leading /, space, HTTP/1.1)
  6550. std::string request =
  6551. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6552. auto res = cli_.Get(request.c_str());
  6553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6554. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6555. }
  6556. TEST_F(ServerTest, LongHeader) {
  6557. Request req;
  6558. req.method = "GET";
  6559. req.path = "/hi";
  6560. std::string host_and_port;
  6561. host_and_port += HOST;
  6562. host_and_port += ":";
  6563. host_and_port += std::to_string(PORT);
  6564. req.headers.emplace("Host", host_and_port.c_str());
  6565. req.headers.emplace("Accept", "*/*");
  6566. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6567. req.headers.emplace(
  6568. "Header-Name",
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6597. "@@@@@@@@@@@@@@@@");
  6598. auto res = std::make_shared<Response>();
  6599. auto error = Error::Success;
  6600. auto ret = cli_.send(req, *res, error);
  6601. ASSERT_TRUE(ret);
  6602. EXPECT_EQ(StatusCode::OK_200, res->status);
  6603. }
  6604. TEST_F(ServerTest, LongQueryValue) {
  6605. auto start = std::chrono::high_resolution_clock::now();
  6606. cli_.set_keep_alive(true);
  6607. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6608. auto end = std::chrono::high_resolution_clock::now();
  6609. auto elapsed =
  6610. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6611. .count();
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6614. EXPECT_LE(elapsed, 1000);
  6615. EXPECT_EQ("close", res->get_header_value("Connection"));
  6616. EXPECT_FALSE(cli_.is_socket_open());
  6617. }
  6618. TEST_F(ServerTest, TooLongQueryValue) {
  6619. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6620. ASSERT_FALSE(res);
  6621. EXPECT_EQ(Error::Read, res.error());
  6622. }
  6623. TEST_F(ServerTest, TooLongHeader) {
  6624. Request req;
  6625. req.method = "GET";
  6626. req.path = "/hi";
  6627. std::string host_and_port;
  6628. host_and_port += HOST;
  6629. host_and_port += ":";
  6630. host_and_port += std::to_string(PORT);
  6631. req.headers.emplace("Host", host_and_port.c_str());
  6632. req.headers.emplace("Accept", "*/*");
  6633. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6634. req.headers.emplace(
  6635. "Header-Name",
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6664. "@@@@@@@@@@@@@@@@@");
  6665. auto res = std::make_shared<Response>();
  6666. auto error = Error::Success;
  6667. auto ret = cli_.send(req, *res, error);
  6668. ASSERT_TRUE(ret);
  6669. EXPECT_EQ(StatusCode::OK_200, res->status);
  6670. }
  6671. TEST_F(ServerTest, HeaderCountAtLimit) {
  6672. // Test with headers just under the 100 limit
  6673. httplib::Headers headers;
  6674. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6675. // This should keep us just under the 100 header limit
  6676. for (int i = 0; i < 95; i++) {
  6677. std::string name = "X-Test-Header-" + std::to_string(i);
  6678. std::string value = "value" + std::to_string(i);
  6679. headers.emplace(name, value);
  6680. }
  6681. // This should work fine as we're under the limit
  6682. auto res = cli_.Get("/hi", headers);
  6683. EXPECT_TRUE(res);
  6684. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6685. }
  6686. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6687. // Test with many headers to exceed the 100 limit
  6688. httplib::Headers headers;
  6689. // Add 150 headers to definitely exceed the 100 limit
  6690. for (int i = 0; i < 150; i++) {
  6691. std::string name = "X-Test-Header-" + std::to_string(i);
  6692. std::string value = "value" + std::to_string(i);
  6693. headers.emplace(name, value);
  6694. }
  6695. // This should fail due to exceeding header count limit
  6696. cli_.set_keep_alive(true);
  6697. auto res = cli_.Get("/hi", headers);
  6698. // The server should respond with 400 Bad Request
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6701. EXPECT_EQ("close", res->get_header_value("Connection"));
  6702. EXPECT_FALSE(cli_.is_socket_open());
  6703. }
  6704. TEST_F(ServerTest, PercentEncoding) {
  6705. auto res = cli_.Get("/e%6edwith%");
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::OK_200, res->status);
  6708. }
  6709. TEST_F(ServerTest, PercentEncodingUnicode) {
  6710. auto res = cli_.Get("/e%u006edwith%");
  6711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6712. EXPECT_EQ(StatusCode::OK_200, res->status);
  6713. }
  6714. TEST_F(ServerTest, InvalidPercentEncoding) {
  6715. auto res = cli_.Get("/%endwith%");
  6716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6717. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6718. }
  6719. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6720. auto res = cli_.Get("/%uendwith%");
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6723. }
  6724. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6725. auto res = cli_.Get("/hello?aaa=bbb%");
  6726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6727. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6728. }
  6729. TEST_F(ServerTest, PlusSignEncoding) {
  6730. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::OK_200, res->status);
  6733. EXPECT_EQ("a +b", res->body);
  6734. }
  6735. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6736. // This test simulates a potential DoS attack using many headers
  6737. // to verify our security fix prevents memory exhaustion
  6738. httplib::Headers attack_headers;
  6739. // Attempt to add many headers like an attacker would (200 headers to far
  6740. // exceed limit)
  6741. for (int i = 0; i < 200; i++) {
  6742. std::string name = "X-Attack-Header-" + std::to_string(i);
  6743. std::string value = "attack_payload_" + std::to_string(i);
  6744. attack_headers.emplace(name, value);
  6745. }
  6746. // Try to POST with excessive headers
  6747. cli_.set_keep_alive(true);
  6748. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6749. // Should either fail or return 400 Bad Request due to security limit
  6750. if (res) {
  6751. // If we get a response, it should be 400 Bad Request
  6752. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6753. EXPECT_EQ("close", res->get_header_value("Connection"));
  6754. }
  6755. EXPECT_FALSE(cli_.is_socket_open());
  6756. }
  6757. TEST_F(ServerTest, MultipartFormData) {
  6758. UploadFormDataItems items = {
  6759. {"text1", "text default", "", ""},
  6760. {"text2", "aωb", "", ""},
  6761. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6762. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6763. {"file3", "", "", "application/octet-stream"},
  6764. {"file4", "", "", " application/json tmp-string "}};
  6765. auto res = cli_.Post("/multipart", items);
  6766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6767. EXPECT_EQ(StatusCode::OK_200, res->status);
  6768. }
  6769. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6770. UploadFormDataItems items = {
  6771. {"text", "default text", "", ""},
  6772. {"multi_text1", "aaaaa", "", ""},
  6773. {"multi_text1", "bbbbb", "", ""},
  6774. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6775. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6776. "application/json"},
  6777. };
  6778. auto res = cli_.Post("/multipart/multi_file_values", items);
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. }
  6782. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6783. auto res = cli_.Get("/hi");
  6784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6785. EXPECT_EQ(StatusCode::OK_200, res->status);
  6786. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6787. EXPECT_EQ("Hello World!", res->body);
  6788. }
  6789. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6790. Request req;
  6791. req.method = "POST";
  6792. req.path = "/chunked";
  6793. std::string host_and_port;
  6794. host_and_port += HOST;
  6795. host_and_port += ":";
  6796. host_and_port += std::to_string(PORT);
  6797. req.headers.emplace("Host", host_and_port.c_str());
  6798. req.headers.emplace("Accept", "*/*");
  6799. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6800. req.headers.emplace("Content-Type", "text/plain");
  6801. req.headers.emplace("Content-Length", "0");
  6802. req.headers.emplace(
  6803. "Transfer-Encoding",
  6804. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6805. // Client does not chunk, so make a chunked body manually.
  6806. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6807. auto res = std::make_shared<Response>();
  6808. auto error = Error::Success;
  6809. auto ret = cli_.send(req, *res, error);
  6810. ASSERT_TRUE(ret);
  6811. EXPECT_EQ(StatusCode::OK_200, res->status);
  6812. }
  6813. template <typename ClientT>
  6814. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6815. int expected_status) {
  6816. Request req;
  6817. req.method = "POST";
  6818. req.path = "/chunked";
  6819. std::string host_and_port;
  6820. host_and_port += HOST;
  6821. host_and_port += ":";
  6822. host_and_port += std::to_string(PORT);
  6823. req.headers.emplace("Host", host_and_port.c_str());
  6824. req.headers.emplace("Content-Length", "0");
  6825. req.headers.emplace("Transfer-Encoding", "chunked");
  6826. req.body = body;
  6827. auto res = std::make_shared<Response>();
  6828. auto error = Error::Success;
  6829. ASSERT_TRUE(cli.send(req, *res, error));
  6830. EXPECT_EQ(expected_status, res->status);
  6831. }
  6832. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6833. // rather than treat them as valid lengths.
  6834. template <typename ClientT>
  6835. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6836. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6837. }
  6838. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6839. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6840. }
  6841. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6842. expect_chunked_body_rejected(
  6843. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6844. }
  6845. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6846. // chunk-size line carries no CR, LF or other control character ahead of its
  6847. // terminator. Such a line must be refused rather than read as extension text.
  6848. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6849. expect_chunked_body_rejected(
  6850. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6851. }
  6852. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6853. expect_chunked_body_rejected(
  6854. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6855. }
  6856. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6857. expect_chunked_body_rejected(
  6858. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6859. }
  6860. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6861. // The literal stays split: a hex escape consumes every hex digit that
  6862. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6863. expect_chunked_body_rejected(
  6864. cli_, "4;a\x01"
  6865. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6866. }
  6867. // The bytes around chunk data are no payload, so they cannot ride on the
  6868. // payload limit
  6869. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6870. // Small enough that the whole request is sent before the server turns it
  6871. // down, yet past the limit by the last chunks
  6872. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  6873. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  6874. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  6875. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6876. SCOPED_TRACE(size_line.substr(0, 2));
  6877. std::string body;
  6878. for (auto c : std::string("dechunked post body")) {
  6879. body += size_line + "\r\n" + c + "\r\n";
  6880. }
  6881. body += "0\r\n\r\n";
  6882. expect_chunked_body_rejected(cli_, body.c_str());
  6883. }
  6884. }
  6885. TEST_F(ServerTest, AcceptsChunkExtension) {
  6886. expect_chunked_body_status(cli_,
  6887. "4;name=value\r\ndech\r\n"
  6888. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6889. "0;last\r\n\r\n",
  6890. StatusCode::OK_200);
  6891. }
  6892. TEST_F(ServerTest, GetStreamed2) {
  6893. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6895. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6896. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6897. EXPECT_EQ(true, res->has_header("Content-Range"));
  6898. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6899. EXPECT_EQ(std::string("ab"), res->body);
  6900. }
  6901. TEST_F(ServerTest, GetStreamed) {
  6902. auto res = cli_.Get("/streamed");
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_EQ(StatusCode::OK_200, res->status);
  6905. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6906. EXPECT_EQ(std::string("aaabbb"), res->body);
  6907. }
  6908. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6909. auto res = cli_.Get("/streamed-without-length",
  6910. Headers{make_range_header({{0, -1}})});
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::OK_200, res->status);
  6913. EXPECT_EQ(false, res->has_header("Content-Length"));
  6914. EXPECT_EQ(false, res->has_header("Content-Range"));
  6915. EXPECT_EQ(std::string("abcdefg"), res->body);
  6916. }
  6917. TEST_F(ServerTest, GetStreamedWithRange1) {
  6918. auto res =
  6919. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6922. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6923. EXPECT_EQ(true, res->has_header("Content-Range"));
  6924. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6925. EXPECT_EQ(std::string("def"), res->body);
  6926. }
  6927. TEST_F(ServerTest, GetStreamedWithRange2) {
  6928. auto res =
  6929. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6932. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6933. EXPECT_EQ(true, res->has_header("Content-Range"));
  6934. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6935. EXPECT_EQ(std::string("bcdefg"), res->body);
  6936. }
  6937. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6938. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6941. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6942. EXPECT_EQ(true, res->has_header("Content-Range"));
  6943. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6944. EXPECT_EQ(std::string("efg"), res->body);
  6945. }
  6946. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6947. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6948. // the entire representation.
  6949. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6950. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6953. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6954. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6955. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6956. }
  6957. }
  6958. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6959. auto res =
  6960. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6963. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6964. EXPECT_EQ(false, res->has_header("Content-Range"));
  6965. EXPECT_EQ(0U, res->body.size());
  6966. }
  6967. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6968. // Only a 206 is served as a partial representation. Under any other status
  6969. // `apply_ranges()` reported the full content length, so the body must match
  6970. // that header, and the content provider must never be asked for an offset
  6971. // outside the representation.
  6972. auto check = [&](int status, const char *range) {
  6973. auto path =
  6974. std::string("/streamed-with-range?status=") + std::to_string(status);
  6975. auto ctx = path + " Range: " + range;
  6976. auto res = cli_.Get(path, Headers{{"Range", range}});
  6977. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6978. EXPECT_EQ(status, res->status) << ctx;
  6979. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6980. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6981. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6982. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6983. };
  6984. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6985. check(403, "bytes=3-5");
  6986. // The offset is far past the representation.
  6987. check(403, "bytes=100000-100200");
  6988. // `first_pos` is still -1 here, and the bounds asserts in
  6989. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6990. check(403, "bytes=-3");
  6991. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6992. // multipart branch would have written one that is empty.
  6993. check(403, "bytes=1-2, 4-5");
  6994. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6995. // covers the whole representation.
  6996. check(200, "bytes=3-5");
  6997. check(200, "bytes=1-2, 4-5");
  6998. }
  6999. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7000. auto res =
  7001. cli_.Get("/streamed-with-range",
  7002. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7003. "92233720368547758079223372036854775807"}});
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7006. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7007. EXPECT_EQ(false, res->has_header("Content-Range"));
  7008. EXPECT_EQ(0U, res->body.size());
  7009. }
  7010. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7011. auto res = cli_.Get(
  7012. "/with-range",
  7013. Headers{{"Range",
  7014. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7015. {"Accept-Encoding", ""}});
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7018. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7019. EXPECT_EQ(true, res->has_header("Content-Range"));
  7020. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7021. EXPECT_EQ(std::string("abcdefg"), res->body);
  7022. }
  7023. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7024. auto res = cli_.Get("/with-range", Headers{
  7025. {"Range", "bytes=0-"},
  7026. {"Accept-Encoding", ""},
  7027. });
  7028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7029. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7030. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7031. EXPECT_EQ(true, res->has_header("Content-Range"));
  7032. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7033. EXPECT_EQ(std::string("abcdefg"), res->body);
  7034. }
  7035. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7036. auto res = cli_.Get("/streamed-with-range",
  7037. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7040. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7041. EXPECT_EQ(false, res->has_header("Content-Range"));
  7042. EXPECT_EQ(267U, res->body.size());
  7043. // Check that both range contents are present
  7044. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7045. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7046. // Check that Content-Range headers are present for both ranges
  7047. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7048. std::string::npos);
  7049. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7050. std::string::npos);
  7051. }
  7052. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7053. Ranges ranges;
  7054. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7055. ranges.emplace_back(0, -1);
  7056. }
  7057. auto res = cli_.Get("/streamed-with-range?error",
  7058. Headers{{make_range_header(ranges)}});
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7061. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7062. EXPECT_EQ(false, res->has_header("Content-Range"));
  7063. EXPECT_EQ(0U, res->body.size());
  7064. }
  7065. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7066. auto res = cli_.Get("/streamed-with-range",
  7067. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7069. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7070. EXPECT_EQ(5U, res->body.size());
  7071. // Check that overlapping ranges are coalesced into a single range
  7072. EXPECT_EQ("bcdef", res->body);
  7073. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7074. // Should be single range, not multipart
  7075. EXPECT_TRUE(res->has_header("Content-Range"));
  7076. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7077. }
  7078. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7079. auto res = cli_.Get("/streamed-with-range",
  7080. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7083. EXPECT_EQ(268U, res->body.size());
  7084. // Check that both range contents are present
  7085. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7086. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7087. // Check that Content-Range headers are present for both ranges
  7088. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7089. std::string::npos);
  7090. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7091. std::string::npos);
  7092. }
  7093. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7094. auto res = cli_.Get("/streamed-with-range",
  7095. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7098. EXPECT_EQ(269U, res->body.size());
  7099. // Check that both duplicate range contents are present
  7100. size_t first_abc = res->body.find("abc\r\n");
  7101. EXPECT_TRUE(first_abc != std::string::npos);
  7102. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7103. EXPECT_TRUE(second_abc != std::string::npos);
  7104. // Check that Content-Range headers are present for both ranges
  7105. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7106. EXPECT_TRUE(first_range != std::string::npos);
  7107. size_t second_range =
  7108. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7109. EXPECT_TRUE(second_range != std::string::npos);
  7110. }
  7111. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7112. auto res =
  7113. cli_.Get("/streamed-with-range?error",
  7114. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7117. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7118. EXPECT_EQ(false, res->has_header("Content-Range"));
  7119. EXPECT_EQ(0U, res->body.size());
  7120. }
  7121. TEST_F(ServerTest, GetStreamedEndless) {
  7122. uint64_t offset = 0;
  7123. auto res = cli_.Get("/streamed-cancel",
  7124. [&](const char * /*data*/, uint64_t data_length) {
  7125. if (offset < 100) {
  7126. offset += data_length;
  7127. return true;
  7128. }
  7129. return false;
  7130. });
  7131. ASSERT_TRUE(!res);
  7132. EXPECT_EQ(Error::Canceled, res.error());
  7133. }
  7134. TEST_F(ServerTest, ClientStop) {
  7135. std::atomic_size_t count{4};
  7136. std::vector<std::thread> threads;
  7137. for (auto i = count.load(); i != 0; --i) {
  7138. threads.emplace_back([&]() {
  7139. auto res = cli_.Get("/streamed-cancel",
  7140. [&](const char *, uint64_t) { return true; });
  7141. --count;
  7142. ASSERT_TRUE(!res);
  7143. EXPECT_TRUE(res.error() == Error::Canceled ||
  7144. res.error() == Error::Read || res.error() == Error::Write);
  7145. });
  7146. }
  7147. std::this_thread::sleep_for(std::chrono::seconds(2));
  7148. while (count != 0) {
  7149. cli_.stop();
  7150. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7151. }
  7152. for (auto &t : threads) {
  7153. t.join();
  7154. }
  7155. }
  7156. TEST_F(ServerTest, GetWithRange1) {
  7157. auto res = cli_.Get("/with-range", Headers{
  7158. make_range_header({{3, 5}}),
  7159. {"Accept-Encoding", ""},
  7160. });
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7164. EXPECT_EQ(true, res->has_header("Content-Range"));
  7165. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7166. EXPECT_EQ(std::string("def"), res->body);
  7167. }
  7168. TEST_F(ServerTest, GetWithRange2) {
  7169. auto res = cli_.Get("/with-range", Headers{
  7170. make_range_header({{1, -1}}),
  7171. {"Accept-Encoding", ""},
  7172. });
  7173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7175. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7176. EXPECT_EQ(true, res->has_header("Content-Range"));
  7177. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7178. EXPECT_EQ(std::string("bcdefg"), res->body);
  7179. }
  7180. TEST_F(ServerTest, GetWithRange3) {
  7181. auto res = cli_.Get("/with-range", Headers{
  7182. make_range_header({{0, 0}}),
  7183. {"Accept-Encoding", ""},
  7184. });
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(true, res->has_header("Content-Range"));
  7189. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7190. EXPECT_EQ(std::string("a"), res->body);
  7191. }
  7192. TEST_F(ServerTest, GetWithRange4) {
  7193. auto res = cli_.Get("/with-range", Headers{
  7194. make_range_header({{-1, 2}}),
  7195. {"Accept-Encoding", ""},
  7196. });
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7199. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7200. EXPECT_EQ(true, res->has_header("Content-Range"));
  7201. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7202. EXPECT_EQ(std::string("fg"), res->body);
  7203. }
  7204. TEST_F(ServerTest, GetWithRange5) {
  7205. auto res = cli_.Get("/with-range", Headers{
  7206. make_range_header({{0, 5}}),
  7207. {"Accept-Encoding", ""},
  7208. });
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7211. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7212. EXPECT_EQ(true, res->has_header("Content-Range"));
  7213. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7214. EXPECT_EQ(std::string("abcdef"), res->body);
  7215. }
  7216. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7217. auto res =
  7218. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7220. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7221. }
  7222. TEST_F(ServerTest, GetWithRangeMultipart) {
  7223. auto res =
  7224. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7227. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7228. EXPECT_EQ(false, res->has_header("Content-Range"));
  7229. EXPECT_EQ(267U, res->body.size());
  7230. }
  7231. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7232. auto res = cli_.Get("/with-range",
  7233. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7236. }
  7237. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7238. auto res = cli_.Get("/with-range-customized-response",
  7239. Headers{{make_range_header({{1, 2}})}});
  7240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7241. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7242. EXPECT_EQ(true, res->has_header("Content-Length"));
  7243. EXPECT_EQ(false, res->has_header("Content-Range"));
  7244. EXPECT_EQ(JSON_DATA, res->body);
  7245. }
  7246. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7247. auto res = cli_.Get("/with-range-customized-response",
  7248. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7251. EXPECT_EQ(true, res->has_header("Content-Length"));
  7252. EXPECT_EQ(false, res->has_header("Content-Range"));
  7253. EXPECT_EQ(JSON_DATA, res->body);
  7254. }
  7255. TEST_F(ServerTest, Issue1772) {
  7256. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7259. }
  7260. TEST_F(ServerTest, Issue609) {
  7261. auto res = cli_.Delete("/issue609");
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::OK_200, res->status);
  7264. EXPECT_EQ(std::string("ok"), res->body);
  7265. }
  7266. TEST_F(ServerTest, GetStreamedChunked) {
  7267. auto res = cli_.Get("/streamed-chunked");
  7268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7269. EXPECT_EQ(StatusCode::OK_200, res->status);
  7270. EXPECT_EQ(std::string("123456789"), res->body);
  7271. }
  7272. TEST_F(ServerTest, GetStreamedChunked2) {
  7273. auto res = cli_.Get("/streamed-chunked2");
  7274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7275. EXPECT_EQ(StatusCode::OK_200, res->status);
  7276. EXPECT_EQ(std::string("123456789"), res->body);
  7277. }
  7278. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7279. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(StatusCode::OK_200, res->status);
  7282. EXPECT_EQ(std::string("123456789"), res->body);
  7283. EXPECT_TRUE(res->has_header("Trailer"));
  7284. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7285. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7286. // Trailers are now stored separately from headers (security fix)
  7287. EXPECT_EQ(2U, res->trailers.size());
  7288. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7289. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7290. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7291. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7292. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7293. // Verify trailers are NOT in headers (security verification)
  7294. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7295. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7296. }
  7297. TEST_F(ServerTest, LargeChunkedPost) {
  7298. Request req;
  7299. req.method = "POST";
  7300. req.path = "/large-chunked";
  7301. std::string host_and_port;
  7302. host_and_port += HOST;
  7303. host_and_port += ":";
  7304. host_and_port += std::to_string(PORT);
  7305. req.headers.emplace("Host", host_and_port.c_str());
  7306. req.headers.emplace("Accept", "*/*");
  7307. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7308. req.headers.emplace("Content-Type", "text/plain");
  7309. req.headers.emplace("Content-Length", "0");
  7310. req.headers.emplace("Transfer-Encoding", "chunked");
  7311. std::string long_string(30 * 1024u, 'a');
  7312. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7313. // Attempt to make a large enough post to exceed OS buffers, to test that
  7314. // the server handles short reads if the full chunk data isn't available.
  7315. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7316. auto res = std::make_shared<Response>();
  7317. auto error = Error::Success;
  7318. auto ret = cli_.send(req, *res, error);
  7319. ASSERT_TRUE(ret);
  7320. EXPECT_EQ(StatusCode::OK_200, res->status);
  7321. }
  7322. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7323. auto res = cli_.Get("/remote_addr");
  7324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7325. EXPECT_EQ(StatusCode::OK_200, res->status);
  7326. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7327. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7328. }
  7329. TEST_F(ServerTest, GetMethodLocalAddr) {
  7330. auto res = cli_.Get("/local_addr");
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::OK_200, res->status);
  7333. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7334. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7335. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7336. }
  7337. TEST_F(ServerTest, HTTPResponseSplitting) {
  7338. auto res = cli_.Get("/http_response_splitting");
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ(StatusCode::OK_200, res->status);
  7341. }
  7342. TEST_F(ServerTest, SlowRequest) {
  7343. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7344. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7345. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7346. }
  7347. #if 0
  7348. TEST_F(ServerTest, SlowPost) {
  7349. char buffer[64 * 1024];
  7350. memset(buffer, 0x42, sizeof(buffer));
  7351. auto res = cli_.Post(
  7352. "/slowpost", 64 * 1024 * 1024,
  7353. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7354. auto ret = sink.write(buffer, sizeof(buffer));
  7355. EXPECT_TRUE(ret);
  7356. return true;
  7357. },
  7358. "text/plain");
  7359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7360. EXPECT_EQ(StatusCode::OK_200, res->status);
  7361. }
  7362. TEST_F(ServerTest, SlowPostFail) {
  7363. char buffer[64 * 1024];
  7364. memset(buffer, 0x42, sizeof(buffer));
  7365. cli_.set_write_timeout(std::chrono::seconds(0));
  7366. auto res = cli_.Post(
  7367. "/slowpost", 64 * 1024 * 1024,
  7368. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7369. sink.write(buffer, sizeof(buffer));
  7370. return true;
  7371. },
  7372. "text/plain");
  7373. ASSERT_TRUE(!res);
  7374. EXPECT_EQ(Error::Write, res.error());
  7375. }
  7376. #endif
  7377. TEST_F(ServerTest, Put) {
  7378. auto res = cli_.Put("/put", "PUT", "text/plain");
  7379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7380. EXPECT_EQ(StatusCode::OK_200, res->status);
  7381. EXPECT_EQ("PUT", res->body);
  7382. }
  7383. TEST_F(ServerTest, PutWithContentProvider) {
  7384. auto res = cli_.Put(
  7385. "/put", 3,
  7386. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7387. sink.os << "PUT";
  7388. return true;
  7389. },
  7390. "text/plain");
  7391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7392. EXPECT_EQ(StatusCode::OK_200, res->status);
  7393. EXPECT_EQ("PUT", res->body);
  7394. }
  7395. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7396. auto res = cli_.Post(
  7397. "/post", 42,
  7398. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7399. return false;
  7400. },
  7401. "text/plain");
  7402. ASSERT_TRUE(!res);
  7403. EXPECT_EQ(Error::Canceled, res.error());
  7404. }
  7405. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7406. auto res = cli_.Put(
  7407. "/put",
  7408. [](size_t /*offset*/, DataSink &sink) {
  7409. sink.os << "PUT";
  7410. sink.done();
  7411. return true;
  7412. },
  7413. "text/plain");
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::OK_200, res->status);
  7416. EXPECT_EQ("PUT", res->body);
  7417. }
  7418. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7419. auto res = cli_.Post(
  7420. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7421. "text/plain");
  7422. ASSERT_TRUE(!res);
  7423. EXPECT_EQ(Error::Canceled, res.error());
  7424. }
  7425. TEST_F(ServerTest, PostLoopBack) {
  7426. std::string body;
  7427. auto res = cli_.Post(
  7428. "/post-loopback", 9,
  7429. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7430. EXPECT_EQ(9u, length);
  7431. sink.write("123", 3);
  7432. sink.write("456", 3);
  7433. sink.write("789", 3);
  7434. return true;
  7435. },
  7436. "text/plain",
  7437. [&body](const char *data, size_t data_length) {
  7438. body.append(data, data_length);
  7439. return true;
  7440. });
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_EQ(StatusCode::OK_200, res->status);
  7443. EXPECT_EQ("123456789", body);
  7444. }
  7445. TEST_F(ServerTest, PutLoopBack) {
  7446. std::string body;
  7447. auto res = cli_.Put(
  7448. "/put-loopback", 9,
  7449. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7450. EXPECT_EQ(9u, length);
  7451. sink.write("123", 3);
  7452. sink.write("456", 3);
  7453. sink.write("789", 3);
  7454. return true;
  7455. },
  7456. "text/plain",
  7457. [&body](const char *data, size_t data_length) {
  7458. body.append(data, data_length);
  7459. return true;
  7460. });
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. EXPECT_EQ("123456789", body);
  7464. }
  7465. TEST_F(ServerTest, PatchLoopBack) {
  7466. std::string body;
  7467. auto res = cli_.Patch(
  7468. "/patch-loopback", 9,
  7469. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7470. EXPECT_EQ(9u, length);
  7471. sink.write("123", 3);
  7472. sink.write("456", 3);
  7473. sink.write("789", 3);
  7474. return true;
  7475. },
  7476. "text/plain",
  7477. [&body](const char *data, size_t data_length) {
  7478. body.append(data, data_length);
  7479. return true;
  7480. });
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. EXPECT_EQ("123456789", body);
  7484. }
  7485. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7486. std::string body;
  7487. auto res = cli_.Post(
  7488. "/post-loopback",
  7489. [](size_t /*offset*/, DataSink &sink) {
  7490. sink.write("123", 3);
  7491. sink.write("456", 3);
  7492. sink.write("789", 3);
  7493. sink.done();
  7494. return true;
  7495. },
  7496. "text/plain",
  7497. [&body](const char *data, size_t data_length) {
  7498. body.append(data, data_length);
  7499. return true;
  7500. });
  7501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7502. EXPECT_EQ(StatusCode::OK_200, res->status);
  7503. EXPECT_EQ("123456789", body);
  7504. }
  7505. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7506. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7507. cli_.set_compress(true);
  7508. auto res = cli_.Put(
  7509. "/put", 3,
  7510. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7511. sink.os << "PUT";
  7512. return true;
  7513. },
  7514. "text/plain");
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. EXPECT_EQ("PUT", res->body);
  7518. }
  7519. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7520. cli_.set_compress(true);
  7521. auto res = cli_.Post(
  7522. "/post", 42,
  7523. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7524. return false;
  7525. },
  7526. "text/plain");
  7527. ASSERT_TRUE(!res);
  7528. EXPECT_EQ(Error::Canceled, res.error());
  7529. }
  7530. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7531. cli_.set_compress(true);
  7532. auto res = cli_.Put(
  7533. "/put",
  7534. [](size_t /*offset*/, DataSink &sink) {
  7535. sink.os << "PUT";
  7536. sink.done();
  7537. return true;
  7538. },
  7539. "text/plain");
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::OK_200, res->status);
  7542. EXPECT_EQ("PUT", res->body);
  7543. }
  7544. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7545. cli_.set_compress(true);
  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, PutLargeFileWithGzip) {
  7553. cli_.set_compress(true);
  7554. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ(LARGE_DATA, res->body);
  7558. }
  7559. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7560. #ifdef CPPHTTPLIB_SSL_ENABLED
  7561. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7562. Client cli(s.c_str());
  7563. cli.enable_server_certificate_verification(false);
  7564. #else
  7565. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7566. Client cli(s.c_str());
  7567. #endif
  7568. cli.set_compress(true);
  7569. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. EXPECT_EQ(LARGE_DATA, res->body);
  7573. // The compressed size should be less than a 10th of the original. May vary
  7574. // depending on the zlib library.
  7575. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7576. static_cast<uint64_t>(10 * 1024 * 1024));
  7577. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7578. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7579. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7580. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7581. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7582. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7583. #endif
  7584. }
  7585. TEST_F(ServerTest, PutContentWithDeflate) {
  7586. cli_.set_compress(false);
  7587. Headers headers;
  7588. headers.emplace("Content-Encoding", "deflate");
  7589. // PUT in deflate format:
  7590. auto res = cli_.Put("/put", headers,
  7591. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7593. EXPECT_EQ(StatusCode::OK_200, res->status);
  7594. EXPECT_EQ("PUT", res->body);
  7595. }
  7596. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7597. Headers headers;
  7598. headers.emplace("Accept-Encoding", "gzip, deflate");
  7599. auto res = cli_.Get("/streamed-chunked", headers);
  7600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7601. EXPECT_EQ(StatusCode::OK_200, res->status);
  7602. EXPECT_EQ(std::string("123456789"), res->body);
  7603. }
  7604. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7605. Headers headers;
  7606. headers.emplace("Accept-Encoding", "gzip, deflate");
  7607. auto res = cli_.Get("/streamed-chunked2", headers);
  7608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7609. EXPECT_EQ(StatusCode::OK_200, res->status);
  7610. EXPECT_EQ(std::string("123456789"), res->body);
  7611. }
  7612. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7613. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. }
  7617. TEST(GzipDecompressor, ChunkedDecompression) {
  7618. std::string data;
  7619. for (size_t i = 0; i < 32 * 1024; ++i) {
  7620. data.push_back(static_cast<char>('a' + i % 26));
  7621. }
  7622. std::string compressed_data;
  7623. {
  7624. httplib::detail::gzip_compressor compressor;
  7625. bool result = compressor.compress(
  7626. data.data(), data.size(),
  7627. /*last=*/true,
  7628. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7629. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7630. compressed_data_size);
  7631. return true;
  7632. });
  7633. ASSERT_TRUE(result);
  7634. }
  7635. std::string decompressed_data;
  7636. {
  7637. httplib::detail::gzip_decompressor decompressor;
  7638. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7639. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7640. size_t chunk_size = 130;
  7641. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7642. chunk_begin += chunk_size) {
  7643. size_t current_chunk_size =
  7644. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7645. bool result = decompressor.decompress(
  7646. compressed_data.data() + chunk_begin, current_chunk_size,
  7647. [&](const char *decompressed_data_chunk,
  7648. size_t decompressed_data_chunk_size) {
  7649. decompressed_data.insert(decompressed_data.size(),
  7650. decompressed_data_chunk,
  7651. decompressed_data_chunk_size);
  7652. return true;
  7653. });
  7654. ASSERT_TRUE(result);
  7655. }
  7656. }
  7657. ASSERT_EQ(data, decompressed_data);
  7658. }
  7659. TEST(GzipDecompressor, DeflateDecompression) {
  7660. std::string original_text = "Raw deflate without gzip";
  7661. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7662. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7663. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7664. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7665. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7666. std::string decompressed_data;
  7667. {
  7668. httplib::detail::gzip_decompressor decompressor;
  7669. bool result = decompressor.decompress(
  7670. compressed_data.data(), compressed_data.size(),
  7671. [&](const char *decompressed_data_chunk,
  7672. size_t decompressed_data_chunk_size) {
  7673. decompressed_data.insert(decompressed_data.size(),
  7674. decompressed_data_chunk,
  7675. decompressed_data_chunk_size);
  7676. return true;
  7677. });
  7678. ASSERT_TRUE(result);
  7679. }
  7680. ASSERT_EQ(original_text, decompressed_data);
  7681. }
  7682. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7683. std::string original_text = "Raw deflate without gzip";
  7684. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7685. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7686. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7687. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7688. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7689. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7690. std::string decompressed_data;
  7691. {
  7692. httplib::detail::gzip_decompressor decompressor;
  7693. bool result = decompressor.decompress(
  7694. compressed_data.data(), compressed_data.size(),
  7695. [&](const char *decompressed_data_chunk,
  7696. size_t decompressed_data_chunk_size) {
  7697. decompressed_data.insert(decompressed_data.size(),
  7698. decompressed_data_chunk,
  7699. decompressed_data_chunk_size);
  7700. return true;
  7701. });
  7702. ASSERT_TRUE(result);
  7703. }
  7704. ASSERT_EQ(original_text, decompressed_data);
  7705. }
  7706. #endif
  7707. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7708. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7709. Headers headers;
  7710. headers.emplace("Accept-Encoding", "br");
  7711. auto res = cli_.Get("/streamed-chunked", headers);
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ(std::string("123456789"), res->body);
  7715. }
  7716. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7717. Headers headers;
  7718. headers.emplace("Accept-Encoding", "br");
  7719. auto res = cli_.Get("/streamed-chunked2", headers);
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::OK_200, res->status);
  7722. EXPECT_EQ(std::string("123456789"), res->body);
  7723. }
  7724. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7725. cli_.set_compress(true);
  7726. auto res = cli_.Put(
  7727. "/put", 3,
  7728. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7729. sink.os << "PUT";
  7730. return true;
  7731. },
  7732. "text/plain");
  7733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7734. EXPECT_EQ(StatusCode::OK_200, res->status);
  7735. EXPECT_EQ("PUT", res->body);
  7736. }
  7737. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7738. cli_.set_compress(true);
  7739. auto res = cli_.Put(
  7740. "/put",
  7741. [](size_t /*offset*/, DataSink &sink) {
  7742. sink.os << "PUT";
  7743. sink.done();
  7744. return true;
  7745. },
  7746. "text/plain");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. EXPECT_EQ("PUT", res->body);
  7750. }
  7751. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7752. cli_.set_compress(true);
  7753. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7755. EXPECT_EQ(StatusCode::OK_200, res->status);
  7756. EXPECT_EQ(LARGE_DATA, res->body);
  7757. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7758. }
  7759. #endif
  7760. TEST_F(ServerTest, Patch) {
  7761. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7763. EXPECT_EQ(StatusCode::OK_200, res->status);
  7764. EXPECT_EQ("PATCH", res->body);
  7765. }
  7766. TEST_F(ServerTest, Delete) {
  7767. auto res = cli_.Delete("/delete");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. EXPECT_EQ("DELETE", res->body);
  7771. }
  7772. TEST_F(ServerTest, DeleteContentReceiver) {
  7773. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. EXPECT_EQ("content", res->body);
  7777. }
  7778. TEST_F(ServerTest, Options) {
  7779. auto res = cli_.Options("*");
  7780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7781. EXPECT_EQ(StatusCode::OK_200, res->status);
  7782. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7783. EXPECT_TRUE(res->body.empty());
  7784. }
  7785. TEST_F(ServerTest, URL) {
  7786. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7788. EXPECT_EQ(StatusCode::OK_200, res->status);
  7789. }
  7790. TEST_F(ServerTest, ArrayParam) {
  7791. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7793. EXPECT_EQ(StatusCode::OK_200, res->status);
  7794. }
  7795. TEST_F(ServerTest, ArrayParamValues) {
  7796. auto res =
  7797. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7799. EXPECT_EQ(StatusCode::OK_200, res->status);
  7800. }
  7801. TEST_F(ServerTest, NoMultipleHeaders) {
  7802. Headers headers = {{"Content-Length", "5"}};
  7803. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7804. "text/plain");
  7805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7806. EXPECT_EQ(StatusCode::OK_200, res->status);
  7807. }
  7808. TEST_F(ServerTest, PostContentReceiver) {
  7809. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7811. ASSERT_EQ(StatusCode::OK_200, res->status);
  7812. ASSERT_EQ("content", res->body);
  7813. }
  7814. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7815. UploadFormDataItems items = {
  7816. {"text1", "text default", "", ""},
  7817. {"text2", "aωb", "", ""},
  7818. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7819. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7820. {"file3", "", "", "application/octet-stream"},
  7821. };
  7822. auto res = cli_.Post("/content_receiver", items);
  7823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7824. EXPECT_EQ(StatusCode::OK_200, res->status);
  7825. }
  7826. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7827. UploadFormDataItems items = {
  7828. {"text1", "text default", "", ""},
  7829. {"text2", "aωb", "", ""},
  7830. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7831. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7832. {"file3", "", "", "application/octet-stream"},
  7833. };
  7834. auto boundary = std::string("+++++");
  7835. std::string body;
  7836. for (const auto &item : items) {
  7837. body += "--" + boundary + "\r\n";
  7838. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7839. if (!item.filename.empty()) {
  7840. body += "; filename=\"" + item.filename + "\"";
  7841. }
  7842. body += "\r\n";
  7843. if (!item.content_type.empty()) {
  7844. body += "Content-Type: " + item.content_type + "\r\n";
  7845. }
  7846. body += "\r\n";
  7847. body += item.content + "\r\n";
  7848. }
  7849. body += "--" + boundary + "--\r\n";
  7850. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7851. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7853. EXPECT_EQ(StatusCode::OK_200, res->status);
  7854. }
  7855. TEST(MultipartFormDataTest, FieldEscaping) {
  7856. Server svr;
  7857. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7858. const ContentReader &content_reader) {
  7859. ASSERT_TRUE(req.is_multipart_form_data());
  7860. std::vector<FormData> received;
  7861. content_reader(
  7862. [&](const FormData &file) {
  7863. received.push_back(file);
  7864. return true;
  7865. },
  7866. [&](const char *data, size_t data_length) {
  7867. received.back().content.append(data, data_length);
  7868. return true;
  7869. });
  7870. // '"', CR and LF in names and filenames are escaped following the
  7871. // WHATWG HTML standard, so each part still parses as a single part
  7872. // with no injected headers. Content types get CR/LF escaped too,
  7873. // while '"' (legal there, e.g. quoted charset) is preserved.
  7874. ASSERT_EQ(4U, received.size());
  7875. EXPECT_EQ("na%22me", received[0].name);
  7876. EXPECT_EQ("quoted name", received[0].content);
  7877. EXPECT_EQ("file", received[1].name);
  7878. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7879. received[1].filename);
  7880. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7881. EXPECT_EQ("injected", received[1].content);
  7882. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7883. EXPECT_EQ("my%22file.txt", received[2].filename);
  7884. EXPECT_EQ("cr lf name", received[2].content);
  7885. EXPECT_EQ("typed", received[3].name);
  7886. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7887. received[3].content_type);
  7888. EXPECT_EQ("typed content", received[3].content);
  7889. });
  7890. auto port = svr.bind_to_any_port("localhost");
  7891. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7892. auto se = detail::scope_exit([&] {
  7893. svr.stop();
  7894. t.join();
  7895. ASSERT_FALSE(svr.is_running());
  7896. });
  7897. svr.wait_until_ready();
  7898. Client cli("localhost", port);
  7899. UploadFormDataItems items = {
  7900. {"na\"me", "quoted name", "", ""},
  7901. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7902. "application/octet-stream"},
  7903. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7904. {"typed", "typed content", "",
  7905. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7906. };
  7907. auto res = cli.Post("/post", items);
  7908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7909. EXPECT_EQ(StatusCode::OK_200, res->status);
  7910. }
  7911. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7912. const UploadFormDataItems items = {
  7913. {"name1", "Content 1", "", ""},
  7914. {"name2", "Content 2", "file2.txt", "text/plain"},
  7915. };
  7916. Server svr;
  7917. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7918. const ContentReader &content_reader) {
  7919. ASSERT_TRUE(req.is_multipart_form_data());
  7920. std::vector<FormData> received;
  7921. content_reader(
  7922. [&](const FormData &file) {
  7923. received.push_back(file);
  7924. return true;
  7925. },
  7926. [&](const char *data, size_t data_length) {
  7927. received.back().content.append(data, data_length);
  7928. return true;
  7929. });
  7930. ASSERT_EQ(2U, received.size());
  7931. EXPECT_EQ("name1", received[0].name);
  7932. EXPECT_EQ("Content 1", received[0].content);
  7933. EXPECT_EQ("name2", received[1].name);
  7934. EXPECT_EQ("Content 2", received[1].content);
  7935. EXPECT_EQ("file2.txt", received[1].filename);
  7936. EXPECT_EQ("text/plain", received[1].content_type);
  7937. });
  7938. auto port = svr.bind_to_any_port("localhost");
  7939. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7940. auto se = detail::scope_exit([&] {
  7941. svr.stop();
  7942. t.join();
  7943. ASSERT_FALSE(svr.is_running());
  7944. });
  7945. svr.wait_until_ready();
  7946. Client cli("localhost", port);
  7947. // Whole-body serialization with a generated boundary
  7948. {
  7949. MultipartFormDataWriter writer;
  7950. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7951. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7952. writer.content_type());
  7953. auto body = writer.serialize(items);
  7954. EXPECT_EQ(body.size(), writer.content_length(items));
  7955. auto res = cli.Post("/post", body, writer.content_type());
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. }
  7959. // Per-part framing with a custom boundary via a content provider
  7960. {
  7961. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7962. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7963. MultipartFormDataWriter writer("custom-boundary_123");
  7964. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7965. std::string body;
  7966. for (const auto &item : items) {
  7967. body += writer.item_begin(item);
  7968. body += item.content;
  7969. body += MultipartFormDataWriter::item_end();
  7970. }
  7971. body += writer.finish();
  7972. EXPECT_EQ(body.size(), writer.content_length(items));
  7973. auto res = cli.Post(
  7974. "/post", body.size(),
  7975. [&](size_t offset, size_t length, DataSink &sink) {
  7976. sink.write(body.data() + offset, length);
  7977. return true;
  7978. },
  7979. writer.content_type());
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::OK_200, res->status);
  7982. }
  7983. }
  7984. TEST_F(ServerTest, PostContentReceiverGzip) {
  7985. cli_.set_compress(true);
  7986. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7988. ASSERT_EQ(StatusCode::OK_200, res->status);
  7989. ASSERT_EQ("content", res->body);
  7990. }
  7991. TEST_F(ServerTest, PutContentReceiver) {
  7992. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7994. ASSERT_EQ(StatusCode::OK_200, res->status);
  7995. ASSERT_EQ("content", res->body);
  7996. }
  7997. TEST_F(ServerTest, PatchContentReceiver) {
  7998. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8000. ASSERT_EQ(StatusCode::OK_200, res->status);
  8001. ASSERT_EQ("content", res->body);
  8002. }
  8003. template <typename ClientType>
  8004. void TestWithHeadersAndContentReceiver(
  8005. ClientType &cli,
  8006. std::function<Result(ClientType &, const std::string &, const Headers &,
  8007. const std::string &, const std::string &,
  8008. ContentReceiver, DownloadProgress)>
  8009. request_func) {
  8010. Headers headers;
  8011. headers.emplace("X-Custom-Header", "test-value");
  8012. std::string received_body;
  8013. auto res = request_func(
  8014. cli, "/content_receiver", headers, "content", "application/json",
  8015. [&](const char *data, size_t data_length) {
  8016. received_body.append(data, data_length);
  8017. return true;
  8018. },
  8019. nullptr);
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ(StatusCode::OK_200, res->status);
  8022. EXPECT_EQ("content", received_body);
  8023. }
  8024. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8025. #ifdef CPPHTTPLIB_SSL_ENABLED
  8026. using ClientT = SSLClient;
  8027. #else
  8028. using ClientT = Client;
  8029. #endif
  8030. TestWithHeadersAndContentReceiver<ClientT>(
  8031. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8032. const std::string &body, const std::string &content_type,
  8033. ContentReceiver receiver, DownloadProgress progress) {
  8034. return cli.Post(path, headers, body, content_type, receiver, progress);
  8035. });
  8036. }
  8037. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8038. #ifdef CPPHTTPLIB_SSL_ENABLED
  8039. using ClientT = SSLClient;
  8040. #else
  8041. using ClientT = Client;
  8042. #endif
  8043. TestWithHeadersAndContentReceiver<ClientT>(
  8044. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8045. const std::string &body, const std::string &content_type,
  8046. ContentReceiver receiver, DownloadProgress progress) {
  8047. return cli.Put(path, headers, body, content_type, receiver, progress);
  8048. });
  8049. }
  8050. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8051. #ifdef CPPHTTPLIB_SSL_ENABLED
  8052. using ClientT = SSLClient;
  8053. #else
  8054. using ClientT = Client;
  8055. #endif
  8056. TestWithHeadersAndContentReceiver<ClientT>(
  8057. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8058. const std::string &body, const std::string &content_type,
  8059. ContentReceiver receiver, DownloadProgress progress) {
  8060. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8061. });
  8062. }
  8063. template <typename ClientType>
  8064. void TestWithHeadersAndContentReceiverWithProgress(
  8065. ClientType &cli,
  8066. std::function<Result(ClientType &, const std::string &, const Headers &,
  8067. const std::string &, const std::string &,
  8068. ContentReceiver, DownloadProgress)>
  8069. request_func) {
  8070. Headers headers;
  8071. headers.emplace("X-Test-Header", "progress-test");
  8072. std::string received_body;
  8073. auto progress_called = false;
  8074. auto res = request_func(
  8075. cli, "/content_receiver", headers, "content", "text/plain",
  8076. [&](const char *data, size_t data_length) {
  8077. received_body.append(data, data_length);
  8078. return true;
  8079. },
  8080. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8081. progress_called = true;
  8082. return true;
  8083. });
  8084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8085. EXPECT_EQ(StatusCode::OK_200, res->status);
  8086. EXPECT_EQ("content", received_body);
  8087. EXPECT_TRUE(progress_called);
  8088. }
  8089. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8090. #ifdef CPPHTTPLIB_SSL_ENABLED
  8091. using ClientT = SSLClient;
  8092. #else
  8093. using ClientT = Client;
  8094. #endif
  8095. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8096. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8097. const std::string &body, const std::string &content_type,
  8098. ContentReceiver receiver, DownloadProgress progress) {
  8099. return cli.Post(path, headers, body, content_type, receiver, progress);
  8100. });
  8101. }
  8102. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8103. #ifdef CPPHTTPLIB_SSL_ENABLED
  8104. using ClientT = SSLClient;
  8105. #else
  8106. using ClientT = Client;
  8107. #endif
  8108. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8109. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8110. const std::string &body, const std::string &content_type,
  8111. ContentReceiver receiver, DownloadProgress progress) {
  8112. return cli.Put(path, headers, body, content_type, receiver, progress);
  8113. });
  8114. }
  8115. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8116. #ifdef CPPHTTPLIB_SSL_ENABLED
  8117. using ClientT = SSLClient;
  8118. #else
  8119. using ClientT = Client;
  8120. #endif
  8121. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8122. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8123. const std::string &body, const std::string &content_type,
  8124. ContentReceiver receiver, DownloadProgress progress) {
  8125. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8126. });
  8127. }
  8128. template <typename ClientType>
  8129. void TestWithHeadersAndContentReceiverError(
  8130. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8131. const Headers &, const std::string &,
  8132. const std::string &, ContentReceiver)>
  8133. request_func) {
  8134. Headers headers;
  8135. headers.emplace("X-Error-Test", "true");
  8136. std::string received_body;
  8137. auto receiver_failed = false;
  8138. auto res =
  8139. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8140. [&](const char *data, size_t data_length) {
  8141. received_body.append(data, data_length);
  8142. receiver_failed = true;
  8143. return false;
  8144. });
  8145. ASSERT_FALSE(res);
  8146. EXPECT_TRUE(receiver_failed);
  8147. }
  8148. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8149. #ifdef CPPHTTPLIB_SSL_ENABLED
  8150. using ClientT = SSLClient;
  8151. #else
  8152. using ClientT = Client;
  8153. #endif
  8154. TestWithHeadersAndContentReceiverError<ClientT>(
  8155. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8156. const std::string &body, const std::string &content_type,
  8157. ContentReceiver receiver) {
  8158. return cli.Post(path, headers, body, content_type, receiver);
  8159. });
  8160. }
  8161. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8162. #ifdef CPPHTTPLIB_SSL_ENABLED
  8163. using ClientT = SSLClient;
  8164. #else
  8165. using ClientT = Client;
  8166. #endif
  8167. TestWithHeadersAndContentReceiverError<ClientT>(
  8168. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8169. const std::string &body, const std::string &content_type,
  8170. ContentReceiver receiver) {
  8171. return cli.Put(path, headers, body, content_type, receiver);
  8172. });
  8173. }
  8174. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8175. #ifdef CPPHTTPLIB_SSL_ENABLED
  8176. using ClientT = SSLClient;
  8177. #else
  8178. using ClientT = Client;
  8179. #endif
  8180. TestWithHeadersAndContentReceiverError<ClientT>(
  8181. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8182. const std::string &body, const std::string &content_type,
  8183. ContentReceiver receiver) {
  8184. return cli.Patch(path, headers, body, content_type, receiver);
  8185. });
  8186. }
  8187. TEST_F(ServerTest, PostQueryStringAndBody) {
  8188. auto res =
  8189. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8191. ASSERT_EQ(StatusCode::OK_200, res->status);
  8192. }
  8193. TEST_F(ServerTest, HTTP2Magic) {
  8194. Request req;
  8195. req.method = "PRI";
  8196. req.path = "*";
  8197. req.body = "SM";
  8198. auto res = std::make_shared<Response>();
  8199. auto error = Error::Success;
  8200. auto ret = cli_.send(req, *res, error);
  8201. ASSERT_TRUE(ret);
  8202. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8203. }
  8204. TEST_F(ServerTest, KeepAlive) {
  8205. auto res = cli_.Get("/hi");
  8206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8207. EXPECT_EQ(StatusCode::OK_200, res->status);
  8208. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8209. EXPECT_EQ("Hello World!", res->body);
  8210. res = cli_.Get("/hi");
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8214. EXPECT_EQ("Hello World!", res->body);
  8215. res = cli_.Get("/hi");
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8219. EXPECT_EQ("Hello World!", res->body);
  8220. res = cli_.Get("/not-exist");
  8221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8223. res = cli_.Post("/empty", "", "text/plain");
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ(StatusCode::OK_200, res->status);
  8226. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8227. EXPECT_EQ("empty", res->body);
  8228. EXPECT_EQ("close", res->get_header_value("Connection"));
  8229. res = cli_.Post(
  8230. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8231. "text/plain");
  8232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8233. EXPECT_EQ(StatusCode::OK_200, res->status);
  8234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8235. EXPECT_EQ("empty", res->body);
  8236. cli_.set_keep_alive(false);
  8237. res = cli_.Get("/last-request");
  8238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8239. EXPECT_EQ(StatusCode::OK_200, res->status);
  8240. EXPECT_EQ("close", res->get_header_value("Connection"));
  8241. }
  8242. TEST_F(ServerTest, TooManyRedirect) {
  8243. cli_.set_follow_location(true);
  8244. auto res = cli_.Get("/redirect/0");
  8245. ASSERT_TRUE(!res);
  8246. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8247. }
  8248. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8249. Request req;
  8250. req.method = "FOOBAR";
  8251. req.path = "/hi";
  8252. cli_.set_keep_alive(true);
  8253. auto res = cli_.send(req);
  8254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8255. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8256. EXPECT_EQ("close", res->get_header_value("Connection"));
  8257. EXPECT_FALSE(cli_.is_socket_open());
  8258. }
  8259. TEST_F(ServerTest, CustomRouteReadsBody) {
  8260. const std::string xml =
  8261. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8262. Request req;
  8263. req.method = "PROPFIND";
  8264. req.path = "/dav/dir";
  8265. req.set_header("Depth", "1");
  8266. req.body = xml;
  8267. auto res = cli_.send(req);
  8268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8269. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8270. EXPECT_EQ(xml, res->body);
  8271. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8272. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8273. }
  8274. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8275. Request req;
  8276. req.method = "PROPFIND";
  8277. req.path = "/dav/42";
  8278. auto res = cli_.send(req);
  8279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8280. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8281. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8282. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8283. }
  8284. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8285. Request req;
  8286. req.method = "PROPFIND";
  8287. req.path = "/dav-re/123";
  8288. auto res = cli_.send(req);
  8289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8290. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8291. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8292. }
  8293. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8294. Request req;
  8295. req.method = "MKCOL";
  8296. req.path = "/dav-mkcol";
  8297. auto res = cli_.send(req);
  8298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8299. EXPECT_EQ(StatusCode::Created_201, res->status);
  8300. }
  8301. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8302. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8303. Request req;
  8304. req.method = "REPORT";
  8305. req.path = "/dav-report";
  8306. req.body = xml;
  8307. auto res = cli_.send(req);
  8308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8309. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8310. EXPECT_EQ(xml, res->body);
  8311. }
  8312. // A content reader route must fire even when the request carries no body,
  8313. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8314. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8315. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8316. Request req;
  8317. req.method = "REPORT";
  8318. req.path = "/dav-report";
  8319. auto res = cli_.send(req);
  8320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8321. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8322. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8323. }
  8324. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8325. Request req;
  8326. req.method = "PROPFIND";
  8327. req.path = "/not-dav";
  8328. auto res = cli_.send(req);
  8329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8331. }
  8332. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8333. Request req;
  8334. req.method = "UNLOCK";
  8335. req.path = "/dav/dir";
  8336. cli_.set_keep_alive(true);
  8337. auto res = cli_.send(req);
  8338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8339. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8340. EXPECT_EQ("close", res->get_header_value("Connection"));
  8341. EXPECT_FALSE(cli_.is_socket_open());
  8342. }
  8343. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8344. // The mount point serves this path, but only for GET and HEAD.
  8345. auto get_res = cli_.Get("/dir/index.html");
  8346. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8347. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8348. Request req;
  8349. req.method = "PROPFIND";
  8350. req.path = "/dir/index.html";
  8351. auto res = cli_.send(req);
  8352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8353. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8354. }
  8355. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8356. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8357. cli_.set_keep_alive(true);
  8358. for (auto i = 0; i < 2; i++) {
  8359. Request req;
  8360. req.method = "PROPFIND";
  8361. req.path = "/dav/dir";
  8362. req.body = xml;
  8363. auto res = cli_.send(req);
  8364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8365. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8366. EXPECT_EQ(xml, res->body);
  8367. EXPECT_TRUE(cli_.is_socket_open());
  8368. }
  8369. // A built-in method must still be served on the same connection.
  8370. cli_.set_keep_alive(false);
  8371. auto res = cli_.Get("/hi");
  8372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8373. EXPECT_EQ(StatusCode::OK_200, res->status);
  8374. EXPECT_EQ("close", res->get_header_value("Connection"));
  8375. }
  8376. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8377. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8378. Request req;
  8379. req.method = "PROPFIND";
  8380. req.path = "/dav/dir";
  8381. req.set_header("Expect", "100-continue");
  8382. req.body = xml;
  8383. auto res = cli_.send(req);
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8386. EXPECT_EQ(xml, res->body);
  8387. }
  8388. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8389. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8390. TEST_F(ServerTest, Gzip) {
  8391. Headers headers;
  8392. headers.emplace("Accept-Encoding", "gzip, deflate");
  8393. auto res = cli_.Get("/compress", headers);
  8394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8395. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8396. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8397. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8398. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8399. "7890123456789012345678901234567890",
  8400. res->body);
  8401. EXPECT_EQ(StatusCode::OK_200, res->status);
  8402. }
  8403. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8404. Headers headers;
  8405. headers.emplace("Accept-Encoding", "gzip, deflate");
  8406. auto res = cli_.Get("/compress-with-charset", headers);
  8407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8408. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8409. EXPECT_EQ("application/json; charset=utf-8",
  8410. res->get_header_value("Content-Type"));
  8411. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8412. "7890123456789012345678901234567890",
  8413. res->body);
  8414. EXPECT_EQ(StatusCode::OK_200, res->status);
  8415. }
  8416. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8417. Headers headers;
  8418. headers.emplace("Accept-Encoding", "");
  8419. auto res = cli_.Get("/compress", headers);
  8420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8421. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8422. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8423. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8424. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8425. "7890123456789012345678901234567890",
  8426. res->body);
  8427. EXPECT_EQ(StatusCode::OK_200, res->status);
  8428. }
  8429. TEST_F(ServerTest, GzipWithContentReceiver) {
  8430. Headers headers;
  8431. headers.emplace("Accept-Encoding", "gzip, deflate");
  8432. std::string body;
  8433. auto res =
  8434. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8435. EXPECT_EQ(100U, data_length);
  8436. body.append(data, data_length);
  8437. return true;
  8438. });
  8439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8440. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8441. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8442. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8443. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8444. "7890123456789012345678901234567890",
  8445. body);
  8446. EXPECT_EQ(StatusCode::OK_200, res->status);
  8447. }
  8448. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8449. Headers headers;
  8450. headers.emplace("Accept-Encoding", "gzip, deflate");
  8451. cli_.set_decompress(false);
  8452. auto res = cli_.Get("/compress", headers);
  8453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8454. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8456. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8457. EXPECT_EQ(33U, res->body.size());
  8458. EXPECT_EQ(StatusCode::OK_200, res->status);
  8459. }
  8460. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8461. Headers headers;
  8462. headers.emplace("Accept-Encoding", "");
  8463. std::string body;
  8464. auto res =
  8465. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8466. EXPECT_EQ(100U, data_length);
  8467. body.append(data, data_length);
  8468. return true;
  8469. });
  8470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8471. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8472. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8473. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8474. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8475. "7890123456789012345678901234567890",
  8476. body);
  8477. EXPECT_EQ(StatusCode::OK_200, res->status);
  8478. }
  8479. TEST_F(ServerTest, NoGzip) {
  8480. Headers headers;
  8481. headers.emplace("Accept-Encoding", "gzip, deflate");
  8482. auto res = cli_.Get("/nocompress", headers);
  8483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8484. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8485. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8486. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8487. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8488. "7890123456789012345678901234567890",
  8489. res->body);
  8490. EXPECT_EQ(StatusCode::OK_200, res->status);
  8491. }
  8492. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8493. Headers headers;
  8494. headers.emplace("Accept-Encoding", "gzip, deflate");
  8495. std::string body;
  8496. auto res = cli_.Get("/nocompress", headers,
  8497. [&](const char *data, size_t data_length) {
  8498. EXPECT_EQ(100U, data_length);
  8499. body.append(data, data_length);
  8500. return true;
  8501. });
  8502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8503. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8504. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8505. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8506. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8507. "7890123456789012345678901234567890",
  8508. body);
  8509. EXPECT_EQ(StatusCode::OK_200, res->status);
  8510. }
  8511. TEST_F(ServerTest, MultipartFormDataGzip) {
  8512. UploadFormDataItems items = {
  8513. {"key1", "test", "", ""},
  8514. {"key2", "--abcdefg123", "", ""},
  8515. };
  8516. cli_.set_compress(true);
  8517. auto res = cli_.Post("/compress-multipart", items);
  8518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8519. EXPECT_EQ(StatusCode::OK_200, res->status);
  8520. }
  8521. #endif
  8522. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8523. // Static file compression is opt-in, so these run their own server rather than
  8524. // flipping it on for the shared ServerTest fixture, which would silently
  8525. // rewrite what every other static file test is asserting.
  8526. class StaticFileCompressionTest : public ::testing::Test {
  8527. protected:
  8528. void TearDown() override {
  8529. if (t_.joinable()) {
  8530. svr_.stop();
  8531. t_.join();
  8532. }
  8533. }
  8534. int start(const std::function<void(Server &)> &configure = nullptr) {
  8535. // Serves the same tree as a directory of build-time compressed assets
  8536. // would be served: the mount point names the coding the files are already
  8537. // stored in. Registered before "/" so it is the one that matches.
  8538. svr_.set_mount_point("/pre-encoded", "./www",
  8539. {{"Content-Encoding", "gzip"}});
  8540. svr_.set_mount_point("/", "./www");
  8541. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8542. res.set_file_content("./www/dir/index.html", "text/html");
  8543. });
  8544. svr_.Get("/pre-encoded-file-content",
  8545. [](const Request & /*req*/, Response &res) {
  8546. res.set_header("Content-Encoding", "gzip");
  8547. res.set_file_content("./www/dir/index.html", "text/html");
  8548. });
  8549. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8550. res.set_content_provider(
  8551. 6, "text/plain",
  8552. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8553. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8554. return true;
  8555. });
  8556. });
  8557. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8558. res.set_content_provider(
  8559. 1000, "text/plain",
  8560. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8561. if (offset < 100) {
  8562. std::string data(100, 'A');
  8563. sink.write(data.data(), data.size());
  8564. return true;
  8565. }
  8566. std::this_thread::sleep_for(std::chrono::seconds(2));
  8567. std::string data(900, 'B');
  8568. sink.write(data.data(), data.size());
  8569. return true;
  8570. });
  8571. });
  8572. if (configure) { configure(svr_); }
  8573. auto port = svr_.bind_to_any_port(HOST);
  8574. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8575. svr_.wait_until_ready();
  8576. return port;
  8577. }
  8578. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8579. // Every file under ./www except 1MB.txt is smaller than the default
  8580. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8581. // it out of the way.
  8582. static void enable_without_floor(Server &svr) {
  8583. svr.set_static_file_compression(true);
  8584. svr.set_static_file_compression_min_length(0);
  8585. }
  8586. Server svr_;
  8587. std::thread t_;
  8588. };
  8589. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8590. auto port = start();
  8591. Client cli(HOST, port);
  8592. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8594. EXPECT_EQ(StatusCode::OK_200, res->status);
  8595. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8596. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8597. EXPECT_EQ(1048576U, res->body.size());
  8598. }
  8599. TEST_F(StaticFileCompressionTest, MountPoint) {
  8600. auto port = start(enable);
  8601. Client cli(HOST, port);
  8602. cli.set_decompress(false);
  8603. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8605. EXPECT_EQ(StatusCode::OK_200, res->status);
  8606. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8607. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8608. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8609. // The response stays self-delimiting: a length, not a chunked body.
  8610. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8611. EXPECT_EQ(std::to_string(res->body.size()),
  8612. res->get_header_value("Content-Length"));
  8613. EXPECT_LT(res->body.size(), 1048576U);
  8614. EXPECT_FALSE(res->body.empty());
  8615. }
  8616. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8617. auto port = start(enable);
  8618. Client cli(HOST, port);
  8619. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ(StatusCode::OK_200, res->status);
  8622. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8623. EXPECT_EQ(1048576U, res->body.size());
  8624. }
  8625. TEST_F(StaticFileCompressionTest, FileContent) {
  8626. auto port = start(enable_without_floor);
  8627. Client cli(HOST, port);
  8628. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8630. EXPECT_EQ(StatusCode::OK_200, res->status);
  8631. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8632. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8633. EXPECT_EQ(104U, res->body.size());
  8634. }
  8635. // A handler that serves an already-encoded file names the coding itself. The
  8636. // file-backed path decided its coding from Accept-Encoding and the content
  8637. // type alone, so it compressed the stored bytes a second time and appended a
  8638. // second Content-Encoding field line.
  8639. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8640. auto port = start(enable_without_floor);
  8641. Client cli(HOST, port);
  8642. cli.set_decompress(false);
  8643. auto res = cli.Get("/pre-encoded-file-content",
  8644. Headers{{"Accept-Encoding", "gzip"}});
  8645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8646. EXPECT_EQ(StatusCode::OK_200, res->status);
  8647. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8648. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8649. // Vary belongs to a coding the server chose, and it chose none here.
  8650. EXPECT_FALSE(res->has_header("Vary"));
  8651. // The file travels exactly as it is stored on disk.
  8652. EXPECT_EQ(104U, res->body.size());
  8653. }
  8654. // The 1MB file clears the default floor, so this one runs the configuration a
  8655. // deployment would actually have.
  8656. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8657. auto port = start(enable);
  8658. Client cli(HOST, port);
  8659. cli.set_decompress(false);
  8660. auto res =
  8661. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8663. EXPECT_EQ(StatusCode::OK_200, res->status);
  8664. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8665. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8666. EXPECT_FALSE(res->has_header("Vary"));
  8667. EXPECT_EQ(1048576U, res->body.size());
  8668. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8669. }
  8670. TEST_F(StaticFileCompressionTest, Head) {
  8671. auto port = start(enable);
  8672. Client cli(HOST, port);
  8673. cli.set_decompress(false);
  8674. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8675. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8676. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8678. EXPECT_EQ(StatusCode::OK_200, res->status);
  8679. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8680. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8681. // HEAD still reports the size a GET would return.
  8682. EXPECT_EQ(get->get_header_value("Content-Length"),
  8683. res->get_header_value("Content-Length"));
  8684. EXPECT_TRUE(res->body.empty());
  8685. }
  8686. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8687. auto port = start(enable);
  8688. Client cli(HOST, port);
  8689. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8690. {"Accept-Encoding", "gzip"}});
  8691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8693. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8694. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8695. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8696. EXPECT_EQ("cd", res->body);
  8697. }
  8698. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8699. auto port = start(enable);
  8700. Client cli(HOST, port);
  8701. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8703. EXPECT_EQ(StatusCode::OK_200, res->status);
  8704. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8705. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8706. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8707. }
  8708. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8709. auto port = start(enable);
  8710. Client cli(HOST, port);
  8711. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8713. EXPECT_EQ(StatusCode::OK_200, res->status);
  8714. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8715. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8716. EXPECT_TRUE(res->body.empty());
  8717. }
  8718. TEST_F(StaticFileCompressionTest, MinLength) {
  8719. auto port = start(enable);
  8720. Client cli(HOST, port);
  8721. // 104 bytes, well under the default floor. Compressing it would add the
  8722. // gzip header and trailer to a body that already fits in one packet.
  8723. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8725. EXPECT_EQ(StatusCode::OK_200, res->status);
  8726. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8727. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8728. }
  8729. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8730. auto port = start([](Server &svr) {
  8731. svr.set_static_file_compression(true);
  8732. svr.set_static_file_compression_min_length(1);
  8733. });
  8734. Client cli(HOST, port);
  8735. cli.set_decompress(false);
  8736. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8738. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8739. // A 9-byte file comes back larger than it went in, because gzip's header and
  8740. // trailer outweigh anything deflate can save. That is the end of the range
  8741. // the floor exists to keep out.
  8742. EXPECT_GT(res->body.size(), 9U);
  8743. }
  8744. TEST_F(StaticFileCompressionTest, MaxLength) {
  8745. auto port = start([](Server &svr) {
  8746. svr.set_static_file_compression(true);
  8747. svr.set_static_file_compression_min_length(0);
  8748. svr.set_static_file_compression_max_length(1024);
  8749. });
  8750. Client cli(HOST, port);
  8751. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8752. // defines `small` as a macro on Windows.
  8753. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8754. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8755. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8756. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8757. // Under it: compressed.
  8758. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8759. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8760. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8761. }
  8762. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8763. auto port = start(enable_without_floor);
  8764. Client cli(HOST, port);
  8765. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8766. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8767. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8768. auto identity_etag = identity->get_header_value("ETag");
  8769. ASSERT_FALSE(identity_etag.empty());
  8770. auto gzipped =
  8771. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8772. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8773. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8774. auto gzip_etag = gzipped->get_header_value("ETag");
  8775. ASSERT_FALSE(gzip_etag.empty());
  8776. // Two representations, two validators.
  8777. EXPECT_NE(identity_etag, gzip_etag);
  8778. // Each one revalidates against the request that would produce it...
  8779. auto fresh =
  8780. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8781. {"If-None-Match", gzip_etag}});
  8782. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8783. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8784. auto fresh_identity =
  8785. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8786. {"If-None-Match", identity_etag}});
  8787. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8788. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8789. // ...and not against the other representation.
  8790. auto crossed =
  8791. cli.Get("/dir/index.html",
  8792. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8793. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8794. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8795. }
  8796. // The opt-in covers responses the server reads off disk itself. A caller's own
  8797. // known-length provider keeps its Content-Length and, more importantly, keeps
  8798. // delivering incrementally: routing it through a compressor would hold every
  8799. // write back until zlib's window filled.
  8800. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8801. auto port = start(enable);
  8802. Client cli(HOST, port);
  8803. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8805. EXPECT_EQ(StatusCode::OK_200, res->status);
  8806. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8807. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8808. EXPECT_EQ("aaabbb", res->body);
  8809. }
  8810. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8811. auto port = start(enable);
  8812. Client cli(HOST, port);
  8813. cli.set_read_timeout(1, 0);
  8814. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8815. Headers{{"Accept-Encoding", "gzip"}});
  8816. ASSERT_TRUE(handle.is_valid());
  8817. // The provider writes 100 bytes and then stalls for longer than the read
  8818. // timeout. Those first bytes have to arrive anyway: run the response through
  8819. // a compressor and zlib holds them until its window fills, so the read would
  8820. // come back empty instead.
  8821. char buf[256];
  8822. auto n = handle.read(buf, sizeof(buf));
  8823. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8824. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8825. }
  8826. #endif
  8827. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8828. TEST_F(ServerTest, Brotli) {
  8829. Headers headers;
  8830. headers.emplace("Accept-Encoding", "br");
  8831. auto res = cli_.Get("/compress", headers);
  8832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8833. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8834. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8835. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8836. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8837. "7890123456789012345678901234567890",
  8838. res->body);
  8839. EXPECT_EQ(StatusCode::OK_200, res->status);
  8840. }
  8841. #endif
  8842. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8843. TEST_F(ServerTest, Zstd) {
  8844. Headers headers;
  8845. headers.emplace("Accept-Encoding", "zstd");
  8846. auto res = cli_.Get("/compress", headers);
  8847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8848. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8850. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8851. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8852. "7890123456789012345678901234567890",
  8853. res->body);
  8854. EXPECT_EQ(StatusCode::OK_200, res->status);
  8855. }
  8856. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8857. Headers headers;
  8858. headers.emplace("Accept-Encoding", "");
  8859. auto res = cli_.Get("/compress", headers);
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8863. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8864. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8865. "7890123456789012345678901234567890",
  8866. res->body);
  8867. EXPECT_EQ(StatusCode::OK_200, res->status);
  8868. }
  8869. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8870. Headers headers;
  8871. headers.emplace("Accept-Encoding", "zstd");
  8872. std::string body;
  8873. auto res =
  8874. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8875. EXPECT_EQ(100U, data_length);
  8876. body.append(data, data_length);
  8877. return true;
  8878. });
  8879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8880. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8881. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8882. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8883. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8884. "7890123456789012345678901234567890",
  8885. body);
  8886. EXPECT_EQ(StatusCode::OK_200, res->status);
  8887. }
  8888. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8889. Headers headers;
  8890. headers.emplace("Accept-Encoding", "zstd");
  8891. cli_.set_decompress(false);
  8892. auto res = cli_.Get("/compress", headers);
  8893. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8894. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8895. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8896. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8898. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8899. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8900. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8901. EXPECT_EQ(StatusCode::OK_200, res->status);
  8902. ASSERT_EQ(26U, res->body.size());
  8903. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8904. 0);
  8905. }
  8906. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8907. Headers headers;
  8908. headers.emplace("Accept-Encoding", "");
  8909. std::string body;
  8910. auto res =
  8911. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8912. EXPECT_EQ(100U, data_length);
  8913. body.append(data, data_length);
  8914. return true;
  8915. });
  8916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8917. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8919. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8920. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8921. "7890123456789012345678901234567890",
  8922. body);
  8923. EXPECT_EQ(StatusCode::OK_200, res->status);
  8924. }
  8925. TEST_F(ServerTest, NoZstd) {
  8926. Headers headers;
  8927. headers.emplace("Accept-Encoding", "zstd");
  8928. auto res = cli_.Get("/nocompress", headers);
  8929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8930. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8931. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8932. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8933. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8934. "7890123456789012345678901234567890",
  8935. res->body);
  8936. EXPECT_EQ(StatusCode::OK_200, res->status);
  8937. }
  8938. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8939. Headers headers;
  8940. headers.emplace("Accept-Encoding", "zstd");
  8941. std::string body;
  8942. auto res = cli_.Get("/nocompress", headers,
  8943. [&](const char *data, size_t data_length) {
  8944. EXPECT_EQ(100U, data_length);
  8945. body.append(data, data_length);
  8946. return true;
  8947. });
  8948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8949. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8950. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8951. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8952. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8953. "7890123456789012345678901234567890",
  8954. body);
  8955. EXPECT_EQ(StatusCode::OK_200, res->status);
  8956. }
  8957. // TODO: How to enable zstd ??
  8958. TEST_F(ServerTest, MultipartFormDataZstd) {
  8959. UploadFormDataItems items = {
  8960. {"key1", "test", "", ""},
  8961. {"key2", "--abcdefg123", "", ""},
  8962. };
  8963. Headers headers;
  8964. headers.emplace("Accept-Encoding", "zstd");
  8965. cli_.set_compress(true);
  8966. auto res = cli_.Post("/compress-multipart", headers, items);
  8967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8968. EXPECT_EQ(StatusCode::OK_200, res->status);
  8969. }
  8970. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8971. Headers headers;
  8972. headers.emplace("Accept-Encoding", "zstd");
  8973. cli_.set_compress(true);
  8974. auto res = cli_.Put(
  8975. "/put", headers, 3,
  8976. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8977. sink.os << "PUT";
  8978. return true;
  8979. },
  8980. "text/plain");
  8981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8982. EXPECT_EQ(StatusCode::OK_200, res->status);
  8983. EXPECT_EQ("PUT", res->body);
  8984. }
  8985. // Pre-compression logging tests
  8986. TEST_F(ServerTest, PreCompressionLogging) {
  8987. // Test data for compression (matches the actual /compress endpoint content)
  8988. const std::string test_content =
  8989. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8990. "3456789012345678901234567890";
  8991. // Variables to capture logging data
  8992. std::string pre_compression_body;
  8993. std::string pre_compression_content_type;
  8994. std::string pre_compression_content_encoding;
  8995. std::string post_compression_body;
  8996. std::string post_compression_content_type;
  8997. std::string post_compression_content_encoding;
  8998. // Set up pre-compression logger
  8999. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9000. const Response &res) {
  9001. pre_compression_body = res.body;
  9002. pre_compression_content_type = res.get_header_value("Content-Type");
  9003. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9004. });
  9005. // Set up post-compression logger
  9006. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9007. post_compression_body = res.body;
  9008. post_compression_content_type = res.get_header_value("Content-Type");
  9009. post_compression_content_encoding =
  9010. res.get_header_value("Content-Encoding");
  9011. });
  9012. // Test with gzip compression
  9013. Headers headers;
  9014. headers.emplace("Accept-Encoding", "gzip");
  9015. auto res = cli_.Get("/compress", headers);
  9016. // Verify response was compressed
  9017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9018. EXPECT_EQ(StatusCode::OK_200, res->status);
  9019. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9020. // Verify pre-compression logger captured uncompressed content
  9021. EXPECT_EQ(test_content, pre_compression_body);
  9022. EXPECT_EQ("text/plain", pre_compression_content_type);
  9023. EXPECT_TRUE(pre_compression_content_encoding
  9024. .empty()); // No encoding header before compression
  9025. // Verify post-compression logger captured compressed content
  9026. EXPECT_NE(test_content,
  9027. post_compression_body); // Should be different after compression
  9028. EXPECT_EQ("text/plain", post_compression_content_type);
  9029. EXPECT_EQ("gzip", post_compression_content_encoding);
  9030. // Verify compressed content is smaller
  9031. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9032. }
  9033. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9034. const std::string test_content =
  9035. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9036. "3456789012345678901234567890";
  9037. std::string pre_compression_body;
  9038. std::string post_compression_body;
  9039. svr_.set_pre_compression_logger(
  9040. [&](const Request & /*req*/, const Response &res) {
  9041. pre_compression_body = res.body;
  9042. });
  9043. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9044. post_compression_body = res.body;
  9045. });
  9046. Headers headers;
  9047. headers.emplace("Accept-Encoding", "br");
  9048. auto res = cli_.Get("/compress", headers);
  9049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9050. EXPECT_EQ(StatusCode::OK_200, res->status);
  9051. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9052. // Verify pre-compression content is uncompressed
  9053. EXPECT_EQ(test_content, pre_compression_body);
  9054. // Verify post-compression content is compressed
  9055. EXPECT_NE(test_content, post_compression_body);
  9056. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9057. }
  9058. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9059. const std::string test_content =
  9060. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9061. "3456789012345678901234567890";
  9062. std::string pre_compression_body;
  9063. std::string post_compression_body;
  9064. svr_.set_pre_compression_logger(
  9065. [&](const Request & /*req*/, const Response &res) {
  9066. pre_compression_body = res.body;
  9067. });
  9068. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9069. post_compression_body = res.body;
  9070. });
  9071. // Request without compression (use /nocompress endpoint)
  9072. Headers headers;
  9073. auto res = cli_.Get("/nocompress", headers);
  9074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9075. EXPECT_EQ(StatusCode::OK_200, res->status);
  9076. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9077. // Pre-compression logger should not be called when no compression is applied
  9078. EXPECT_TRUE(
  9079. pre_compression_body.empty()); // Pre-compression logger not called
  9080. EXPECT_EQ(
  9081. test_content,
  9082. post_compression_body); // Post-compression logger captures final content
  9083. }
  9084. TEST_F(ServerTest, LoggerSeesContentLength) {
  9085. size_t logged_content_length = 0;
  9086. std::string logged_content_length_header;
  9087. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9088. logged_content_length = res.content_length_;
  9089. logged_content_length_header = res.get_header_value("Content-Length");
  9090. });
  9091. auto res = cli_.Get("/nocompress");
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. EXPECT_EQ(res->body.size(), logged_content_length);
  9095. EXPECT_EQ(std::to_string(logged_content_length),
  9096. logged_content_length_header);
  9097. }
  9098. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9099. const std::string test_content =
  9100. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9101. "3456789012345678901234567890";
  9102. std::string pre_compression_body;
  9103. bool pre_logger_called = false;
  9104. // Set only pre-compression logger
  9105. svr_.set_pre_compression_logger(
  9106. [&](const Request & /*req*/, const Response &res) {
  9107. pre_compression_body = res.body;
  9108. pre_logger_called = true;
  9109. });
  9110. Headers headers;
  9111. headers.emplace("Accept-Encoding", "gzip");
  9112. auto res = cli_.Get("/compress", headers);
  9113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9114. EXPECT_EQ(StatusCode::OK_200, res->status);
  9115. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9116. // Verify pre-compression logger was called
  9117. EXPECT_TRUE(pre_logger_called);
  9118. EXPECT_EQ(test_content, pre_compression_body);
  9119. }
  9120. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9121. {
  9122. // Test with Expect: 100-continue header - success case
  9123. // Server returns 100 Continue, client sends body, server returns 200 OK
  9124. Request req;
  9125. req.method = "POST";
  9126. req.path = "/post-large";
  9127. req.set_header("Expect", "100-continue");
  9128. req.body = LARGE_DATA;
  9129. Response res;
  9130. auto error = Error::Success;
  9131. cli_.set_keep_alive(true);
  9132. auto ret = cli_.send(req, res, error);
  9133. EXPECT_TRUE(ret);
  9134. EXPECT_EQ(StatusCode::OK_200, res.status);
  9135. EXPECT_EQ(LARGE_DATA, res.body);
  9136. }
  9137. {
  9138. // Test with Expect: 100-continue header - error case
  9139. // Client should not send the body when server returns an error
  9140. Request req;
  9141. req.method = "POST";
  9142. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9143. req.set_header("Expect", "100-continue");
  9144. req.body = LARGE_DATA;
  9145. Response res;
  9146. auto error = Error::Success;
  9147. auto start = std::chrono::high_resolution_clock::now();
  9148. cli_.set_keep_alive(true);
  9149. auto ret = cli_.send(req, res, error);
  9150. auto end = std::chrono::high_resolution_clock::now();
  9151. auto elapsed =
  9152. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9153. .count();
  9154. // With Expect: 100-continue, request completes successfully but with error
  9155. EXPECT_TRUE(ret);
  9156. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9157. EXPECT_EQ("close", res.get_header_value("Connection"));
  9158. EXPECT_FALSE(cli_.is_socket_open());
  9159. EXPECT_LE(elapsed, 2000);
  9160. }
  9161. {
  9162. // Send an extra GET request to ensure error recovery without hanging
  9163. Request req;
  9164. req.method = "GET";
  9165. req.path = "/hi";
  9166. auto start = std::chrono::high_resolution_clock::now();
  9167. auto res = cli_.send(req);
  9168. auto end = std::chrono::high_resolution_clock::now();
  9169. auto elapsed =
  9170. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9171. .count();
  9172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9173. EXPECT_EQ(StatusCode::OK_200, res->status);
  9174. EXPECT_EQ("Hello World!", res->body);
  9175. EXPECT_LE(elapsed, 500);
  9176. }
  9177. }
  9178. TEST(ZstdDecompressor, ChunkedDecompression) {
  9179. std::string data;
  9180. for (size_t i = 0; i < 32 * 1024; ++i) {
  9181. data.push_back(static_cast<char>('a' + i % 26));
  9182. }
  9183. std::string compressed_data;
  9184. {
  9185. httplib::detail::zstd_compressor compressor;
  9186. bool result = compressor.compress(
  9187. data.data(), data.size(),
  9188. /*last=*/true,
  9189. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9190. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9191. compressed_data_size);
  9192. return true;
  9193. });
  9194. ASSERT_TRUE(result);
  9195. }
  9196. std::string decompressed_data;
  9197. {
  9198. httplib::detail::zstd_decompressor decompressor;
  9199. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9200. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9201. size_t chunk_size = 130;
  9202. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9203. chunk_begin += chunk_size) {
  9204. size_t current_chunk_size =
  9205. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9206. bool result = decompressor.decompress(
  9207. compressed_data.data() + chunk_begin, current_chunk_size,
  9208. [&](const char *decompressed_data_chunk,
  9209. size_t decompressed_data_chunk_size) {
  9210. decompressed_data.insert(decompressed_data.size(),
  9211. decompressed_data_chunk,
  9212. decompressed_data_chunk_size);
  9213. return true;
  9214. });
  9215. ASSERT_TRUE(result);
  9216. }
  9217. }
  9218. ASSERT_EQ(data, decompressed_data);
  9219. }
  9220. TEST(ZstdDecompressor, Decompress) {
  9221. std::string original_text = "Compressed with ZSTD";
  9222. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9223. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9224. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9225. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9226. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9227. std::string decompressed_data;
  9228. {
  9229. httplib::detail::zstd_decompressor decompressor;
  9230. bool result = decompressor.decompress(
  9231. compressed_data.data(), compressed_data.size(),
  9232. [&](const char *decompressed_data_chunk,
  9233. size_t decompressed_data_chunk_size) {
  9234. decompressed_data.insert(decompressed_data.size(),
  9235. decompressed_data_chunk,
  9236. decompressed_data_chunk_size);
  9237. return true;
  9238. });
  9239. ASSERT_TRUE(result);
  9240. }
  9241. ASSERT_EQ(original_text, decompressed_data);
  9242. }
  9243. #endif
  9244. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9245. // separate chunks so that the server sees each part in its own read(). Used to
  9246. // place a read boundary at a specific offset of a request body.
  9247. static bool send_request_in_parts(time_t read_timeout_sec,
  9248. const std::vector<std::string> &parts,
  9249. std::string *resp = nullptr,
  9250. int port = PORT) {
  9251. auto error = Error::Success;
  9252. auto client_sock = detail::create_client_socket(
  9253. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9254. /*connection_timeout_sec=*/5, 0,
  9255. /*read_timeout_sec=*/5, 0,
  9256. /*write_timeout_sec=*/5, 0, std::string(), error);
  9257. if (client_sock == INVALID_SOCKET) { return false; }
  9258. auto ret = detail::process_client_socket(
  9259. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9260. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9261. for (size_t i = 0; i < parts.size(); i++) {
  9262. const auto &part = parts[i];
  9263. if (part.size() !=
  9264. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9265. return false;
  9266. }
  9267. if (i + 1 < parts.size()) {
  9268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9269. }
  9270. }
  9271. char buf[512];
  9272. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9273. while (line_reader.getline()) {
  9274. if (resp) { *resp += line_reader.ptr(); }
  9275. }
  9276. return true;
  9277. });
  9278. detail::close_socket(client_sock);
  9279. return ret;
  9280. }
  9281. // Sends a raw request to a server listening at HOST:PORT.
  9282. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9283. std::string *resp = nullptr, int port = PORT) {
  9284. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9285. }
  9286. #ifdef CPPHTTPLIB_SSL_ENABLED
  9287. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9289. ASSERT_TRUE(svr.is_valid());
  9290. svr.set_read_timeout(1, 0);
  9291. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9292. auto se = detail::scope_exit([&] {
  9293. svr.stop();
  9294. t.join();
  9295. ASSERT_FALSE(svr.is_running());
  9296. });
  9297. svr.wait_until_ready();
  9298. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9299. // keeps each wait well within the read timeout. The server gives up a
  9300. // second in, so the bytes sent after that fail.
  9301. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9302. parts.resize(26, std::string(1, '\0'));
  9303. EXPECT_FALSE(send_request_in_parts(5, parts));
  9304. }
  9305. #endif
  9306. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9307. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9308. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9309. const std::vector<std::string> &parts,
  9310. std::string *resp = nullptr,
  9311. int port = PORT) {
  9312. auto error = Error::Success;
  9313. auto sock = detail::create_client_socket(
  9314. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9315. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9316. /*write_timeout_sec=*/5, 0, std::string(), error);
  9317. if (sock == INVALID_SOCKET) { return false; }
  9318. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9319. auto ctx = SSL_CTX_new(TLS_client_method());
  9320. auto ssl = SSL_new(ctx);
  9321. auto ssl_se = detail::scope_exit([&] {
  9322. SSL_free(ssl);
  9323. SSL_CTX_free(ctx);
  9324. });
  9325. SSL_set_fd(ssl, static_cast<int>(sock));
  9326. if (SSL_connect(ssl) != 1) { return false; }
  9327. for (size_t i = 0; i < parts.size(); i++) {
  9328. const auto &part = parts[i];
  9329. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9330. static_cast<int>(part.size())) {
  9331. return false;
  9332. }
  9333. if (i + 1 < parts.size()) {
  9334. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9335. }
  9336. }
  9337. char buf[512];
  9338. int n;
  9339. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9340. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9341. }
  9342. return true;
  9343. }
  9344. #endif
  9345. // The request line, then a header value a byte at a time.
  9346. static std::vector<std::string> slow_request_head_parts() {
  9347. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9348. parts.resize(26, "a");
  9349. parts.emplace_back("\r\n\r\n");
  9350. return parts;
  9351. }
  9352. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9353. // within the one-second read timeout. The server gives up a second in, before
  9354. // the head is complete.
  9355. static void
  9356. expect_slow_request_head_dropped(Server &svr,
  9357. const std::function<std::string()> &send) {
  9358. std::atomic<bool> handled(false);
  9359. svr.Get("/", [&](const Request &, Response &res) {
  9360. handled = true;
  9361. res.set_content("ok", "text/plain");
  9362. });
  9363. svr.set_read_timeout(1, 0);
  9364. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9365. auto se = detail::scope_exit([&] {
  9366. svr.stop();
  9367. t.join();
  9368. ASSERT_FALSE(svr.is_running());
  9369. });
  9370. svr.wait_until_ready();
  9371. auto resp = send();
  9372. EXPECT_FALSE(handled);
  9373. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9374. }
  9375. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9376. Server svr;
  9377. expect_slow_request_head_dropped(svr, [] {
  9378. std::string resp;
  9379. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9380. return resp;
  9381. });
  9382. }
  9383. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9384. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9386. ASSERT_TRUE(svr.is_valid());
  9387. expect_slow_request_head_dropped(svr, [] {
  9388. std::string resp;
  9389. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9390. return resp;
  9391. });
  9392. }
  9393. #endif
  9394. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9395. Server svr;
  9396. std::string header_value;
  9397. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9398. header_value = req.get_header_value("foo");
  9399. res.set_content("ok", "text/plain");
  9400. });
  9401. thread t = thread([&] { svr.listen(HOST, PORT); });
  9402. auto se = detail::scope_exit([&] {
  9403. svr.stop();
  9404. t.join();
  9405. ASSERT_FALSE(svr.is_running());
  9406. });
  9407. svr.wait_until_ready();
  9408. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9409. // like characters are not treated the same - use vertical tab and escape.
  9410. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9411. "foo: \t \v bar \x1B\t \r\n"
  9412. "Connection: close\r\n"
  9413. "\r\n";
  9414. std::string res;
  9415. ASSERT_TRUE(send_request(5, req, &res));
  9416. EXPECT_EQ(header_value, "");
  9417. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9418. }
  9419. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9420. Server svr;
  9421. std::string received;
  9422. svr.Get("/order", [&](const Request &req, Response &res) {
  9423. received = entries_to_string(req.headers);
  9424. res.set_content("ok", "text/plain");
  9425. });
  9426. auto port = svr.bind_to_any_port(HOST);
  9427. thread t = thread([&] { svr.listen_after_bind(); });
  9428. auto se = detail::scope_exit([&] {
  9429. svr.stop();
  9430. t.join();
  9431. ASSERT_FALSE(svr.is_running());
  9432. });
  9433. svr.wait_until_ready();
  9434. const std::string req = "GET /order HTTP/1.1\r\n"
  9435. "Host: localhost\r\n"
  9436. "X-First: 1\r\n"
  9437. "X-Dup: a\r\n"
  9438. "X-Second: 2\r\n"
  9439. "X-Dup: b\r\n"
  9440. "Connection: close\r\n"
  9441. "\r\n";
  9442. std::string res;
  9443. ASSERT_TRUE(send_request(5, req, &res, port));
  9444. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9445. EXPECT_EQ(
  9446. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9447. received);
  9448. }
  9449. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9450. Server svr;
  9451. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9452. res.set_header("Set-Cookie", "first=1");
  9453. res.set_header("X-Between", "y");
  9454. res.set_header("Set-Cookie", "second=2");
  9455. res.set_content("ok", "text/plain");
  9456. });
  9457. auto port = svr.bind_to_any_port(HOST);
  9458. thread t = thread([&] { svr.listen_after_bind(); });
  9459. auto se = detail::scope_exit([&] {
  9460. svr.stop();
  9461. t.join();
  9462. ASSERT_FALSE(svr.is_running());
  9463. });
  9464. svr.wait_until_ready();
  9465. Client cli(HOST, port);
  9466. auto res = cli.Get("/cookies");
  9467. ASSERT_TRUE(res);
  9468. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9469. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9470. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9471. }
  9472. // A stream may send a byte at a time with a small extension on each chunk,
  9473. // however long it runs
  9474. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9475. Server svr;
  9476. svr.Post("/count", [](const Request &req, Response &res) {
  9477. res.set_content(std::to_string(req.body.size()), "text/plain");
  9478. });
  9479. auto port = svr.bind_to_any_port(HOST);
  9480. ASSERT_LT(0, port);
  9481. thread t = thread([&] { svr.listen_after_bind(); });
  9482. auto se = detail::scope_exit([&] {
  9483. svr.stop();
  9484. t.join();
  9485. ASSERT_FALSE(svr.is_running());
  9486. });
  9487. svr.wait_until_ready();
  9488. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9489. "\r\nTransfer-Encoding: chunked\r\n"
  9490. "Connection: close\r\n\r\n";
  9491. for (auto i = 0; i < 4096; i++) {
  9492. req += "1;a=b\r\nx\r\n";
  9493. }
  9494. req += "0\r\n\r\n";
  9495. std::string res;
  9496. ASSERT_TRUE(send_request(5, req, &res, port));
  9497. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9498. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9499. }
  9500. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9501. Server svr;
  9502. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9503. auto i = new int(0);
  9504. res.set_header("Trailer", "X-Safe, X-Reflected");
  9505. res.set_chunked_content_provider(
  9506. "text/plain",
  9507. [i](size_t /*offset*/, DataSink &sink) {
  9508. if (*i == 0) {
  9509. sink.os << "body";
  9510. } else {
  9511. Headers trailer;
  9512. // A valid trailer that must survive.
  9513. trailer.emplace("X-Safe", "safe");
  9514. // Attacker-controlled value carrying CR/LF (response splitting).
  9515. trailer.emplace("X-Reflected",
  9516. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9517. // Attacker-controlled name carrying CR/LF.
  9518. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9519. sink.done_with_trailer(trailer);
  9520. }
  9521. (*i)++;
  9522. return true;
  9523. },
  9524. [i](bool /*success*/) { delete i; });
  9525. });
  9526. thread t = thread([&] { svr.listen(HOST, PORT); });
  9527. auto se = detail::scope_exit([&] {
  9528. svr.stop();
  9529. t.join();
  9530. ASSERT_FALSE(svr.is_running());
  9531. });
  9532. svr.wait_until_ready();
  9533. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9534. "Host: " + HOST +
  9535. "\r\n"
  9536. "Connection: close\r\n"
  9537. "\r\n";
  9538. std::string res;
  9539. ASSERT_TRUE(send_request(5, req, &res));
  9540. // The injected fields must not appear anywhere in the raw response.
  9541. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9542. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9543. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9544. // Invalid trailers are dropped entirely, matching set_header().
  9545. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9546. // The valid trailer still passes through.
  9547. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9548. }
  9549. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9550. // A custom header writer gets only the fields the default one writes
  9551. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9552. std::string s;
  9553. for (const auto &h : hdrs) {
  9554. s += h.first + ": " + h.second + "\r\n";
  9555. }
  9556. s += "\r\n";
  9557. return strm.write(s.data(), s.size());
  9558. };
  9559. for (auto custom_writer : {false, true}) {
  9560. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9561. Server svr;
  9562. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9563. svr.set_post_routing_handler([](const Request &, Response &res) {
  9564. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9565. });
  9566. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9567. // res.headers is a public field an application can populate directly,
  9568. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9569. // A valid header that must survive.
  9570. res.headers.emplace("X-Safe", "safe");
  9571. // Attacker-controlled value carrying CR/LF (response splitting).
  9572. res.headers.emplace("X-Reflected",
  9573. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9574. // Attacker-controlled name carrying CR/LF.
  9575. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9576. res.set_content("body", "text/plain");
  9577. });
  9578. thread t = thread([&] { svr.listen(HOST, PORT); });
  9579. auto se = detail::scope_exit([&] {
  9580. svr.stop();
  9581. t.join();
  9582. ASSERT_FALSE(svr.is_running());
  9583. });
  9584. svr.wait_until_ready();
  9585. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9586. "Host: " + HOST +
  9587. "\r\n"
  9588. "Connection: close\r\n"
  9589. "\r\n";
  9590. std::string res;
  9591. ASSERT_TRUE(send_request(5, req, &res));
  9592. // The injected fields must not appear anywhere in the raw response.
  9593. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9594. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9595. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9596. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9597. // Invalid headers are dropped entirely, matching set_header().
  9598. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9599. // The valid header still passes through.
  9600. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9601. }
  9602. }
  9603. // Forward declaration: in split builds split.py strips `inline` and moves the
  9604. // definition into httplib.cc, so detail::write_request_line is not visible from
  9605. // the public httplib.h. Re-declaring it here lets the tests link against the
  9606. // symbol in both header-only and split builds.
  9607. namespace httplib {
  9608. namespace detail {
  9609. ssize_t write_request_line(Stream &strm, const std::string &method,
  9610. const std::string &path);
  9611. } // namespace detail
  9612. } // namespace httplib
  9613. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9614. // A well-formed target is written verbatim.
  9615. {
  9616. detail::BufferStream strm;
  9617. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9618. EXPECT_GT(n, 0);
  9619. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9620. }
  9621. // A target carrying CR/LF, SP or other control octets must be rejected
  9622. // before anything reaches the wire, otherwise it splits the request line and
  9623. // injects a header or a whole request.
  9624. const std::string evil_targets[] = {
  9625. "/a\r\nInjected: pwned",
  9626. "/a\rInjected",
  9627. "/a\nInjected",
  9628. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9629. "/a b",
  9630. "/a\tb",
  9631. "/a\x7f",
  9632. };
  9633. for (const auto &evil : evil_targets) {
  9634. detail::BufferStream strm;
  9635. auto n = detail::write_request_line(strm, "GET", evil);
  9636. EXPECT_LT(n, 0);
  9637. EXPECT_TRUE(strm.get_buffer().empty());
  9638. }
  9639. }
  9640. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9641. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9642. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9643. // target reaches write_request. The client must fail cleanly with
  9644. // Error::Write instead of putting a request-line-less, header-injecting
  9645. // request on the wire.
  9646. Server svr;
  9647. svr.Get("/a", [](const Request &, Response &res) {
  9648. res.set_content("ok", "text/plain");
  9649. });
  9650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9651. auto se = detail::scope_exit([&] {
  9652. svr.stop();
  9653. thread.join();
  9654. ASSERT_FALSE(svr.is_running());
  9655. });
  9656. svr.wait_until_ready();
  9657. {
  9658. Client cli(HOST, PORT);
  9659. cli.set_path_encode(false);
  9660. // The request is rejected before anything is written, so the connection
  9661. // stays silent and the subsequent response read would otherwise block for
  9662. // the full default read timeout. Shorten it -- the assertion is on the
  9663. // error, not the timeout.
  9664. cli.set_read_timeout(1, 0);
  9665. auto res = cli.Get("/a\r\nInjected: pwned");
  9666. EXPECT_FALSE(res);
  9667. EXPECT_EQ(Error::Write, res.error());
  9668. }
  9669. }
  9670. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9671. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9672. // including extension methods.
  9673. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9674. for (const auto &method : good_methods) {
  9675. detail::BufferStream strm;
  9676. auto n = detail::write_request_line(strm, method, "/");
  9677. EXPECT_GT(n, 0);
  9678. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9679. }
  9680. // A method carrying CR/LF would split the request line and smuggle a whole
  9681. // request ahead of the real one. A space or an empty method corrupts the
  9682. // request line. All must be rejected before anything reaches the wire.
  9683. const std::string evil_methods[] = {
  9684. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9685. "GET\r\nInjected: pwned",
  9686. "GET\r",
  9687. "GET\n",
  9688. "GE T",
  9689. "",
  9690. };
  9691. for (const auto &evil : evil_methods) {
  9692. detail::BufferStream strm;
  9693. auto n = detail::write_request_line(strm, evil, "/");
  9694. EXPECT_LT(n, 0);
  9695. EXPECT_TRUE(strm.get_buffer().empty());
  9696. }
  9697. }
  9698. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9699. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9700. // through Client::send must fail with Error::Write and no request, neither
  9701. // the smuggled one nor the real one, may reach the server.
  9702. Server svr;
  9703. std::atomic<int> request_count(0);
  9704. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9705. request_count++;
  9706. res.status = StatusCode::OK_200;
  9707. return Server::HandlerResponse::Handled;
  9708. });
  9709. auto port = svr.bind_to_any_port(HOST);
  9710. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9711. auto se = detail::scope_exit([&] {
  9712. svr.stop();
  9713. thread.join();
  9714. ASSERT_FALSE(svr.is_running());
  9715. });
  9716. svr.wait_until_ready();
  9717. {
  9718. Client cli(HOST, port);
  9719. const std::string evil_methods[] = {
  9720. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9721. "GE T",
  9722. "",
  9723. };
  9724. for (const auto &evil : evil_methods) {
  9725. Request req;
  9726. req.method = evil;
  9727. req.path = "/";
  9728. auto res = cli.send(req);
  9729. EXPECT_FALSE(res);
  9730. EXPECT_EQ(Error::Write, res.error());
  9731. }
  9732. auto handle =
  9733. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9734. EXPECT_FALSE(handle.is_valid());
  9735. EXPECT_EQ(Error::Write, handle.error);
  9736. // A valid request on the same client still goes through.
  9737. auto res = cli.Get("/");
  9738. ASSERT_TRUE(res);
  9739. EXPECT_EQ(StatusCode::OK_200, res->status);
  9740. }
  9741. EXPECT_EQ(1, request_count.load());
  9742. }
  9743. // Sends a raw request and verifies that there isn't a crash or exception.
  9744. static void test_raw_request(const std::string &req,
  9745. std::string *out = nullptr) {
  9746. Server svr;
  9747. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9748. res.set_content("ok", "text/plain");
  9749. });
  9750. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9751. res.set_content("ok", "text/plain");
  9752. });
  9753. svr.Get("/header_field_value_check",
  9754. [&](const Request & /*req*/, Response &res) {
  9755. res.set_content("ok", "text/plain");
  9756. });
  9757. svr.CustomRoute("PROPFIND", "/dav",
  9758. [&](const Request & /*req*/, Response &res) {
  9759. res.status = StatusCode::MultiStatus_207;
  9760. });
  9761. // Server read timeout must be longer than the client read timeout for the
  9762. // bug to reproduce, probably to force the server to process a request
  9763. // without a trailing blank line.
  9764. const time_t client_read_timeout_sec = 1;
  9765. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9766. bool listen_thread_ok = false;
  9767. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9768. auto se = detail::scope_exit([&] {
  9769. svr.stop();
  9770. t.join();
  9771. ASSERT_FALSE(svr.is_running());
  9772. EXPECT_TRUE(listen_thread_ok);
  9773. });
  9774. svr.wait_until_ready();
  9775. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9776. }
  9777. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9778. // A certain header line causes an exception if the header property is parsed
  9779. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9780. test_raw_request(
  9781. "GET /hi HTTP/1.1\r\n"
  9782. " : "
  9783. " "
  9784. " ");
  9785. }
  9786. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9787. // A certain header line causes an exception if the header property *name* is
  9788. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9789. // greedy matcher and requires backtracking when there are a lot of ":"
  9790. // characters.
  9791. // This occurs with libc++ but not libstdc++.
  9792. test_raw_request(
  9793. "GET /hi HTTP/1.1\r\n"
  9794. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9795. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9796. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9797. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9798. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9799. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9800. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9801. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9802. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9803. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9804. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9805. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9806. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9807. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9808. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9809. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9810. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9811. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9812. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9813. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9814. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9815. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9816. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9817. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9818. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9819. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9820. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9821. "&&&%%%");
  9822. }
  9823. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9824. // Make sure this doesn't crash the server.
  9825. // In a previous version of the header line regex, the "\r" rendered the line
  9826. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9827. // a new position where the leading white space ended and the field value
  9828. // began.
  9829. // The crash occurs with libc++ but not libstdc++.
  9830. test_raw_request("GET /hi HTTP/1.1\r\n"
  9831. "a:" +
  9832. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9833. "\r\n"
  9834. "\r\n");
  9835. }
  9836. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9837. const char *rejected[] = {
  9838. // RFC 9112 §3: one SP between the parts, and nothing else
  9839. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9840. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9841. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9842. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9843. // A request-target has no fragment
  9844. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9845. // An HTTP/1.1 request needs a Host
  9846. "GET /hi HTTP/1.1\r\n\r\n",
  9847. };
  9848. for (auto request : rejected) {
  9849. std::string out;
  9850. test_raw_request(request, &out);
  9851. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9852. }
  9853. std::string out;
  9854. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9855. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9856. }
  9857. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9858. // RFC 9112 §6.1
  9859. const char *requests[] = {
  9860. "PUT /put_hi HTTP/1.1\r\n"
  9861. "Host: localhost\r\n"
  9862. "Content-Length: 0\r\n"
  9863. "Transfer-Encoding: chunked\r\n"
  9864. "\r\n"
  9865. "0\r\n\r\n",
  9866. "PUT /put_hi HTTP/1.0\r\n"
  9867. "Connection: keep-alive\r\n"
  9868. "Transfer-Encoding: chunked\r\n"
  9869. "\r\n"
  9870. "0\r\n\r\n",
  9871. };
  9872. for (auto request : requests) {
  9873. std::string out;
  9874. test_raw_request(request, &out);
  9875. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9876. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9877. }
  9878. }
  9879. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9880. std::string out;
  9881. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9882. "Content-Type: text/plain\r\n"
  9883. "Transfer-Encoding: chunked\r\n"
  9884. "\r\n"
  9885. "nothex\r\n",
  9886. &out);
  9887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9888. }
  9889. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9890. std::string out;
  9891. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9892. "Content-Type: text/plain\r\n"
  9893. "Transfer-Encoding: chunked\r\n"
  9894. "\r\n"
  9895. "3\r\n"
  9896. "xyz\r\n"
  9897. "NaN\r\n",
  9898. &out);
  9899. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9900. }
  9901. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9902. std::string out;
  9903. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9904. "Content-Type: text/plain\r\n"
  9905. "Transfer-Encoding: chunked\r\n"
  9906. "\r\n"
  9907. // Length is too large for 64 bits.
  9908. "1ffffffffffffffff\r\n"
  9909. "xyz\r\n",
  9910. &out);
  9911. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9912. }
  9913. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9914. test_raw_request("GET /hi HTTP/1.1\r\n"
  9915. "Content-Type: text/plain\r\n\r");
  9916. }
  9917. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9918. std::string out;
  9919. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9920. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9921. }
  9922. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9923. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9924. std::string out;
  9925. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9926. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9927. }
  9928. }
  9929. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9930. std::string out;
  9931. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9932. "Host: localhost\r\n"
  9933. "Connection: close\r\n\r\n",
  9934. &out);
  9935. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9936. }
  9937. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9938. Server svr;
  9939. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9940. EXPECT_TRUE(!req.remote_addr.empty());
  9941. });
  9942. thread t = thread([&] { svr.listen(HOST, PORT); });
  9943. auto se = detail::scope_exit([&] {
  9944. svr.stop();
  9945. t.join();
  9946. ASSERT_FALSE(svr.is_running());
  9947. });
  9948. svr.wait_until_ready();
  9949. // Send an invalid request line to trigger Bad Request
  9950. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9951. std::string out;
  9952. ASSERT_TRUE(send_request(5, bad_req, &out));
  9953. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9954. }
  9955. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9956. // answered right away rather than blocking on a read that waits for EOF.
  9957. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9958. std::string out;
  9959. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9960. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9961. }
  9962. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9963. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9964. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9965. for (const auto *method : methods) {
  9966. Server svr;
  9967. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9968. EXPECT_FALSE(svr.is_valid()) << method;
  9969. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9970. }
  9971. }
  9972. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9973. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9974. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9975. for (const auto *method : methods) {
  9976. Server svr;
  9977. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9978. EXPECT_FALSE(svr.is_valid()) << method;
  9979. }
  9980. }
  9981. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9982. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9983. "COPY", "MOVE", "LOCK",
  9984. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9985. Server svr;
  9986. for (const auto *method : methods) {
  9987. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9988. }
  9989. EXPECT_TRUE(svr.is_valid());
  9990. }
  9991. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9992. Server svr;
  9993. svr.CustomRoute("POST", "/x",
  9994. [](const Request &, Response &, const ContentReader &) {});
  9995. EXPECT_FALSE(svr.is_valid());
  9996. }
  9997. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9998. Server svr;
  9999. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10000. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10001. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10002. EXPECT_FALSE(svr.is_valid());
  10003. }
  10004. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10005. Server svr;
  10006. auto captured = Error::Success;
  10007. svr.set_error_logger(
  10008. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10009. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10010. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10011. }
  10012. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10013. std::string out;
  10014. std::string request(
  10015. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10016. test_raw_request(request, &out);
  10017. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10018. }
  10019. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10020. std::string out;
  10021. std::string request(
  10022. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10023. test_raw_request(request, &out);
  10024. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10025. }
  10026. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10027. std::string out;
  10028. std::string request(
  10029. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10030. test_raw_request(request, &out);
  10031. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10032. }
  10033. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10034. std::string out;
  10035. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10036. "Host: localhost\r\n"
  10037. "Test: \r\n\r\n",
  10038. &out);
  10039. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10040. }
  10041. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10042. Server svr;
  10043. std::string x_custom;
  10044. std::string cookie;
  10045. std::string xff;
  10046. std::string x_unicode;
  10047. std::string x_iis;
  10048. svr.Get("/check", [&](const Request &req, Response &res) {
  10049. x_custom = req.get_header_value("X-Custom");
  10050. cookie = req.get_header_value("Cookie");
  10051. xff = req.get_header_value("X-Forwarded-For");
  10052. x_unicode = req.get_header_value("X-Unicode");
  10053. x_iis = req.get_header_value("X-IIS");
  10054. res.set_content("ok", "text/plain");
  10055. });
  10056. thread t = thread([&] { svr.listen(HOST, PORT); });
  10057. auto se = detail::scope_exit([&] {
  10058. svr.stop();
  10059. t.join();
  10060. ASSERT_FALSE(svr.is_running());
  10061. });
  10062. svr.wait_until_ready();
  10063. const std::string req = "GET /check HTTP/1.1\r\n"
  10064. "Host: localhost\r\n"
  10065. "X-Custom: a%0D%0AInjected: b\r\n"
  10066. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10067. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10068. "X-Unicode: %E3%81%82\r\n"
  10069. "X-IIS: %u00E9\r\n"
  10070. "Connection: close\r\n"
  10071. "\r\n";
  10072. std::string res;
  10073. ASSERT_TRUE(send_request(5, req, &res));
  10074. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10075. // Every value must be returned verbatim (wire form), with no decoding.
  10076. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10077. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10078. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10079. EXPECT_EQ("%E3%81%82", x_unicode);
  10080. EXPECT_EQ("%u00E9", x_iis);
  10081. }
  10082. // Applications that previously relied on automatic percent-decoding can
  10083. // reproduce the old behavior by explicitly calling decode_path_component()
  10084. // or, for RFC 3986 conformance, decode_uri_component().
  10085. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10086. Server svr;
  10087. std::string decoded;
  10088. svr.Get("/check", [&](const Request &req, Response &res) {
  10089. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10090. res.set_content("ok", "text/plain");
  10091. });
  10092. thread t = thread([&] { svr.listen(HOST, PORT); });
  10093. auto se = detail::scope_exit([&] {
  10094. svr.stop();
  10095. t.join();
  10096. ASSERT_FALSE(svr.is_running());
  10097. });
  10098. svr.wait_until_ready();
  10099. const std::string req = "GET /check HTTP/1.1\r\n"
  10100. "Host: localhost\r\n"
  10101. "X-Custom: hello%20world\r\n"
  10102. "Connection: close\r\n"
  10103. "\r\n";
  10104. std::string res;
  10105. ASSERT_TRUE(send_request(5, req, &res));
  10106. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10107. EXPECT_EQ("hello world", decoded);
  10108. }
  10109. // Regression test for #2033. Browsers send Referer values that include
  10110. // percent-encoded characters such as %0A inside the URL. Decoding the
  10111. // header value would either trip the post-decode CR/LF/NUL guard (the
  10112. // original bug, returning 400) or, after that guard was relaxed, silently
  10113. // store a literal LF — both unacceptable. The wire form must round-trip.
  10114. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10115. Server svr;
  10116. std::string referer;
  10117. svr.Get("/check", [&](const Request &req, Response &res) {
  10118. referer = req.get_header_value("Referer");
  10119. res.set_content("ok", "text/plain");
  10120. });
  10121. thread t = thread([&] { svr.listen(HOST, PORT); });
  10122. auto se = detail::scope_exit([&] {
  10123. svr.stop();
  10124. t.join();
  10125. ASSERT_FALSE(svr.is_running());
  10126. });
  10127. svr.wait_until_ready();
  10128. const std::string req = "GET /check HTTP/1.1\r\n"
  10129. "Host: localhost\r\n"
  10130. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10131. "Connection: close\r\n"
  10132. "\r\n";
  10133. std::string res;
  10134. ASSERT_TRUE(send_request(5, req, &res));
  10135. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10136. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10137. }
  10138. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10139. Server svr;
  10140. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10141. res.set_header("Cache-Control", "no-cache");
  10142. res.set_chunked_content_provider(
  10143. "text/event-stream", [](size_t offset, DataSink &sink) {
  10144. std::string s = "data:";
  10145. s += std::to_string(offset);
  10146. s += "\n\n";
  10147. auto ret = sink.write(s.data(), s.size());
  10148. EXPECT_TRUE(ret);
  10149. std::this_thread::sleep_for(std::chrono::seconds(1));
  10150. return true;
  10151. });
  10152. });
  10153. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10154. svr.wait_until_ready();
  10155. Client client(HOST, PORT);
  10156. const Headers headers = {{"Accept", "text/event-stream"}};
  10157. auto get_thread = std::thread([&client, &headers]() {
  10158. auto res = client.Get(
  10159. "/events", headers,
  10160. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10161. });
  10162. auto se = detail::scope_exit([&] {
  10163. svr.stop();
  10164. get_thread.join();
  10165. listen_thread.join();
  10166. ASSERT_FALSE(svr.is_running());
  10167. });
  10168. // Give GET time to get a few messages.
  10169. std::this_thread::sleep_for(std::chrono::seconds(2));
  10170. }
  10171. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10172. httplib::Server svr;
  10173. svr.Post("/hi",
  10174. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10175. res.status = StatusCode::OK_200;
  10176. });
  10177. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10178. svr.wait_until_ready();
  10179. Client cli(HOST, PORT);
  10180. auto res = cli.Post("/hi", "data", "text/plain");
  10181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10182. EXPECT_EQ(StatusCode::OK_200, res->status);
  10183. svr.stop();
  10184. thread.join();
  10185. ASSERT_FALSE(svr.is_running());
  10186. res = cli.Post("/hi", "data", "text/plain");
  10187. ASSERT_FALSE(res);
  10188. }
  10189. TEST(ServerStopTest, ListenFailure) {
  10190. Server svr;
  10191. auto t = thread([&]() {
  10192. auto ret = svr.listen("????", PORT);
  10193. EXPECT_FALSE(ret);
  10194. });
  10195. svr.wait_until_ready();
  10196. svr.stop();
  10197. t.join();
  10198. }
  10199. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10200. TEST(ServerStopTest, Decommision) {
  10201. Server svr;
  10202. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10203. for (int i = 0; i < 4; i++) {
  10204. auto is_even = !(i % 2);
  10205. std::thread t{[&] {
  10206. try {
  10207. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10208. if (is_even) {
  10209. throw std::runtime_error("Some thing that happens to go wrong.");
  10210. }
  10211. svr.listen(HOST, PORT);
  10212. } catch (...) { svr.decommission(); }
  10213. }};
  10214. svr.wait_until_ready();
  10215. // Server is up
  10216. {
  10217. Client cli(HOST, PORT);
  10218. auto res = cli.Get("/hi");
  10219. if (is_even) {
  10220. EXPECT_FALSE(res);
  10221. } else {
  10222. EXPECT_TRUE(res);
  10223. EXPECT_EQ("hi...", res->body);
  10224. }
  10225. }
  10226. svr.stop();
  10227. t.join();
  10228. // Server is down...
  10229. {
  10230. Client cli(HOST, PORT);
  10231. auto res = cli.Get("/hi");
  10232. EXPECT_FALSE(res);
  10233. }
  10234. }
  10235. }
  10236. #endif
  10237. // Helper function for string body upload progress tests
  10238. template <typename SetupHandler, typename ClientCall>
  10239. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10240. ClientCall &&client_call,
  10241. const string &body) {
  10242. Server svr;
  10243. setup_handler(svr);
  10244. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10245. auto se = detail::scope_exit([&] {
  10246. svr.stop();
  10247. t.join();
  10248. });
  10249. svr.wait_until_ready();
  10250. Client cli(HOST, PORT);
  10251. vector<uint64_t> progress_values;
  10252. bool progress_called = false;
  10253. auto res =
  10254. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10255. progress_values.push_back(current);
  10256. progress_called = true;
  10257. return true;
  10258. });
  10259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10260. EXPECT_EQ(200, res->status);
  10261. EXPECT_TRUE(progress_called);
  10262. }
  10263. TEST(UploadProgressTest, PostStringBodyBasic) {
  10264. TestStringBodyUploadProgress(
  10265. [](Server &svr) {
  10266. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10267. res.set_content("received", "text/plain");
  10268. });
  10269. },
  10270. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10271. return cli.Post("/test", body, "text/plain", progress_callback);
  10272. },
  10273. "test data for upload progress");
  10274. }
  10275. TEST(UploadProgressTest, PutStringBodyBasic) {
  10276. TestStringBodyUploadProgress(
  10277. [](Server &svr) {
  10278. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10279. res.set_content("put received", "text/plain");
  10280. });
  10281. },
  10282. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10283. return cli.Put("/test", body, "text/plain", progress_callback);
  10284. },
  10285. "put test data for upload progress");
  10286. }
  10287. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10288. TestStringBodyUploadProgress(
  10289. [](Server &svr) {
  10290. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10291. res.set_content("patch received", "text/plain");
  10292. });
  10293. },
  10294. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10295. return cli.Patch("/test", body, "text/plain", progress_callback);
  10296. },
  10297. "patch test data for upload progress");
  10298. }
  10299. // Helper function for content provider upload progress tests
  10300. template <typename SetupHandler, typename ClientCall>
  10301. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10302. ClientCall &&client_call) {
  10303. Server svr;
  10304. setup_handler(svr);
  10305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10306. auto se = detail::scope_exit([&] {
  10307. svr.stop();
  10308. t.join();
  10309. });
  10310. svr.wait_until_ready();
  10311. Client cli(HOST, PORT);
  10312. vector<uint64_t> progress_values;
  10313. auto res =
  10314. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10315. progress_values.push_back(current);
  10316. return true;
  10317. });
  10318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10319. EXPECT_EQ(200, res->status);
  10320. EXPECT_FALSE(progress_values.empty());
  10321. }
  10322. TEST(UploadProgressTest, PostContentProviderProgress) {
  10323. TestContentProviderUploadProgress(
  10324. [](Server &svr) {
  10325. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10326. res.set_content("provider received", "text/plain");
  10327. });
  10328. },
  10329. [](Client &cli, UploadProgress progress_callback) {
  10330. return cli.Post(
  10331. "/test", 9,
  10332. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10333. sink.os << "test data";
  10334. return true;
  10335. },
  10336. "text/plain", progress_callback);
  10337. });
  10338. }
  10339. // Helper function for multipart upload progress tests
  10340. template <typename SetupHandler, typename ClientCall>
  10341. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10342. ClientCall &&client_call,
  10343. const string &endpoint) {
  10344. Server svr;
  10345. setup_handler(svr);
  10346. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10347. auto se = detail::scope_exit([&] {
  10348. svr.stop();
  10349. t.join();
  10350. });
  10351. svr.wait_until_ready();
  10352. Client cli(HOST, PORT);
  10353. vector<uint64_t> progress_values;
  10354. UploadFormDataItems items = {
  10355. {"field1", "value1", "", ""},
  10356. {"field2", "longer value for progress tracking test", "", ""},
  10357. {"file1", "file content data for upload progress", "test.txt",
  10358. "text/plain"}};
  10359. auto res = client_call(cli, endpoint, items,
  10360. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10361. progress_values.push_back(current);
  10362. return true;
  10363. });
  10364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10365. EXPECT_EQ(200, res->status);
  10366. EXPECT_FALSE(progress_values.empty());
  10367. }
  10368. TEST(UploadProgressTest, PostMultipartProgress) {
  10369. TestMultipartUploadProgress(
  10370. [](Server &svr) {
  10371. svr.Post("/multipart", [](const Request &req, Response &res) {
  10372. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10373. res.set_content("multipart received", "text/plain");
  10374. });
  10375. },
  10376. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10377. UploadProgress progress_callback) {
  10378. return cli.Post(endpoint, items, progress_callback);
  10379. },
  10380. "/multipart");
  10381. }
  10382. // Helper function for basic download progress tests
  10383. template <typename SetupHandler, typename ClientCall>
  10384. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10385. ClientCall &&client_call, const string &endpoint,
  10386. size_t expected_content_size) {
  10387. Server svr;
  10388. setup_handler(svr);
  10389. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10390. auto se = detail::scope_exit([&] {
  10391. svr.stop();
  10392. t.join();
  10393. });
  10394. svr.wait_until_ready();
  10395. Client cli(HOST, PORT);
  10396. vector<uint64_t> progress_values;
  10397. auto res = client_call(cli, endpoint,
  10398. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10399. progress_values.push_back(current);
  10400. return true;
  10401. });
  10402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10403. EXPECT_EQ(200, res->status);
  10404. EXPECT_FALSE(progress_values.empty());
  10405. EXPECT_EQ(expected_content_size, res->body.size());
  10406. }
  10407. TEST(DownloadProgressTest, GetBasic) {
  10408. TestBasicDownloadProgress(
  10409. [](Server &svr) {
  10410. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10411. string content(1000, 'D');
  10412. res.set_content(content, "text/plain");
  10413. });
  10414. },
  10415. [](Client &cli, const string &endpoint,
  10416. DownloadProgress progress_callback) {
  10417. return cli.Get(endpoint, progress_callback);
  10418. },
  10419. "/download", 1000u);
  10420. }
  10421. // Helper function for content receiver download progress tests
  10422. template <typename SetupHandler, typename ClientCall>
  10423. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10424. ClientCall &&client_call,
  10425. const string &endpoint,
  10426. size_t expected_content_size) {
  10427. Server svr;
  10428. setup_handler(svr);
  10429. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10430. auto se = detail::scope_exit([&] {
  10431. svr.stop();
  10432. t.join();
  10433. });
  10434. svr.wait_until_ready();
  10435. Client cli(HOST, PORT);
  10436. vector<uint64_t> progress_values;
  10437. string received_body;
  10438. auto res = client_call(
  10439. cli, endpoint,
  10440. [&](const char *data, size_t data_length) -> bool {
  10441. received_body.append(data, data_length);
  10442. return true;
  10443. },
  10444. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10445. progress_values.push_back(current);
  10446. return true;
  10447. });
  10448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10449. EXPECT_EQ(200, res->status);
  10450. EXPECT_FALSE(progress_values.empty());
  10451. EXPECT_EQ(expected_content_size, received_body.size());
  10452. EXPECT_TRUE(res->body.empty());
  10453. }
  10454. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10455. TestContentReceiverDownloadProgress(
  10456. [](Server &svr) {
  10457. svr.Get("/download-receiver",
  10458. [](const Request & /*req*/, Response &res) {
  10459. string content(2000, 'R');
  10460. res.set_content(content, "text/plain");
  10461. });
  10462. },
  10463. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10464. DownloadProgress progress_callback) {
  10465. return cli.Get(endpoint, content_receiver, progress_callback);
  10466. },
  10467. "/download-receiver", 2000u);
  10468. }
  10469. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10470. // A provider reaching a pass with nothing to hand over - an empty buffer
  10471. // popped off a queue, say - must not be taken to mean the body is finished.
  10472. // It used to end the loop with the terminating chunk unwritten while the
  10473. // server still considered the response complete, so the peer waited for an
  10474. // end that never arrived.
  10475. Server svr;
  10476. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10477. auto step = std::make_shared<int>(0);
  10478. res.set_chunked_content_provider("text/plain",
  10479. [step](size_t /*offset*/, DataSink &sink) {
  10480. switch ((*step)++) {
  10481. case 0: sink.write("", 0); break;
  10482. case 1: sink.write("hello", 5); break;
  10483. default: sink.done(); break;
  10484. }
  10485. return true;
  10486. });
  10487. });
  10488. auto port = svr.bind_to_any_port(HOST);
  10489. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10490. auto listen_se = detail::scope_exit([&] {
  10491. svr.stop();
  10492. listen_thread.join();
  10493. ASSERT_FALSE(svr.is_running());
  10494. });
  10495. svr.wait_until_ready();
  10496. Client cli(HOST, port);
  10497. // Without the fix the body is never terminated, so bound the wait rather
  10498. // than letting the test hang on the default read timeout.
  10499. cli.set_read_timeout(5, 0);
  10500. auto res = cli.Get("/stream");
  10501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10502. EXPECT_EQ(StatusCode::OK_200, res->status);
  10503. EXPECT_EQ("hello", res->body);
  10504. }
  10505. TEST(StreamingTest, NoContentLengthStreaming) {
  10506. Server svr;
  10507. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10508. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10509. if (offset < 6) {
  10510. sink.os << (offset < 3 ? "a" : "b");
  10511. } else {
  10512. sink.done();
  10513. }
  10514. return true;
  10515. });
  10516. });
  10517. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10518. auto listen_se = detail::scope_exit([&] {
  10519. svr.stop();
  10520. listen_thread.join();
  10521. ASSERT_FALSE(svr.is_running());
  10522. });
  10523. svr.wait_until_ready();
  10524. Client client(HOST, PORT);
  10525. auto get_thread = std::thread([&client]() {
  10526. std::string s;
  10527. auto res =
  10528. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10529. s += std::string(data, len);
  10530. return true;
  10531. });
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::OK_200, res->status);
  10534. EXPECT_EQ("aaabbb", s);
  10535. });
  10536. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10537. // Give GET time to get a few messages.
  10538. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10539. }
  10540. TEST(MountTest, Unmount) {
  10541. Server svr;
  10542. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10543. auto se = detail::scope_exit([&] {
  10544. svr.stop();
  10545. listen_thread.join();
  10546. ASSERT_FALSE(svr.is_running());
  10547. });
  10548. svr.wait_until_ready();
  10549. Client cli("localhost", PORT);
  10550. svr.set_mount_point("/mount2", "./www2");
  10551. auto res = cli.Get("/");
  10552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10554. res = cli.Get("/mount2/dir/test.html");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::OK_200, res->status);
  10557. svr.set_mount_point("/", "./www");
  10558. res = cli.Get("/dir/");
  10559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10560. EXPECT_EQ(StatusCode::OK_200, res->status);
  10561. svr.remove_mount_point("/");
  10562. res = cli.Get("/dir/");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10565. svr.remove_mount_point("/mount2");
  10566. res = cli.Get("/mount2/dir/test.html");
  10567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10569. }
  10570. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10571. Server svr;
  10572. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10573. svr.Get("/api/hello", [](const Request &, Response &res) {
  10574. res.set_content("api", "text/plain");
  10575. });
  10576. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10577. auto se = detail::scope_exit([&] {
  10578. svr.stop();
  10579. listen_thread.join();
  10580. ASSERT_FALSE(svr.is_running());
  10581. });
  10582. svr.wait_until_ready();
  10583. Client cli(HOST, PORT);
  10584. auto res = cli.Get("/dir/test.html");
  10585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10586. EXPECT_EQ(StatusCode::OK_200, res->status);
  10587. res = cli.Get("/api/hello");
  10588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10589. EXPECT_EQ(StatusCode::OK_200, res->status);
  10590. EXPECT_EQ("api", res->body);
  10591. }
  10592. TEST(MountTest, PathSegmentBoundary) {
  10593. Server svr;
  10594. svr.set_mount_point("/mount2", "./www2");
  10595. svr.set_mount_point("/", "./www");
  10596. auto port = svr.bind_to_any_port(HOST);
  10597. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10598. auto se = detail::scope_exit([&] {
  10599. svr.stop();
  10600. listen_thread.join();
  10601. ASSERT_FALSE(svr.is_running());
  10602. });
  10603. svr.wait_until_ready();
  10604. Client cli(HOST, port);
  10605. auto res = cli.Get("/mount2/dir/test.html");
  10606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10607. EXPECT_EQ(StatusCode::OK_200, res->status);
  10608. // "/mount2" must not match part-way through a path segment.
  10609. res = cli.Get("/mount2dir/test.html");
  10610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10611. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10612. // A mount point ending in '/' keeps matching every path below it.
  10613. res = cli.Get("/dir/test.html");
  10614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10615. EXPECT_EQ(StatusCode::OK_200, res->status);
  10616. }
  10617. TEST(MountTest, Redicect) {
  10618. Server svr;
  10619. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10620. auto se = detail::scope_exit([&] {
  10621. svr.stop();
  10622. listen_thread.join();
  10623. ASSERT_FALSE(svr.is_running());
  10624. });
  10625. svr.set_mount_point("/", "./www");
  10626. svr.wait_until_ready();
  10627. Client cli("localhost", PORT);
  10628. auto res = cli.Get("/dir/");
  10629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10630. EXPECT_EQ(StatusCode::OK_200, res->status);
  10631. res = cli.Get("/dir");
  10632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10633. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10634. res = cli.Get("/file");
  10635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10636. EXPECT_EQ(StatusCode::OK_200, res->status);
  10637. res = cli.Get("/file/");
  10638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10639. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10640. cli.set_follow_location(true);
  10641. res = cli.Get("/dir");
  10642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10643. EXPECT_EQ(StatusCode::OK_200, res->status);
  10644. }
  10645. TEST(MountTest, MultibytesPathName) {
  10646. Server svr;
  10647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10648. auto se = detail::scope_exit([&] {
  10649. svr.stop();
  10650. listen_thread.join();
  10651. ASSERT_FALSE(svr.is_running());
  10652. });
  10653. svr.set_mount_point("/", "./www");
  10654. svr.wait_until_ready();
  10655. Client cli("localhost", PORT);
  10656. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10658. EXPECT_EQ(StatusCode::OK_200, res->status);
  10659. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10660. }
  10661. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10662. // in the pre-routing handler sees the path of every file that is served
  10663. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10664. Server svr;
  10665. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10666. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10667. if (req.path == "/dir/test.html") {
  10668. res.status = StatusCode::Unauthorized_401;
  10669. return Server::HandlerResponse::Handled;
  10670. }
  10671. return Server::HandlerResponse::Unhandled;
  10672. });
  10673. auto port = svr.bind_to_any_port(HOST);
  10674. ASSERT_LT(0, port);
  10675. thread t = thread([&] { svr.listen_after_bind(); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. t.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. Client cli(HOST, port);
  10683. for (auto path :
  10684. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10685. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10686. SCOPED_TRACE(path);
  10687. auto res = cli.Get(path);
  10688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10689. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10690. }
  10691. }
  10692. #ifdef _WIN32
  10693. // Issue #2435: mmap::open() must succeed even when another handle holds
  10694. // the file open for writing (e.g. an active log file).
  10695. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10696. const char *path = "mmap_concurrent_writer_test.txt";
  10697. const char *content = "hello";
  10698. {
  10699. std::ofstream f(path, std::ios::binary);
  10700. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10701. }
  10702. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10703. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10704. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10705. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10706. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10707. detail::mmap m(path);
  10708. ASSERT_TRUE(m.is_open());
  10709. EXPECT_EQ(strlen(content), m.size());
  10710. char buf[8];
  10711. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10712. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10713. }
  10714. #endif
  10715. #ifndef _WIN32
  10716. // A directory or a device has no size to serve.
  10717. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10718. const char *path = "./mmap_not_regular_test_dir";
  10719. ASSERT_EQ(0, ::mkdir(path, 0755));
  10720. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10721. for (auto p : {path, "/dev/null"}) {
  10722. detail::mmap m(p);
  10723. EXPECT_FALSE(m.is_open()) << p;
  10724. EXPECT_EQ(0U, m.size()) << p;
  10725. }
  10726. Server svr;
  10727. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10728. res.set_file_content("/dev/null");
  10729. });
  10730. auto port = svr.bind_to_any_port(HOST);
  10731. thread t = thread([&] { svr.listen_after_bind(); });
  10732. auto se = detail::scope_exit([&] {
  10733. svr.stop();
  10734. t.join();
  10735. });
  10736. svr.wait_until_ready();
  10737. auto res = Client(HOST, port).Get("/null");
  10738. ASSERT_TRUE(res);
  10739. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10740. }
  10741. #endif
  10742. #ifdef __linux__
  10743. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10744. TEST(MmapTest, FileIsNotMapped) {
  10745. const char *path = "mmap_not_mapped_test.txt";
  10746. {
  10747. std::ofstream f(path, std::ios::binary);
  10748. f << "hello";
  10749. }
  10750. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10751. detail::mmap m(path);
  10752. ASSERT_TRUE(m.is_open());
  10753. std::ifstream maps("/proc/self/maps");
  10754. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10755. std::istreambuf_iterator<char>());
  10756. EXPECT_EQ(std::string::npos, mappings.find(path));
  10757. }
  10758. #endif
  10759. TEST(KeepAliveTest, ReadTimeout) {
  10760. Server svr;
  10761. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10762. std::this_thread::sleep_for(std::chrono::seconds(2));
  10763. res.set_content("a", "text/plain");
  10764. });
  10765. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10766. res.set_content("b", "text/plain");
  10767. });
  10768. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10769. auto se = detail::scope_exit([&] {
  10770. svr.stop();
  10771. listen_thread.join();
  10772. ASSERT_FALSE(svr.is_running());
  10773. });
  10774. svr.wait_until_ready();
  10775. Client cli("localhost", PORT);
  10776. cli.set_keep_alive(true);
  10777. cli.set_read_timeout(std::chrono::seconds(1));
  10778. auto resa = cli.Get("/a");
  10779. ASSERT_FALSE(resa);
  10780. EXPECT_EQ(Error::Read, resa.error());
  10781. auto resb = cli.Get("/b");
  10782. ASSERT_TRUE(resb);
  10783. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10784. EXPECT_EQ("b", resb->body);
  10785. }
  10786. TEST(KeepAliveTest, MaxCount) {
  10787. size_t keep_alive_max_count = 3;
  10788. Server svr;
  10789. svr.set_keep_alive_max_count(keep_alive_max_count);
  10790. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10791. res.set_content("Hello World!", "text/plain");
  10792. });
  10793. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10794. auto se = detail::scope_exit([&] {
  10795. svr.stop();
  10796. listen_thread.join();
  10797. ASSERT_FALSE(svr.is_running());
  10798. });
  10799. svr.wait_until_ready();
  10800. Client cli(HOST, PORT);
  10801. cli.set_keep_alive(true);
  10802. for (size_t i = 0; i < 5; i++) {
  10803. auto result = cli.Get("/hi");
  10804. ASSERT_TRUE(result);
  10805. EXPECT_EQ(StatusCode::OK_200, result->status);
  10806. if (i == keep_alive_max_count - 1) {
  10807. EXPECT_EQ("close", result->get_header_value("Connection"));
  10808. } else {
  10809. EXPECT_FALSE(result->has_header("Connection"));
  10810. }
  10811. }
  10812. }
  10813. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10814. // can pull the next one into the server's buffer. The server must serve it
  10815. // without waiting for the socket to become readable again. The keep-alive
  10816. // timeout outlasts the client's read timeout, so a request left waiting for it
  10817. // shows up as a missing response.
  10818. static void serve_pipelining_routes(Server &svr,
  10819. const std::function<void(int)> &client) {
  10820. svr.set_keep_alive_timeout(5);
  10821. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10822. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10823. });
  10824. svr.Post("/echo", [](const Request &req, Response &res) {
  10825. res.set_content("echo " + req.body, "text/plain");
  10826. });
  10827. auto port = svr.bind_to_any_port(HOST);
  10828. thread t = thread([&] { svr.listen_after_bind(); });
  10829. auto se = detail::scope_exit([&] {
  10830. svr.stop();
  10831. t.join();
  10832. });
  10833. svr.wait_until_ready();
  10834. client(port);
  10835. }
  10836. static std::string
  10837. send_pipelined_requests(const std::vector<std::string> &parts) {
  10838. Server svr;
  10839. std::string res;
  10840. serve_pipelining_routes(svr, [&](int port) {
  10841. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10842. });
  10843. return res;
  10844. }
  10845. static void expect_in_order(const std::string &res,
  10846. const std::vector<std::string> &bodies) {
  10847. size_t pos = 0;
  10848. for (const auto &body : bodies) {
  10849. pos = res.find(body, pos);
  10850. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10851. pos += body.size();
  10852. }
  10853. }
  10854. TEST(KeepAliveTest, PipelinedRequests) {
  10855. auto res = send_pipelined_requests(
  10856. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10857. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10858. "Content-Length: 4\r\n\r\nbody"
  10859. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10860. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10861. }
  10862. // The second request starts in the server's buffer and ends on the socket.
  10863. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10864. auto res =
  10865. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10866. "GET /hi/2 HTTP/1.1\r\nHo",
  10867. "st: localhost\r\nConnection: close\r\n\r\n"});
  10868. expect_in_order(res, {"hi 1", "hi 2"});
  10869. }
  10870. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10871. // CRLF after a body does not turn into a 400 for the next request.
  10872. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10873. auto res = send_pipelined_requests(
  10874. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10875. "Content-Length: 4\r\n\r\nbody\r\n"
  10876. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10877. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10878. expect_in_order(res, {"echo body", "hi 2"});
  10879. }
  10880. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10881. // must not be served as the next request.
  10882. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10883. auto res = send_pipelined_requests(
  10884. {"INVALID REQUEST LINE\r\n\r\n"
  10885. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10886. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10887. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10888. }
  10889. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10890. // Over TLS, the next request is held by the TLS library as already decrypted
  10891. // data rather than on the socket.
  10892. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10894. std::string res;
  10895. serve_pipelining_routes(svr, [&](int port) {
  10896. // One part, so all three requests arrive in one TLS record
  10897. EXPECT_TRUE(send_ssl_request_in_parts(
  10898. 2,
  10899. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10900. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10901. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10902. &res, port));
  10903. });
  10904. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10905. }
  10906. #endif
  10907. TEST(KeepAliveTest, Issue1041) {
  10908. Server svr;
  10909. svr.set_keep_alive_timeout(3);
  10910. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10911. res.set_content("Hello World!", "text/plain");
  10912. });
  10913. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10914. auto se = detail::scope_exit([&] {
  10915. svr.stop();
  10916. listen_thread.join();
  10917. ASSERT_FALSE(svr.is_running());
  10918. });
  10919. svr.wait_until_ready();
  10920. Client cli(HOST, PORT);
  10921. cli.set_keep_alive(true);
  10922. auto result = cli.Get("/hi");
  10923. ASSERT_TRUE(result);
  10924. EXPECT_EQ(StatusCode::OK_200, result->status);
  10925. std::this_thread::sleep_for(std::chrono::seconds(5));
  10926. result = cli.Get("/hi");
  10927. ASSERT_TRUE(result);
  10928. EXPECT_EQ(StatusCode::OK_200, result->status);
  10929. }
  10930. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10931. Server svr;
  10932. svr.set_keep_alive_max_count(0);
  10933. std::set<int> remote_ports;
  10934. svr.Get("/hi", [&](const Request &req, Response &res) {
  10935. remote_ports.insert(req.remote_port);
  10936. res.set_content("hi", "text/plain");
  10937. });
  10938. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10939. auto se = detail::scope_exit([&] {
  10940. svr.stop();
  10941. listen_thread.join();
  10942. ASSERT_FALSE(svr.is_running());
  10943. });
  10944. svr.wait_until_ready();
  10945. Client cli(HOST, PORT);
  10946. cli.set_keep_alive(true);
  10947. for (int i = 0; i < 3; i++) {
  10948. auto res = cli.Get("/hi");
  10949. ASSERT_TRUE(res);
  10950. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10951. }
  10952. // All three over one connection
  10953. EXPECT_EQ(1u, remote_ports.size());
  10954. }
  10955. TEST(KeepAliveTest, Issue1959) {
  10956. Server svr;
  10957. svr.set_keep_alive_timeout(5);
  10958. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10959. res.set_content("a", "text/plain");
  10960. });
  10961. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10962. auto se = detail::scope_exit([&] {
  10963. if (!svr.is_running()) return;
  10964. svr.stop();
  10965. listen_thread.join();
  10966. ASSERT_FALSE(svr.is_running());
  10967. });
  10968. svr.wait_until_ready();
  10969. Client cli("localhost", PORT);
  10970. cli.set_keep_alive(true);
  10971. using namespace std::chrono;
  10972. auto start = steady_clock::now();
  10973. cli.Get("/a");
  10974. svr.stop();
  10975. listen_thread.join();
  10976. auto end = steady_clock::now();
  10977. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10978. EXPECT_LT(elapsed, 5000);
  10979. }
  10980. #ifdef CPPHTTPLIB_SSL_ENABLED
  10981. TEST(KeepAliveTest, SSLClientReconnection) {
  10982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10983. ASSERT_TRUE(svr.is_valid());
  10984. svr.set_keep_alive_timeout(1);
  10985. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10986. res.set_content("Hello World!", "text/plain");
  10987. });
  10988. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. listen_thread.join();
  10992. ASSERT_FALSE(svr.is_running());
  10993. });
  10994. svr.wait_until_ready();
  10995. SSLClient cli(HOST, PORT);
  10996. cli.enable_server_certificate_verification(false);
  10997. cli.set_keep_alive(true);
  10998. auto result = cli.Get("/hi");
  10999. ASSERT_TRUE(result);
  11000. EXPECT_EQ(StatusCode::OK_200, result->status);
  11001. result = cli.Get("/hi");
  11002. ASSERT_TRUE(result);
  11003. EXPECT_EQ(StatusCode::OK_200, result->status);
  11004. std::this_thread::sleep_for(std::chrono::seconds(2));
  11005. // Recoonect
  11006. result = cli.Get("/hi");
  11007. ASSERT_TRUE(result);
  11008. EXPECT_EQ(StatusCode::OK_200, result->status);
  11009. result = cli.Get("/hi");
  11010. ASSERT_TRUE(result);
  11011. EXPECT_EQ(StatusCode::OK_200, result->status);
  11012. }
  11013. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11015. ASSERT_TRUE(svr.is_valid());
  11016. svr.set_keep_alive_timeout(1);
  11017. std::string content = "reconnect";
  11018. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11019. res.set_content("Hello World!", "text/plain");
  11020. });
  11021. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11022. auto se = detail::scope_exit([&] {
  11023. svr.stop();
  11024. listen_thread.join();
  11025. ASSERT_FALSE(svr.is_running());
  11026. });
  11027. svr.wait_until_ready();
  11028. SSLClient cli(HOST, PORT);
  11029. cli.enable_server_certificate_verification(false);
  11030. cli.set_keep_alive(true);
  11031. auto result = cli.Post(
  11032. "/hi", content.size(),
  11033. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11034. sink.write(content.c_str(), content.size());
  11035. return true;
  11036. },
  11037. "text/plain");
  11038. ASSERT_TRUE(result);
  11039. EXPECT_EQ(200, result->status);
  11040. std::this_thread::sleep_for(std::chrono::seconds(2));
  11041. // Recoonect
  11042. result = cli.Post(
  11043. "/hi", content.size(),
  11044. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11045. sink.write(content.c_str(), content.size());
  11046. return true;
  11047. },
  11048. "text/plain");
  11049. ASSERT_TRUE(result);
  11050. EXPECT_EQ(200, result->status);
  11051. result = cli.Post(
  11052. "/hi", content.size(),
  11053. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11054. sink.write(content.c_str(), content.size());
  11055. return true;
  11056. },
  11057. "text/plain");
  11058. ASSERT_TRUE(result);
  11059. EXPECT_EQ(200, result->status);
  11060. }
  11061. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11062. using namespace httplib::tls;
  11063. {
  11064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11065. ASSERT_TRUE(svr.is_valid());
  11066. svr.Get("/sni", [&](const Request &req, Response &res) {
  11067. std::string expected = req.sni();
  11068. EXPECT_EQ(expected, req.get_param_value("expected"));
  11069. res.set_content("ok", "text/plain");
  11070. });
  11071. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11072. auto se = detail::scope_exit([&] {
  11073. svr.stop();
  11074. listen_thread.join();
  11075. ASSERT_FALSE(svr.is_running());
  11076. });
  11077. svr.wait_until_ready();
  11078. {
  11079. SSLClient cli("localhost", PORT);
  11080. cli.enable_server_certificate_verification(false);
  11081. auto res = cli.Get("/sni?expected=localhost");
  11082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11083. }
  11084. {
  11085. SSLClient cli("::1", PORT);
  11086. cli.enable_server_certificate_verification(false);
  11087. auto res = cli.Get("/sni?expected=");
  11088. // NOTE: This may fail if the server is listening on IPv4 only
  11089. // (e.g., when localhost resolves to 127.0.0.1 only)
  11090. if (res) {
  11091. EXPECT_EQ(StatusCode::OK_200, res->status);
  11092. } else {
  11093. EXPECT_EQ(Error::Connection, res.error());
  11094. }
  11095. }
  11096. }
  11097. }
  11098. // The SNI of a failed handshake does not reach the next connection that the
  11099. // same worker thread serves
  11100. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11102. ASSERT_TRUE(svr.is_valid());
  11103. svr.new_task_queue = [] { return new ThreadPool(1); };
  11104. svr.Get("/sni", [](const Request &req, Response &res) {
  11105. res.set_content(req.sni(), "text/plain");
  11106. });
  11107. auto port = svr.bind_to_any_port("127.0.0.1");
  11108. ASSERT_LT(0, port);
  11109. thread t = thread([&] { svr.listen_after_bind(); });
  11110. auto se = detail::scope_exit([&] {
  11111. svr.stop();
  11112. t.join();
  11113. ASSERT_FALSE(svr.is_running());
  11114. });
  11115. svr.wait_until_ready();
  11116. {
  11117. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11118. SSLClient cli("localhost", port);
  11119. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11120. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11121. auto res = cli.Get("/sni");
  11122. ASSERT_FALSE(res);
  11123. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11124. }
  11125. // An IP host sends no SNI (RFC 6066)
  11126. SSLClient cli("127.0.0.1", port);
  11127. cli.enable_server_certificate_verification(false);
  11128. auto res = cli.Get("/sni");
  11129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11130. EXPECT_EQ("", res->body);
  11131. }
  11132. #endif
  11133. TEST(ClientProblemDetectionTest, ContentProvider) {
  11134. Server svr;
  11135. size_t content_length = 1024 * 1024;
  11136. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11137. res.set_content_provider(
  11138. content_length, "text/plain",
  11139. [&](size_t offset, size_t length, DataSink &sink) {
  11140. auto out_len = std::min(length, static_cast<size_t>(1024));
  11141. std::string out(out_len, '@');
  11142. sink.write(out.data(), out_len);
  11143. return offset < 4096;
  11144. },
  11145. [](bool success) { ASSERT_FALSE(success); });
  11146. });
  11147. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11148. res.set_content_provider(
  11149. 0, "text/plain",
  11150. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11151. EXPECT_TRUE(false);
  11152. return true;
  11153. },
  11154. [](bool success) { ASSERT_FALSE(success); });
  11155. });
  11156. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11157. auto se = detail::scope_exit([&] {
  11158. svr.stop();
  11159. listen_thread.join();
  11160. ASSERT_FALSE(svr.is_running());
  11161. });
  11162. svr.wait_until_ready();
  11163. Client cli("localhost", PORT);
  11164. {
  11165. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11166. size_t /*data_length*/) { return false; });
  11167. ASSERT_FALSE(res);
  11168. }
  11169. {
  11170. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11171. size_t /*data_length*/) { return false; });
  11172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11173. }
  11174. }
  11175. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11176. // A provider that reports success without writing anything and without
  11177. // calling done() used to be handed the same offset and length again on every
  11178. // pass, so it spun for as long as the peer stayed connected.
  11179. Server svr;
  11180. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11181. res.set_content("ok", "text/plain");
  11182. });
  11183. auto port = svr.bind_to_any_port(HOST);
  11184. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11185. auto se = detail::scope_exit([&] {
  11186. svr.stop();
  11187. listen_thread.join();
  11188. ASSERT_FALSE(svr.is_running());
  11189. });
  11190. svr.wait_until_ready();
  11191. std::atomic<int> call_count{0};
  11192. Client cli(HOST, port);
  11193. auto res = cli.Post(
  11194. "/", 1024,
  11195. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11196. // Give up after enough passes to show the spin, so that losing the
  11197. // check below fails this test instead of hanging it.
  11198. return ++call_count < 100;
  11199. },
  11200. "text/plain");
  11201. ASSERT_FALSE(res);
  11202. EXPECT_EQ(Error::Write, res.error());
  11203. EXPECT_EQ(1, call_count.load());
  11204. }
  11205. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11206. // A writer only has to assign `write`. The other three used to be left as
  11207. // empty std::functions, so a provider calling one threw
  11208. // std::bad_function_call out of the thread running it and took the whole
  11209. // process down.
  11210. DataSink sink;
  11211. std::string written;
  11212. sink.write = [&](const char *data, size_t data_len) {
  11213. written.append(data, data_len);
  11214. return true;
  11215. };
  11216. EXPECT_TRUE(sink.is_writable());
  11217. sink.done();
  11218. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11219. EXPECT_TRUE(written.empty());
  11220. }
  11221. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11222. // A sink that cannot carry trailers still has to finish.
  11223. DataSink sink;
  11224. auto done_count = 0;
  11225. sink.done = [&]() { done_count++; };
  11226. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11227. EXPECT_EQ(1, done_count);
  11228. }
  11229. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11230. Server svr;
  11231. const std::string body(4096, 'x');
  11232. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11233. res.set_content_provider(body.size(), "text/plain",
  11234. [&](size_t offset, size_t length, DataSink &sink) {
  11235. sink.write(body.data() + offset, length);
  11236. sink.done();
  11237. return true;
  11238. });
  11239. });
  11240. auto port = svr.bind_to_any_port(HOST);
  11241. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11242. auto se = detail::scope_exit([&] {
  11243. svr.stop();
  11244. listen_thread.join();
  11245. ASSERT_FALSE(svr.is_running());
  11246. });
  11247. svr.wait_until_ready();
  11248. Client cli(HOST, port);
  11249. auto res = cli.Get("/");
  11250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11251. EXPECT_EQ(StatusCode::OK_200, res->status);
  11252. EXPECT_EQ(body, res->body);
  11253. }
  11254. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11255. Server svr;
  11256. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11257. res.set_content_provider(
  11258. 1024, "text/plain",
  11259. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11260. sink.write("hello", 5);
  11261. sink.done(); // short of the 1024 bytes the response promised
  11262. return true;
  11263. });
  11264. });
  11265. auto port = svr.bind_to_any_port(HOST);
  11266. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11267. auto se = detail::scope_exit([&] {
  11268. svr.stop();
  11269. listen_thread.join();
  11270. ASSERT_FALSE(svr.is_running());
  11271. });
  11272. svr.wait_until_ready();
  11273. Client cli(HOST, port);
  11274. cli.set_read_timeout(5, 0);
  11275. // The response is short of its Content-Length, so the client cannot read a
  11276. // complete body. What matters is that this returns at all: a no-op done()
  11277. // would leave the writer looping over a provider that never makes progress.
  11278. auto res = cli.Get("/");
  11279. EXPECT_FALSE(res);
  11280. }
  11281. // Read as the next response by a peer that sees it after a framed body.
  11282. static const std::string smuggled_response =
  11283. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11284. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11285. Server svr;
  11286. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11287. res.set_content_provider(
  11288. 5, "text/plain",
  11289. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11290. auto data = "AAAAA" + smuggled_response;
  11291. sink.write(data.data(), data.size());
  11292. return true;
  11293. });
  11294. });
  11295. thread t = thread([&] { svr.listen(HOST, PORT); });
  11296. auto se = detail::scope_exit([&] {
  11297. svr.stop();
  11298. t.join();
  11299. ASSERT_FALSE(svr.is_running());
  11300. });
  11301. svr.wait_until_ready();
  11302. std::string resp;
  11303. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11304. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11305. resp.clear();
  11306. ASSERT_TRUE(send_request(
  11307. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11308. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11309. }
  11310. TEST(NoContentTest, BodyIsNotSent) {
  11311. Server svr;
  11312. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11313. res.status = StatusCode::NoContent_204;
  11314. res.set_content(smuggled_response, "text/plain");
  11315. });
  11316. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11317. res.status = StatusCode::NotModified_304;
  11318. res.set_chunked_content_provider(
  11319. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11320. sink.write(smuggled_response.data(), smuggled_response.size());
  11321. sink.done();
  11322. return true;
  11323. });
  11324. });
  11325. thread t = thread([&] { svr.listen(HOST, PORT); });
  11326. auto se = detail::scope_exit([&] {
  11327. svr.stop();
  11328. t.join();
  11329. ASSERT_FALSE(svr.is_running());
  11330. });
  11331. svr.wait_until_ready();
  11332. for (auto path : {"/204", "/304"}) {
  11333. std::string resp;
  11334. ASSERT_TRUE(send_request(
  11335. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11336. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11337. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11338. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11339. }
  11340. }
  11341. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11342. Server svr;
  11343. std::atomic<bool> smuggled(false);
  11344. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11345. res.set_content("ok", "text/plain");
  11346. });
  11347. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11348. smuggled = true;
  11349. });
  11350. auto port = svr.bind_to_any_port(HOST);
  11351. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11352. auto se = detail::scope_exit([&] {
  11353. svr.stop();
  11354. listen_thread.join();
  11355. ASSERT_FALSE(svr.is_running());
  11356. });
  11357. svr.wait_until_ready();
  11358. // What follows the body would be read as the next request.
  11359. Client cli(HOST, port);
  11360. auto res = cli.Post(
  11361. "/", 5,
  11362. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11363. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11364. sink.write(data.data(), data.size());
  11365. return true;
  11366. },
  11367. "text/plain");
  11368. ASSERT_FALSE(res);
  11369. EXPECT_EQ(Error::Write, res.error());
  11370. EXPECT_FALSE(smuggled);
  11371. }
  11372. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11373. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11374. // The compressed path builds the whole body before connecting, so this
  11375. // fails client-side and never reaches a server.
  11376. Client cli(HOST, PORT);
  11377. cli.set_compress(true);
  11378. auto res = cli.Post(
  11379. "/", 1024,
  11380. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11381. sink.write("hello", 5);
  11382. sink.done(); // short of the 1024 bytes the request announced
  11383. return true;
  11384. },
  11385. "text/plain");
  11386. ASSERT_FALSE(res);
  11387. EXPECT_EQ(Error::Write, res.error());
  11388. }
  11389. #endif
  11390. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11391. Server svr;
  11392. svr.set_error_handler([](Request const &, Response &res) -> void {
  11393. res.set_chunked_content_provider(
  11394. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11395. sink.os << "hello";
  11396. sink.os << "world";
  11397. sink.done();
  11398. return true;
  11399. });
  11400. });
  11401. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11402. auto se = detail::scope_exit([&] {
  11403. svr.stop();
  11404. listen_thread.join();
  11405. ASSERT_FALSE(svr.is_running());
  11406. });
  11407. svr.wait_until_ready();
  11408. Client cli("localhost", PORT);
  11409. auto res = cli.Get("/");
  11410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11411. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11412. EXPECT_EQ("helloworld", res->body);
  11413. }
  11414. // A body set after a content provider must replace it, not be sent through it.
  11415. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11416. Server svr;
  11417. svr.set_mount_point("/", "./www");
  11418. svr.set_file_request_handler([](const Request &req, Response &res) {
  11419. if (req.path == "/dir/test.html") {
  11420. res.status = StatusCode::Forbidden_403;
  11421. res.set_content(std::string(5000, 'D'), "text/plain");
  11422. } else if (req.path == "/file") {
  11423. res.status = StatusCode::Forbidden_403;
  11424. res.body = "Denied";
  11425. }
  11426. });
  11427. auto port = svr.bind_to_any_port(HOST);
  11428. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11429. auto se = detail::scope_exit([&] {
  11430. svr.stop();
  11431. t.join();
  11432. ASSERT_FALSE(svr.is_running());
  11433. });
  11434. svr.wait_until_ready();
  11435. Client cli(HOST, port);
  11436. {
  11437. auto res = cli.Get("/dir/test.html");
  11438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11439. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11440. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11441. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11442. }
  11443. {
  11444. auto res = cli.Get("/file");
  11445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11446. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11447. EXPECT_EQ("Denied", res->body);
  11448. }
  11449. {
  11450. auto res = cli.Get("/dir/index.html");
  11451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11452. EXPECT_EQ(StatusCode::OK_200, res->status);
  11453. EXPECT_EQ(0U, res->body.find("<html>"));
  11454. }
  11455. }
  11456. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11457. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11458. Server svr;
  11459. std::vector<bool> released;
  11460. std::mutex released_mutex;
  11461. auto releaser = [&](bool success) {
  11462. std::lock_guard<std::mutex> guard(released_mutex);
  11463. released.push_back(success);
  11464. };
  11465. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11466. return sink.write(&"hello"[offset], length);
  11467. };
  11468. svr.Get("/sized", [&](const Request &, Response &res) {
  11469. res.status = StatusCode::NotFound_404;
  11470. res.set_content_provider(5, "text/plain", provider, releaser);
  11471. });
  11472. svr.Get("/chunked", [&](const Request &, Response &res) {
  11473. res.status = StatusCode::ServiceUnavailable_503;
  11474. res.set_chunked_content_provider(
  11475. "text/plain",
  11476. [](size_t, DataSink &sink) {
  11477. sink.os << "chunk";
  11478. sink.done();
  11479. return true;
  11480. },
  11481. releaser);
  11482. });
  11483. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11484. res.set_content_provider(5, "text/plain", provider, releaser);
  11485. throw std::runtime_error("after the provider");
  11486. });
  11487. svr.set_error_handler([](const Request &req, Response &res) {
  11488. // Leave the exception handler's content to it.
  11489. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11490. res.set_content(std::string(1000, 'E'), "text/html");
  11491. return Server::HandlerResponse::Handled;
  11492. });
  11493. svr.set_exception_handler(
  11494. [](const Request &, Response &res, std::exception_ptr) {
  11495. res.status = StatusCode::InternalServerError_500;
  11496. res.set_content(std::string(1000, 'X'), "text/html");
  11497. });
  11498. auto port = svr.bind_to_any_port(HOST);
  11499. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11500. auto se = detail::scope_exit([&] {
  11501. svr.stop();
  11502. t.join();
  11503. ASSERT_FALSE(svr.is_running());
  11504. });
  11505. svr.wait_until_ready();
  11506. Client cli(HOST, port);
  11507. {
  11508. auto res = cli.Get("/sized");
  11509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11511. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11512. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11513. }
  11514. {
  11515. auto res = cli.Get("/chunked");
  11516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11517. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11518. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11519. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11520. }
  11521. {
  11522. auto res = cli.Get("/throw");
  11523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11524. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11525. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11526. }
  11527. std::lock_guard<std::mutex> guard(released_mutex);
  11528. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11529. }
  11530. #endif
  11531. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11532. Server svr;
  11533. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11534. return sink.write(&"abc"[offset], length);
  11535. };
  11536. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11537. res.set_file_content("./www/dir/test.html");
  11538. res.set_content("body", "text/plain");
  11539. });
  11540. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11541. res.set_content(std::string(100, 'B'), "text/plain");
  11542. res.set_file_content("./www/dir/test.html");
  11543. });
  11544. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11545. res.set_content(std::string(100, 'B'), "text/plain");
  11546. res.set_content_provider(3, "text/x-provider", abc);
  11547. });
  11548. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11549. res.set_content_provider(3, "text/x-provider", abc);
  11550. res.set_content(std::string(100, 'B'), "text/plain");
  11551. });
  11552. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11553. res.set_content_provider(3, "text/x-provider", abc);
  11554. res.set_file_content("./www/dir/test.html", "text/x-file");
  11555. });
  11556. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11557. res.set_file_content("./www/dir/test.html");
  11558. res.set_header("Content-Type", "text/x-handler");
  11559. });
  11560. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11561. res.set_content_provider(3, "text/plain", abc);
  11562. res.body = "direct";
  11563. });
  11564. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11565. res.set_file_content("./www/dir/test.html");
  11566. res.body = "direct";
  11567. });
  11568. auto port = svr.bind_to_any_port(HOST);
  11569. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11570. auto se = detail::scope_exit([&] {
  11571. svr.stop();
  11572. t.join();
  11573. ASSERT_FALSE(svr.is_running());
  11574. });
  11575. svr.wait_until_ready();
  11576. Client cli(HOST, port);
  11577. auto expect_body = [&](const char *path, const std::string &body,
  11578. const std::string &type) {
  11579. // Uncompressed, so Content-Length can be compared with the body.
  11580. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11581. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11582. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11583. EXPECT_EQ(body, res->body) << path;
  11584. EXPECT_EQ(std::to_string(body.size()),
  11585. res->get_header_value("Content-Length"))
  11586. << path;
  11587. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11588. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11589. };
  11590. expect_body("/file-then-body", "body", "text/plain");
  11591. expect_body("/body-then-file", "test.html", "text/html");
  11592. expect_body("/body-then-provider", "abc", "text/x-provider");
  11593. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11594. expect_body("/provider-then-file", "test.html", "text/x-file");
  11595. expect_body("/file-then-header", "test.html", "text/x-handler");
  11596. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11597. expect_body("/file-then-direct-body", "direct", "text/plain");
  11598. // Ranges are checked against the body, not the dropped provider.
  11599. {
  11600. auto res = cli.Get("/provider-then-direct-body",
  11601. Headers{{make_range_header({{1, 2}})}});
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11604. EXPECT_EQ("ir", res->body);
  11605. }
  11606. {
  11607. auto res = cli.Get("/file-then-direct-body",
  11608. Headers{{make_range_header({{7, 8}})}});
  11609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11610. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11611. }
  11612. }
  11613. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11614. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11615. const char *path = "./truncated_while_served.txt";
  11616. const size_t size = 32 * 1024 * 1024;
  11617. {
  11618. std::ofstream f(path, std::ios::binary);
  11619. f << std::string(size, 'x');
  11620. }
  11621. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11622. // Over TLS, where the bytes are encrypted in this process rather than
  11623. // copied by send().
  11624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11625. svr.Get("/file", [&](const Request &, Response &res) {
  11626. res.set_file_content(path, "text/plain");
  11627. });
  11628. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11629. auto se = detail::scope_exit([&] {
  11630. svr.stop();
  11631. thread.join();
  11632. ASSERT_FALSE(svr.is_running());
  11633. });
  11634. svr.wait_until_ready();
  11635. // The file shrinks once the first bytes are in, as a rewrite in place
  11636. // would, and reading the mapping past its new end used to raise SIGBUS.
  11637. SSLClient cli(HOST, PORT);
  11638. cli.enable_server_certificate_verification(false);
  11639. size_t received = 0;
  11640. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11641. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11642. received += len;
  11643. return true;
  11644. });
  11645. EXPECT_FALSE(res);
  11646. EXPECT_LT(received, size);
  11647. }
  11648. #endif
  11649. // Forward declaration (see the base64_encode note).
  11650. namespace httplib {
  11651. namespace detail {
  11652. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11653. const std::string &content_type,
  11654. EncodingType encoding);
  11655. } // namespace detail
  11656. } // namespace httplib
  11657. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11658. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11659. ASSERT_TRUE(mm->is_open());
  11660. Response res;
  11661. detail::set_file_content_provider(res, mm, "text/html",
  11662. detail::EncodingType::None);
  11663. std::string out;
  11664. DataSink sink;
  11665. sink.write = [&](const char *d, size_t l) {
  11666. out.append(d, l);
  11667. return true;
  11668. };
  11669. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11670. EXPECT_EQ("test.html", out);
  11671. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11672. EXPECT_EQ("test.html", out);
  11673. }
  11674. TEST(LongPollingTest, ClientCloseDetection) {
  11675. Server svr;
  11676. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11677. res.set_chunked_content_provider(
  11678. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11679. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11680. sink.os << "hello";
  11681. auto count = 10;
  11682. while (count > 0 && sink.is_writable()) {
  11683. this_thread::sleep_for(chrono::milliseconds(10));
  11684. count--;
  11685. }
  11686. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11687. return true;
  11688. });
  11689. });
  11690. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11691. auto se = detail::scope_exit([&] {
  11692. svr.stop();
  11693. listen_thread.join();
  11694. ASSERT_FALSE(svr.is_running());
  11695. });
  11696. svr.wait_until_ready();
  11697. Client cli("localhost", PORT);
  11698. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11699. EXPECT_EQ("hello", string(data, data_length));
  11700. return false; // close the socket immediately.
  11701. });
  11702. ASSERT_FALSE(res);
  11703. }
  11704. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11705. Server svr;
  11706. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11707. res.set_chunked_content_provider(
  11708. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11709. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11710. sink.os << "hello";
  11711. EXPECT_TRUE(sink.os.good());
  11712. // Wait for the client to close the connection
  11713. auto count = 10;
  11714. while (count > 0 && sink.is_writable()) {
  11715. this_thread::sleep_for(chrono::milliseconds(10));
  11716. count--;
  11717. }
  11718. // After client disconnect, write repeatedly until the socket
  11719. // write actually fails (small writes may be absorbed by the
  11720. // kernel buffer)
  11721. std::string chunk(1024, 'x');
  11722. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11723. sink.os << chunk;
  11724. }
  11725. EXPECT_TRUE(sink.os.fail());
  11726. return true;
  11727. });
  11728. });
  11729. auto port = svr.bind_to_any_port("localhost");
  11730. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11731. auto se = detail::scope_exit([&] {
  11732. svr.stop();
  11733. listen_thread.join();
  11734. ASSERT_FALSE(svr.is_running());
  11735. });
  11736. svr.wait_until_ready();
  11737. Client cli("localhost", port);
  11738. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11739. EXPECT_EQ("hello", string(data, data_length));
  11740. return false; // close the socket immediately.
  11741. });
  11742. ASSERT_FALSE(res);
  11743. }
  11744. TEST(GetWithParametersTest, GetWithParameters) {
  11745. Server svr;
  11746. svr.Get("/", [&](const Request &req, Response &) {
  11747. EXPECT_EQ("world", req.get_param_value("hello"));
  11748. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11749. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11750. });
  11751. svr.Get("/params", [&](const Request &req, Response &) {
  11752. EXPECT_EQ("world", req.get_param_value("hello"));
  11753. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11754. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11755. });
  11756. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11757. EXPECT_EQ("resource-id", req.matches[1]);
  11758. EXPECT_EQ("foo", req.get_param_value("param1"));
  11759. EXPECT_EQ("bar", req.get_param_value("param2"));
  11760. });
  11761. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11762. EXPECT_EQ("user-id", req.path_params.at("id"));
  11763. EXPECT_EQ("foo", req.get_param_value("param1"));
  11764. EXPECT_EQ("bar", req.get_param_value("param2"));
  11765. });
  11766. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11767. auto se = detail::scope_exit([&] {
  11768. svr.stop();
  11769. listen_thread.join();
  11770. ASSERT_FALSE(svr.is_running());
  11771. });
  11772. svr.wait_until_ready();
  11773. {
  11774. Client cli(HOST, PORT);
  11775. Params params;
  11776. params.emplace("hello", "world");
  11777. params.emplace("hello2", "world2");
  11778. params.emplace("hello3", "world3");
  11779. auto res = cli.Get("/", params, Headers{});
  11780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11781. EXPECT_EQ(StatusCode::OK_200, res->status);
  11782. }
  11783. {
  11784. Client cli(HOST, PORT);
  11785. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11787. EXPECT_EQ(StatusCode::OK_200, res->status);
  11788. }
  11789. {
  11790. Client cli(HOST, PORT);
  11791. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11793. EXPECT_EQ(StatusCode::OK_200, res->status);
  11794. }
  11795. {
  11796. Client cli(HOST, PORT);
  11797. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11799. EXPECT_EQ(StatusCode::OK_200, res->status);
  11800. }
  11801. }
  11802. TEST(GetWithParametersTest, GetWithParameters2) {
  11803. Server svr;
  11804. svr.Get("/", [&](const Request &req, Response &res) {
  11805. auto text = req.get_param_value("hello");
  11806. res.set_content(text, "text/plain");
  11807. });
  11808. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. listen_thread.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. Client cli("localhost", PORT);
  11816. Params params;
  11817. params.emplace("hello", "world");
  11818. std::string body;
  11819. auto res = cli.Get("/", params, Headers{},
  11820. [&](const char *data, size_t data_length) {
  11821. body.append(data, data_length);
  11822. return true;
  11823. });
  11824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11825. EXPECT_EQ(StatusCode::OK_200, res->status);
  11826. EXPECT_EQ("world", body);
  11827. }
  11828. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11829. Server svr;
  11830. svr.Get("/search", [&](const Request &req, Response &res) {
  11831. auto q = req.get_param_value("q");
  11832. res.set_content(q, "text/plain");
  11833. });
  11834. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11835. auto se = detail::scope_exit([&] {
  11836. svr.stop();
  11837. listen_thread.join();
  11838. ASSERT_FALSE(svr.is_running());
  11839. });
  11840. svr.wait_until_ready();
  11841. Client cli("localhost", PORT);
  11842. // Verify that Get(path, params) works without requiring Headers argument
  11843. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11845. EXPECT_EQ(StatusCode::OK_200, res->status);
  11846. EXPECT_EQ("cpp-httplib", res->body);
  11847. }
  11848. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11849. auto host = "httpbingo.org";
  11850. auto path = std::string{"/range/32"};
  11851. #ifdef CPPHTTPLIB_SSL_ENABLED
  11852. SSLClient cli(host);
  11853. #else
  11854. Client cli(host);
  11855. #endif
  11856. cli.set_default_headers({make_range_header({{1, 10}})});
  11857. cli.set_connection_timeout(5);
  11858. {
  11859. auto res = cli.Get(path);
  11860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11861. EXPECT_EQ("bcdefghijk", res->body);
  11862. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11863. }
  11864. {
  11865. auto res = cli.Get(path);
  11866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11867. EXPECT_EQ("bcdefghijk", res->body);
  11868. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11869. }
  11870. }
  11871. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11872. Server svr;
  11873. svr.set_default_headers({{"Hello", "World"}});
  11874. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11875. res.set_content("ok", "text/plain");
  11876. });
  11877. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11878. auto se = detail::scope_exit([&] {
  11879. svr.stop();
  11880. listen_thread.join();
  11881. ASSERT_FALSE(svr.is_running());
  11882. });
  11883. svr.wait_until_ready();
  11884. Client cli("localhost", PORT);
  11885. auto res = cli.Get("/");
  11886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11887. EXPECT_EQ(StatusCode::OK_200, res->status);
  11888. EXPECT_EQ("ok", res->body);
  11889. EXPECT_EQ("World", res->get_header_value("Hello"));
  11890. }
  11891. #ifdef CPPHTTPLIB_SSL_ENABLED
  11892. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11894. ASSERT_TRUE(svr.is_valid());
  11895. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11896. std::this_thread::sleep_for(std::chrono::seconds(2));
  11897. res.set_content("a", "text/plain");
  11898. });
  11899. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11900. res.set_content("b", "text/plain");
  11901. });
  11902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11903. auto se = detail::scope_exit([&] {
  11904. svr.stop();
  11905. listen_thread.join();
  11906. ASSERT_FALSE(svr.is_running());
  11907. });
  11908. svr.wait_until_ready();
  11909. SSLClient cli("localhost", PORT);
  11910. cli.enable_server_certificate_verification(false);
  11911. cli.set_keep_alive(true);
  11912. cli.set_read_timeout(std::chrono::seconds(1));
  11913. auto resa = cli.Get("/a");
  11914. ASSERT_TRUE(!resa);
  11915. EXPECT_EQ(Error::Read, resa.error());
  11916. auto resb = cli.Get("/b");
  11917. ASSERT_TRUE(resb);
  11918. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11919. EXPECT_EQ("b", resb->body);
  11920. }
  11921. // Closing an idle keep-alive connection sends close_notify and returns. The
  11922. // server must not wait for the client's close_notify: an idle client never
  11923. // sends one, so the worker would be held until the read timeout expires, and
  11924. // stop() would wait for it.
  11925. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11927. ASSERT_TRUE(svr.is_valid());
  11928. svr.set_keep_alive_timeout(1);
  11929. svr.set_read_timeout(10, 0);
  11930. svr.Get("/", [](const Request &, Response &res) {
  11931. res.set_content("ok", "text/plain");
  11932. });
  11933. auto port = svr.bind_to_any_port(HOST);
  11934. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11935. auto se = detail::scope_exit([&] {
  11936. if (listen_thread.joinable()) {
  11937. svr.stop();
  11938. listen_thread.join();
  11939. }
  11940. });
  11941. svr.wait_until_ready();
  11942. SSLClient cli(HOST, port);
  11943. cli.enable_server_certificate_verification(false);
  11944. cli.set_keep_alive(true);
  11945. auto res = cli.Get("/");
  11946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11947. EXPECT_EQ(StatusCode::OK_200, res->status);
  11948. // Stay idle past the keep-alive timeout so the server closes the connection.
  11949. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11950. auto start = std::chrono::steady_clock::now();
  11951. svr.stop();
  11952. listen_thread.join();
  11953. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11954. std::chrono::steady_clock::now() - start)
  11955. .count();
  11956. EXPECT_LT(elapsed, 3000);
  11957. }
  11958. #endif
  11959. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11960. protected:
  11961. ServerTestWithAI_PASSIVE()
  11962. : cli_(HOST, PORT)
  11963. #ifdef CPPHTTPLIB_SSL_ENABLED
  11964. ,
  11965. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11966. #endif
  11967. {
  11968. #ifdef CPPHTTPLIB_SSL_ENABLED
  11969. cli_.enable_server_certificate_verification(false);
  11970. #endif
  11971. }
  11972. virtual void SetUp() {
  11973. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11974. res.set_content("Hello World!", "text/plain");
  11975. });
  11976. t_ = thread(
  11977. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11978. svr_.wait_until_ready();
  11979. }
  11980. virtual void TearDown() {
  11981. svr_.stop();
  11982. t_.join();
  11983. }
  11984. #ifdef CPPHTTPLIB_SSL_ENABLED
  11985. SSLClient cli_;
  11986. SSLServer svr_;
  11987. #else
  11988. Client cli_;
  11989. Server svr_;
  11990. #endif
  11991. thread t_;
  11992. };
  11993. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11994. auto res = cli_.Get("/hi");
  11995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11996. EXPECT_EQ(StatusCode::OK_200, res->status);
  11997. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11998. EXPECT_EQ("Hello World!", res->body);
  11999. }
  12000. class ServerUpDownTest : public ::testing::Test {
  12001. protected:
  12002. ServerUpDownTest() : cli_(HOST, PORT) {}
  12003. virtual void SetUp() {
  12004. t_ = thread([&]() {
  12005. svr_.bind_to_any_port(HOST);
  12006. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12007. ASSERT_TRUE(svr_.listen_after_bind());
  12008. });
  12009. svr_.wait_until_ready();
  12010. }
  12011. virtual void TearDown() {
  12012. svr_.stop();
  12013. t_.join();
  12014. }
  12015. Client cli_;
  12016. Server svr_;
  12017. thread t_;
  12018. };
  12019. TEST_F(ServerUpDownTest, QuickStartStop) {
  12020. // Should not crash, especially when run with
  12021. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12022. }
  12023. class PayloadMaxLengthTest : public ::testing::Test {
  12024. protected:
  12025. PayloadMaxLengthTest()
  12026. : cli_(HOST, PORT)
  12027. #ifdef CPPHTTPLIB_SSL_ENABLED
  12028. ,
  12029. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12030. #endif
  12031. {
  12032. #ifdef CPPHTTPLIB_SSL_ENABLED
  12033. cli_.enable_server_certificate_verification(false);
  12034. #endif
  12035. }
  12036. virtual void SetUp() {
  12037. svr_.set_payload_max_length(8);
  12038. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12039. res.set_content("test", "text/plain");
  12040. });
  12041. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12042. svr_.wait_until_ready();
  12043. }
  12044. virtual void TearDown() {
  12045. svr_.stop();
  12046. t_.join();
  12047. }
  12048. #ifdef CPPHTTPLIB_SSL_ENABLED
  12049. SSLClient cli_;
  12050. SSLServer svr_;
  12051. #else
  12052. Client cli_;
  12053. Server svr_;
  12054. #endif
  12055. thread t_;
  12056. };
  12057. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12058. auto res = cli_.Post("/test", "123456789", "text/plain");
  12059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12060. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12061. res = cli_.Post("/test", "12345678", "text/plain");
  12062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12063. EXPECT_EQ(StatusCode::OK_200, res->status);
  12064. }
  12065. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12066. // Test chunked encoding with payload exceeding the 8-byte limit
  12067. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12068. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12070. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12071. }
  12072. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12073. // Test chunked encoding with payload within the 8-byte limit
  12074. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12075. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12077. EXPECT_EQ(StatusCode::OK_200, res->status);
  12078. }
  12079. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12080. // Test using send_request to send chunked data exceeding payload limit
  12081. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12082. "Host: " +
  12083. std::string(HOST) + ":" + std::to_string(PORT) +
  12084. "\r\n"
  12085. "Transfer-Encoding: chunked\r\n"
  12086. "Connection: close\r\n"
  12087. "\r\n"
  12088. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12089. "0123456789\r\n"
  12090. "0\r\n" // End chunk
  12091. "\r\n";
  12092. std::string response;
  12093. bool result = send_request(1, chunked_request, &response);
  12094. if (!result) {
  12095. // If send_request fails, it might be because the server closed the
  12096. // connection due to payload limit enforcement, which is acceptable
  12097. SUCCEED()
  12098. << "Server rejected oversized chunked request (connection closed)";
  12099. } else {
  12100. // If we got a response, check if it's an error response or connection was
  12101. // closed early Short response length indicates connection was closed due to
  12102. // payload limit
  12103. if (response.length() <= 10) {
  12104. SUCCEED() << "Server closed connection for oversized chunked request";
  12105. } else {
  12106. // Check for error status codes
  12107. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12108. response.find("Payload Too Large") != std::string::npos ||
  12109. response.find("400") != std::string::npos);
  12110. }
  12111. }
  12112. }
  12113. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  12114. // Test request without Content-Length header exceeding payload limit
  12115. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12116. "Host: " +
  12117. std::string(HOST) + ":" +
  12118. std::to_string(PORT) +
  12119. "\r\n"
  12120. "Connection: close\r\n"
  12121. "\r\n";
  12122. // Add payload exceeding the 8-byte limit
  12123. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12124. request_without_content_length += large_payload;
  12125. std::string response;
  12126. bool result = send_request(1, request_without_content_length, &response);
  12127. if (!result) {
  12128. // If send_request fails, server likely closed connection due to payload
  12129. // limit
  12130. SUCCEED() << "Server rejected oversized request without Content-Length "
  12131. "(connection closed)";
  12132. } else {
  12133. // Check if server responded with error or closed connection early
  12134. if (response.length() <= 10) {
  12135. SUCCEED() << "Server closed connection for oversized request without "
  12136. "Content-Length";
  12137. } else {
  12138. // Check for error status codes
  12139. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12140. response.find("Payload Too Large") != std::string::npos ||
  12141. response.find("400") != std::string::npos);
  12142. }
  12143. }
  12144. }
  12145. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12146. // Test request without Content-Length header within payload limit
  12147. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12148. "Host: " +
  12149. std::string(HOST) + ":" +
  12150. std::to_string(PORT) +
  12151. "\r\n"
  12152. "Connection: close\r\n"
  12153. "\r\n";
  12154. // Add payload within the 8-byte limit
  12155. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12156. request_without_content_length += small_payload;
  12157. std::string response;
  12158. bool result = send_request(1, request_without_content_length, &response);
  12159. // For requests without Content-Length, the server may have different behavior
  12160. // The key is that it should not reject due to payload limit for small
  12161. // payloads
  12162. if (result) {
  12163. // Check for any HTTP response (success or error, but not connection closed)
  12164. if (response.length() > 10) {
  12165. SUCCEED()
  12166. << "Server processed request without Content-Length within limit";
  12167. } else {
  12168. // Short response might indicate connection closed, which is acceptable
  12169. SUCCEED() << "Server closed connection for request without "
  12170. "Content-Length (acceptable behavior)";
  12171. }
  12172. } else {
  12173. // Connection failure might be due to protocol requirements
  12174. SUCCEED() << "Connection issue with request without Content-Length "
  12175. "(environment-specific)";
  12176. }
  12177. }
  12178. class LargePayloadMaxLengthTest : public ::testing::Test {
  12179. protected:
  12180. LargePayloadMaxLengthTest()
  12181. : cli_(HOST, PORT)
  12182. #ifdef CPPHTTPLIB_SSL_ENABLED
  12183. ,
  12184. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12185. #endif
  12186. {
  12187. #ifdef CPPHTTPLIB_SSL_ENABLED
  12188. cli_.enable_server_certificate_verification(false);
  12189. #endif
  12190. }
  12191. virtual void SetUp() {
  12192. // Set 10MB payload limit
  12193. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12194. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12195. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12196. res.set_content("Large payload test", "text/plain");
  12197. });
  12198. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12199. svr_.wait_until_ready();
  12200. }
  12201. virtual void TearDown() {
  12202. svr_.stop();
  12203. t_.join();
  12204. }
  12205. #ifdef CPPHTTPLIB_SSL_ENABLED
  12206. SSLClient cli_;
  12207. SSLServer svr_;
  12208. #else
  12209. Client cli_;
  12210. Server svr_;
  12211. #endif
  12212. thread t_;
  12213. };
  12214. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12215. // Test chunked encoding with payload within 10MB limit
  12216. std::string medium_payload(5 * 1024 * 1024,
  12217. 'A'); // 5MB payload, within 10MB limit
  12218. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12220. EXPECT_EQ(StatusCode::OK_200, res->status);
  12221. }
  12222. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12223. // Test chunked encoding with payload exceeding 10MB limit
  12224. std::string large_payload(12 * 1024 * 1024,
  12225. 'B'); // 12MB payload, exceeds 10MB limit
  12226. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12227. // Server may either return 413 or close the connection
  12228. if (res) {
  12229. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12230. } else {
  12231. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12232. }
  12233. }
  12234. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12235. // Test request without Content-Length header within 10MB limit
  12236. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12237. "Host: " +
  12238. std::string(HOST) + ":" +
  12239. std::to_string(PORT) +
  12240. "\r\n"
  12241. "Connection: close\r\n"
  12242. "\r\n";
  12243. // Add 1MB payload (within 10MB limit)
  12244. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12245. request_without_content_length += medium_payload;
  12246. std::string response;
  12247. bool result = send_request(5, request_without_content_length, &response);
  12248. if (result) {
  12249. // Should get a proper HTTP response for payloads within limit
  12250. if (response.length() > 10) {
  12251. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12252. "10MB limit";
  12253. } else {
  12254. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12255. "Content-Length)";
  12256. }
  12257. } else {
  12258. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12259. }
  12260. }
  12261. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12262. // Test request without Content-Length header exceeding 10MB limit
  12263. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12264. "Host: " +
  12265. std::string(HOST) + ":" +
  12266. std::to_string(PORT) +
  12267. "\r\n"
  12268. "Connection: close\r\n"
  12269. "\r\n";
  12270. // Add 12MB payload (exceeds 10MB limit)
  12271. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12272. request_without_content_length += large_payload;
  12273. std::string response;
  12274. bool result = send_request(10, request_without_content_length, &response);
  12275. if (!result) {
  12276. // Server should close connection due to payload limit
  12277. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12278. "(connection closed)";
  12279. } else {
  12280. // Check for error response
  12281. if (response.length() <= 10) {
  12282. SUCCEED()
  12283. << "Server closed connection for 12MB request exceeding 10MB limit";
  12284. } else {
  12285. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12286. response.find("Payload Too Large") != std::string::npos ||
  12287. response.find("400") != std::string::npos);
  12288. }
  12289. }
  12290. }
  12291. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12292. Server svr;
  12293. svr.Get("/", [](const Request &, Response &res) {
  12294. // Claims the most the client accepts, far more than it sends, then drops
  12295. // the connection.
  12296. res.set_content_provider(std::string().max_size(), "text/plain",
  12297. [](size_t, size_t, DataSink &sink) {
  12298. sink.write("abc", 3);
  12299. return false;
  12300. });
  12301. });
  12302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12303. auto se = detail::scope_exit([&] {
  12304. svr.stop();
  12305. thread.join();
  12306. ASSERT_FALSE(svr.is_running());
  12307. });
  12308. svr.wait_until_ready();
  12309. Client cli(HOST, PORT);
  12310. cli.set_payload_max_length(0);
  12311. EXPECT_FALSE(cli.Get("/"));
  12312. }
  12313. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12314. // Stream API does, not as a plain read failure
  12315. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12316. Server svr;
  12317. svr.Get("/big", [](const Request &, Response &res) {
  12318. res.set_content(std::string(100000, 'b'), "text/plain");
  12319. });
  12320. auto port = svr.bind_to_any_port(HOST);
  12321. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12322. auto se = detail::scope_exit([&] {
  12323. svr.stop();
  12324. thread.join();
  12325. });
  12326. svr.wait_until_ready();
  12327. Client cli(HOST, port);
  12328. cli.set_payload_max_length(1000);
  12329. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12330. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12331. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12332. [](const char *, size_t) { return true; });
  12333. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12334. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12335. // Small on the wire, over the limit once decompressed
  12336. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12337. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12338. #endif
  12339. }
  12340. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12341. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12342. // path.
  12343. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12344. Server svr;
  12345. const size_t LIMIT = 64 * 1024; // 64KB
  12346. svr.set_payload_max_length(LIMIT);
  12347. size_t total = 0;
  12348. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12349. const ContentReader &content_reader) {
  12350. content_reader([&](const char * /*data*/, size_t len) {
  12351. total += len;
  12352. return true;
  12353. });
  12354. res.status = 200;
  12355. res.set_content("stream_ok", "text/plain");
  12356. });
  12357. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12358. auto se = detail::scope_exit([&] {
  12359. svr.stop();
  12360. thread.join();
  12361. ASSERT_FALSE(svr.is_running());
  12362. });
  12363. svr.wait_until_ready();
  12364. // Prepare 256KB raw data and gzip-compress it
  12365. std::string raw(256 * 1024, 'A');
  12366. std::string gz;
  12367. {
  12368. z_stream zs{};
  12369. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12370. Z_DEFAULT_STRATEGY);
  12371. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12372. zs.avail_in = static_cast<uInt>(raw.size());
  12373. char outbuf[4096];
  12374. int ret;
  12375. do {
  12376. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12377. zs.avail_out = sizeof(outbuf);
  12378. ret = deflate(&zs, Z_FINISH);
  12379. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12380. } while (ret != Z_STREAM_END);
  12381. deflateEnd(&zs);
  12382. }
  12383. Client cli(HOST, PORT);
  12384. cli.set_connection_timeout(std::chrono::seconds(5));
  12385. Headers headers = {{"Content-Encoding", "gzip"}};
  12386. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12387. "application/octet-stream");
  12388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12389. // Server must reject oversized decompressed payloads with 413.
  12390. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12391. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12392. EXPECT_LE(total, LIMIT);
  12393. }
  12394. #ifndef CPPHTTPLIB_SSL_ENABLED
  12395. // For a request with neither Content-Length nor Transfer-Encoding, the
  12396. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12397. // compressed wire bytes straight to the ContentReader without ever routing
  12398. // them through the decompressor, so payload_max_length_ only bounded the
  12399. // compressed size on the wire, not the decompressed size.
  12400. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12401. Server svr;
  12402. const size_t LIMIT = 64 * 1024; // 64KB
  12403. svr.set_payload_max_length(LIMIT);
  12404. size_t total = 0;
  12405. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12406. const ContentReader &content_reader) {
  12407. content_reader([&](const char * /*data*/, size_t len) {
  12408. total += len;
  12409. return true;
  12410. });
  12411. res.status = 200;
  12412. res.set_content("stream_ok", "text/plain");
  12413. });
  12414. auto port = svr.bind_to_any_port(HOST);
  12415. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12416. auto se = detail::scope_exit([&] {
  12417. svr.stop();
  12418. thread.join();
  12419. ASSERT_FALSE(svr.is_running());
  12420. });
  12421. svr.wait_until_ready();
  12422. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12423. // StreamingGzipDecompression test above.
  12424. std::string raw(256 * 1024, 'A');
  12425. std::string gz;
  12426. {
  12427. httplib::detail::gzip_compressor compressor;
  12428. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12429. [&](const char *chunk, size_t len) {
  12430. gz.append(chunk, len);
  12431. return true;
  12432. });
  12433. ASSERT_TRUE(result);
  12434. }
  12435. // Send the gzip body over raw TCP with neither Content-Length nor
  12436. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12437. // kicks in.
  12438. std::string req = "POST /stream HTTP/1.1\r\n"
  12439. "Host: " +
  12440. std::string(HOST) + ":" + std::to_string(port) +
  12441. "\r\n"
  12442. "Content-Encoding: gzip\r\n"
  12443. "Connection: close\r\n"
  12444. "\r\n" +
  12445. gz;
  12446. std::string response;
  12447. ASSERT_TRUE(send_request(5, req, &response, port));
  12448. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12449. EXPECT_LE(total, LIMIT);
  12450. }
  12451. #endif
  12452. #endif
  12453. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12454. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12455. // the payload must be passed through untouched instead of being rejected.
  12456. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12457. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12458. Server svr;
  12459. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12460. res.set_content(body, "image/jpeg");
  12461. res.set_header("Content-Encoding", "UTF-8");
  12462. });
  12463. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12464. res.set_content(body, "image/jpeg");
  12465. res.set_header("Content-Encoding", "identity");
  12466. });
  12467. svr.Post("/echo", [](const Request &req, Response &res) {
  12468. res.set_content(req.body, "image/jpeg");
  12469. });
  12470. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12471. auto se = detail::scope_exit([&] {
  12472. svr.stop();
  12473. t.join();
  12474. ASSERT_FALSE(svr.is_running());
  12475. });
  12476. svr.wait_until_ready();
  12477. Client cli(HOST, PORT);
  12478. {
  12479. auto res = cli.Get("/image");
  12480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12481. EXPECT_EQ(StatusCode::OK_200, res->status);
  12482. EXPECT_EQ(body, res->body);
  12483. }
  12484. {
  12485. auto res = cli.Get("/identity");
  12486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12487. EXPECT_EQ(StatusCode::OK_200, res->status);
  12488. EXPECT_EQ(body, res->body);
  12489. }
  12490. {
  12491. // The same applies to a request body reaching the server.
  12492. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12493. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12495. EXPECT_EQ(StatusCode::OK_200, res->status);
  12496. EXPECT_EQ(body, res->body);
  12497. }
  12498. }
  12499. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12500. // gzip-encoded response even when the build has no zlib support.
  12501. static const char GZIPPED_HELLO_WORLD[] = {
  12502. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12503. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12504. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12505. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12506. // A content coding is a whole token, not something the field value merely
  12507. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12508. // as "fibre" look like Brotli, and turned a multi-coding value like
  12509. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12510. // it was never meant to see.
  12511. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12512. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12513. Server svr;
  12514. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12515. res.set_content(body, "image/jpeg");
  12516. res.set_header("Content-Encoding", "fibre");
  12517. });
  12518. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12519. res.set_content(body, "image/jpeg");
  12520. res.set_header("Content-Encoding", "gzip, br");
  12521. });
  12522. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12523. res.set_content(body, "image/jpeg");
  12524. res.set_header("Content-Encoding", "x-zstd-ish");
  12525. });
  12526. auto port = svr.bind_to_any_port(HOST);
  12527. thread t = thread([&]() { svr.listen_after_bind(); });
  12528. auto se = detail::scope_exit([&] {
  12529. svr.stop();
  12530. t.join();
  12531. ASSERT_FALSE(svr.is_running());
  12532. });
  12533. svr.wait_until_ready();
  12534. Client cli(HOST, port);
  12535. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12536. auto res = cli.Get(path);
  12537. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12538. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12539. // Not a coding we recognize, so the payload comes back untouched
  12540. EXPECT_EQ(body, res->body) << path;
  12541. }
  12542. }
  12543. // A content coding cpp-httplib recognizes but was not built with must be
  12544. // reported as such. Handing the still-compressed payload back to the caller
  12545. // would silently corrupt it.
  12546. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12547. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12548. Server svr;
  12549. // "image/jpeg" keeps the server from applying a content coding of its own,
  12550. // so the hand-crafted Content-Encoding below survives.
  12551. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12552. res.set_content(gzipped, "image/jpeg");
  12553. res.set_header("Content-Encoding", "gzip");
  12554. });
  12555. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12556. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12557. res.set_content(gzipped, "image/jpeg");
  12558. res.set_header("Content-Encoding", "GZIP");
  12559. });
  12560. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12561. auto se = detail::scope_exit([&] {
  12562. svr.stop();
  12563. t.join();
  12564. ASSERT_FALSE(svr.is_running());
  12565. });
  12566. svr.wait_until_ready();
  12567. Client cli(HOST, PORT);
  12568. {
  12569. auto res = cli.Get("/gzipped");
  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. // open_stream() must behave the same way.
  12580. auto handle = cli.open_stream("GET", "/gzipped");
  12581. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12582. ASSERT_TRUE(handle.is_valid());
  12583. std::string received;
  12584. char buf[256];
  12585. ssize_t n;
  12586. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12587. received.append(buf, static_cast<size_t>(n));
  12588. }
  12589. EXPECT_EQ("Hello World!", received);
  12590. #else
  12591. EXPECT_FALSE(handle.is_valid());
  12592. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12593. #endif
  12594. }
  12595. {
  12596. // A differently-cased coding must not be mistaken for an unknown one, or
  12597. // the body would be handed back still compressed.
  12598. auto res = cli.Get("/gzipped-uppercase");
  12599. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12601. EXPECT_EQ("Hello World!", res->body);
  12602. #else
  12603. ASSERT_FALSE(res);
  12604. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12605. #endif
  12606. }
  12607. }
  12608. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12609. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12610. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12611. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12612. // body a second time and appending a second Content-Encoding field line, so
  12613. // clients that decode one coding per listed value handed back raw gzip bytes.
  12614. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12615. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12616. Server svr;
  12617. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12618. // keeps the server from applying a coding of its own.
  12619. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12620. res.set_content(gzipped, "text/plain");
  12621. res.set_header("Content-Encoding", "gzip");
  12622. });
  12623. auto port = svr.bind_to_any_port(HOST);
  12624. thread t = thread([&]() { svr.listen_after_bind(); });
  12625. auto se = detail::scope_exit([&] {
  12626. svr.stop();
  12627. t.join();
  12628. ASSERT_FALSE(svr.is_running());
  12629. });
  12630. svr.wait_until_ready();
  12631. Client cli(HOST, port);
  12632. Headers headers = {{"Accept-Encoding", "gzip"}};
  12633. auto res = cli.Get("/pre-gzipped", headers);
  12634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12635. EXPECT_EQ(StatusCode::OK_200, res->status);
  12636. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12637. EXPECT_EQ("Hello World!", res->body);
  12638. }
  12639. // set_compress(false) sends every handler response as it is, buffered or
  12640. // streamed
  12641. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12642. const std::string text(1000, 'a');
  12643. Server svr;
  12644. svr.set_compress(false);
  12645. svr.Get("/buffered", [&](const Request &, Response &res) {
  12646. res.set_content(text, "text/plain");
  12647. });
  12648. svr.Get("/streamed", [&](const Request &, Response &res) {
  12649. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12650. sink.write(text.data(), text.size());
  12651. sink.done();
  12652. return true;
  12653. });
  12654. });
  12655. auto port = svr.bind_to_any_port(HOST);
  12656. ASSERT_LT(0, port);
  12657. thread t = thread([&] { svr.listen_after_bind(); });
  12658. auto se = detail::scope_exit([&] {
  12659. svr.stop();
  12660. t.join();
  12661. ASSERT_FALSE(svr.is_running());
  12662. });
  12663. svr.wait_until_ready();
  12664. Client cli(HOST, port);
  12665. cli.set_decompress(false);
  12666. for (auto path : {"/buffered", "/streamed"}) {
  12667. SCOPED_TRACE(path);
  12668. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12670. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12671. EXPECT_EQ(text, res->body);
  12672. }
  12673. }
  12674. // A chunked provider settles its coding where the headers are written and
  12675. // reuses it at write time. Both ends of that have to hold: a handler's own
  12676. // Content-Encoding suppresses the coding, and a response without one is still
  12677. // compressed as it always was.
  12678. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12679. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12680. const std::string plain = "Hello World! Hello World! Hello World!";
  12681. Server svr;
  12682. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12683. res.set_header("Content-Encoding", "gzip");
  12684. res.set_chunked_content_provider(
  12685. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12686. sink.write(gzipped.data(), gzipped.size());
  12687. sink.done();
  12688. return true;
  12689. });
  12690. });
  12691. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12692. res.set_chunked_content_provider(
  12693. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12694. sink.write(plain.data(), plain.size());
  12695. sink.done();
  12696. return true;
  12697. });
  12698. });
  12699. auto port = svr.bind_to_any_port(HOST);
  12700. thread t = thread([&]() { svr.listen_after_bind(); });
  12701. auto se = detail::scope_exit([&] {
  12702. svr.stop();
  12703. t.join();
  12704. ASSERT_FALSE(svr.is_running());
  12705. });
  12706. svr.wait_until_ready();
  12707. Client cli(HOST, port);
  12708. Headers headers = {{"Accept-Encoding", "gzip"}};
  12709. {
  12710. auto res = cli.Get("/pre-gzipped", headers);
  12711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12712. EXPECT_EQ(StatusCode::OK_200, res->status);
  12713. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12714. EXPECT_EQ("Hello World!", res->body);
  12715. }
  12716. {
  12717. auto res = cli.Get("/negotiated", headers);
  12718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12719. EXPECT_EQ(StatusCode::OK_200, res->status);
  12720. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12721. EXPECT_EQ(plain, res->body);
  12722. }
  12723. }
  12724. #endif
  12725. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12726. // the same message as the comma-joined one, so both have to be read the same
  12727. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12728. // single gzip coding, and a body the sender says was encoded twice was handed
  12729. // back after one pass, still compressed but presented as decoded.
  12730. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12731. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12732. Server svr;
  12733. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12734. res.set_content(body, "image/jpeg");
  12735. res.headers.emplace("Content-Encoding", "gzip");
  12736. res.headers.emplace("Content-Encoding", "gzip");
  12737. });
  12738. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12739. res.set_content(body, "image/jpeg");
  12740. res.set_header("Content-Encoding", "gzip, gzip");
  12741. });
  12742. auto port = svr.bind_to_any_port(HOST);
  12743. thread t = thread([&]() { svr.listen_after_bind(); });
  12744. auto se = detail::scope_exit([&] {
  12745. svr.stop();
  12746. t.join();
  12747. ASSERT_FALSE(svr.is_running());
  12748. });
  12749. svr.wait_until_ready();
  12750. Client cli(HOST, port);
  12751. // Two codings is not something cpp-httplib decodes, so both representations
  12752. // take the pass-through path rather than one of them being gunzipped once.
  12753. for (const char *path : {"/split", "/joined"}) {
  12754. auto res = cli.Get(path);
  12755. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12756. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12757. EXPECT_EQ(body, res->body) << path;
  12758. }
  12759. }
  12760. // Regression test for DoS vulnerability: a malicious server sending a response
  12761. // without Content-Length header must not cause unbounded memory consumption on
  12762. // the client side. The client should stop reading after a reasonable limit,
  12763. // similar to the server-side set_payload_max_length protection.
  12764. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12765. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12766. #ifndef _WIN32
  12767. signal(SIGPIPE, SIG_IGN);
  12768. #endif
  12769. auto server_thread = std::thread([] {
  12770. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12771. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12772. default_socket_options(srv);
  12773. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12774. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12775. sockaddr_in addr{};
  12776. addr.sin_family = AF_INET;
  12777. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12778. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12779. int opt = 1;
  12780. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12781. #ifdef _WIN32
  12782. reinterpret_cast<const char *>(&opt),
  12783. #else
  12784. &opt,
  12785. #endif
  12786. sizeof(opt));
  12787. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12788. ::listen(srv, 1);
  12789. sockaddr_in cli_addr{};
  12790. socklen_t cli_len = sizeof(cli_addr);
  12791. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12792. if (cli != INVALID_SOCKET) {
  12793. char buf[4096];
  12794. ::recv(cli, buf, sizeof(buf), 0);
  12795. // Malicious response: no Content-Length, no chunked encoding
  12796. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12797. "Connection: close\r\n"
  12798. "\r\n";
  12799. ::send(cli,
  12800. #ifdef _WIN32
  12801. static_cast<const char *>(response_header.c_str()),
  12802. static_cast<int>(response_header.size()),
  12803. #else
  12804. response_header.c_str(), response_header.size(),
  12805. #endif
  12806. 0);
  12807. // Send 10MB of data
  12808. std::string chunk(64 * 1024, 'A');
  12809. size_t total_sent = 0;
  12810. while (total_sent < MALICIOUS_DATA_SIZE) {
  12811. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12812. auto sent = ::send(cli,
  12813. #ifdef _WIN32
  12814. static_cast<const char *>(chunk.c_str()),
  12815. static_cast<int>(to_send),
  12816. #else
  12817. chunk.c_str(), to_send,
  12818. #endif
  12819. 0);
  12820. if (sent <= 0) break;
  12821. total_sent += static_cast<size_t>(sent);
  12822. }
  12823. detail::close_socket(cli);
  12824. }
  12825. detail::close_socket(srv);
  12826. });
  12827. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12828. size_t total_read = 0;
  12829. {
  12830. Client cli("127.0.0.1", PORT + 2);
  12831. cli.set_read_timeout(5, 0);
  12832. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12833. auto stream = cli.open_stream("GET", "/malicious");
  12834. ASSERT_TRUE(stream.is_valid());
  12835. char buffer[64 * 1024];
  12836. ssize_t n;
  12837. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12838. total_read += static_cast<size_t>(n);
  12839. }
  12840. } // StreamHandle and Client destroyed here, closing the socket
  12841. server_thread.join();
  12842. // With set_payload_max_length, the client must stop reading before consuming
  12843. // all 10MB. The read loop should be cut off at or near the configured limit.
  12844. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12845. << "Client read " << total_read << " bytes, exceeding the configured "
  12846. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12847. }
  12848. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12849. // the entire response body without truncation.
  12850. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12851. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12852. #ifndef _WIN32
  12853. signal(SIGPIPE, SIG_IGN);
  12854. #endif
  12855. auto server_thread = std::thread([] {
  12856. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12857. default_socket_options(srv);
  12858. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12859. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12860. sockaddr_in addr{};
  12861. addr.sin_family = AF_INET;
  12862. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12863. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12864. int opt = 1;
  12865. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12866. #ifdef _WIN32
  12867. reinterpret_cast<const char *>(&opt),
  12868. #else
  12869. &opt,
  12870. #endif
  12871. sizeof(opt));
  12872. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12873. ::listen(srv, 1);
  12874. sockaddr_in cli_addr{};
  12875. socklen_t cli_len = sizeof(cli_addr);
  12876. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12877. if (cli != INVALID_SOCKET) {
  12878. char buf[4096];
  12879. ::recv(cli, buf, sizeof(buf), 0);
  12880. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12881. "Connection: close\r\n"
  12882. "\r\n";
  12883. ::send(cli,
  12884. #ifdef _WIN32
  12885. static_cast<const char *>(response_header.c_str()),
  12886. static_cast<int>(response_header.size()),
  12887. #else
  12888. response_header.c_str(), response_header.size(),
  12889. #endif
  12890. 0);
  12891. std::string chunk(64 * 1024, 'A');
  12892. size_t total_sent = 0;
  12893. while (total_sent < DATA_SIZE) {
  12894. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12895. auto sent = ::send(cli,
  12896. #ifdef _WIN32
  12897. static_cast<const char *>(chunk.c_str()),
  12898. static_cast<int>(to_send),
  12899. #else
  12900. chunk.c_str(), to_send,
  12901. #endif
  12902. 0);
  12903. if (sent <= 0) break;
  12904. total_sent += static_cast<size_t>(sent);
  12905. }
  12906. #ifdef _WIN32
  12907. ::shutdown(cli, SD_SEND);
  12908. #else
  12909. ::shutdown(cli, SHUT_WR);
  12910. #endif
  12911. // Drain until the client closes its end, ensuring all data is delivered
  12912. char drain[1024];
  12913. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12914. detail::close_socket(cli);
  12915. }
  12916. detail::close_socket(srv);
  12917. });
  12918. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12919. size_t total_read = 0;
  12920. {
  12921. Client cli("127.0.0.1", PORT + 2);
  12922. cli.set_read_timeout(5, 0);
  12923. cli.set_payload_max_length(0); // 0 means no limit
  12924. auto stream = cli.open_stream("GET", "/data");
  12925. ASSERT_TRUE(stream.is_valid());
  12926. char buffer[64 * 1024];
  12927. ssize_t n;
  12928. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12929. total_read += static_cast<size_t>(n);
  12930. }
  12931. }
  12932. server_thread.join();
  12933. EXPECT_EQ(total_read, DATA_SIZE)
  12934. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12935. << " bytes without truncation, but only read " << total_read << " bytes.";
  12936. }
  12937. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12938. // enormous Content-Length must not cause the client to pre-allocate a huge
  12939. // response body buffer. The reservation is capped at payload_max_length_, and
  12940. // the read itself fails when the body exceeds the limit.
  12941. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12942. #ifndef _WIN32
  12943. signal(SIGPIPE, SIG_IGN);
  12944. #endif
  12945. auto server_thread = std::thread([] {
  12946. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12947. default_socket_options(srv);
  12948. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12949. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12950. sockaddr_in addr{};
  12951. addr.sin_family = AF_INET;
  12952. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12953. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12954. int opt = 1;
  12955. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12956. #ifdef _WIN32
  12957. reinterpret_cast<const char *>(&opt),
  12958. #else
  12959. &opt,
  12960. #endif
  12961. sizeof(opt));
  12962. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12963. ::listen(srv, 1);
  12964. sockaddr_in cli_addr{};
  12965. socklen_t cli_len = sizeof(cli_addr);
  12966. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12967. if (cli != INVALID_SOCKET) {
  12968. char buf[4096];
  12969. ::recv(cli, buf, sizeof(buf), 0);
  12970. // Malicious response: claim a 20GB body but send only a tiny payload.
  12971. std::string response = "HTTP/1.1 200 OK\r\n"
  12972. "Content-Length: 20000000000\r\n"
  12973. "\r\n"
  12974. "abc";
  12975. ::send(cli,
  12976. #ifdef _WIN32
  12977. static_cast<const char *>(response.c_str()),
  12978. static_cast<int>(response.size()),
  12979. #else
  12980. response.c_str(), response.size(),
  12981. #endif
  12982. 0);
  12983. detail::close_socket(cli);
  12984. }
  12985. detail::close_socket(srv);
  12986. });
  12987. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12988. {
  12989. Client cli("127.0.0.1", PORT + 2);
  12990. cli.set_read_timeout(5, 0);
  12991. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12992. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12993. // (server claims more bytes than payload_max_length permits), but it must
  12994. // not exhaust memory before getting there.
  12995. auto res = cli.Get("/malicious");
  12996. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12997. }
  12998. server_thread.join();
  12999. }
  13000. // Verify that content_receiver bypasses the default payload_max_length,
  13001. // allowing streaming downloads larger than 100MB without requiring an explicit
  13002. // set_payload_max_length call.
  13003. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13004. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13005. #ifndef _WIN32
  13006. signal(SIGPIPE, SIG_IGN);
  13007. #endif
  13008. auto server_thread = std::thread([] {
  13009. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13010. default_socket_options(srv);
  13011. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13012. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13013. sockaddr_in addr{};
  13014. addr.sin_family = AF_INET;
  13015. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13016. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13017. int opt = 1;
  13018. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13019. #ifdef _WIN32
  13020. reinterpret_cast<const char *>(&opt),
  13021. #else
  13022. &opt,
  13023. #endif
  13024. sizeof(opt));
  13025. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13026. ::listen(srv, 1);
  13027. sockaddr_in cli_addr{};
  13028. socklen_t cli_len = sizeof(cli_addr);
  13029. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13030. if (cli != INVALID_SOCKET) {
  13031. char buf[4096];
  13032. ::recv(cli, buf, sizeof(buf), 0);
  13033. // Response with Content-Length larger than default 100MB limit
  13034. auto content_length = std::to_string(DATA_SIZE);
  13035. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13036. "Content-Length: " +
  13037. content_length +
  13038. "\r\n"
  13039. "Connection: close\r\n"
  13040. "\r\n";
  13041. ::send(cli,
  13042. #ifdef _WIN32
  13043. static_cast<const char *>(response_header.c_str()),
  13044. static_cast<int>(response_header.size()),
  13045. #else
  13046. response_header.c_str(), response_header.size(),
  13047. #endif
  13048. 0);
  13049. std::string chunk(64 * 1024, 'A');
  13050. size_t total_sent = 0;
  13051. while (total_sent < DATA_SIZE) {
  13052. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13053. auto sent = ::send(cli,
  13054. #ifdef _WIN32
  13055. static_cast<const char *>(chunk.c_str()),
  13056. static_cast<int>(to_send),
  13057. #else
  13058. chunk.c_str(), to_send,
  13059. #endif
  13060. 0);
  13061. if (sent <= 0) break;
  13062. total_sent += static_cast<size_t>(sent);
  13063. }
  13064. detail::close_socket(cli);
  13065. }
  13066. detail::close_socket(srv);
  13067. });
  13068. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13069. size_t total_received = 0;
  13070. {
  13071. Client cli("127.0.0.1", PORT + 2);
  13072. cli.set_read_timeout(10, 0);
  13073. // Do NOT call set_payload_max_length — use the default 100MB limit
  13074. auto res =
  13075. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13076. total_received += data_length;
  13077. return true;
  13078. });
  13079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13080. EXPECT_EQ(StatusCode::OK_200, res->status);
  13081. }
  13082. server_thread.join();
  13083. EXPECT_EQ(total_received, DATA_SIZE)
  13084. << "With content_receiver, the client should read all " << DATA_SIZE
  13085. << " bytes despite the default 100MB payload_max_length, but only read "
  13086. << total_received << " bytes.";
  13087. }
  13088. // Verify that an explicit set_payload_max_length smaller than the response is
  13089. // enforced even when a content_receiver is used.
  13090. TEST(ClientVulnerabilityTest,
  13091. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13092. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13093. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13094. #ifndef _WIN32
  13095. signal(SIGPIPE, SIG_IGN);
  13096. #endif
  13097. auto server_thread = std::thread([] {
  13098. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13099. default_socket_options(srv);
  13100. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13101. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13102. sockaddr_in addr{};
  13103. addr.sin_family = AF_INET;
  13104. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13105. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13106. int opt = 1;
  13107. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13108. #ifdef _WIN32
  13109. reinterpret_cast<const char *>(&opt),
  13110. #else
  13111. &opt,
  13112. #endif
  13113. sizeof(opt));
  13114. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13115. ::listen(srv, 1);
  13116. sockaddr_in cli_addr{};
  13117. socklen_t cli_len = sizeof(cli_addr);
  13118. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13119. if (cli != INVALID_SOCKET) {
  13120. char buf[4096];
  13121. ::recv(cli, buf, sizeof(buf), 0);
  13122. auto content_length = std::to_string(DATA_SIZE);
  13123. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13124. "Content-Length: " +
  13125. content_length +
  13126. "\r\n"
  13127. "Connection: close\r\n"
  13128. "\r\n";
  13129. ::send(cli,
  13130. #ifdef _WIN32
  13131. static_cast<const char *>(response_header.c_str()),
  13132. static_cast<int>(response_header.size()),
  13133. #else
  13134. response_header.c_str(), response_header.size(),
  13135. #endif
  13136. 0);
  13137. std::string chunk(64 * 1024, 'A');
  13138. size_t total_sent = 0;
  13139. while (total_sent < DATA_SIZE) {
  13140. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13141. auto sent = ::send(cli,
  13142. #ifdef _WIN32
  13143. static_cast<const char *>(chunk.c_str()),
  13144. static_cast<int>(to_send),
  13145. #else
  13146. chunk.c_str(), to_send,
  13147. #endif
  13148. 0);
  13149. if (sent <= 0) break;
  13150. total_sent += static_cast<size_t>(sent);
  13151. }
  13152. detail::close_socket(cli);
  13153. }
  13154. detail::close_socket(srv);
  13155. });
  13156. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13157. size_t total_received = 0;
  13158. {
  13159. Client cli("127.0.0.1", PORT + 2);
  13160. cli.set_read_timeout(10, 0);
  13161. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13162. auto res =
  13163. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13164. total_received += data_length;
  13165. return true;
  13166. });
  13167. // Should fail because 200MB exceeds the explicit 150MB limit
  13168. EXPECT_FALSE(res);
  13169. }
  13170. server_thread.join();
  13171. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13172. << "Client with content_receiver should respect the explicit "
  13173. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13174. << total_received << " bytes.";
  13175. }
  13176. // Verify that an explicit set_payload_max_length larger than the response
  13177. // allows the content_receiver to read all data successfully.
  13178. TEST(ClientVulnerabilityTest,
  13179. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13180. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13181. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13182. #ifndef _WIN32
  13183. signal(SIGPIPE, SIG_IGN);
  13184. #endif
  13185. auto server_thread = std::thread([] {
  13186. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13187. default_socket_options(srv);
  13188. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13189. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13190. sockaddr_in addr{};
  13191. addr.sin_family = AF_INET;
  13192. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13193. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13194. int opt = 1;
  13195. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13196. #ifdef _WIN32
  13197. reinterpret_cast<const char *>(&opt),
  13198. #else
  13199. &opt,
  13200. #endif
  13201. sizeof(opt));
  13202. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13203. ::listen(srv, 1);
  13204. sockaddr_in cli_addr{};
  13205. socklen_t cli_len = sizeof(cli_addr);
  13206. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13207. if (cli != INVALID_SOCKET) {
  13208. char buf[4096];
  13209. ::recv(cli, buf, sizeof(buf), 0);
  13210. auto content_length = std::to_string(DATA_SIZE);
  13211. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13212. "Content-Length: " +
  13213. content_length +
  13214. "\r\n"
  13215. "Connection: close\r\n"
  13216. "\r\n";
  13217. ::send(cli,
  13218. #ifdef _WIN32
  13219. static_cast<const char *>(response_header.c_str()),
  13220. static_cast<int>(response_header.size()),
  13221. #else
  13222. response_header.c_str(), response_header.size(),
  13223. #endif
  13224. 0);
  13225. std::string chunk(64 * 1024, 'A');
  13226. size_t total_sent = 0;
  13227. while (total_sent < DATA_SIZE) {
  13228. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13229. auto sent = ::send(cli,
  13230. #ifdef _WIN32
  13231. static_cast<const char *>(chunk.c_str()),
  13232. static_cast<int>(to_send),
  13233. #else
  13234. chunk.c_str(), to_send,
  13235. #endif
  13236. 0);
  13237. if (sent <= 0) break;
  13238. total_sent += static_cast<size_t>(sent);
  13239. }
  13240. #ifdef _WIN32
  13241. ::shutdown(cli, SD_SEND);
  13242. #else
  13243. ::shutdown(cli, SHUT_WR);
  13244. #endif
  13245. char drain[1024];
  13246. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13247. detail::close_socket(cli);
  13248. }
  13249. detail::close_socket(srv);
  13250. });
  13251. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13252. size_t total_received = 0;
  13253. {
  13254. Client cli("127.0.0.1", PORT + 2);
  13255. cli.set_read_timeout(10, 0);
  13256. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13257. auto res =
  13258. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13259. total_received += data_length;
  13260. return true;
  13261. });
  13262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13263. EXPECT_EQ(StatusCode::OK_200, res->status);
  13264. }
  13265. server_thread.join();
  13266. EXPECT_EQ(total_received, DATA_SIZE)
  13267. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13268. << " bytes (larger than " << DATA_SIZE
  13269. << " bytes response), content_receiver should read all data, but only "
  13270. "read "
  13271. << total_received << " bytes.";
  13272. }
  13273. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13274. // Regression test for "zip bomb" attack on the client side: a malicious server
  13275. // sends a small gzip-compressed response that decompresses to a huge payload.
  13276. // The client must enforce payload_max_length on the decompressed size.
  13277. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13278. constexpr size_t DECOMPRESSED_SIZE =
  13279. 10 * 1024 * 1024; // 10MB after decompression
  13280. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13281. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13282. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13283. std::string compressed;
  13284. {
  13285. httplib::detail::gzip_compressor compressor;
  13286. bool ok =
  13287. compressor.compress(uncompressed.data(), uncompressed.size(),
  13288. /*last=*/true, [&](const char *buf, size_t len) {
  13289. compressed.append(buf, len);
  13290. return true;
  13291. });
  13292. ASSERT_TRUE(ok);
  13293. }
  13294. // Sanity: compressed data should be much smaller than the decompressed size
  13295. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13296. #ifndef _WIN32
  13297. signal(SIGPIPE, SIG_IGN);
  13298. #endif
  13299. // Set up the listening socket in the main thread so the server is guaranteed
  13300. // to be ready before the client connects (eliminates race condition).
  13301. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13302. default_socket_options(srv);
  13303. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13304. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13305. sockaddr_in addr{};
  13306. addr.sin_family = AF_INET;
  13307. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13308. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13309. int opt = 1;
  13310. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13311. #ifdef _WIN32
  13312. reinterpret_cast<const char *>(&opt),
  13313. #else
  13314. &opt,
  13315. #endif
  13316. sizeof(opt));
  13317. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13318. ASSERT_EQ(0, ::listen(srv, 1));
  13319. auto server_thread = std::thread([&compressed, srv] {
  13320. sockaddr_in cli_addr{};
  13321. socklen_t cli_len = sizeof(cli_addr);
  13322. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13323. if (cli != INVALID_SOCKET) {
  13324. // Read the full HTTP request (until \r\n\r\n)
  13325. char buf[4096];
  13326. size_t total = 0;
  13327. while (total < sizeof(buf)) {
  13328. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13329. if (n <= 0) break;
  13330. total += static_cast<size_t>(n);
  13331. // Check for end of headers
  13332. if (total >= 4) {
  13333. std::string req(buf, total);
  13334. if (req.find("\r\n\r\n") != std::string::npos) break;
  13335. }
  13336. }
  13337. // Malicious response: gzip-compressed body, no Content-Length
  13338. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13339. "Content-Encoding: gzip\r\n"
  13340. "Connection: close\r\n"
  13341. "\r\n";
  13342. ::send(cli,
  13343. #ifdef _WIN32
  13344. static_cast<const char *>(response_header.c_str()),
  13345. static_cast<int>(response_header.size()),
  13346. #else
  13347. response_header.c_str(), response_header.size(),
  13348. #endif
  13349. 0);
  13350. // Send the compressed payload (small on the wire, huge when decompressed)
  13351. size_t total_sent = 0;
  13352. while (total_sent < compressed.size()) {
  13353. auto to_send = std::min(compressed.size() - total_sent,
  13354. static_cast<size_t>(64 * 1024));
  13355. auto sent =
  13356. ::send(cli,
  13357. #ifdef _WIN32
  13358. static_cast<const char *>(compressed.c_str() + total_sent),
  13359. static_cast<int>(to_send),
  13360. #else
  13361. compressed.c_str() + total_sent, to_send,
  13362. #endif
  13363. 0);
  13364. if (sent <= 0) break;
  13365. total_sent += static_cast<size_t>(sent);
  13366. }
  13367. detail::close_socket(cli);
  13368. }
  13369. });
  13370. auto se = detail::scope_exit([&] {
  13371. detail::close_socket(srv);
  13372. server_thread.join();
  13373. });
  13374. size_t total_decompressed = 0;
  13375. {
  13376. Client cli("127.0.0.1", PORT + 3);
  13377. cli.set_read_timeout(5, 0);
  13378. cli.set_decompress(true);
  13379. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13380. auto stream = cli.open_stream("GET", "/zipbomb");
  13381. ASSERT_TRUE(stream.is_valid());
  13382. char buffer[64 * 1024];
  13383. ssize_t n;
  13384. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13385. total_decompressed += static_cast<size_t>(n);
  13386. }
  13387. }
  13388. // The decompressed size must be capped by payload_max_length. Without
  13389. // protection, the client would decompress the full 10MB from a tiny
  13390. // compressed payload, enabling a zip bomb DoS attack.
  13391. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13392. << "Client decompressed " << total_decompressed
  13393. << " bytes from a gzip response. The decompressed size should be "
  13394. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13395. }
  13396. #endif
  13397. TEST(HostAndPortPropertiesTest, NoSSL) {
  13398. httplib::Client cli("www.google.com", 1234);
  13399. ASSERT_EQ("www.google.com", cli.host());
  13400. ASSERT_EQ(1234, cli.port());
  13401. }
  13402. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13403. httplib::Client cli("www.google.com:1234");
  13404. ASSERT_EQ("www.google.com", cli.host());
  13405. ASSERT_EQ(1234, cli.port());
  13406. }
  13407. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13408. // Port number that overflows int — should not crash, client becomes invalid
  13409. httplib::Client cli("http://www.google.com:99999999999999999999");
  13410. ASSERT_FALSE(cli.is_valid());
  13411. }
  13412. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13413. // Port 99999 exceeds valid range (1-65535) — should not crash
  13414. httplib::Client cli("http://www.google.com:99999");
  13415. ASSERT_FALSE(cli.is_valid());
  13416. auto res = cli.Get("/");
  13417. EXPECT_FALSE(res);
  13418. EXPECT_EQ(Error::Connection, res.error());
  13419. }
  13420. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13421. httplib::Client cli("http://user:pass@localhost:1234");
  13422. ASSERT_FALSE(cli.is_valid());
  13423. EXPECT_FALSE(cli.Get("/"));
  13424. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13425. }
  13426. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13427. httplib::Client cli("http://www.google.com:80abc");
  13428. ASSERT_FALSE(cli.is_valid());
  13429. }
  13430. #ifdef CPPHTTPLIB_SSL_ENABLED
  13431. TEST(HostAndPortPropertiesTest, SSL) {
  13432. httplib::SSLClient cli("www.google.com");
  13433. ASSERT_EQ("www.google.com", cli.host());
  13434. ASSERT_EQ(443, cli.port());
  13435. }
  13436. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13437. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13438. std::string cert;
  13439. read_file(CA_CERT_FILE, cert);
  13440. httplib::SSLClient httplib_client("www.google.com");
  13441. // Load CA store first time
  13442. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13443. // Load CA store second time (update)
  13444. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13445. // Verify client is still valid and can make connections
  13446. httplib_client.enable_server_certificate_verification(true);
  13447. auto res = httplib_client.Get("/");
  13448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13449. // Google may return 200 or 301 depending on various factors
  13450. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13451. res->status == StatusCode::MovedPermanently_301);
  13452. }
  13453. TEST(SSLClientTest, ServerNameIndication_Online) {
  13454. auto host = "httpbingo.org";
  13455. auto path = std::string{"/get"};
  13456. SSLClient cli(host, 443);
  13457. auto res = cli.Get(path);
  13458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13459. ASSERT_EQ(StatusCode::OK_200, res->status);
  13460. }
  13461. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13462. // Use a site that will cause SSL verification failure due to self-signed cert
  13463. SSLClient cli("self-signed.badssl.com", 443);
  13464. cli.enable_server_certificate_verification(true);
  13465. auto res = cli.Get("/");
  13466. ASSERT_TRUE(!res);
  13467. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13468. // Verify backend error is captured for SSLServerVerification
  13469. // This occurs when certificate verification fails
  13470. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13471. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13472. EXPECT_NE(0UL, res.ssl_backend_error());
  13473. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13474. res.ssl_error());
  13475. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13476. #if !defined(_WIN32) || \
  13477. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13478. // On non-Windows or when Windows Schannel is disabled, the error comes
  13479. // from OpenSSL's verification
  13480. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13481. res.ssl_backend_error());
  13482. #endif
  13483. #endif
  13484. }
  13485. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13486. // Use a site where hostname doesn't match the certificate
  13487. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13488. SSLClient cli("wrong.host.badssl.com", 443);
  13489. cli.enable_server_certificate_verification(true);
  13490. cli.enable_server_hostname_verification(true);
  13491. auto res = cli.Get("/");
  13492. ASSERT_TRUE(!res);
  13493. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13494. // Verify backend error is captured for hostname verification failure
  13495. EXPECT_NE(0UL, res.ssl_backend_error());
  13496. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13497. res.ssl_error());
  13498. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13499. #if !defined(_WIN32) || \
  13500. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13501. // On non-Windows or when Windows Schannel is disabled, the error comes
  13502. // from OpenSSL's hostname verification
  13503. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13504. res.ssl_backend_error());
  13505. #endif
  13506. #endif
  13507. }
  13508. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13509. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13510. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13511. SSLClient cli("www.google.com", 443);
  13512. cli.enable_server_certificate_verification(true);
  13513. auto res = cli.Get("/");
  13514. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13515. }
  13516. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13517. SSLClient cli("www.google.com", 443);
  13518. cli.enable_server_certificate_verification(true);
  13519. cli.enable_windows_certificate_verification(false);
  13520. auto res = cli.Get("/");
  13521. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13522. }
  13523. // The server sends an intermediate cross-signed by a root Windows trusts,
  13524. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13525. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13526. SSLClient cli("accounts.spotify.com", 443);
  13527. auto res = cli.Get("/");
  13528. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13529. << " ssl_backend_error=" << res.ssl_backend_error();
  13530. }
  13531. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13532. // policy status, which no backend reports for a self-signed certificate.
  13533. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13534. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13535. ASSERT_TRUE(svr.is_valid());
  13536. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13537. auto se = detail::scope_exit([&] {
  13538. svr.stop();
  13539. t.join();
  13540. ASSERT_FALSE(svr.is_running());
  13541. });
  13542. svr.wait_until_ready();
  13543. SSLClient cli("127.0.0.1", PORT);
  13544. cli.set_connection_timeout(30);
  13545. auto res = cli.Get("/");
  13546. ASSERT_FALSE(res);
  13547. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13548. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13549. }
  13550. #endif
  13551. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13552. Client cli("https://google.com");
  13553. auto res = cli.Get("/");
  13554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13555. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13556. }
  13557. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13558. SSLClient cli("google.com");
  13559. cli.set_ca_cert_path(CA_CERT_FILE);
  13560. auto res = cli.Get("/");
  13561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13562. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13563. }
  13564. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13565. SSLClient cli("google.com");
  13566. cli.enable_server_certificate_verification(true);
  13567. cli.set_ca_cert_path("hello");
  13568. auto res = cli.Get("/");
  13569. ASSERT_TRUE(!res);
  13570. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13571. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13572. // should be set
  13573. EXPECT_EQ(0, res.ssl_error());
  13574. // Verify backend error is captured for SSLLoadingCerts
  13575. // This error occurs when loading CA certificates fails
  13576. EXPECT_NE(0UL, res.ssl_backend_error());
  13577. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13578. // OpenSSL specific error codes:
  13579. // > openssl errstr 0x80000002
  13580. // error:80000002:system library::No such file or directory
  13581. // > openssl errstr 0xA000126
  13582. // error:0A000126:SSL routines::unexpected eof while reading
  13583. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13584. res.ssl_backend_error() == 0xA000126);
  13585. #endif
  13586. }
  13587. TEST(SSLClientTest, ServerCertificateVerification4) {
  13588. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13589. ASSERT_TRUE(svr.is_valid());
  13590. svr.Get("/test", [&](const Request &, Response &res) {
  13591. res.set_content("test", "text/plain");
  13592. svr.stop();
  13593. ASSERT_TRUE(true);
  13594. });
  13595. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13596. auto se = detail::scope_exit([&] {
  13597. t.join();
  13598. ASSERT_FALSE(svr.is_running());
  13599. });
  13600. svr.wait_until_ready();
  13601. SSLClient cli("127.0.0.1", PORT);
  13602. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13603. cli.enable_server_certificate_verification(true);
  13604. cli.set_connection_timeout(30);
  13605. auto res = cli.Get("/test");
  13606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13607. ASSERT_EQ(StatusCode::OK_200, res->status);
  13608. }
  13609. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13610. std::string cert;
  13611. read_file(CA_CERT_FILE, cert);
  13612. SSLClient cli("google.com");
  13613. cli.load_ca_cert_store(cert.data(), cert.size());
  13614. const auto res = cli.Get("/");
  13615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13616. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13617. }
  13618. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13619. // clang-format off
  13620. static constexpr char cert[] =
  13621. "GlobalSign Root CA\n"
  13622. "==================\n"
  13623. "-----BEGIN CERTIFICATE-----\n"
  13624. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13625. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13626. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13627. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13628. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13629. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13630. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13631. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13632. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13633. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13634. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13635. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13636. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13637. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13638. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13639. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13640. "-----END CERTIFICATE-----\n";
  13641. // clang-format on
  13642. SSLClient cli("google.com");
  13643. cli.load_ca_cert_store(cert, sizeof(cert));
  13644. const auto res = cli.Get("/");
  13645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13646. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13647. }
  13648. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13649. SSLClient cli("www.youtube.com");
  13650. cli.set_ca_cert_path(CA_CERT_FILE);
  13651. cli.enable_server_certificate_verification(true);
  13652. cli.set_follow_location(true);
  13653. auto res = cli.Get("/");
  13654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13655. ASSERT_EQ(StatusCode::OK_200, res->status);
  13656. }
  13657. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13658. SSLClient cli("wWw.YouTube.Com");
  13659. cli.set_ca_cert_path(CA_CERT_FILE);
  13660. cli.enable_server_certificate_verification(true);
  13661. cli.enable_server_hostname_verification(true);
  13662. cli.set_follow_location(true);
  13663. auto res = cli.Get("/");
  13664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13665. ASSERT_EQ(StatusCode::OK_200, res->status);
  13666. }
  13667. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13668. SSLClient cli("gOoGlE.COm");
  13669. cli.enable_server_certificate_verification(true);
  13670. cli.enable_server_hostname_verification(true);
  13671. cli.set_follow_location(true);
  13672. auto res = cli.Get("/");
  13673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13674. ASSERT_EQ(StatusCode::OK_200, res->status);
  13675. }
  13676. TEST(SSLClientTest, Issue2004_Online) {
  13677. Client client("https://google.com");
  13678. client.set_follow_location(true);
  13679. auto res = client.Get("/");
  13680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13681. ASSERT_EQ(StatusCode::OK_200, res->status);
  13682. auto body = res->body;
  13683. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13684. }
  13685. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13686. // Create SSLClient with invalid cert/key to make is_valid() return false
  13687. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13688. "nonexistent_key.pem");
  13689. // is_valid() should be false due to cert loading failure
  13690. ASSERT_FALSE(cli.is_valid());
  13691. auto res = cli.Get("/");
  13692. ASSERT_FALSE(res);
  13693. EXPECT_EQ(Error::SSLConnection, res.error());
  13694. }
  13695. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13696. // Test for Issue #2251: SSL error not properly reported when client cert
  13697. // and key paths are swapped or mismatched
  13698. // This simulates the scenario where user accidentally swaps the cert and key
  13699. // files
  13700. // Using client cert file as private key and vice versa (completely wrong)
  13701. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13702. // Should fail validation due to cert/key mismatch
  13703. ASSERT_FALSE(cli.is_valid());
  13704. // Attempt to make a request should fail with proper error
  13705. auto res = cli.Get("/");
  13706. ASSERT_FALSE(res);
  13707. EXPECT_EQ(Error::SSLConnection, res.error());
  13708. // SSL error should be recorded in the Result object (this is the key fix for
  13709. // Issue #2251)
  13710. auto backend_error = res.ssl_backend_error();
  13711. EXPECT_NE(0u, backend_error);
  13712. }
  13713. // Tests cert/key mismatch detection at the TLS context level
  13714. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13715. // Test that using mismatched cert/key causes connection failure.
  13716. // We verify this at the SSLClient level rather than through internal
  13717. // TLS API functions.
  13718. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13719. cli.enable_server_certificate_verification(false);
  13720. cli.set_connection_timeout(2);
  13721. // The mismatch should cause a connection or handshake error
  13722. auto res = cli.Get("/test");
  13723. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13724. // Either way, the request should fail
  13725. EXPECT_FALSE(res);
  13726. }
  13727. #endif
  13728. #if 0
  13729. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13730. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13731. ASSERT_TRUE(cli != nullptr);
  13732. cli->set_address_family(AF_INET6);
  13733. cli->set_interface("en0");
  13734. auto res = cli->Get("/get");
  13735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13736. ASSERT_EQ(StatusCode::OK_200, res->status);
  13737. }
  13738. #endif
  13739. // Client certificate tests - work with all TLS backends
  13740. #ifdef CPPHTTPLIB_SSL_ENABLED
  13741. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13742. void ClientCertPresent(
  13743. const std::string &client_cert_file,
  13744. const std::string &client_private_key_file,
  13745. const std::string &client_encrypted_private_key_pass = std::string(),
  13746. const ClientCertServerSetup &setup = nullptr) {
  13747. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13748. ASSERT_TRUE(svr.is_valid());
  13749. if (setup) { setup(svr); }
  13750. svr.Get("/test", [&](const Request &req, Response &res) {
  13751. res.set_content("test", "text/plain");
  13752. auto cert = req.peer_cert();
  13753. ASSERT_TRUE(static_cast<bool>(cert));
  13754. std::string common_name = cert.subject_cn();
  13755. EXPECT_EQ("Common Name", common_name);
  13756. });
  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, client_cert_file, client_private_key_file,
  13767. client_encrypted_private_key_pass);
  13768. cli.enable_server_certificate_verification(false);
  13769. cli.set_connection_timeout(30);
  13770. auto res = cli.Get("/test");
  13771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13772. ASSERT_EQ(StatusCode::OK_200, res->status);
  13773. }
  13774. TEST(SSLClientServerTest, ClientCertPresent) {
  13775. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13776. }
  13777. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13778. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13779. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13780. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13781. }
  13782. // Expects svr, which must require client certificates, to reject a client
  13783. // that has none
  13784. void RejectsClientWithoutCert(SSLServer &svr) {
  13785. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13786. auto port = svr.bind_to_any_port(HOST);
  13787. ASSERT_LT(0, port);
  13788. thread t = thread([&]() { svr.listen_after_bind(); });
  13789. auto se = detail::scope_exit([&] {
  13790. svr.stop();
  13791. t.join();
  13792. ASSERT_FALSE(svr.is_running());
  13793. });
  13794. svr.wait_until_ready();
  13795. SSLClient cli(HOST, port);
  13796. cli.set_connection_timeout(30);
  13797. // Skip the server certificate check, so that the request fails because the
  13798. // client certificate is missing rather than because cert.pem is not trusted
  13799. cli.enable_server_certificate_verification(false);
  13800. auto res = cli.Get("/test");
  13801. ASSERT_FALSE(res);
  13802. // The server rejects the client during the handshake, or on TLS 1.3 right
  13803. // after it, which the client notices on its first write or read
  13804. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13805. res.error() == Error::Write || res.error() == Error::Read)
  13806. << to_string(res.error());
  13807. if (res.error() == Error::SSLConnection) {
  13808. EXPECT_NE(0UL, res.ssl_backend_error());
  13809. }
  13810. // A rejection noticed on the write keeps the TLS error the write hit
  13811. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13812. }
  13813. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13815. ASSERT_TRUE(svr.is_valid());
  13816. if (setup) { setup(svr); }
  13817. RejectsClientWithoutCert(svr);
  13818. }
  13819. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13820. // A server that requires client certificates must keep requiring them after
  13821. // setup changes it, and keep accepting a client that has one
  13822. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13823. ClientCertMissing(setup);
  13824. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13825. setup);
  13826. }
  13827. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13828. ClientCertStillRequired([](SSLServer &svr) {
  13829. ASSERT_TRUE(tls::set_verify_callback(
  13830. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13831. });
  13832. }
  13833. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13834. ClientCertStillRequired([](SSLServer &svr) {
  13835. ASSERT_TRUE(tls::set_verify_callback(
  13836. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13837. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13838. });
  13839. }
  13840. // The client verifies the server certificate during the handshake, so a
  13841. // server that fails the check never gets the client certificate, even when a
  13842. // verifier of the client's own accepts it
  13843. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13844. struct Case {
  13845. const char *trusted_ca;
  13846. const char *host;
  13847. Error error;
  13848. };
  13849. // cert2.pem names localhost: the first client does not trust it, and the
  13850. // second trusts it but asks for another name
  13851. for (const auto &c :
  13852. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13853. Case{SERVER_CERT2_FILE, "example.com",
  13854. Error::SSLServerHostnameVerification}}) {
  13855. for (auto with_verifier : {false, true}) {
  13856. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13857. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13858. CLIENT_CA_CERT_FILE);
  13859. ASSERT_TRUE(svr.is_valid());
  13860. std::atomic<bool> got_client_cert{false};
  13861. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13862. [&](const tls::VerifyContext &) {
  13863. got_client_cert = true;
  13864. return true;
  13865. }));
  13866. auto port = svr.bind_to_any_port("127.0.0.1");
  13867. ASSERT_LT(0, port);
  13868. thread t = thread([&] { svr.listen_after_bind(); });
  13869. svr.wait_until_ready();
  13870. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13871. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13872. cli.set_ca_cert_path(c.trusted_ca);
  13873. if (with_verifier) {
  13874. cli.set_server_certificate_verifier(
  13875. [](const tls::VerifyContext &) { return true; });
  13876. }
  13877. auto res = cli.Get("/");
  13878. EXPECT_FALSE(res);
  13879. EXPECT_EQ(c.error, res.error());
  13880. svr.stop();
  13881. t.join();
  13882. EXPECT_FALSE(got_client_cert);
  13883. }
  13884. }
  13885. }
  13886. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13887. std::string cert_pem, key_pem, ca_pem;
  13888. read_file(SERVER_CERT_FILE, cert_pem);
  13889. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13890. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13891. ASSERT_TRUE(
  13892. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13893. }
  13894. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13895. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13896. ASSERT_TRUE(svr.is_valid());
  13897. UpdateCertsPemWithClientCA(svr);
  13898. RejectsClientWithoutCert(svr);
  13899. }
  13900. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13901. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13902. }
  13903. // A TLS error from one request must not show up in a later request's Result
  13904. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13906. ASSERT_TRUE(svr.is_valid());
  13907. svr.Get("/test", [](const Request &, Response &res) {
  13908. res.set_content("test", "text/plain");
  13909. });
  13910. auto port = svr.bind_to_any_port(HOST);
  13911. ASSERT_LT(0, port);
  13912. thread t = thread([&]() { svr.listen_after_bind(); });
  13913. auto se = detail::scope_exit([&] {
  13914. svr.stop();
  13915. t.join();
  13916. ASSERT_FALSE(svr.is_running());
  13917. });
  13918. svr.wait_until_ready();
  13919. SSLClient cli(HOST, port);
  13920. cli.set_connection_timeout(30);
  13921. cli.enable_server_hostname_verification(false);
  13922. // cert.pem is not trusted, so the handshake fails
  13923. ASSERT_FALSE(cli.Get("/test"));
  13924. cli.enable_server_certificate_verification(false);
  13925. auto res = cli.Get("/test");
  13926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13927. EXPECT_EQ(0, res.ssl_error());
  13928. EXPECT_EQ(0UL, res.ssl_backend_error());
  13929. }
  13930. // PEM memory-based constructor tests (works with all TLS backends).
  13931. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13932. // terminator after it.
  13933. void PemMemoryClientCertPresent(
  13934. const std::string &client_cert_file,
  13935. const std::string &client_private_key_file,
  13936. const std::string &client_encrypted_private_key_pass = std::string(),
  13937. bool exact_size = false) {
  13938. // Read PEM files into memory
  13939. std::string server_cert_pem, server_key_pem;
  13940. std::string client_ca_pem;
  13941. std::string client_cert_pem, client_key_pem;
  13942. read_file(SERVER_CERT_FILE, server_cert_pem);
  13943. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13944. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13945. read_file(client_cert_file, client_cert_pem);
  13946. read_file(client_private_key_file, client_key_pem);
  13947. std::list<std::vector<char>> exact_copies;
  13948. auto data = [&](const std::string &pem) -> const char * {
  13949. if (!exact_size) { return pem.c_str(); }
  13950. exact_copies.emplace_back(pem.begin(), pem.end());
  13951. return exact_copies.back().data();
  13952. };
  13953. // Create server with PEM memory
  13954. SSLServer::PemMemory server_pem = {
  13955. data(server_cert_pem),
  13956. server_cert_pem.size(),
  13957. data(server_key_pem),
  13958. server_key_pem.size(),
  13959. data(client_ca_pem),
  13960. client_ca_pem.size(),
  13961. nullptr // no password for server key
  13962. };
  13963. SSLServer svr(server_pem);
  13964. ASSERT_TRUE(svr.is_valid());
  13965. svr.Get("/test", [&](const Request &req, Response &res) {
  13966. res.set_content("test", "text/plain");
  13967. auto cert = req.peer_cert();
  13968. ASSERT_TRUE(static_cast<bool>(cert));
  13969. EXPECT_EQ("Common Name", cert.subject_cn());
  13970. });
  13971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13972. auto se = detail::scope_exit([&] {
  13973. svr.stop();
  13974. t.join();
  13975. ASSERT_FALSE(svr.is_running());
  13976. });
  13977. svr.wait_until_ready();
  13978. // Create client with PEM memory
  13979. const char *password = client_encrypted_private_key_pass.empty()
  13980. ? nullptr
  13981. : client_encrypted_private_key_pass.c_str();
  13982. SSLClient::PemMemory client_pem = {
  13983. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13984. client_key_pem.size(), password};
  13985. SSLClient cli(HOST, PORT, client_pem);
  13986. cli.enable_server_certificate_verification(false);
  13987. cli.set_connection_timeout(30);
  13988. auto res = cli.Get("/test");
  13989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13990. ASSERT_EQ(StatusCode::OK_200, res->status);
  13991. }
  13992. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13993. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13994. }
  13995. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13996. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13997. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13998. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13999. }
  14000. // A server built from PEM memory with a client CA requires client certificates,
  14001. // also when the CA is a NUL-terminated string passed with a length of 0
  14002. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14003. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14004. read_file(SERVER_CERT_FILE, server_cert_pem);
  14005. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14006. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14007. SSLServer::PemMemory server_pem = {
  14008. server_cert_pem.c_str(),
  14009. server_cert_pem.size(),
  14010. server_key_pem.c_str(),
  14011. server_key_pem.size(),
  14012. client_ca_pem.c_str(),
  14013. client_ca_pem.size(),
  14014. nullptr // no password for server key
  14015. };
  14016. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14017. SCOPED_TRACE(client_ca_pem_len);
  14018. server_pem.client_ca_pem_len = client_ca_pem_len;
  14019. SSLServer svr(server_pem);
  14020. ASSERT_TRUE(svr.is_valid());
  14021. RejectsClientWithoutCert(svr);
  14022. }
  14023. // An empty CA fails to load instead of turning the check off
  14024. server_pem.client_ca_pem = "";
  14025. server_pem.client_ca_pem_len = 0;
  14026. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14027. }
  14028. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14029. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14030. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14031. true);
  14032. }
  14033. // A length shorter than the PEM cuts it short, so it no longer loads
  14034. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14035. std::string cert, key;
  14036. read_file(SERVER_CERT_FILE, cert);
  14037. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14038. for (auto cut_cert : {true, false}) {
  14039. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14040. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14041. SSLServer::PemMemory server_pem = {
  14042. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14043. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14044. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14045. key_len, nullptr};
  14046. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14047. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14048. key.c_str(), key_len, nullptr};
  14049. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14050. }
  14051. }
  14052. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14053. class NoListenSSLServer : public SSLServer {
  14054. public:
  14055. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14056. const char *client_ca_cert_file_path,
  14057. const char *client_ca_cert_dir_path = nullptr)
  14058. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14059. client_ca_cert_dir_path),
  14060. stop_(false) {}
  14061. std::atomic_bool stop_;
  14062. private:
  14063. bool process_and_close_socket(socket_t /*sock*/) override {
  14064. // Don't create SSL context
  14065. while (!stop_.load()) {
  14066. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14067. }
  14068. return true;
  14069. }
  14070. };
  14071. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14072. CLIENT_CA_CERT_FILE);
  14073. ASSERT_TRUE(svr.is_valid());
  14074. svr.Get("/test", [&](const Request &, Response &res) {
  14075. res.set_content("test", "text/plain");
  14076. });
  14077. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14078. auto se = detail::scope_exit([&] {
  14079. svr.stop_ = true;
  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(1);
  14088. auto res = cli.Get("/test");
  14089. ASSERT_TRUE(!res);
  14090. EXPECT_EQ(Error::SSLConnection, res.error());
  14091. // Timeout results in WantRead error code (maps to backend-specific value)
  14092. EXPECT_NE(0, res.ssl_error());
  14093. }
  14094. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14095. // Test SSLServer with client certificate verification using the standard
  14096. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14098. CLIENT_CA_CERT_DIR);
  14099. ASSERT_TRUE(svr.is_valid());
  14100. svr.Get("/test", [&](const Request &req, Response &res) {
  14101. res.set_content("test", "text/plain");
  14102. auto cert = req.peer_cert();
  14103. ASSERT_TRUE(static_cast<bool>(cert));
  14104. auto common_name = cert.subject_cn();
  14105. EXPECT_EQ("Common Name", common_name);
  14106. });
  14107. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14108. auto se = detail::scope_exit([&] {
  14109. svr.stop();
  14110. t.join();
  14111. ASSERT_FALSE(svr.is_running());
  14112. });
  14113. svr.wait_until_ready();
  14114. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14115. cli.enable_server_certificate_verification(false);
  14116. cli.set_connection_timeout(30);
  14117. auto res = cli.Get("/test");
  14118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14119. ASSERT_EQ(StatusCode::OK_200, res->status);
  14120. }
  14121. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14122. // Verifies that wildcard matching and exact matching work consistently
  14123. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14124. using namespace httplib::tls;
  14125. // We need a running server to test against
  14126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14127. ASSERT_TRUE(svr.is_valid());
  14128. svr.Get("/test", [](const Request &, Response &res) {
  14129. res.set_content("ok", "text/plain");
  14130. });
  14131. thread t([&]() { svr.listen(HOST, PORT); });
  14132. auto se = detail::scope_exit([&] {
  14133. svr.stop();
  14134. t.join();
  14135. });
  14136. svr.wait_until_ready();
  14137. bool verify_callback_called = false;
  14138. bool verify_result_wrong = false;
  14139. SSLClient cli(HOST, PORT);
  14140. cli.enable_server_certificate_verification(true);
  14141. cli.set_ca_cert_path(CA_CERT_FILE);
  14142. cli.set_connection_timeout(5);
  14143. // Note: Test certificate has CN="Common Name", not "localhost"
  14144. bool verify_result_cn = false;
  14145. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14146. verify_callback_called = true;
  14147. if (!ctx.cert) return false;
  14148. // Test 1: "Common Name" should match (our test server cert CN)
  14149. verify_result_cn = ctx.check_hostname("Common Name");
  14150. // Test 2: wrong hostname should not match
  14151. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14152. return true; // Accept for the purpose of this test
  14153. });
  14154. auto res = cli.Get("/test");
  14155. // The request may succeed or fail depending on cert configuration
  14156. // but the callback should have been called
  14157. ASSERT_TRUE(verify_callback_called)
  14158. << "Verify callback should have been called";
  14159. // CN="Common Name" should match our test certificate
  14160. //
  14161. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14162. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14163. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14164. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14165. // <openssl/base.h>, which is included transitively when
  14166. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14167. #if defined(OPENSSL_IS_BORINGSSL)
  14168. EXPECT_FALSE(verify_result_cn)
  14169. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14170. #else
  14171. EXPECT_TRUE(verify_result_cn)
  14172. << "verify_hostname should match 'Common Name' (certificate CN)";
  14173. #endif
  14174. // Wrong hostname should not match
  14175. EXPECT_FALSE(verify_result_wrong)
  14176. << "verify_hostname should not match 'wronghost.example.com'";
  14177. }
  14178. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14179. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14180. // X509_check_ip behavior and must hold for every backend.
  14181. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14182. using namespace httplib::tls;
  14183. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14184. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14185. ASSERT_TRUE(svr.is_valid());
  14186. svr.Get("/test", [](const Request &, Response &res) {
  14187. res.set_content("ok", "text/plain");
  14188. });
  14189. thread t([&]() { svr.listen(HOST, PORT); });
  14190. auto se = detail::scope_exit([&] {
  14191. svr.stop();
  14192. t.join();
  14193. });
  14194. svr.wait_until_ready();
  14195. bool verify_callback_called = false;
  14196. bool ip_matched_via_cn = true;
  14197. SSLClient cli(HOST, PORT);
  14198. cli.enable_server_certificate_verification(true);
  14199. cli.set_ca_cert_path(CA_CERT_FILE);
  14200. cli.set_connection_timeout(5);
  14201. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14202. verify_callback_called = true;
  14203. if (!ctx.cert) return false;
  14204. // The IP appears only in the CN, so it must NOT be accepted.
  14205. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14206. return true; // Accept for the purpose of this test
  14207. });
  14208. cli.Get("/test");
  14209. ASSERT_TRUE(verify_callback_called)
  14210. << "Verify callback should have been called";
  14211. EXPECT_FALSE(ip_matched_via_cn)
  14212. << "An IP host must not be authenticated via the certificate CN";
  14213. }
  14214. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14215. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14216. using namespace httplib::tls;
  14217. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14218. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14219. ASSERT_TRUE(svr.is_valid());
  14220. svr.Get("/test", [](const Request &, Response &res) {
  14221. res.set_content("ok", "text/plain");
  14222. });
  14223. thread t([&]() { svr.listen(HOST, PORT); });
  14224. auto se = detail::scope_exit([&] {
  14225. svr.stop();
  14226. t.join();
  14227. });
  14228. svr.wait_until_ready();
  14229. bool verify_callback_called = false;
  14230. bool san_matched = false;
  14231. bool wrong_ipv6_matched = true;
  14232. bool cn_ipv6_matched = true;
  14233. SSLClient cli(HOST, PORT);
  14234. cli.enable_server_certificate_verification(true);
  14235. cli.set_ca_cert_path(CA_CERT_FILE);
  14236. cli.set_connection_timeout(5);
  14237. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14238. verify_callback_called = true;
  14239. if (!ctx.cert) return false;
  14240. // Matches the IPv6 iPAddress SAN.
  14241. san_matched = ctx.check_hostname("2001:db8::1");
  14242. // A different IPv6 address must not match.
  14243. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14244. // "::1" lives only in the CN, so it must not be accepted.
  14245. cn_ipv6_matched = ctx.check_hostname("::1");
  14246. return true; // Accept for the purpose of this test
  14247. });
  14248. cli.Get("/test");
  14249. ASSERT_TRUE(verify_callback_called)
  14250. << "Verify callback should have been called";
  14251. EXPECT_TRUE(san_matched)
  14252. << "verify_hostname should match an IPv6 iPAddress SAN";
  14253. EXPECT_FALSE(wrong_ipv6_matched)
  14254. << "verify_hostname should not match a non-matching IPv6 address";
  14255. EXPECT_FALSE(cn_ipv6_matched)
  14256. << "An IPv6 host must not be authenticated via the certificate CN";
  14257. }
  14258. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14259. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14260. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14261. using namespace httplib::tls;
  14262. // SANs: DNS:a.zz, IP:42.46.122.122
  14263. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14264. ASSERT_TRUE(svr.is_valid());
  14265. svr.Get("/test", [](const Request &, Response &res) {
  14266. res.set_content("ok", "text/plain");
  14267. });
  14268. auto port = svr.bind_to_any_port(HOST);
  14269. thread t([&]() { svr.listen_after_bind(); });
  14270. auto se = detail::scope_exit([&] {
  14271. svr.stop();
  14272. t.join();
  14273. });
  14274. svr.wait_until_ready();
  14275. bool verify_callback_called = false;
  14276. bool dns_san_matched = false;
  14277. bool ip_san_matched = false;
  14278. bool ip_matched_via_dns_san = true;
  14279. bool dns_matched_via_ip_san = true;
  14280. bool cn_matched_next_to_dns_san = true;
  14281. SSLClient cli(HOST, port);
  14282. cli.enable_server_certificate_verification(true);
  14283. cli.set_ca_cert_path(CA_CERT_FILE);
  14284. cli.set_connection_timeout(5);
  14285. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14286. verify_callback_called = true;
  14287. if (!ctx.cert) return false;
  14288. dns_san_matched = ctx.check_hostname("a.zz");
  14289. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14290. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14291. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14292. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14293. return true; // Accept for the purpose of this test
  14294. });
  14295. cli.Get("/test");
  14296. ASSERT_TRUE(verify_callback_called)
  14297. << "Verify callback should have been called";
  14298. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14299. EXPECT_TRUE(ip_san_matched)
  14300. << "verify_hostname should match an iPAddress SAN";
  14301. EXPECT_FALSE(ip_matched_via_dns_san)
  14302. << "An IP host must not be authenticated via a dNSName SAN";
  14303. EXPECT_FALSE(dns_matched_via_ip_san)
  14304. << "A DNS host must not be authenticated via an iPAddress SAN";
  14305. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14306. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14307. }
  14308. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14309. // "www.*.example.test" names one host and not every host under example.test.
  14310. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14311. using namespace httplib::tls;
  14312. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14313. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14314. ASSERT_TRUE(svr.is_valid());
  14315. svr.Get("/test", [](const Request &, Response &res) {
  14316. res.set_content("ok", "text/plain");
  14317. });
  14318. auto port = svr.bind_to_any_port(HOST);
  14319. thread t([&]() { svr.listen_after_bind(); });
  14320. auto se = detail::scope_exit([&] {
  14321. svr.stop();
  14322. t.join();
  14323. });
  14324. svr.wait_until_ready();
  14325. bool verify_callback_called = false;
  14326. bool leftmost_wildcard_matched = false;
  14327. bool wildcard_spanned_labels = true;
  14328. bool inner_wildcard_matched = true;
  14329. SSLClient cli(HOST, port);
  14330. cli.enable_server_certificate_verification(true);
  14331. cli.set_ca_cert_path(CA_CERT_FILE);
  14332. cli.set_connection_timeout(5);
  14333. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14334. verify_callback_called = true;
  14335. if (!ctx.cert) return false;
  14336. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14337. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14338. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14339. return true; // Accept for the purpose of this test
  14340. });
  14341. cli.Get("/test");
  14342. ASSERT_TRUE(verify_callback_called)
  14343. << "Verify callback should have been called";
  14344. EXPECT_TRUE(leftmost_wildcard_matched)
  14345. << "A leftmost wildcard should match a single label";
  14346. EXPECT_FALSE(wildcard_spanned_labels)
  14347. << "A wildcard label must not match more than one label";
  14348. EXPECT_FALSE(inner_wildcard_matched)
  14349. << "A wildcard outside the leftmost label must not be honoured";
  14350. }
  14351. // sans() must report each SAN entry under its own type.
  14352. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14353. using namespace httplib::tls;
  14354. // SANs: DNS:a.zz, IP:42.46.122.122
  14355. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14356. ASSERT_TRUE(svr.is_valid());
  14357. svr.Get("/test", [](const Request &, Response &res) {
  14358. res.set_content("ok", "text/plain");
  14359. });
  14360. auto port = svr.bind_to_any_port(HOST);
  14361. thread t([&]() { svr.listen_after_bind(); });
  14362. auto se = detail::scope_exit([&] {
  14363. svr.stop();
  14364. t.join();
  14365. });
  14366. svr.wait_until_ready();
  14367. bool verify_callback_called = false;
  14368. std::vector<SanEntry> sans;
  14369. SSLClient cli(HOST, port);
  14370. cli.enable_server_certificate_verification(true);
  14371. cli.set_ca_cert_path(CA_CERT_FILE);
  14372. cli.set_connection_timeout(5);
  14373. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14374. verify_callback_called = true;
  14375. if (!ctx.cert) return false;
  14376. sans = ctx.sans();
  14377. return true; // Accept for the purpose of this test
  14378. });
  14379. cli.Get("/test");
  14380. ASSERT_TRUE(verify_callback_called)
  14381. << "Verify callback should have been called";
  14382. auto has_san = [&](SanType type, const std::string &value) {
  14383. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14384. return san.type == type && san.value == value;
  14385. });
  14386. };
  14387. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14388. << "sans() should report the dNSName SAN";
  14389. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14390. << "sans() should report the iPAddress SAN";
  14391. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14392. << "sans() must not report the dNSName SAN as an address";
  14393. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14394. << "sans() must not report the iPAddress SAN as a DNS name";
  14395. }
  14396. #endif
  14397. // mbedTLS-specific callback constructor test
  14398. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14399. #ifdef CPPHTTPLIB_SSL_ENABLED
  14400. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14402. ASSERT_TRUE(svr.is_valid());
  14403. // Set up a handler to verify client certificate is present
  14404. bool client_cert_verified = false;
  14405. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14406. // Verify that client certificate was provided
  14407. client_cert_verified = true;
  14408. res.set_content("success", "text/plain");
  14409. });
  14410. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14411. auto se = detail::scope_exit([&] {
  14412. svr.stop();
  14413. t.join();
  14414. ASSERT_FALSE(svr.is_running());
  14415. });
  14416. svr.wait_until_ready();
  14417. // Client with certificate
  14418. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14419. cli.enable_server_certificate_verification(false);
  14420. cli.set_connection_timeout(30);
  14421. auto res = cli.Get("/test");
  14422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14423. ASSERT_EQ(StatusCode::OK_200, res->status);
  14424. ASSERT_TRUE(client_cert_verified);
  14425. EXPECT_EQ("success", res->body);
  14426. }
  14427. #endif
  14428. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14429. // backends
  14430. #ifdef CPPHTTPLIB_SSL_ENABLED
  14431. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14432. using namespace httplib::tls;
  14433. // Test that when client CA cert file is provided,
  14434. // the server properly requests and validates client certificates
  14435. // Create a server with client authentication
  14436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14437. ASSERT_TRUE(svr.is_valid());
  14438. bool handler_called = false;
  14439. svr.Get("/test", [&](const Request &req, Response &res) {
  14440. handler_called = true;
  14441. // Verify that a client certificate was provided
  14442. auto cert = req.peer_cert();
  14443. ASSERT_TRUE(static_cast<bool>(cert));
  14444. // Get the issuer name
  14445. std::string issuer_str = cert.issuer_name();
  14446. ASSERT_FALSE(issuer_str.empty());
  14447. // The client certificate should be issued by our test CA
  14448. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14449. res.set_content("authenticated", "text/plain");
  14450. });
  14451. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14452. auto se = detail::scope_exit([&] {
  14453. svr.stop();
  14454. t.join();
  14455. ASSERT_FALSE(svr.is_running());
  14456. });
  14457. svr.wait_until_ready();
  14458. // Connect with a client certificate issued by the CA
  14459. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14460. cli.enable_server_certificate_verification(false);
  14461. cli.set_connection_timeout(30);
  14462. auto res = cli.Get("/test");
  14463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14464. ASSERT_EQ(StatusCode::OK_200, res->status);
  14465. ASSERT_TRUE(handler_called);
  14466. EXPECT_EQ("authenticated", res->body);
  14467. }
  14468. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14469. using namespace httplib::tls;
  14470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14471. ASSERT_TRUE(svr.is_valid());
  14472. svr.Get("/test", [](const Request &, Response &res) {
  14473. res.set_content("ok", "text/plain");
  14474. });
  14475. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14476. auto se = detail::scope_exit([&] {
  14477. svr.stop();
  14478. t.join();
  14479. });
  14480. svr.wait_until_ready();
  14481. SSLClient cli(HOST, PORT);
  14482. cli.enable_server_certificate_verification(false);
  14483. cli.set_connection_timeout(30);
  14484. bool cert_checked = false;
  14485. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14486. if (ctx.cert) {
  14487. auto sans = ctx.sans();
  14488. // Test certificate may or may not have SANs - just verify the API
  14489. // works If SANs exist, verify the types are valid
  14490. for (const auto &san : sans) {
  14491. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14492. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14493. san.type == SanType::OTHER);
  14494. EXPECT_FALSE(san.value.empty());
  14495. }
  14496. cert_checked = true;
  14497. }
  14498. return true;
  14499. });
  14500. auto res = cli.Get("/test");
  14501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14502. EXPECT_TRUE(cert_checked);
  14503. }
  14504. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14505. using namespace httplib::tls;
  14506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14507. ASSERT_TRUE(svr.is_valid());
  14508. svr.Get("/test", [](const Request &, Response &res) {
  14509. res.set_content("ok", "text/plain");
  14510. });
  14511. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14512. auto se = detail::scope_exit([&] {
  14513. svr.stop();
  14514. t.join();
  14515. });
  14516. svr.wait_until_ready();
  14517. SSLClient cli(HOST, PORT);
  14518. cli.enable_server_certificate_verification(false);
  14519. cli.set_connection_timeout(30);
  14520. bool validity_checked = false;
  14521. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14522. if (ctx.cert) {
  14523. time_t not_before = 0, not_after = 0;
  14524. bool result = ctx.validity(not_before, not_after);
  14525. EXPECT_TRUE(result);
  14526. // Verify that not_before < now < not_after for a valid cert
  14527. time_t now = time(nullptr);
  14528. EXPECT_LT(not_before, now);
  14529. EXPECT_GT(not_after, now);
  14530. validity_checked = true;
  14531. }
  14532. return true;
  14533. });
  14534. auto res = cli.Get("/test");
  14535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14536. EXPECT_TRUE(validity_checked);
  14537. }
  14538. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14539. using namespace httplib::tls;
  14540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14541. ASSERT_TRUE(svr.is_valid());
  14542. svr.Get("/test", [](const Request &, Response &res) {
  14543. res.set_content("ok", "text/plain");
  14544. });
  14545. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14546. auto se = detail::scope_exit([&] {
  14547. svr.stop();
  14548. t.join();
  14549. });
  14550. svr.wait_until_ready();
  14551. SSLClient cli(HOST, PORT);
  14552. cli.enable_server_certificate_verification(false);
  14553. cli.set_connection_timeout(30);
  14554. bool serial_checked = false;
  14555. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14556. if (ctx.cert) {
  14557. std::string serial = ctx.serial();
  14558. EXPECT_FALSE(serial.empty());
  14559. // Serial should be a hex string
  14560. for (char c : serial) {
  14561. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14562. (c >= 'a' && c <= 'f'));
  14563. }
  14564. serial_checked = true;
  14565. }
  14566. return true;
  14567. });
  14568. auto res = cli.Get("/test");
  14569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14570. EXPECT_TRUE(serial_checked);
  14571. }
  14572. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14573. // Test 1: Valid CA file - no error should be recorded
  14574. {
  14575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14576. CLIENT_CA_CERT_FILE);
  14577. ASSERT_TRUE(svr.is_valid());
  14578. // With valid setup, last_ssl_error should be 0
  14579. EXPECT_EQ(0, svr.ssl_last_error());
  14580. }
  14581. // Test 2: Invalid CA file content
  14582. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14583. {
  14584. // Create a temporary file with completely invalid content
  14585. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14586. {
  14587. std::ofstream ofs(temp_invalid_ca);
  14588. ofs << "This is not a certificate file at all\n";
  14589. ofs << "Just plain text content\n";
  14590. }
  14591. // Create server with invalid CA file
  14592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14593. // Clean up temporary file
  14594. std::remove(temp_invalid_ca);
  14595. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14596. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14597. // Note: SSL_CTX_load_verify_locations typically fails first,
  14598. // but our error handling code path is still exercised
  14599. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14600. }
  14601. }
  14602. TEST(VerifyCallbackTest, VerifyContextFields) {
  14603. using namespace httplib::tls;
  14604. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14605. ASSERT_TRUE(svr.is_valid());
  14606. svr.Get("/test", [](const Request &, Response &res) {
  14607. res.set_content("ok", "text/plain");
  14608. });
  14609. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14610. auto se = detail::scope_exit([&] {
  14611. svr.stop();
  14612. t.join();
  14613. });
  14614. svr.wait_until_ready();
  14615. SSLClient cli(HOST, PORT);
  14616. cli.enable_server_certificate_verification(false);
  14617. cli.set_connection_timeout(30);
  14618. int callback_count = 0;
  14619. bool saw_leaf_cert = false;
  14620. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14621. if (ctx.cert) {
  14622. callback_count++;
  14623. // We should see at least one certificate (the leaf)
  14624. std::string cn = ctx.subject_cn();
  14625. if (!cn.empty()) { saw_leaf_cert = true; }
  14626. // Verify context fields are populated
  14627. EXPECT_NE(ctx.session, nullptr);
  14628. EXPECT_GE(ctx.depth, 0);
  14629. }
  14630. return true;
  14631. });
  14632. auto res = cli.Get("/test");
  14633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14634. EXPECT_GT(callback_count, 0);
  14635. EXPECT_TRUE(saw_leaf_cert);
  14636. }
  14637. // A verifier that accepts runs alongside the built-in verification, and is the
  14638. // only check once that is turned off.
  14639. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14640. using namespace httplib::tls;
  14641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14642. ASSERT_TRUE(svr.is_valid());
  14643. svr.Get("/test", [](const Request &, Response &res) {
  14644. res.set_content("ok", "text/plain");
  14645. });
  14646. auto port = svr.bind_to_any_port(HOST);
  14647. thread t([&]() { svr.listen_after_bind(); });
  14648. auto se = detail::scope_exit([&] {
  14649. svr.stop();
  14650. t.join();
  14651. });
  14652. svr.wait_until_ready();
  14653. SSLClient cli(HOST, port);
  14654. cli.enable_server_hostname_verification(false);
  14655. auto calls = 0;
  14656. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14657. calls++;
  14658. return true;
  14659. });
  14660. // cert.pem is not trusted
  14661. auto res = cli.Get("/test");
  14662. ASSERT_FALSE(res);
  14663. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14664. EXPECT_GT(calls, 0);
  14665. cli.enable_server_certificate_verification(false);
  14666. res = cli.Get("/test");
  14667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14668. EXPECT_EQ("ok", res->body);
  14669. }
  14670. // A verifier belongs to the client that set it, not to the thread that set it.
  14671. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14672. using namespace httplib::tls;
  14673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14674. ASSERT_TRUE(svr.is_valid());
  14675. svr.Get("/test", [](const Request &, Response &res) {
  14676. res.set_content("ok", "text/plain");
  14677. });
  14678. auto port = svr.bind_to_any_port(HOST);
  14679. thread t([&]() { svr.listen_after_bind(); });
  14680. auto se = detail::scope_exit([&] {
  14681. svr.stop();
  14682. t.join();
  14683. });
  14684. svr.wait_until_ready();
  14685. auto rejecting_calls = 0;
  14686. SSLClient rejecting(HOST, port);
  14687. rejecting.enable_server_certificate_verification(false);
  14688. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14689. rejecting_calls++;
  14690. return false;
  14691. });
  14692. auto accepting_calls = 0;
  14693. SSLClient accepting(HOST, port);
  14694. accepting.enable_server_certificate_verification(false);
  14695. // Set on another thread than the requests below.
  14696. thread([&]() {
  14697. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14698. accepting_calls++;
  14699. return true;
  14700. });
  14701. }).join();
  14702. // Requested on another thread than the verifier was set on.
  14703. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14704. EXPECT_GT(rejecting_calls, 0);
  14705. auto res = accepting.Get("/test");
  14706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14707. EXPECT_GT(accepting_calls, 0);
  14708. }
  14709. // A verifier replaced while a handshake runs it lives until it returns.
  14710. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14711. using namespace httplib::tls;
  14712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14713. ASSERT_TRUE(svr.is_valid());
  14714. svr.Get("/test", [](const Request &, Response &res) {
  14715. res.set_content("ok", "text/plain");
  14716. });
  14717. auto port = svr.bind_to_any_port(HOST);
  14718. thread t([&]() { svr.listen_after_bind(); });
  14719. auto se = detail::scope_exit([&] {
  14720. svr.stop();
  14721. t.join();
  14722. });
  14723. svr.wait_until_ready();
  14724. SSLClient cli(HOST, port);
  14725. cli.enable_server_certificate_verification(false);
  14726. std::promise<void> entered;
  14727. std::promise<void> replaced;
  14728. auto replaced_future = replaced.get_future();
  14729. auto first_call = true;
  14730. // Long enough to live on the heap
  14731. std::string expected(64, 'v');
  14732. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14733. if (first_call) {
  14734. first_call = false;
  14735. entered.set_value();
  14736. replaced_future.wait();
  14737. }
  14738. return expected == std::string(64, 'v');
  14739. });
  14740. thread request([&]() {
  14741. auto res = cli.Get("/test");
  14742. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14743. });
  14744. entered.get_future().wait();
  14745. cli.set_server_certificate_verifier(
  14746. [](const VerifyContext &) { return true; });
  14747. replaced.set_value();
  14748. request.join();
  14749. }
  14750. // VerifyContext::session is the same handle the other tls:: functions take.
  14751. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14752. using namespace httplib::tls;
  14753. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14754. ASSERT_TRUE(svr.is_valid());
  14755. svr.Get("/test", [](const Request &, Response &res) {
  14756. res.set_content("ok", "text/plain");
  14757. });
  14758. auto port = svr.bind_to_any_port(HOST);
  14759. thread t([&]() { svr.listen_after_bind(); });
  14760. auto se = detail::scope_exit([&] {
  14761. svr.stop();
  14762. t.join();
  14763. });
  14764. svr.wait_until_ready();
  14765. SSLClient cli(HOST, port);
  14766. cli.enable_server_certificate_verification(false);
  14767. session_t verifier_session = nullptr;
  14768. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14769. verifier_session = ctx.session;
  14770. return true;
  14771. });
  14772. session_t session_verifier_session = nullptr;
  14773. cli.set_session_verifier([&](session_t session) {
  14774. session_verifier_session = session;
  14775. return SSLVerifierResponse::NoDecisionMade;
  14776. });
  14777. auto res = cli.Get("/test");
  14778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14779. EXPECT_NE(nullptr, verifier_session);
  14780. EXPECT_EQ(session_verifier_session, verifier_session);
  14781. }
  14782. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14783. using httplib::tls::TlsError;
  14784. // Test that verify_error_to_string returns empty for success
  14785. std::string success_str = TlsError::verify_error_to_string(0);
  14786. EXPECT_TRUE(success_str.empty());
  14787. // Test that verify_error_to_string returns non-empty for error codes
  14788. // Using a common error code (certificate expired)
  14789. std::string error_str =
  14790. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14791. EXPECT_FALSE(error_str.empty());
  14792. }
  14793. TEST(SessionVerifierTest, CertificateAccepted) {
  14794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14795. ASSERT_TRUE(svr.is_valid());
  14796. svr.Get("/test", [](const Request &, Response &res) {
  14797. res.set_content("ok", "text/plain");
  14798. });
  14799. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14800. auto se = detail::scope_exit([&] {
  14801. svr.stop();
  14802. t.join();
  14803. });
  14804. svr.wait_until_ready();
  14805. SSLClient cli(HOST, PORT);
  14806. cli.enable_server_certificate_verification(false);
  14807. cli.set_connection_timeout(30);
  14808. bool callback_called = false;
  14809. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14810. EXPECT_NE(session, nullptr);
  14811. callback_called = true;
  14812. return SSLVerifierResponse::CertificateAccepted;
  14813. });
  14814. auto res = cli.Get("/test");
  14815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14816. EXPECT_EQ(200, res->status);
  14817. EXPECT_TRUE(callback_called);
  14818. }
  14819. TEST(SessionVerifierTest, CertificateRejected) {
  14820. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14821. ASSERT_TRUE(svr.is_valid());
  14822. svr.Get("/test", [](const Request &, Response &res) {
  14823. res.set_content("ok", "text/plain");
  14824. });
  14825. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14826. auto se = detail::scope_exit([&] {
  14827. svr.stop();
  14828. t.join();
  14829. });
  14830. svr.wait_until_ready();
  14831. SSLClient cli(HOST, PORT);
  14832. cli.enable_server_certificate_verification(false);
  14833. cli.set_connection_timeout(30);
  14834. bool callback_called = false;
  14835. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14836. EXPECT_NE(session, nullptr);
  14837. callback_called = true;
  14838. return SSLVerifierResponse::CertificateRejected;
  14839. });
  14840. auto res = cli.Get("/test");
  14841. EXPECT_FALSE(res);
  14842. EXPECT_TRUE(callback_called);
  14843. }
  14844. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14846. ASSERT_TRUE(svr.is_valid());
  14847. svr.Get("/test", [](const Request &, Response &res) {
  14848. res.set_content("ok", "text/plain");
  14849. });
  14850. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14851. auto se = detail::scope_exit([&] {
  14852. svr.stop();
  14853. t.join();
  14854. });
  14855. svr.wait_until_ready();
  14856. // NoDecisionMade with verification disabled should succeed (no default check)
  14857. SSLClient cli(HOST, PORT);
  14858. cli.enable_server_certificate_verification(false);
  14859. cli.set_connection_timeout(30);
  14860. bool callback_called = false;
  14861. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14862. EXPECT_NE(session, nullptr);
  14863. callback_called = true;
  14864. return SSLVerifierResponse::NoDecisionMade;
  14865. });
  14866. auto res = cli.Get("/test");
  14867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14868. EXPECT_EQ(200, res->status);
  14869. EXPECT_TRUE(callback_called);
  14870. }
  14871. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14873. ASSERT_TRUE(svr.is_valid());
  14874. svr.Get("/test", [](const Request &, Response &res) {
  14875. res.set_content("ok", "text/plain");
  14876. });
  14877. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14878. auto se = detail::scope_exit([&] {
  14879. svr.stop();
  14880. t.join();
  14881. });
  14882. svr.wait_until_ready();
  14883. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14884. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14885. // so we only check that the request fails, not whether the callback was
  14886. // called.
  14887. SSLClient cli(HOST, PORT);
  14888. cli.enable_server_certificate_verification(true);
  14889. cli.set_connection_timeout(30);
  14890. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14891. EXPECT_NE(session, nullptr);
  14892. return SSLVerifierResponse::NoDecisionMade;
  14893. });
  14894. auto res = cli.Get("/test");
  14895. EXPECT_FALSE(res);
  14896. }
  14897. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14898. // Test SSL server using PemMemory constructor with client CA certificates
  14899. // Read PEM files
  14900. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14901. read_file(SERVER_CERT_FILE, server_cert_pem);
  14902. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14903. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14904. // Create SSLServer with PemMemory constructor including client CA
  14905. SSLServer::PemMemory server_pem = {
  14906. server_cert_pem.c_str(),
  14907. server_cert_pem.size(),
  14908. server_key_pem.c_str(),
  14909. server_key_pem.size(),
  14910. client_ca_pem.c_str(),
  14911. client_ca_pem.size(),
  14912. nullptr // no password for server key
  14913. };
  14914. SSLServer svr(server_pem);
  14915. ASSERT_TRUE(svr.is_valid());
  14916. // No SSL error should be recorded for valid setup
  14917. EXPECT_EQ(0, svr.ssl_last_error());
  14918. // Set up server endpoints
  14919. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14920. res.set_content("ok", "text/plain");
  14921. });
  14922. // Start server in a thread
  14923. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14924. svr.wait_until_ready();
  14925. // Connect with client certificate (using constructor with paths)
  14926. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14927. cli.enable_server_certificate_verification(false);
  14928. auto res = cli.Get("/test-pem-ca");
  14929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14930. EXPECT_EQ(200, res->status);
  14931. EXPECT_EQ("ok", res->body);
  14932. svr.stop();
  14933. server_thread.join();
  14934. }
  14935. #endif
  14936. #ifdef _WIN32
  14937. TEST(CleanupTest, WSACleanup) {
  14938. int ret = WSACleanup();
  14939. ASSERT_EQ(0, ret);
  14940. }
  14941. #endif
  14942. #ifndef CPPHTTPLIB_SSL_ENABLED
  14943. TEST(NoSSLSupport, SimpleInterface) {
  14944. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14945. }
  14946. #endif
  14947. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14948. TEST(InvalidScheme, SimpleInterface) {
  14949. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14950. }
  14951. #endif
  14952. TEST(NoScheme, SimpleInterface) {
  14953. Client cli("yahoo.com:80");
  14954. ASSERT_TRUE(cli.is_valid());
  14955. }
  14956. TEST(SendAPI, SimpleInterface_Online) {
  14957. Client cli("http://yahoo.com");
  14958. Request req;
  14959. req.method = "GET";
  14960. req.path = "/";
  14961. auto res = cli.send(req);
  14962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14963. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14964. }
  14965. TEST(SendAPI, WithParamsInRequest) {
  14966. Server svr;
  14967. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14968. EXPECT_TRUE(req.has_param("test"));
  14969. EXPECT_EQ("test_value", req.get_param_value("test"));
  14970. });
  14971. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14972. auto se = detail::scope_exit([&] {
  14973. svr.stop();
  14974. t.join();
  14975. ASSERT_FALSE(svr.is_running());
  14976. });
  14977. svr.wait_until_ready();
  14978. Client cli(HOST, PORT);
  14979. {
  14980. Request req;
  14981. req.method = "GET";
  14982. req.path = "/";
  14983. req.params.emplace("test", "test_value");
  14984. auto res = cli.send(req);
  14985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14986. }
  14987. {
  14988. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14990. }
  14991. }
  14992. TEST(ClientImplMethods, GetSocketTest) {
  14993. httplib::Server svr;
  14994. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14995. res.status = StatusCode::OK_200;
  14996. });
  14997. auto port = svr.bind_to_any_port("127.0.0.1");
  14998. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14999. auto se = detail::scope_exit([&] {
  15000. svr.stop();
  15001. thread.join();
  15002. ASSERT_FALSE(svr.is_running());
  15003. });
  15004. svr.wait_until_ready();
  15005. {
  15006. httplib::Client cli("127.0.0.1", port);
  15007. cli.set_keep_alive(true);
  15008. // Use the behavior of cpp-httplib of opening the connection
  15009. // only when the first request happens. If that changes,
  15010. // this test would be obsolete.
  15011. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15012. // This also implicitly tests the server. But other tests would fail much
  15013. // earlier than this one to be considered.
  15014. auto res = cli.Get("/");
  15015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15016. EXPECT_EQ(StatusCode::OK_200, res->status);
  15017. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15018. }
  15019. }
  15020. #ifdef CPPHTTPLIB_SSL_ENABLED
  15021. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15022. Client cli("http://yahoo.com");
  15023. auto res = cli.Get("/");
  15024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15025. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15026. cli.set_follow_location(true);
  15027. res = cli.Get("/");
  15028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15029. EXPECT_EQ(StatusCode::OK_200, res->status);
  15030. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15031. }
  15032. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15033. Client cli("https://yahoo.com");
  15034. auto res = cli.Get("/");
  15035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15036. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15037. cli.set_follow_location(true);
  15038. res = cli.Get("/");
  15039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15040. EXPECT_EQ(StatusCode::OK_200, res->status);
  15041. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15042. }
  15043. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15044. Client cli("https://yahoo.com");
  15045. auto res = cli.Get("/");
  15046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15047. ASSERT_FALSE(!res);
  15048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15049. ASSERT_FALSE(res == nullptr);
  15050. ASSERT_TRUE(res != nullptr);
  15051. EXPECT_EQ(Error::Success, res.error());
  15052. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15053. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15054. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15055. cli.set_follow_location(true);
  15056. res = cli.Get("/");
  15057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15058. EXPECT_EQ(Error::Success, res.error());
  15059. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15060. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15061. EXPECT_EQ(StatusCode::OK_200, res->status);
  15062. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15063. }
  15064. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15065. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15066. Client cli("https://cdnjs.cloudflare.com");
  15067. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15068. Headers{{"Accept-Encoding", "br"}});
  15069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15070. EXPECT_EQ(StatusCode::OK_200, res->status);
  15071. EXPECT_EQ(287630U, res->body.size());
  15072. EXPECT_EQ("application/javascript; charset=utf-8",
  15073. res->get_header_value("Content-Type"));
  15074. }
  15075. #endif
  15076. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15077. #undef REDIR_HOST // Silence compiler warning
  15078. #define REDIR_HOST "https://httpbingo.org"
  15079. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15080. Client cli(REDIR_HOST);
  15081. cli.set_follow_location(true);
  15082. auto res =
  15083. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15085. EXPECT_EQ(StatusCode::OK_200, res->status);
  15086. }
  15087. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15088. Client cli(REDIR_HOST);
  15089. cli.set_follow_location(true);
  15090. Params params;
  15091. params.emplace("url", "http://example.com");
  15092. params.emplace("status_code", "302");
  15093. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15095. EXPECT_EQ(StatusCode::OK_200, res->status);
  15096. }
  15097. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15098. Client cli(REDIR_HOST);
  15099. cli.set_follow_location(true);
  15100. Params params;
  15101. params.emplace("url", "http://example.com");
  15102. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15104. EXPECT_EQ(StatusCode::OK_200, res->status);
  15105. }
  15106. TEST(HttpToHttpsRedirectTest, CertFile) {
  15107. auto ssl_port = PORT + 1;
  15108. Server svr;
  15109. ASSERT_TRUE(svr.is_valid());
  15110. svr.Get("/index", [&](const Request &, Response &res) {
  15111. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15112. "/index");
  15113. svr.stop();
  15114. });
  15115. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15116. ASSERT_TRUE(ssl_svr.is_valid());
  15117. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15118. res.set_content("test", "text/plain");
  15119. ssl_svr.stop();
  15120. });
  15121. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15122. thread t2 =
  15123. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15124. auto se = detail::scope_exit([&] {
  15125. t2.join();
  15126. t.join();
  15127. ASSERT_FALSE(svr.is_running());
  15128. });
  15129. svr.wait_until_ready();
  15130. ssl_svr.wait_until_ready();
  15131. Client cli("127.0.0.1", PORT);
  15132. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15133. cli.enable_server_certificate_verification(true);
  15134. cli.set_follow_location(true);
  15135. cli.set_connection_timeout(30);
  15136. auto res = cli.Get("/index");
  15137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15138. ASSERT_EQ(StatusCode::OK_200, res->status);
  15139. }
  15140. TEST(SSLClientRedirectTest, CertFile) {
  15141. auto ssl_port = PORT + 1;
  15142. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15143. ASSERT_TRUE(ssl_svr1.is_valid());
  15144. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15145. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15146. "/index");
  15147. ssl_svr1.stop();
  15148. });
  15149. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15150. ASSERT_TRUE(ssl_svr2.is_valid());
  15151. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15152. res.set_content("test", "text/plain");
  15153. ssl_svr2.stop();
  15154. });
  15155. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15156. thread t2 =
  15157. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15158. auto se = detail::scope_exit([&] {
  15159. t2.join();
  15160. t.join();
  15161. ASSERT_FALSE(ssl_svr1.is_running());
  15162. });
  15163. ssl_svr1.wait_until_ready();
  15164. ssl_svr2.wait_until_ready();
  15165. SSLClient cli("127.0.0.1", PORT);
  15166. std::string cert;
  15167. read_file(SERVER_CERT2_FILE, cert);
  15168. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15169. cli.enable_server_certificate_verification(true);
  15170. cli.set_follow_location(true);
  15171. cli.set_connection_timeout(30);
  15172. auto res = cli.Get("/index");
  15173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15174. ASSERT_EQ(StatusCode::OK_200, res->status);
  15175. }
  15176. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15177. // another port, so the client follows it with a new client.
  15178. static Result GetThroughTlsRedirectToDifferentPort(
  15179. const std::function<void(SSLClient &)> &setup,
  15180. const char *target_cert = SERVER_CERT2_FILE,
  15181. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15182. auto ssl_port = PORT + 1;
  15183. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15184. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15185. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15186. "/index");
  15187. });
  15188. SSLServer ssl_svr2(target_cert, target_key);
  15189. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15190. res.set_content("test", "text/plain");
  15191. });
  15192. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15193. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15194. auto se = detail::scope_exit([&] {
  15195. ssl_svr2.stop();
  15196. ssl_svr1.stop();
  15197. t2.join();
  15198. t.join();
  15199. });
  15200. ssl_svr1.wait_until_ready();
  15201. ssl_svr2.wait_until_ready();
  15202. SSLClient cli("127.0.0.1", PORT);
  15203. cli.set_follow_location(true);
  15204. cli.set_connection_timeout(30);
  15205. setup(cli);
  15206. return cli.Get("/index");
  15207. }
  15208. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15209. auto calls = 0;
  15210. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15211. cli.enable_server_certificate_verification(false);
  15212. // Accept the first server only.
  15213. cli.set_session_verifier([&](tls::session_t) {
  15214. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15215. : SSLVerifierResponse::CertificateRejected;
  15216. });
  15217. });
  15218. ASSERT_FALSE(res);
  15219. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15220. EXPECT_EQ(2, calls);
  15221. }
  15222. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15223. std::string pinned;
  15224. auto res = GetThroughTlsRedirectToDifferentPort(
  15225. [&](SSLClient &cli) {
  15226. cli.enable_server_certificate_verification(false);
  15227. // Pin the first certificate seen.
  15228. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15229. if (pinned.empty()) { pinned = ctx.serial(); }
  15230. return ctx.serial() == pinned;
  15231. });
  15232. },
  15233. // A certificate other than the first server's.
  15234. SERVER_CERT_FILE);
  15235. EXPECT_FALSE(res);
  15236. EXPECT_FALSE(pinned.empty());
  15237. }
  15238. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15239. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15240. std::string cert;
  15241. read_file(SERVER_CERT2_FILE, cert);
  15242. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15243. });
  15244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15245. EXPECT_EQ(StatusCode::OK_200, res->status);
  15246. }
  15247. // The target's certificate is signed by the root CA, which the first server's
  15248. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15249. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15250. auto res = GetThroughTlsRedirectToDifferentPort(
  15251. [](SSLClient &cli) {
  15252. std::string root_ca, cert;
  15253. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15254. read_file(SERVER_CERT2_FILE, cert);
  15255. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15256. cli.load_ca_cert_store(cert.data(), cert.size());
  15257. cli.enable_server_hostname_verification(false);
  15258. },
  15259. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15261. EXPECT_EQ(StatusCode::OK_200, res->status);
  15262. }
  15263. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15264. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15265. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15266. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15267. auto res = GetThroughTlsRedirectToDifferentPort(
  15268. [](SSLClient &cli) {
  15269. std::string root_ca, cert;
  15270. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15271. read_file(SERVER_CERT2_FILE, cert);
  15272. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15273. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15274. cli.enable_server_hostname_verification(false);
  15275. },
  15276. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15277. ASSERT_FALSE(res);
  15278. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15279. }
  15280. #endif
  15281. #endif
  15282. #ifdef CPPHTTPLIB_SSL_ENABLED
  15283. // Test that set_ca_cert_store() skips system certs (consistent with
  15284. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15285. // should be trusted - system certs should NOT be loaded.
  15286. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15287. // Load a specific cert that is NOT a system CA cert
  15288. std::string cert;
  15289. read_file(SERVER_CERT2_FILE, cert);
  15290. SSLClient cli("google.com");
  15291. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15292. cli.enable_server_certificate_verification(true);
  15293. // This should FAIL because:
  15294. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15295. // 2. System certs should NOT be loaded when custom store is set
  15296. // If system certs WERE loaded, this would succeed
  15297. auto res = cli.Get("/");
  15298. ASSERT_FALSE(res);
  15299. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15300. }
  15301. // Same as above, but through the native store handle path. Regression test:
  15302. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15303. // merged system certs into the user-provided store.
  15304. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15305. std::string cert;
  15306. read_file(SERVER_CERT2_FILE, cert);
  15307. SSLClient cli("google.com");
  15308. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15309. cli.enable_server_certificate_verification(true);
  15310. auto res = cli.Get("/");
  15311. ASSERT_FALSE(res);
  15312. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15313. }
  15314. // A custom store set via the native handle must still verify a server whose
  15315. // cert it does contain.
  15316. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15317. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15318. ASSERT_TRUE(svr.is_valid());
  15319. svr.Get("/test", [&](const Request &, Response &res) {
  15320. res.set_content("test", "text/plain");
  15321. });
  15322. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15323. auto se = detail::scope_exit([&] {
  15324. svr.stop();
  15325. t.join();
  15326. ASSERT_FALSE(svr.is_running());
  15327. });
  15328. svr.wait_until_ready();
  15329. SSLClient cli("127.0.0.1", PORT);
  15330. std::string cert;
  15331. read_file(SERVER_CERT2_FILE, cert);
  15332. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15333. cli.enable_server_certificate_verification(true);
  15334. cli.set_connection_timeout(30);
  15335. auto res = cli.Get("/test");
  15336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15337. ASSERT_EQ(StatusCode::OK_200, res->status);
  15338. }
  15339. // CA certs loaded through the universal Client must be transferred to the
  15340. // client created internally for following an HTTPS redirect. Regression test:
  15341. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15342. // the CA data for redirect transfer.
  15343. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15344. auto ssl_port = PORT + 1;
  15345. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15346. ASSERT_TRUE(ssl_svr1.is_valid());
  15347. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15348. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15349. "/index");
  15350. });
  15351. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15352. ASSERT_TRUE(ssl_svr2.is_valid());
  15353. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15354. res.set_content("test", "text/plain");
  15355. });
  15356. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15357. thread t2 =
  15358. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15359. auto se = detail::scope_exit([&] {
  15360. ssl_svr2.stop();
  15361. ssl_svr1.stop();
  15362. t2.join();
  15363. t.join();
  15364. ASSERT_FALSE(ssl_svr1.is_running());
  15365. });
  15366. ssl_svr1.wait_until_ready();
  15367. ssl_svr2.wait_until_ready();
  15368. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15369. std::string cert;
  15370. read_file(SERVER_CERT2_FILE, cert);
  15371. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15372. cli.enable_server_certificate_verification(true);
  15373. cli.set_follow_location(true);
  15374. cli.set_connection_timeout(30);
  15375. auto res = cli.Get("/index");
  15376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15377. ASSERT_EQ(StatusCode::OK_200, res->status);
  15378. }
  15379. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15380. // so a host signed by a system CA verifies even though a custom CA is set
  15381. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15382. std::string cert;
  15383. read_file(SERVER_CERT2_FILE, cert);
  15384. SSLClient cli("google.com");
  15385. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15386. cli.enable_system_ca(true);
  15387. cli.enable_server_certificate_verification(true);
  15388. auto res = cli.Get("/");
  15389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15390. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15391. }
  15392. // The custom CA remains effective when combined with the system CA
  15393. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15394. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15395. ASSERT_TRUE(svr.is_valid());
  15396. svr.Get("/test", [&](const Request &, Response &res) {
  15397. res.set_content("test", "text/plain");
  15398. });
  15399. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15400. auto se = detail::scope_exit([&] {
  15401. svr.stop();
  15402. t.join();
  15403. ASSERT_FALSE(svr.is_running());
  15404. });
  15405. svr.wait_until_ready();
  15406. SSLClient cli("127.0.0.1", PORT);
  15407. std::string cert;
  15408. read_file(SERVER_CERT2_FILE, cert);
  15409. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15410. cli.enable_system_ca(true);
  15411. cli.enable_server_certificate_verification(true);
  15412. cli.set_connection_timeout(30);
  15413. auto res = cli.Get("/test");
  15414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15415. ASSERT_EQ(StatusCode::OK_200, res->status);
  15416. }
  15417. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15418. // skip chain verification entirely (only the certificate identity was
  15419. // checked), so a server presenting an untrusted certificate with a matching
  15420. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15421. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15422. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15423. ASSERT_TRUE(svr.is_valid());
  15424. svr.Get("/test", [&](const Request &, Response &res) {
  15425. res.set_content("test", "text/plain");
  15426. });
  15427. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15428. auto se = detail::scope_exit([&] {
  15429. svr.stop();
  15430. t.join();
  15431. ASSERT_FALSE(svr.is_running());
  15432. });
  15433. svr.wait_until_ready();
  15434. SSLClient cli("127.0.0.1", PORT);
  15435. std::string cert;
  15436. // A trusted CA that did not sign the server certificate. The server cert
  15437. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15438. // this connection.
  15439. read_file(CLIENT_CA_CERT_FILE, cert);
  15440. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15441. cli.enable_server_certificate_verification(true);
  15442. cli.set_connection_timeout(30);
  15443. auto res = cli.Get("/test");
  15444. ASSERT_FALSE(res);
  15445. }
  15446. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15447. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15448. // CA that failed to come through fails verification instead of trusting them.
  15449. // (wolfSSL does not list the system CAs it loaded.)
  15450. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15451. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15452. ASSERT_TRUE(svr.is_valid());
  15453. auto port = svr.bind_to_any_port("127.0.0.1");
  15454. ASSERT_LT(0, port);
  15455. thread t = thread([&] { svr.listen_after_bind(); });
  15456. auto se = detail::scope_exit([&] {
  15457. svr.stop();
  15458. t.join();
  15459. ASSERT_FALSE(svr.is_running());
  15460. });
  15461. svr.wait_until_ready();
  15462. // The CAs a client trusts once its first request has loaded them
  15463. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15464. Client cli("https://127.0.0.1:" + std::to_string(port));
  15465. setup(cli);
  15466. cli.Get("/");
  15467. return tls::get_ca_names(cli.tls_context()).size();
  15468. };
  15469. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15470. EXPECT_EQ(0u,
  15471. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15472. }
  15473. #endif
  15474. // A TLS setting changed between requests applies to the next one, not just to
  15475. // the next connection
  15476. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15477. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15478. ASSERT_TRUE(svr.is_valid());
  15479. svr.Get("/", [](const Request &req, Response &res) {
  15480. res.set_content(std::to_string(req.remote_port), "text/plain");
  15481. });
  15482. auto port = svr.bind_to_any_port("127.0.0.1");
  15483. ASSERT_LT(0, port);
  15484. thread t = thread([&] { svr.listen_after_bind(); });
  15485. auto se = detail::scope_exit([&] {
  15486. svr.stop();
  15487. t.join();
  15488. ASSERT_FALSE(svr.is_running());
  15489. });
  15490. svr.wait_until_ready();
  15491. SSLClient cli("127.0.0.1", port);
  15492. cli.set_keep_alive(true);
  15493. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15494. cli.enable_server_certificate_verification(false);
  15495. // The port the request went out from, so a new one means a new connection
  15496. auto client_port = [&] {
  15497. auto res = cli.Get("/");
  15498. return res ? res->body : std::string();
  15499. };
  15500. auto last = client_port();
  15501. ASSERT_FALSE(last.empty());
  15502. // Setting a value it already has keeps the connection
  15503. cli.enable_server_certificate_verification(false);
  15504. cli.enable_server_hostname_verification(true);
  15505. EXPECT_EQ(last, client_port());
  15506. cli.enable_server_certificate_verification(true);
  15507. auto res = cli.Get("/");
  15508. EXPECT_FALSE(res);
  15509. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15510. std::string ca;
  15511. read_file(SERVER_CERT2_FILE, ca);
  15512. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15513. last = client_port();
  15514. ASSERT_FALSE(last.empty());
  15515. std::vector<std::function<void()>> setters = {
  15516. [&] { cli.enable_server_hostname_verification(false); },
  15517. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15518. [&] {
  15519. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15520. },
  15521. [&] {
  15522. cli.set_server_certificate_verifier(
  15523. [](const tls::VerifyContext &) { return true; });
  15524. },
  15525. [&] {
  15526. cli.set_session_verifier(
  15527. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15528. },
  15529. };
  15530. for (const auto &setter : setters) {
  15531. setter();
  15532. auto next = client_port();
  15533. ASSERT_FALSE(next.empty());
  15534. EXPECT_NE(last, next);
  15535. last = next;
  15536. }
  15537. cli.set_session_verifier(
  15538. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15539. auto handle = cli.open_stream("GET", "/");
  15540. EXPECT_FALSE(handle.is_valid());
  15541. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15542. }
  15543. // A PEM given to create_ca_store() needs no NUL after it
  15544. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15545. std::string pem;
  15546. read_file(SERVER_CERT2_FILE, pem);
  15547. auto buf = pem + "X";
  15548. auto store = tls::create_ca_store(buf.data(), pem.size());
  15549. EXPECT_TRUE(store != nullptr);
  15550. SSLClient cli("localhost");
  15551. cli.set_ca_cert_store(store);
  15552. }
  15553. // enable_system_ca(false) prevents system CA loading entirely
  15554. TEST(SSLClientTest, DisableSystemCa_Online) {
  15555. SSLClient cli("google.com");
  15556. cli.enable_system_ca(false);
  15557. cli.enable_server_certificate_verification(true);
  15558. auto res = cli.Get("/");
  15559. ASSERT_FALSE(res);
  15560. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15561. // itself when the CA chain is empty
  15562. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15563. res.error() == Error::SSLConnection);
  15564. }
  15565. // The universal Client forwards enable_system_ca()
  15566. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15567. std::string cert;
  15568. read_file(SERVER_CERT2_FILE, cert);
  15569. Client cli("https://google.com");
  15570. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15571. cli.enable_system_ca(true);
  15572. cli.enable_server_certificate_verification(true);
  15573. auto res = cli.Get("/");
  15574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15575. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15576. }
  15577. // The system CA policy must carry over to the client created internally for
  15578. // following a cross-host HTTPS redirect
  15579. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15580. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15581. ASSERT_TRUE(svr.is_valid());
  15582. svr.Get("/index", [&](const Request &, Response &res) {
  15583. res.set_redirect("https://www.google.com/");
  15584. });
  15585. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15586. auto se = detail::scope_exit([&] {
  15587. svr.stop();
  15588. t.join();
  15589. ASSERT_FALSE(svr.is_running());
  15590. });
  15591. svr.wait_until_ready();
  15592. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15593. std::string cert;
  15594. read_file(SERVER_CERT2_FILE, cert);
  15595. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15596. cli.enable_system_ca(true);
  15597. cli.enable_server_certificate_verification(true);
  15598. cli.set_follow_location(true);
  15599. cli.set_connection_timeout(30);
  15600. // Receiving any response proves the redirect client completed the TLS
  15601. // handshake with a system-CA-signed host
  15602. auto res = cli.Get("/index");
  15603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15604. }
  15605. TEST(MultipartFormDataTest, LargeData) {
  15606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15607. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15608. const ContentReader &content_reader) {
  15609. if (req.is_multipart_form_data()) {
  15610. std::vector<FormData> items;
  15611. content_reader(
  15612. [&](const FormData &file) {
  15613. items.push_back(file);
  15614. return true;
  15615. },
  15616. [&](const char *data, size_t data_length) {
  15617. items.back().content.append(data, data_length);
  15618. return true;
  15619. });
  15620. EXPECT_TRUE(std::string(items[0].name) == "document");
  15621. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15622. EXPECT_TRUE(items[0].filename == "2MB_data");
  15623. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15624. EXPECT_TRUE(items[1].name == "hello");
  15625. EXPECT_TRUE(items[1].content == "world");
  15626. EXPECT_TRUE(items[1].filename == "");
  15627. EXPECT_TRUE(items[1].content_type == "");
  15628. } else {
  15629. std::string body;
  15630. content_reader([&](const char *data, size_t data_length) {
  15631. body.append(data, data_length);
  15632. return true;
  15633. });
  15634. }
  15635. });
  15636. auto port = svr.bind_to_any_port(HOST);
  15637. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15638. auto se = detail::scope_exit([&] {
  15639. svr.stop();
  15640. t.join();
  15641. ASSERT_FALSE(svr.is_running());
  15642. });
  15643. svr.wait_until_ready();
  15644. {
  15645. std::string data(1024 * 1024 * 2, '.');
  15646. std::stringstream buffer;
  15647. buffer << data;
  15648. SSLClient cli(HOST, port);
  15649. cli.enable_server_certificate_verification(false);
  15650. UploadFormDataItems items{
  15651. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15652. {"hello", "world", "", ""},
  15653. };
  15654. auto res = cli.Post("/post", items);
  15655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15656. ASSERT_EQ(StatusCode::OK_200, res->status);
  15657. }
  15658. }
  15659. TEST(MultipartFormDataTest, DataProviderItems) {
  15660. std::random_device seed_gen;
  15661. std::mt19937 random(seed_gen());
  15662. std::string rand1;
  15663. rand1.resize(1000);
  15664. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15665. std::string rand2;
  15666. rand2.resize(3000);
  15667. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15668. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15669. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15670. const ContentReader &content_reader) {
  15671. ASSERT_FALSE(req.is_multipart_form_data());
  15672. std::string body;
  15673. content_reader([&](const char *data, size_t data_length) {
  15674. body.append(data, data_length);
  15675. return true;
  15676. });
  15677. EXPECT_EQ(body, "");
  15678. });
  15679. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15680. const ContentReader &content_reader) {
  15681. ASSERT_TRUE(req.is_multipart_form_data());
  15682. std::vector<FormData> items;
  15683. content_reader(
  15684. [&](const FormData &file) {
  15685. items.push_back(file);
  15686. return true;
  15687. },
  15688. [&](const char *data, size_t data_length) {
  15689. items.back().content.append(data, data_length);
  15690. return true;
  15691. });
  15692. ASSERT_TRUE(items.size() == 2);
  15693. EXPECT_EQ(std::string(items[0].name), "name1");
  15694. EXPECT_EQ(items[0].content, "Testing123");
  15695. EXPECT_EQ(items[0].filename, "filename1");
  15696. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15697. EXPECT_EQ(items[1].name, "name2");
  15698. EXPECT_EQ(items[1].content, "Testing456");
  15699. EXPECT_EQ(items[1].filename, "");
  15700. EXPECT_EQ(items[1].content_type, "");
  15701. });
  15702. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15703. const ContentReader &content_reader) {
  15704. ASSERT_TRUE(req.is_multipart_form_data());
  15705. std::vector<FormData> items;
  15706. content_reader(
  15707. [&](const FormData &file) {
  15708. items.push_back(file);
  15709. return true;
  15710. },
  15711. [&](const char *data, size_t data_length) {
  15712. items.back().content.append(data, data_length);
  15713. return true;
  15714. });
  15715. ASSERT_TRUE(items.size() == 2);
  15716. EXPECT_EQ(items[0].name, "name3");
  15717. EXPECT_EQ(items[0].content, rand1);
  15718. EXPECT_EQ(items[0].filename, "filename3");
  15719. EXPECT_EQ(items[0].content_type, "");
  15720. EXPECT_EQ(items[1].name, "name4");
  15721. EXPECT_EQ(items[1].content, rand2);
  15722. EXPECT_EQ(items[1].filename, "filename4");
  15723. EXPECT_EQ(items[1].content_type, "");
  15724. });
  15725. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15726. const ContentReader &content_reader) {
  15727. ASSERT_TRUE(req.is_multipart_form_data());
  15728. std::vector<FormData> items;
  15729. content_reader(
  15730. [&](const FormData &file) {
  15731. items.push_back(file);
  15732. return true;
  15733. },
  15734. [&](const char *data, size_t data_length) {
  15735. items.back().content.append(data, data_length);
  15736. return true;
  15737. });
  15738. ASSERT_TRUE(items.size() == 4);
  15739. EXPECT_EQ(std::string(items[0].name), "name1");
  15740. EXPECT_EQ(items[0].content, "Testing123");
  15741. EXPECT_EQ(items[0].filename, "filename1");
  15742. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15743. EXPECT_EQ(items[1].name, "name2");
  15744. EXPECT_EQ(items[1].content, "Testing456");
  15745. EXPECT_EQ(items[1].filename, "");
  15746. EXPECT_EQ(items[1].content_type, "");
  15747. EXPECT_EQ(items[2].name, "name3");
  15748. EXPECT_EQ(items[2].content, rand1);
  15749. EXPECT_EQ(items[2].filename, "filename3");
  15750. EXPECT_EQ(items[2].content_type, "");
  15751. EXPECT_EQ(items[3].name, "name4");
  15752. EXPECT_EQ(items[3].content, rand2);
  15753. EXPECT_EQ(items[3].filename, "filename4");
  15754. EXPECT_EQ(items[3].content_type, "");
  15755. });
  15756. auto port = svr.bind_to_any_port("localhost");
  15757. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15758. auto se = detail::scope_exit([&] {
  15759. svr.stop();
  15760. t.join();
  15761. ASSERT_FALSE(svr.is_running());
  15762. });
  15763. svr.wait_until_ready();
  15764. {
  15765. SSLClient cli("localhost", port);
  15766. cli.enable_server_certificate_verification(false);
  15767. UploadFormDataItems items{
  15768. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15769. {"name2", "Testing456", "", ""}, // not a file
  15770. };
  15771. {
  15772. auto res = cli.Post("/post-none", {}, {}, {});
  15773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15774. ASSERT_EQ(StatusCode::OK_200, res->status);
  15775. }
  15776. FormDataProviderItems providers;
  15777. {
  15778. auto res =
  15779. cli.Post("/post-items", {}, items, providers); // empty providers
  15780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15781. ASSERT_EQ(StatusCode::OK_200, res->status);
  15782. }
  15783. providers.push_back({"name3",
  15784. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15785. // test the offset is given correctly at each step
  15786. if (!offset)
  15787. sink.os.write(rand1.data(), 30);
  15788. else if (offset == 30)
  15789. sink.os.write(rand1.data() + 30, 300);
  15790. else if (offset == 330)
  15791. sink.os.write(rand1.data() + 330, 670);
  15792. else if (offset == rand1.size())
  15793. sink.done();
  15794. return true;
  15795. },
  15796. "filename3",
  15797. {}});
  15798. providers.push_back({"name4",
  15799. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15800. // test the offset is given correctly at each step
  15801. if (!offset)
  15802. sink.os.write(rand2.data(), 2000);
  15803. else if (offset == 2000)
  15804. sink.os.write(rand2.data() + 2000, 1);
  15805. else if (offset == 2001)
  15806. sink.os.write(rand2.data() + 2001, 999);
  15807. else if (offset == rand2.size())
  15808. sink.done();
  15809. return true;
  15810. },
  15811. "filename4",
  15812. {}});
  15813. {
  15814. auto res = cli.Post("/post-providers", {}, {}, providers);
  15815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15816. ASSERT_EQ(StatusCode::OK_200, res->status);
  15817. }
  15818. {
  15819. auto res = cli.Post("/post-both", {}, items, providers);
  15820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15821. ASSERT_EQ(StatusCode::OK_200, res->status);
  15822. }
  15823. }
  15824. }
  15825. TEST(MultipartFormDataTest, BadHeader) {
  15826. Server svr;
  15827. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15828. res.set_content("ok", "text/plain");
  15829. });
  15830. thread t = thread([&] { svr.listen(HOST, PORT); });
  15831. auto se = detail::scope_exit([&] {
  15832. svr.stop();
  15833. t.join();
  15834. ASSERT_FALSE(svr.is_running());
  15835. });
  15836. svr.wait_until_ready();
  15837. const std::string body =
  15838. "This is the preamble. It is to be ignored, though it\r\n"
  15839. "is a handy place for composition agents to include an\r\n"
  15840. "explanatory note to non-MIME conformant readers.\r\n"
  15841. "\r\n"
  15842. "\r\n"
  15843. "--simple boundary\r\n"
  15844. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15845. ": BAD...\r\n"
  15846. "\r\n"
  15847. "value1\r\n"
  15848. "--simple boundary\r\n"
  15849. "Content-Disposition: form-data; name=\"field2\"; "
  15850. "filename=\"example.txt\"\r\n"
  15851. "\r\n"
  15852. "value2\r\n"
  15853. "--simple boundary--\r\n"
  15854. "This is the epilogue. It is also to be ignored.\r\n";
  15855. std::string content_type =
  15856. R"(multipart/form-data; boundary="simple boundary")";
  15857. Client cli(HOST, PORT);
  15858. auto res = cli.Post("/post", body, content_type.c_str());
  15859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15860. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15861. }
  15862. TEST(MultipartFormDataTest, WithPreamble) {
  15863. Server svr;
  15864. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15865. res.set_content("ok", "text/plain");
  15866. });
  15867. thread t = thread([&] { svr.listen(HOST, PORT); });
  15868. auto se = detail::scope_exit([&] {
  15869. svr.stop();
  15870. t.join();
  15871. ASSERT_FALSE(svr.is_running());
  15872. });
  15873. svr.wait_until_ready();
  15874. const std::string body =
  15875. "This is the preamble. It is to be ignored, though it\r\n"
  15876. "is a handy place for composition agents to include an\r\n"
  15877. "explanatory note to non-MIME conformant readers.\r\n"
  15878. "\r\n"
  15879. "\r\n"
  15880. "--simple boundary\r\n"
  15881. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15882. "\r\n"
  15883. "value1\r\n"
  15884. "--simple boundary\r\n"
  15885. "Content-Disposition: form-data; name=\"field2\"; "
  15886. "filename=\"example.txt\"\r\n"
  15887. "\r\n"
  15888. "value2\r\n"
  15889. "--simple boundary--\r\n"
  15890. "This is the epilogue. It is also to be ignored.\r\n";
  15891. std::string content_type =
  15892. R"(multipart/form-data; boundary="simple boundary")";
  15893. Client cli(HOST, PORT);
  15894. auto res = cli.Post("/post", body, content_type.c_str());
  15895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15896. EXPECT_EQ(StatusCode::OK_200, res->status);
  15897. }
  15898. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15900. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15901. const ContentReader &content_reader) {
  15902. if (req.is_multipart_form_data()) {
  15903. std::vector<FormData> items;
  15904. content_reader(
  15905. [&](const FormData &file) {
  15906. items.push_back(file);
  15907. return true;
  15908. },
  15909. [&](const char *data, size_t data_length) {
  15910. items.back().content.append(data, data_length);
  15911. return true;
  15912. });
  15913. EXPECT_TRUE(std::string(items[0].name) == "document");
  15914. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15915. EXPECT_TRUE(items[0].filename == "2MB_data");
  15916. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15917. EXPECT_TRUE(items[1].name == "hello");
  15918. EXPECT_TRUE(items[1].content == "world");
  15919. EXPECT_TRUE(items[1].filename == "");
  15920. EXPECT_TRUE(items[1].content_type == "");
  15921. } else {
  15922. std::string body;
  15923. content_reader([&](const char *data, size_t data_length) {
  15924. body.append(data, data_length);
  15925. return true;
  15926. });
  15927. }
  15928. });
  15929. auto port = svr.bind_to_any_port("localhost");
  15930. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15931. auto se = detail::scope_exit([&] {
  15932. svr.stop();
  15933. t.join();
  15934. ASSERT_FALSE(svr.is_running());
  15935. });
  15936. svr.wait_until_ready();
  15937. {
  15938. std::string data(1024 * 1024 * 2, '.');
  15939. std::stringstream buffer;
  15940. buffer << data;
  15941. SSLClient cli("localhost", port);
  15942. cli.enable_server_certificate_verification(false);
  15943. UploadFormDataItems items{
  15944. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15945. {"hello", "world", "", ""},
  15946. };
  15947. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15949. ASSERT_EQ(StatusCode::OK_200, res->status);
  15950. }
  15951. }
  15952. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15953. std::string data(1024 * 1024 * 2, '&');
  15954. std::stringstream buffer;
  15955. buffer << data;
  15956. Client cli("https://localhost:8080");
  15957. UploadFormDataItems items{
  15958. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15959. {"hello", "world", "", ""},
  15960. };
  15961. for (const char &c : " \t\r\n") {
  15962. auto res =
  15963. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15964. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15965. ASSERT_FALSE(res);
  15966. }
  15967. }
  15968. TEST(MultipartFormDataTest, PutFormData) {
  15969. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15970. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15971. const ContentReader &content_reader) {
  15972. if (req.is_multipart_form_data()) {
  15973. std::vector<FormData> items;
  15974. content_reader(
  15975. [&](const FormData &file) {
  15976. items.push_back(file);
  15977. return true;
  15978. },
  15979. [&](const char *data, size_t data_length) {
  15980. items.back().content.append(data, data_length);
  15981. return true;
  15982. });
  15983. EXPECT_TRUE(std::string(items[0].name) == "document");
  15984. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15985. EXPECT_TRUE(items[0].filename == "2MB_data");
  15986. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15987. EXPECT_TRUE(items[1].name == "hello");
  15988. EXPECT_TRUE(items[1].content == "world");
  15989. EXPECT_TRUE(items[1].filename == "");
  15990. EXPECT_TRUE(items[1].content_type == "");
  15991. } else {
  15992. std::string body;
  15993. content_reader([&](const char *data, size_t data_length) {
  15994. body.append(data, data_length);
  15995. return true;
  15996. });
  15997. }
  15998. });
  15999. auto port = svr.bind_to_any_port("localhost");
  16000. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16001. auto se = detail::scope_exit([&] {
  16002. svr.stop();
  16003. t.join();
  16004. ASSERT_FALSE(svr.is_running());
  16005. });
  16006. svr.wait_until_ready();
  16007. {
  16008. std::string data(1024 * 1024 * 2, '&');
  16009. std::stringstream buffer;
  16010. buffer << data;
  16011. SSLClient cli("localhost", port);
  16012. cli.enable_server_certificate_verification(false);
  16013. UploadFormDataItems items{
  16014. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16015. {"hello", "world", "", ""},
  16016. };
  16017. auto res = cli.Put("/put", items);
  16018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16019. ASSERT_EQ(StatusCode::OK_200, res->status);
  16020. }
  16021. }
  16022. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16024. svr.Put("/put_customboundary",
  16025. [&](const Request &req, const Response & /*res*/,
  16026. const ContentReader &content_reader) {
  16027. if (req.is_multipart_form_data()) {
  16028. std::vector<FormData> items;
  16029. content_reader(
  16030. [&](const FormData &file) {
  16031. items.push_back(file);
  16032. return true;
  16033. },
  16034. [&](const char *data, size_t data_length) {
  16035. items.back().content.append(data, data_length);
  16036. return true;
  16037. });
  16038. EXPECT_TRUE(std::string(items[0].name) == "document");
  16039. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16040. EXPECT_TRUE(items[0].filename == "2MB_data");
  16041. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16042. EXPECT_TRUE(items[1].name == "hello");
  16043. EXPECT_TRUE(items[1].content == "world");
  16044. EXPECT_TRUE(items[1].filename == "");
  16045. EXPECT_TRUE(items[1].content_type == "");
  16046. } else {
  16047. std::string body;
  16048. content_reader([&](const char *data, size_t data_length) {
  16049. body.append(data, data_length);
  16050. return true;
  16051. });
  16052. }
  16053. });
  16054. auto port = svr.bind_to_any_port("localhost");
  16055. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16056. auto se = detail::scope_exit([&] {
  16057. svr.stop();
  16058. t.join();
  16059. ASSERT_FALSE(svr.is_running());
  16060. });
  16061. svr.wait_until_ready();
  16062. {
  16063. std::string data(1024 * 1024 * 2, '&');
  16064. std::stringstream buffer;
  16065. buffer << data;
  16066. SSLClient cli("localhost", port);
  16067. cli.enable_server_certificate_verification(false);
  16068. UploadFormDataItems items{
  16069. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16070. {"hello", "world", "", ""},
  16071. };
  16072. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16074. ASSERT_EQ(StatusCode::OK_200, res->status);
  16075. }
  16076. }
  16077. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16078. std::string data(1024 * 1024 * 2, '&');
  16079. std::stringstream buffer;
  16080. buffer << data;
  16081. Client cli("https://localhost:8080");
  16082. cli.enable_server_certificate_verification(false);
  16083. UploadFormDataItems items{
  16084. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16085. {"hello", "world", "", ""},
  16086. };
  16087. for (const char &c : " \t\r\n") {
  16088. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16089. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16090. ASSERT_FALSE(res);
  16091. }
  16092. }
  16093. TEST(MultipartFormDataTest, AlternateFilename) {
  16094. auto handled = false;
  16095. Server svr;
  16096. svr.Post("/test", [&](const Request &req, Response &res) {
  16097. ASSERT_EQ(2u, req.form.files.size());
  16098. ASSERT_EQ(1u, req.form.fields.size());
  16099. // Test files
  16100. const auto &file1 = req.form.get_file("file1");
  16101. ASSERT_EQ("file1", file1.name);
  16102. ASSERT_EQ("A.txt", file1.filename);
  16103. ASSERT_EQ("text/plain", file1.content_type);
  16104. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16105. const auto &file2 = req.form.get_file("file2");
  16106. ASSERT_EQ("file2", file2.name);
  16107. ASSERT_EQ("a.html", file2.filename);
  16108. ASSERT_EQ("text/html", file2.content_type);
  16109. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16110. file2.content);
  16111. // Test text field
  16112. const auto &text = req.form.get_field("text");
  16113. ASSERT_EQ("text default", text);
  16114. res.set_content("ok", "text/plain");
  16115. handled = true;
  16116. });
  16117. thread t = thread([&] { svr.listen(HOST, PORT); });
  16118. auto se = detail::scope_exit([&] {
  16119. svr.stop();
  16120. t.join();
  16121. ASSERT_FALSE(svr.is_running());
  16122. ASSERT_TRUE(handled);
  16123. });
  16124. svr.wait_until_ready();
  16125. auto req = "POST /test HTTP/1.1\r\n"
  16126. "Host: localhost\r\n"
  16127. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16128. "Content-Length: 399\r\n"
  16129. "\r\n"
  16130. "----------\r\n"
  16131. "Content-Disposition: form-data; name=\"text\"\r\n"
  16132. "\r\n"
  16133. "text default\r\n"
  16134. "----------\r\n"
  16135. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16136. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16137. "Content-Type: text/plain\r\n"
  16138. "\r\n"
  16139. "Content of a.txt.\r\n"
  16140. "\r\n"
  16141. "----------\r\n"
  16142. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16143. "\"a.html\"\r\n"
  16144. "Content-Type: text/html\r\n"
  16145. "\r\n"
  16146. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16147. "\r\n"
  16148. "------------\r\n";
  16149. ASSERT_TRUE(send_request(1, req));
  16150. }
  16151. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16152. auto handled = false;
  16153. Server svr;
  16154. svr.Post("/test", [&](const Request &req, Response &res) {
  16155. // Case-insensitive "utf-8''" prefix with a long value
  16156. const auto &file = req.form.get_file("file1");
  16157. ASSERT_EQ("file1", file.name);
  16158. // 8000 chars exercises both the Content-Disposition parser and the
  16159. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16160. // Prior to the fix, std::regex_match on this header would cause O(N)
  16161. // stack recursion in libstdc++, leading to SIGSEGV.
  16162. std::string expected_filename(8000, 'A');
  16163. ASSERT_EQ(expected_filename, file.filename);
  16164. res.set_content("ok", "text/plain");
  16165. handled = true;
  16166. });
  16167. thread t = thread([&] { svr.listen(HOST, PORT); });
  16168. auto se = detail::scope_exit([&] {
  16169. svr.stop();
  16170. t.join();
  16171. ASSERT_FALSE(svr.is_running());
  16172. ASSERT_TRUE(handled);
  16173. });
  16174. svr.wait_until_ready();
  16175. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16176. // Regression test for GHSA-qq6v-r583-3h69
  16177. std::string long_filename(8000, 'A');
  16178. std::string body = "----------\r\n"
  16179. "Content-Disposition: form-data; name=\"file1\"; "
  16180. "filename*=\"Utf-8''" +
  16181. long_filename +
  16182. "\"\r\n"
  16183. "\r\n"
  16184. "hello\r\n"
  16185. "------------\r\n";
  16186. auto req = "POST /test HTTP/1.1\r\n"
  16187. "Host: localhost\r\n"
  16188. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16189. "Content-Length: " +
  16190. std::to_string(body.size()) + "\r\n\r\n" + body;
  16191. ASSERT_TRUE(send_request(1, req));
  16192. }
  16193. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16194. auto handled = false;
  16195. Server svr;
  16196. svr.Post("/test", [&](const Request &req, Response &) {
  16197. ASSERT_EQ(2u, req.form.fields.size());
  16198. const auto &text1 = req.form.get_field("text1");
  16199. ASSERT_EQ("text1", text1);
  16200. const auto &text2 = req.form.get_field("text2");
  16201. ASSERT_EQ("text2", text2);
  16202. handled = true;
  16203. });
  16204. thread t = thread([&] { svr.listen(HOST, PORT); });
  16205. auto se = detail::scope_exit([&] {
  16206. svr.stop();
  16207. t.join();
  16208. ASSERT_FALSE(svr.is_running());
  16209. ASSERT_TRUE(handled);
  16210. });
  16211. svr.wait_until_ready();
  16212. auto req = "POST /test HTTP/1.1\r\n"
  16213. "Host: localhost\r\n"
  16214. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16215. "Content-Length: 146\r\n"
  16216. "\r\n----------\r\n"
  16217. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16218. "\r\n"
  16219. "text1"
  16220. "\r\n----------\r\n"
  16221. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16222. "\r\n"
  16223. "text2"
  16224. "\r\n------------";
  16225. std::string response;
  16226. ASSERT_TRUE(send_request(1, req, &response));
  16227. ASSERT_EQ("200", response.substr(9, 3));
  16228. }
  16229. TEST(MultipartFormDataTest, ContentLength) {
  16230. auto handled = false;
  16231. Server svr;
  16232. svr.Post("/test", [&](const Request &req, Response &) {
  16233. ASSERT_EQ(2u, req.form.fields.size());
  16234. const auto &text1 = req.form.get_field("text1");
  16235. ASSERT_EQ("text1", text1);
  16236. const auto &text2 = req.form.get_field("text2");
  16237. ASSERT_EQ("text2", text2);
  16238. handled = true;
  16239. });
  16240. thread t = thread([&] { svr.listen(HOST, PORT); });
  16241. auto se = detail::scope_exit([&] {
  16242. svr.stop();
  16243. t.join();
  16244. ASSERT_FALSE(svr.is_running());
  16245. ASSERT_TRUE(handled);
  16246. });
  16247. svr.wait_until_ready();
  16248. auto req = "POST /test HTTP/1.1\r\n"
  16249. "Host: localhost\r\n"
  16250. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16251. "Content-Length: 167\r\n"
  16252. "\r\n----------\r\n"
  16253. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16254. "Content-Length: 5\r\n"
  16255. "\r\n"
  16256. "text1"
  16257. "\r\n----------\r\n"
  16258. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16259. "\r\n"
  16260. "text2"
  16261. "\r\n------------\r\n";
  16262. std::string response;
  16263. ASSERT_TRUE(send_request(1, req, &response));
  16264. ASSERT_EQ("200", response.substr(9, 3));
  16265. }
  16266. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16267. auto handled = false;
  16268. Server svr;
  16269. svr.Post("/test", [&](const Request &req, Response &) {
  16270. ASSERT_EQ(2u, req.form.fields.size());
  16271. const auto &text1 = req.form.get_field("text1");
  16272. ASSERT_EQ("text1", text1);
  16273. // TODO: Add header access for text fields if needed
  16274. const auto &text2 = req.form.get_field("text2");
  16275. ASSERT_EQ("text2", text2);
  16276. // TODO: Header access for text fields needs to be implemented
  16277. // auto &headers = it->second.headers;
  16278. // ASSERT_EQ(3U, headers.size());
  16279. // auto custom_header = headers.find("x-whatever");
  16280. // ASSERT_TRUE(custom_header != headers.end());
  16281. // ASSERT_NE("customvalue", custom_header->second);
  16282. // ASSERT_EQ("CustomValue", custom_header->second);
  16283. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16284. handled = true;
  16285. });
  16286. thread t = thread([&] { svr.listen(HOST, PORT); });
  16287. auto se = detail::scope_exit([&] {
  16288. svr.stop();
  16289. t.join();
  16290. ASSERT_FALSE(svr.is_running());
  16291. ASSERT_TRUE(handled);
  16292. });
  16293. svr.wait_until_ready();
  16294. auto req = "POST /test HTTP/1.1\r\n"
  16295. "Host: localhost\r\n"
  16296. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16297. "Content-Length: 232\r\n"
  16298. "\r\n----------\r\n"
  16299. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16300. "Content-Length: 5\r\n"
  16301. "X-Test: 1\r\n"
  16302. "\r\n"
  16303. "text1"
  16304. "\r\n----------\r\n"
  16305. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16306. "Content-Type: text/plain\r\n"
  16307. "X-Whatever: CustomValue\r\n"
  16308. "\r\n"
  16309. "text2"
  16310. "\r\n------------\r\n"
  16311. "That should be disregarded. Not even read";
  16312. std::string response;
  16313. ASSERT_TRUE(send_request(1, req, &response));
  16314. ASSERT_EQ("200", response.substr(9, 3));
  16315. }
  16316. TEST(MultipartFormDataTest, LargeHeader) {
  16317. auto handled = false;
  16318. Server svr;
  16319. svr.Post("/test", [&](const Request &req, Response &) {
  16320. ASSERT_EQ(1u, req.form.fields.size());
  16321. const auto &text = req.form.get_field("name1");
  16322. ASSERT_EQ("text1", text);
  16323. handled = true;
  16324. });
  16325. thread t = thread([&] { svr.listen(HOST, PORT); });
  16326. auto se = detail::scope_exit([&] {
  16327. svr.stop();
  16328. t.join();
  16329. ASSERT_FALSE(svr.is_running());
  16330. ASSERT_TRUE(handled);
  16331. });
  16332. svr.wait_until_ready();
  16333. auto boundary = std::string("cpp-httplib-multipart-data");
  16334. std::string content = "--" + boundary +
  16335. "\r\n"
  16336. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16337. "\r\n"
  16338. "text1\r\n"
  16339. "--" +
  16340. boundary + "--\r\n";
  16341. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16342. "Host: localhost\r\n"
  16343. "Content-Type: multipart/form-data;boundary=" +
  16344. boundary +
  16345. "\r\n"
  16346. "Content-Length: " +
  16347. std::to_string(content.size()) +
  16348. "\r\n"
  16349. "Dummy-Header: ";
  16350. std::string header_suffix = "\r\n"
  16351. "\r\n";
  16352. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16353. size_t header_dummy_size =
  16354. read_buff_size -
  16355. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16356. auto header_dummy = std::string(header_dummy_size, '@');
  16357. auto req = header_prefix + header_dummy + header_suffix + content;
  16358. std::string response;
  16359. ASSERT_TRUE(send_request(1, req, &response));
  16360. ASSERT_EQ("200", response.substr(9, 3));
  16361. }
  16362. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16363. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16364. // (not chunked Transfer-Encoding) after the streaming refactor.
  16365. auto handled = false;
  16366. Server svr;
  16367. svr.Post("/upload", [&](const Request &req, Response &res) {
  16368. auto cl_it = req.headers.find("Content-Length");
  16369. EXPECT_TRUE(cl_it != req.headers.end());
  16370. auto te_it = req.headers.find("Transfer-Encoding");
  16371. EXPECT_TRUE(te_it == req.headers.end());
  16372. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16373. res.set_content("ok", "text/plain");
  16374. handled = true;
  16375. });
  16376. auto port = svr.bind_to_any_port(HOST);
  16377. auto t = thread([&] { svr.listen_after_bind(); });
  16378. auto se = detail::scope_exit([&] {
  16379. svr.stop();
  16380. t.join();
  16381. ASSERT_FALSE(svr.is_running());
  16382. ASSERT_TRUE(handled);
  16383. });
  16384. svr.wait_until_ready();
  16385. UploadFormDataItems items = {
  16386. {"field1", "hello", "", "text/plain"},
  16387. {"file1", "world", "test.txt", "application/octet-stream"},
  16388. };
  16389. Client cli(HOST, port);
  16390. auto res = cli.Post("/upload", {}, items);
  16391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16392. EXPECT_EQ(StatusCode::OK_200, res->status);
  16393. }
  16394. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16395. // Verify that make_multipart_content_provider coalesces many small segments
  16396. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16397. constexpr size_t kItemCount = 1000;
  16398. UploadFormDataItems items;
  16399. items.reserve(kItemCount);
  16400. for (size_t i = 0; i < kItemCount; i++) {
  16401. items.push_back(
  16402. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16403. }
  16404. const std::string boundary = "----test-boundary";
  16405. auto content_length = detail::get_multipart_content_length(items, boundary);
  16406. auto provider = detail::make_multipart_content_provider(items, boundary);
  16407. // Drive the provider the same way write_content_with_progress does
  16408. size_t write_count = 0;
  16409. size_t total_bytes = 0;
  16410. DataSink sink;
  16411. size_t offset = 0;
  16412. sink.write = [&](const char *d, size_t l) -> bool {
  16413. (void)d;
  16414. write_count++;
  16415. total_bytes += l;
  16416. offset += l;
  16417. return true;
  16418. };
  16419. sink.is_writable = []() -> bool { return true; };
  16420. while (offset < content_length) {
  16421. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16422. }
  16423. EXPECT_EQ(content_length, total_bytes);
  16424. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16425. // With buffering into 64KB blocks, write_count should be much smaller.
  16426. auto segment_count = 3 * kItemCount + 1;
  16427. EXPECT_LT(write_count, segment_count / 10);
  16428. }
  16429. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16430. // Integration test: send many UploadFormDataItems and verify the server
  16431. // receives all of them correctly (#2410).
  16432. constexpr size_t kItemCount = 500;
  16433. auto handled = false;
  16434. Server svr;
  16435. svr.Post("/upload", [&](const Request &req, Response &res) {
  16436. EXPECT_EQ(kItemCount, req.form.fields.size());
  16437. for (size_t i = 0; i < kItemCount; i++) {
  16438. auto key = "field" + std::to_string(i);
  16439. auto val = "value" + std::to_string(i);
  16440. auto it = req.form.fields.find(key);
  16441. if (it != req.form.fields.end()) {
  16442. EXPECT_EQ(val, it->second.content);
  16443. } else {
  16444. ADD_FAILURE() << "Missing field: " << key;
  16445. }
  16446. }
  16447. res.set_content("ok", "text/plain");
  16448. handled = true;
  16449. });
  16450. auto port = svr.bind_to_any_port(HOST);
  16451. auto t = thread([&] { svr.listen_after_bind(); });
  16452. auto se = detail::scope_exit([&] {
  16453. svr.stop();
  16454. t.join();
  16455. ASSERT_FALSE(svr.is_running());
  16456. ASSERT_TRUE(handled);
  16457. });
  16458. svr.wait_until_ready();
  16459. UploadFormDataItems items;
  16460. items.reserve(kItemCount);
  16461. for (size_t i = 0; i < kItemCount; i++) {
  16462. items.push_back(
  16463. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16464. }
  16465. Client cli(HOST, port);
  16466. auto res = cli.Post("/upload", items);
  16467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16468. EXPECT_EQ(StatusCode::OK_200, res->status);
  16469. }
  16470. TEST(MultipartFormDataTest, MakeFileProvider) {
  16471. // Verify make_file_provider sends a file's contents correctly.
  16472. const std::string file_content(4096, 'Z');
  16473. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16474. {
  16475. std::ofstream ofs(tmp_path, std::ios::binary);
  16476. ofs.write(file_content.data(),
  16477. static_cast<std::streamsize>(file_content.size()));
  16478. }
  16479. auto handled = false;
  16480. Server svr;
  16481. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16482. const ContentReader &content_reader) {
  16483. ASSERT_TRUE(req.is_multipart_form_data());
  16484. std::vector<FormData> items;
  16485. content_reader(
  16486. [&](const FormData &file) {
  16487. items.push_back(file);
  16488. return true;
  16489. },
  16490. [&](const char *data, size_t data_length) {
  16491. items.back().content.append(data, data_length);
  16492. return true;
  16493. });
  16494. ASSERT_EQ(1u, items.size());
  16495. EXPECT_EQ("myfile", items[0].name);
  16496. EXPECT_EQ("data.bin", items[0].filename);
  16497. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16498. EXPECT_EQ(file_content, items[0].content);
  16499. handled = true;
  16500. });
  16501. auto port = svr.bind_to_any_port(HOST);
  16502. auto t = thread([&] { svr.listen_after_bind(); });
  16503. auto se = detail::scope_exit([&] {
  16504. svr.stop();
  16505. t.join();
  16506. ASSERT_FALSE(svr.is_running());
  16507. ASSERT_TRUE(handled);
  16508. std::remove(tmp_path.c_str());
  16509. });
  16510. svr.wait_until_ready();
  16511. FormDataProviderItems providers;
  16512. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16513. "application/octet-stream"));
  16514. Client cli(HOST, port);
  16515. auto res = cli.Post("/upload", {}, {}, providers);
  16516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16517. EXPECT_EQ(StatusCode::OK_200, res->status);
  16518. }
  16519. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16520. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16521. // (100) headers is rejected with a 400 Bad Request response.
  16522. Server svr;
  16523. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16524. res.set_content("ok", "text/plain");
  16525. });
  16526. thread t = thread([&] { svr.listen(HOST, PORT); });
  16527. auto se = detail::scope_exit([&] {
  16528. svr.stop();
  16529. t.join();
  16530. ASSERT_FALSE(svr.is_running());
  16531. });
  16532. svr.wait_until_ready();
  16533. // Build a multipart part with 101 custom headers (exceeding
  16534. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16535. std::stringstream body;
  16536. body << "--simpleboundary\r\n"
  16537. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16538. for (int i = 0; i < 101; i++) {
  16539. body << "X-Custom-Header-" << i << ": value\r\n";
  16540. }
  16541. body << "\r\n"
  16542. << "value1\r\n"
  16543. << "--simpleboundary--\r\n";
  16544. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16545. Client cli(HOST, PORT);
  16546. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16548. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16549. }
  16550. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16551. // A body that never contains the declared boundary must not be accumulated
  16552. // while the parser waits for it. Buffering it would also make every read
  16553. // rescan everything seen so far, which is quadratic in the body size.
  16554. Server svr;
  16555. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16556. res.set_content("ok", "text/plain");
  16557. });
  16558. auto port = svr.bind_to_any_port(HOST);
  16559. thread t = thread([&] { svr.listen_after_bind(); });
  16560. auto se = detail::scope_exit([&] {
  16561. svr.stop();
  16562. t.join();
  16563. ASSERT_FALSE(svr.is_running());
  16564. });
  16565. svr.wait_until_ready();
  16566. Client cli(HOST, port);
  16567. cli.set_read_timeout(60, 0);
  16568. cli.set_write_timeout(60, 0);
  16569. // '-' is the worst case: it matches the first character of the boundary, so
  16570. // every position has to be checked against it.
  16571. auto post_dashes = [&](size_t size) {
  16572. const std::string body(size, '-');
  16573. auto start = std::chrono::steady_clock::now();
  16574. auto res =
  16575. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16576. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16577. std::chrono::steady_clock::now() - start)
  16578. .count();
  16579. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16580. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16581. return ms;
  16582. };
  16583. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16584. // Windows.
  16585. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16586. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16587. // Comparing the two sizes rather than checking an absolute duration keeps
  16588. // this meaningful across build types and CI load, both of which move the
  16589. // absolute numbers by more than an order of magnitude. Four times the bytes
  16590. // costs about four times the time when parsing is linear, and about sixteen
  16591. // times when the body is buffered and rescanned.
  16592. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16593. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16594. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16595. << "ms, which suggests the body is being buffered and rescanned";
  16596. }
  16597. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16598. // A boundary can only be followed by CRLF or by "--", so anything else is
  16599. // malformed no matter what comes next. The parser must say so right away
  16600. // instead of buffering the rest of the declared body.
  16601. Server svr;
  16602. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16603. res.set_content("ok", "text/plain");
  16604. });
  16605. auto port = svr.bind_to_any_port(HOST);
  16606. thread t = thread([&] { svr.listen_after_bind(); });
  16607. auto se = detail::scope_exit([&] {
  16608. svr.stop();
  16609. t.join();
  16610. ASSERT_FALSE(svr.is_running());
  16611. });
  16612. svr.wait_until_ready();
  16613. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16614. // buffers instead of failing would still be waiting for the remaining bytes.
  16615. const std::string body = "--zzzz\r\n"
  16616. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16617. "\r\n"
  16618. "text1"
  16619. "\r\n--zzzzXX";
  16620. const std::string req = "POST /post HTTP/1.1\r\n"
  16621. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16622. "Content-Length: 1048576\r\n"
  16623. "\r\n" +
  16624. body;
  16625. std::string response;
  16626. ASSERT_TRUE(send_request(3, req, &response, port));
  16627. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16628. EXPECT_EQ("400", response.substr(9, 3));
  16629. }
  16630. // Posts a multipart body split into two writes, so that the server sees the
  16631. // split at whatever offset the caller chose, and expects the single "text1"
  16632. // field to come through.
  16633. static void expect_split_multipart_ok(const std::string &body1,
  16634. const std::string &body2) {
  16635. auto handled = false;
  16636. Server svr;
  16637. svr.Post("/post", [&](const Request &req, Response &) {
  16638. EXPECT_EQ(1u, req.form.fields.size());
  16639. EXPECT_EQ("text1", req.form.get_field("text1"));
  16640. handled = true;
  16641. });
  16642. auto port = svr.bind_to_any_port(HOST);
  16643. thread t = thread([&] { svr.listen_after_bind(); });
  16644. auto se = detail::scope_exit([&] {
  16645. svr.stop();
  16646. t.join();
  16647. ASSERT_FALSE(svr.is_running());
  16648. ASSERT_TRUE(handled);
  16649. });
  16650. svr.wait_until_ready();
  16651. // "Connection: close" makes the server close once it has answered, so the
  16652. // response drain ends immediately instead of idling until the read timeout.
  16653. const std::string head =
  16654. "POST /post HTTP/1.1\r\n"
  16655. "Host: localhost\r\n"
  16656. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16657. "Connection: close\r\n"
  16658. "Content-Length: " +
  16659. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16660. std::string response;
  16661. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16662. ASSERT_GE(response.size(), 12u) << "no response";
  16663. EXPECT_EQ("200", response.substr(9, 3));
  16664. }
  16665. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16666. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16667. // ignored, including when it does not arrive in the same read as the
  16668. // close-delimiter itself.
  16669. expect_split_multipart_ok("--zzzz\r\n"
  16670. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16671. "\r\n"
  16672. "text1"
  16673. "\r\n--zzzz--",
  16674. "\r\nthis epilogue must be ignored\r\n");
  16675. }
  16676. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16677. // The initial boundary may be preceded by a preamble of any length and may
  16678. // straddle a read boundary. Discarding data while waiting for it must not
  16679. // throw away a partial boundary sitting at the end of the buffer.
  16680. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16681. "zz\r\n"
  16682. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16683. "\r\n"
  16684. "text1"
  16685. "\r\n--zzzz--\r\n");
  16686. }
  16687. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16688. // The received boundary was only checked for being non-empty, so it could be
  16689. // as long as a header is allowed to be. The parser scans the body for
  16690. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16691. // costs a nearly full comparison at nearly every position, making the
  16692. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16693. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16694. Server svr;
  16695. svr.Post("/post", [](const Request &req, Response &res) {
  16696. EXPECT_EQ(1u, req.form.fields.size());
  16697. EXPECT_EQ("text1", req.form.get_field("text1"));
  16698. res.set_content("ok", "text/plain");
  16699. });
  16700. auto port = svr.bind_to_any_port(HOST);
  16701. thread t = thread([&] { svr.listen_after_bind(); });
  16702. auto se = detail::scope_exit([&] {
  16703. svr.stop();
  16704. t.join();
  16705. ASSERT_FALSE(svr.is_running());
  16706. });
  16707. svr.wait_until_ready();
  16708. Client cli(HOST, port);
  16709. auto post_with_boundary_of_length = [&](size_t len) {
  16710. const std::string boundary(len, 'a');
  16711. const std::string body =
  16712. "--" + boundary +
  16713. "\r\n"
  16714. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16715. "\r\n"
  16716. "text1"
  16717. "\r\n--" +
  16718. boundary + "--\r\n";
  16719. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16720. };
  16721. auto res = post_with_boundary_of_length(70);
  16722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16723. EXPECT_EQ(StatusCode::OK_200, res->status);
  16724. res = post_with_boundary_of_length(71);
  16725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16726. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16727. }
  16728. TEST(MakeFileBodyTest, Basic) {
  16729. const std::string file_content(4096, 'Z');
  16730. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16731. {
  16732. std::ofstream ofs(tmp_path, std::ios::binary);
  16733. ofs.write(file_content.data(),
  16734. static_cast<std::streamsize>(file_content.size()));
  16735. }
  16736. auto handled = false;
  16737. Server svr;
  16738. svr.Post("/upload", [&](const Request &req, Response &res) {
  16739. EXPECT_EQ(file_content, req.body);
  16740. handled = true;
  16741. res.status = StatusCode::OK_200;
  16742. });
  16743. auto port = svr.bind_to_any_port(HOST);
  16744. auto t = thread([&] { svr.listen_after_bind(); });
  16745. auto se = detail::scope_exit([&] {
  16746. svr.stop();
  16747. t.join();
  16748. ASSERT_FALSE(svr.is_running());
  16749. ASSERT_TRUE(handled);
  16750. std::remove(tmp_path.c_str());
  16751. });
  16752. svr.wait_until_ready();
  16753. auto fb = make_file_body(tmp_path);
  16754. ASSERT_GT(fb.first, 0u);
  16755. Client cli(HOST, port);
  16756. auto res =
  16757. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16759. EXPECT_EQ(StatusCode::OK_200, res->status);
  16760. }
  16761. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16762. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16763. {
  16764. std::ofstream ofs(path, std::ios::binary);
  16765. const std::string content(100, 'A');
  16766. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16767. }
  16768. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16769. auto body = make_file_body(path);
  16770. ASSERT_EQ(100u, body.first);
  16771. ASSERT_TRUE(static_cast<bool>(body.second));
  16772. // Rewritten shorter after its length was measured - and, on a server, after
  16773. // that length has already gone out as Content-Length.
  16774. {
  16775. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16776. const std::string content(10, 'A');
  16777. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16778. }
  16779. std::string written;
  16780. DataSink sink;
  16781. sink.write = [&](const char *d, size_t l) {
  16782. written.append(d, l);
  16783. return true;
  16784. };
  16785. // The provider has to report failure. write_content_with_progress() advances
  16786. // its offset only by what was written, so a provider that returns true
  16787. // without completing the length it promised is called again straight away,
  16788. // and again.
  16789. EXPECT_FALSE(body.second(0, body.first, sink));
  16790. EXPECT_EQ(std::string(10, 'A'), written);
  16791. }
  16792. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16793. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16794. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16795. {
  16796. std::ofstream ofs(path, std::ios::binary);
  16797. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16798. }
  16799. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16800. auto body = make_file_body(path);
  16801. ASSERT_EQ(content.size(), body.first);
  16802. ASSERT_TRUE(static_cast<bool>(body.second));
  16803. std::string written;
  16804. DataSink sink;
  16805. sink.write = [&](const char *d, size_t l) {
  16806. written.append(d, l);
  16807. return true;
  16808. };
  16809. EXPECT_TRUE(body.second(0, body.first, sink));
  16810. EXPECT_EQ(content, written);
  16811. }
  16812. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16813. static constexpr unsigned int number_of_tasks{1000000};
  16814. std::atomic_uint count{0};
  16815. std::unique_ptr<TaskQueue> task_queue{
  16816. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16817. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16818. auto queued = task_queue->enqueue(
  16819. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16820. EXPECT_TRUE(queued);
  16821. }
  16822. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16823. task_queue->shutdown();
  16824. #else
  16825. EXPECT_NO_THROW(task_queue->shutdown());
  16826. #endif
  16827. EXPECT_EQ(number_of_tasks, count.load());
  16828. }
  16829. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16830. static constexpr unsigned int number_of_tasks{1000000};
  16831. static constexpr unsigned int qlimit{2};
  16832. unsigned int queued_count{0};
  16833. std::atomic_uint count{0};
  16834. std::unique_ptr<TaskQueue> task_queue{
  16835. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16836. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16837. if (task_queue->enqueue(
  16838. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16839. queued_count++;
  16840. }
  16841. }
  16842. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16843. task_queue->shutdown();
  16844. #else
  16845. EXPECT_NO_THROW(task_queue->shutdown());
  16846. #endif
  16847. EXPECT_EQ(queued_count, count.load());
  16848. EXPECT_TRUE(queued_count <= number_of_tasks);
  16849. EXPECT_TRUE(queued_count >= qlimit);
  16850. }
  16851. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16852. // Use a short idle timeout so a dynamic thread spawns, times out and
  16853. // exits during the test, and the pool keeps working afterwards.
  16854. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16855. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16856. /*idle_timeout_sec=*/1}};
  16857. std::atomic_uint count{0};
  16858. std::condition_variable cv;
  16859. std::mutex mtx;
  16860. bool release = false;
  16861. // Block the base thread so the second task spawns a dynamic thread.
  16862. EXPECT_TRUE(task_queue->enqueue([&] {
  16863. std::unique_lock<std::mutex> lock(mtx);
  16864. while (!release) {
  16865. cv.wait(lock);
  16866. }
  16867. count++;
  16868. }));
  16869. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16870. // Let the dynamic thread finish its task and exceed the idle timeout.
  16871. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16872. {
  16873. std::unique_lock<std::mutex> lock(mtx);
  16874. release = true;
  16875. }
  16876. cv.notify_all();
  16877. // The pool must still accept and run tasks after the dynamic thread exited.
  16878. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16879. task_queue->shutdown();
  16880. EXPECT_EQ(3u, count.load());
  16881. }
  16882. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16883. static constexpr size_t number_of_tasks{32};
  16884. std::unique_ptr<TaskQueue> task_queue{
  16885. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16886. // Let the base threads go idle so the burst below finds them waiting.
  16887. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16888. std::mutex mtx;
  16889. std::condition_variable cv;
  16890. size_t running = 0;
  16891. bool release = false;
  16892. for (size_t i = 0; i < number_of_tasks; i++) {
  16893. EXPECT_TRUE(task_queue->enqueue([&] {
  16894. std::unique_lock<std::mutex> lock(mtx);
  16895. running++;
  16896. cv.notify_all();
  16897. cv.wait(lock, [&] { return release; });
  16898. }));
  16899. }
  16900. {
  16901. std::unique_lock<std::mutex> lock(mtx);
  16902. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16903. [&] { return running == number_of_tasks; }));
  16904. release = true;
  16905. }
  16906. cv.notify_all();
  16907. task_queue->shutdown();
  16908. }
  16909. TEST(TaskQueueTest, MaxQueuedRequests) {
  16910. static constexpr unsigned int qlimit{3};
  16911. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16912. std::condition_variable sem_cv;
  16913. std::mutex sem_mtx;
  16914. int credits = 0;
  16915. bool queued;
  16916. /* Fill up the queue with tasks that will block until we give them credits to
  16917. * complete. */
  16918. for (unsigned int n = 0; n <= qlimit;) {
  16919. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16920. std::unique_lock<std::mutex> lock(sem_mtx);
  16921. while (credits <= 0) {
  16922. sem_cv.wait(lock);
  16923. }
  16924. /* Consume the credit and signal the test code if they are all gone. */
  16925. if (--credits == 0) { sem_cv.notify_one(); }
  16926. });
  16927. if (n < qlimit) {
  16928. /* The first qlimit enqueues must succeed. */
  16929. EXPECT_TRUE(queued);
  16930. } else {
  16931. /* The last one will succeed only when the worker thread
  16932. * starts and dequeues the first blocking task. Although
  16933. * not necessary for the correctness of this test, we sleep for
  16934. * a short while to avoid busy waiting. */
  16935. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16936. }
  16937. if (queued) { n++; }
  16938. }
  16939. /* Further enqueues must fail since the queue is full. */
  16940. for (auto i = 0; i < 4; i++) {
  16941. queued = task_queue->enqueue([] {});
  16942. EXPECT_FALSE(queued);
  16943. }
  16944. /* Give the credits to allow the previous tasks to complete. */
  16945. {
  16946. std::unique_lock<std::mutex> lock(sem_mtx);
  16947. credits += qlimit + 1;
  16948. }
  16949. sem_cv.notify_all();
  16950. /* Wait for all the credits to be consumed. */
  16951. {
  16952. std::unique_lock<std::mutex> lock(sem_mtx);
  16953. while (credits > 0) {
  16954. sem_cv.wait(lock);
  16955. }
  16956. }
  16957. /* Check that we are able again to enqueue at least qlimit tasks. */
  16958. for (unsigned int i = 0; i < qlimit; i++) {
  16959. queued = task_queue->enqueue([] {});
  16960. EXPECT_TRUE(queued);
  16961. }
  16962. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16963. task_queue->shutdown();
  16964. #else
  16965. EXPECT_NO_THROW(task_queue->shutdown());
  16966. #endif
  16967. }
  16968. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16969. Server svr;
  16970. std::string method;
  16971. std::string body;
  16972. auto has_content_length = false;
  16973. auto has_transfer_encoding = false;
  16974. std::atomic<int> bad_requests{0};
  16975. // Leftover body bytes get parsed as a malformed request and answered with
  16976. // 400
  16977. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16978. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16979. });
  16980. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16981. res.set_redirect("/down", StatusCode::SeeOther_303);
  16982. });
  16983. svr.Get("/down", [&](const Request &req, Response &res) {
  16984. method = req.method;
  16985. body = req.body;
  16986. has_content_length = req.has_header("Content-Length");
  16987. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16988. res.set_content("ok", "text/plain");
  16989. });
  16990. auto port = svr.bind_to_any_port(HOST);
  16991. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16992. auto se = detail::scope_exit([&] {
  16993. svr.stop();
  16994. thread.join();
  16995. ASSERT_FALSE(svr.is_running());
  16996. });
  16997. svr.wait_until_ready();
  16998. const std::string payload = "SECRET-BODY";
  16999. auto check = [&](Client &cli, const Result &res) {
  17000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17001. EXPECT_EQ(StatusCode::OK_200, res->status);
  17002. EXPECT_EQ("ok", res->body);
  17003. EXPECT_EQ("GET", method);
  17004. EXPECT_TRUE(body.empty());
  17005. EXPECT_FALSE(has_content_length);
  17006. EXPECT_FALSE(has_transfer_encoding);
  17007. // Nothing of the original body may be left on the connection
  17008. auto res2 = cli.Get("/down");
  17009. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17010. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17011. EXPECT_EQ("ok", res2->body);
  17012. EXPECT_EQ(0, bad_requests);
  17013. };
  17014. // With content length
  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", payload.size(),
  17021. [&](size_t offset, size_t length, DataSink &sink) {
  17022. return sink.write(payload.data() + offset, length);
  17023. },
  17024. "text/plain");
  17025. check(cli, res);
  17026. }
  17027. // Without content length (chunked)
  17028. {
  17029. Client cli(HOST, port);
  17030. cli.set_keep_alive(true);
  17031. cli.set_follow_location(true);
  17032. auto res = cli.Post(
  17033. "/up",
  17034. [&](size_t /*offset*/, DataSink &sink) {
  17035. sink.write(payload.data(), payload.size());
  17036. sink.done();
  17037. return true;
  17038. },
  17039. "text/plain");
  17040. check(cli, res);
  17041. }
  17042. }
  17043. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17044. Server svr;
  17045. std::string target;
  17046. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17047. // Echo the still-encoded name back in the Location
  17048. const std::string prefix = "/start/";
  17049. res.status = StatusCode::Found_302;
  17050. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17051. });
  17052. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17053. target = req.target;
  17054. res.set_content("ok", "text/plain");
  17055. });
  17056. auto port = svr.bind_to_any_port(HOST);
  17057. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17058. auto se = detail::scope_exit([&] {
  17059. svr.stop();
  17060. thread.join();
  17061. ASSERT_FALSE(svr.is_running());
  17062. });
  17063. svr.wait_until_ready();
  17064. // Decoding the Location path would turn the first four into a path
  17065. // separator, a query delimiter, a fragment delimiter and a different
  17066. // percent-encoded octet. The rest must keep reaching the server as they are.
  17067. const std::vector<std::string> names = {
  17068. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17069. };
  17070. for (auto path_encode : {true, false}) {
  17071. Client cli(HOST, port);
  17072. cli.set_follow_location(true);
  17073. cli.set_path_encode(path_encode);
  17074. for (const auto &name : names) {
  17075. target.clear();
  17076. auto res = cli.Get("/start/" + name);
  17077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17078. EXPECT_EQ(StatusCode::OK_200, res->status);
  17079. EXPECT_EQ("/dest/" + name, target);
  17080. }
  17081. }
  17082. }
  17083. TEST(RedirectTest, NotModifiedIsReturned) {
  17084. Server svr;
  17085. svr.Get("/cached", [](const Request &, Response &res) {
  17086. res.status = StatusCode::NotModified_304;
  17087. });
  17088. auto port = svr.bind_to_any_port(HOST);
  17089. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17090. auto se = detail::scope_exit([&] {
  17091. svr.stop();
  17092. thread.join();
  17093. ASSERT_FALSE(svr.is_running());
  17094. });
  17095. svr.wait_until_ready();
  17096. Client cli(HOST, port);
  17097. cli.set_follow_location(true);
  17098. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17100. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17101. }
  17102. TEST(RedirectTest, NoLocationIsReturned) {
  17103. Server svr;
  17104. svr.Get("/no-location", [](const Request &, Response &res) {
  17105. res.status = StatusCode::Found_302;
  17106. res.set_content("no location", "text/plain");
  17107. });
  17108. auto port = svr.bind_to_any_port(HOST);
  17109. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17110. auto se = detail::scope_exit([&] {
  17111. svr.stop();
  17112. thread.join();
  17113. ASSERT_FALSE(svr.is_running());
  17114. });
  17115. svr.wait_until_ready();
  17116. Client cli(HOST, port);
  17117. cli.set_follow_location(true);
  17118. auto res = cli.Get("/no-location");
  17119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17120. EXPECT_EQ(StatusCode::Found_302, res->status);
  17121. EXPECT_EQ("no location", res->body);
  17122. // The callbacks see the body of the response that is returned
  17123. auto handler_called = false;
  17124. auto progress_called = false;
  17125. std::string body;
  17126. auto res2 = cli.Get(
  17127. "/no-location",
  17128. [&](const Response &) {
  17129. handler_called = true;
  17130. return true;
  17131. },
  17132. [&](const char *data, size_t data_length) {
  17133. body.append(data, data_length);
  17134. return true;
  17135. },
  17136. [&](size_t, size_t) {
  17137. progress_called = true;
  17138. return true;
  17139. });
  17140. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17141. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17142. EXPECT_TRUE(handler_called);
  17143. EXPECT_TRUE(progress_called);
  17144. EXPECT_EQ("no location", body);
  17145. }
  17146. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17147. Server svr;
  17148. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17149. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17150. });
  17151. svr.Get("/hello", [](const Request &req, Response &res) {
  17152. res.set_content(req.get_param_value("key"), "text/plain");
  17153. });
  17154. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17155. auto se = detail::scope_exit([&] {
  17156. svr.stop();
  17157. thread.join();
  17158. ASSERT_FALSE(svr.is_running());
  17159. });
  17160. svr.wait_until_ready();
  17161. {
  17162. Client cli(HOST, PORT);
  17163. cli.set_follow_location(true);
  17164. auto res = cli.Get("/");
  17165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17166. EXPECT_EQ(StatusCode::OK_200, res->status);
  17167. EXPECT_EQ("val&key2=val2", res->body);
  17168. }
  17169. }
  17170. #endif
  17171. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17172. Server svr;
  17173. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17174. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17175. });
  17176. svr.Get("/hello", [](const Request &req, Response &res) {
  17177. res.set_content(req.get_param_value("key"), "text/plain");
  17178. });
  17179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17180. auto se = detail::scope_exit([&] {
  17181. svr.stop();
  17182. thread.join();
  17183. ASSERT_FALSE(svr.is_running());
  17184. });
  17185. svr.wait_until_ready();
  17186. {
  17187. Client cli(HOST, PORT);
  17188. cli.set_follow_location(true);
  17189. auto res = cli.Get("/");
  17190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17191. EXPECT_EQ(StatusCode::OK_200, res->status);
  17192. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17193. }
  17194. }
  17195. TEST(RedirectTest, RedirectWithPlusInPath) {
  17196. Server svr;
  17197. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17198. res.set_redirect("/a+b");
  17199. });
  17200. // Route pattern uses regex; escape + as \\+
  17201. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17202. res.set_content(req.path, "text/plain");
  17203. });
  17204. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17205. auto se = detail::scope_exit([&] {
  17206. svr.stop();
  17207. thread.join();
  17208. ASSERT_FALSE(svr.is_running());
  17209. });
  17210. svr.wait_until_ready();
  17211. {
  17212. Client cli(HOST, PORT);
  17213. cli.set_follow_location(true);
  17214. auto res = cli.Get("/");
  17215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17216. EXPECT_EQ(StatusCode::OK_200, res->status);
  17217. EXPECT_EQ("/a+b", res->body);
  17218. }
  17219. }
  17220. TEST(RedirectTest, ResolveRelativeLocation) {
  17221. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17222. const std::vector<std::pair<std::string, std::string>> cases = {
  17223. {"g", "/b/c/g"},
  17224. {"./g", "/b/c/g"},
  17225. {"g/", "/b/c/g/"},
  17226. {"?y", "/b/c/d;p?y"},
  17227. {"g?y", "/b/c/g?y"},
  17228. {"#s", "/b/c/d;p?q#s"},
  17229. {"g#s", "/b/c/g#s"},
  17230. {"g?y#s", "/b/c/g?y#s"},
  17231. {";x", "/b/c/;x"},
  17232. {"g;x", "/b/c/g;x"},
  17233. {".", "/b/c/"},
  17234. {"./", "/b/c/"},
  17235. {"..", "/b/"},
  17236. {"../", "/b/"},
  17237. {"../g", "/b/g"},
  17238. {"../..", "/"},
  17239. {"../../", "/"},
  17240. {"../../g", "/g"},
  17241. {"../../../g", "/g"},
  17242. {"g.", "/b/c/g."},
  17243. {".g", "/b/c/.g"},
  17244. {"g..", "/b/c/g.."},
  17245. {"..g", "/b/c/..g"},
  17246. {"./../g", "/b/g"},
  17247. {"./g/.", "/b/c/g/"},
  17248. {"g/./h", "/b/c/g/h"},
  17249. {"g/../h", "/b/c/h"},
  17250. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17251. {"g;x=1/../y", "/b/c/y"},
  17252. {"g?y/./x", "/b/c/g?y/./x"},
  17253. {"g#s/../x", "/b/c/g#s/../x"},
  17254. // Not relative-path references, so left for parse_url.
  17255. {"/g", "/g"},
  17256. {"//g", "//g"},
  17257. {"http://g/x", "http://g/x"},
  17258. {"g:h", "g:h"},
  17259. };
  17260. for (const auto &c : cases) {
  17261. EXPECT_EQ(c.second,
  17262. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17263. << c.first;
  17264. }
  17265. }
  17266. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17267. Server svr;
  17268. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17269. res.set_redirect(req.get_param_value("to"));
  17270. });
  17271. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17272. res.set_content(req.target, "text/plain");
  17273. });
  17274. svr.Get("/other", [](const Request &req, Response &res) {
  17275. res.set_content(req.target, "text/plain");
  17276. });
  17277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17278. auto se = detail::scope_exit([&] {
  17279. svr.stop();
  17280. thread.join();
  17281. ASSERT_FALSE(svr.is_running());
  17282. });
  17283. svr.wait_until_ready();
  17284. const std::vector<std::pair<std::string, std::string>> cases = {
  17285. {"next", "/dir/next"},
  17286. {"./next?x=1", "/dir/next?x=1"},
  17287. {"../other", "/other"},
  17288. };
  17289. for (const auto &c : cases) {
  17290. Client cli(HOST, PORT);
  17291. cli.set_follow_location(true);
  17292. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17293. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17294. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17295. EXPECT_EQ(c.second, res->body) << c.first;
  17296. }
  17297. }
  17298. #ifdef CPPHTTPLIB_SSL_ENABLED
  17299. TEST(RedirectTest, Issue2185_Online) {
  17300. SSLClient client("github.com");
  17301. client.set_follow_location(true);
  17302. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17303. "Coollab-Windows.zip");
  17304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17305. EXPECT_EQ(StatusCode::OK_200, res->status);
  17306. EXPECT_EQ(9920427U, res->body.size());
  17307. }
  17308. #endif
  17309. TEST(VulnerabilityTest, CRLFInjection) {
  17310. Server svr;
  17311. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17312. res.set_content("Hello 1", "text/plain");
  17313. });
  17314. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17315. res.set_content("Hello 2", "text/plain");
  17316. });
  17317. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17318. res.set_content("Hello 3", "text/plain");
  17319. });
  17320. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17321. res.set_content("Hello 4", "text/plain");
  17322. });
  17323. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17324. for (const auto &x : req.headers) {
  17325. auto key = x.first;
  17326. EXPECT_STRNE("evil", key.c_str());
  17327. }
  17328. });
  17329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17330. auto se = detail::scope_exit([&] {
  17331. svr.stop();
  17332. thread.join();
  17333. ASSERT_FALSE(svr.is_running());
  17334. });
  17335. svr.wait_until_ready();
  17336. {
  17337. Client cli(HOST, PORT);
  17338. cli.Post("/test1", "A=B",
  17339. "application/x-www-form-urlencoded\r\nevil: hello1");
  17340. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17341. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17342. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17343. }
  17344. }
  17345. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17346. auto server_thread = std::thread([] {
  17347. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17348. default_socket_options(srv);
  17349. sockaddr_in addr{};
  17350. addr.sin_family = AF_INET;
  17351. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17352. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17353. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17354. ::listen(srv, 1);
  17355. sockaddr_in cli_addr{};
  17356. socklen_t cli_len = sizeof(cli_addr);
  17357. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17358. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17359. std::string buf_all;
  17360. char buf[2048];
  17361. ssize_t n;
  17362. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17363. buf_all.append(buf, static_cast<size_t>(n));
  17364. size_t pos;
  17365. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17366. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17367. auto e = request_block.find("\r\n");
  17368. if (e != std::string::npos) {
  17369. auto request_line = request_block.substr(0, e);
  17370. std::string msg =
  17371. "CRLF injection detected in request line: '" + request_line + "'";
  17372. EXPECT_FALSE(true) << msg;
  17373. }
  17374. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17375. ::send(cli,
  17376. #ifdef _WIN32
  17377. static_cast<const char *>(resp.c_str()),
  17378. static_cast<int>(resp.size()),
  17379. #else
  17380. resp.c_str(), resp.size(),
  17381. #endif
  17382. 0);
  17383. buf_all.erase(0, pos + 4);
  17384. }
  17385. }
  17386. detail::close_socket(cli);
  17387. detail::close_socket(srv);
  17388. });
  17389. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17390. auto cli = Client("127.0.0.1", PORT + 1);
  17391. auto headers = Headers{
  17392. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17393. {"Connection", "keep-alive"}};
  17394. auto res = cli.Get("/hi", headers);
  17395. EXPECT_FALSE(res);
  17396. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17397. server_thread.join();
  17398. }
  17399. // A request rejected before any byte reaches the socket must fail right away
  17400. // instead of waiting for a response the server will never send.
  17401. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17402. // The kernel completes the TCP handshake from the listen backlog, so the
  17403. // client connects, but nothing ever reads, responds or closes.
  17404. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17405. default_socket_options(srv);
  17406. sockaddr_in addr{};
  17407. addr.sin_family = AF_INET;
  17408. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17409. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17410. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17411. ASSERT_EQ(0, ::listen(srv, 8));
  17412. auto cli = Client("127.0.0.1", PORT + 1);
  17413. cli.set_read_timeout(10, 0);
  17414. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17415. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17416. std::chrono::steady_clock::now() - start)
  17417. .count();
  17418. };
  17419. {
  17420. Request req;
  17421. req.method = "GE T";
  17422. req.path = "/";
  17423. auto start = std::chrono::steady_clock::now();
  17424. auto res = cli.send(req);
  17425. EXPECT_FALSE(res);
  17426. EXPECT_EQ(Error::Write, res.error());
  17427. EXPECT_LT(elapsed_ms(start), 1000);
  17428. }
  17429. {
  17430. auto start = std::chrono::steady_clock::now();
  17431. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17432. EXPECT_FALSE(res);
  17433. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17434. EXPECT_LT(elapsed_ms(start), 1000);
  17435. }
  17436. EXPECT_FALSE(cli.is_socket_open());
  17437. detail::close_socket(srv);
  17438. }
  17439. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17440. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17441. default_socket_options(srv);
  17442. sockaddr_in addr{};
  17443. addr.sin_family = AF_INET;
  17444. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17445. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17446. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17447. ASSERT_EQ(0, ::listen(srv, 1));
  17448. std::string received;
  17449. auto server_thread = std::thread([&] {
  17450. auto sock = ::accept(srv, nullptr, nullptr);
  17451. if (sock == INVALID_SOCKET) { return; }
  17452. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17453. char buf[2048];
  17454. ssize_t n;
  17455. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17456. received.append(buf, static_cast<size_t>(n));
  17457. }
  17458. detail::close_socket(sock);
  17459. });
  17460. {
  17461. auto cli = Client("127.0.0.1", PORT + 1);
  17462. // "Z" sorts after the default headers, so writing straight to the socket
  17463. // would have sent the request line and those headers before the rejection.
  17464. auto handle =
  17465. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17466. EXPECT_FALSE(handle.is_valid());
  17467. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17468. }
  17469. server_thread.join();
  17470. detail::close_socket(srv);
  17471. EXPECT_TRUE(received.empty()) << received;
  17472. }
  17473. TEST(PathParamsTest, StaticMatch) {
  17474. const auto pattern = "/users/all";
  17475. detail::PathParamsMatcher matcher(pattern);
  17476. Request request;
  17477. request.path = "/users/all";
  17478. ASSERT_TRUE(matcher.match(request));
  17479. std::unordered_map<std::string, std::string> expected_params = {};
  17480. EXPECT_EQ(request.path_params, expected_params);
  17481. }
  17482. TEST(PathParamsTest, StaticMismatch) {
  17483. const auto pattern = "/users/all";
  17484. detail::PathParamsMatcher matcher(pattern);
  17485. Request request;
  17486. request.path = "/users/1";
  17487. ASSERT_FALSE(matcher.match(request));
  17488. }
  17489. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17490. const auto pattern = "/users/:id/subscriptions";
  17491. detail::PathParamsMatcher matcher(pattern);
  17492. Request request;
  17493. request.path = "/users/42/subscriptions";
  17494. ASSERT_TRUE(matcher.match(request));
  17495. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17496. EXPECT_EQ(request.path_params, expected_params);
  17497. }
  17498. TEST(PathParamsTest, SingleParamInTheEnd) {
  17499. const auto pattern = "/users/:id";
  17500. detail::PathParamsMatcher matcher(pattern);
  17501. Request request;
  17502. request.path = "/users/24";
  17503. ASSERT_TRUE(matcher.match(request));
  17504. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17505. EXPECT_EQ(request.path_params, expected_params);
  17506. }
  17507. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17508. const auto pattern = "/users/:id/";
  17509. detail::PathParamsMatcher matcher(pattern);
  17510. Request request;
  17511. request.path = "/users/42/";
  17512. ASSERT_TRUE(matcher.match(request));
  17513. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17514. EXPECT_EQ(request.path_params, expected_params);
  17515. }
  17516. TEST(PathParamsTest, EmptyParam) {
  17517. const auto pattern = "/users/:id/";
  17518. detail::PathParamsMatcher matcher(pattern);
  17519. Request request;
  17520. request.path = "/users//";
  17521. ASSERT_TRUE(matcher.match(request));
  17522. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17523. EXPECT_EQ(request.path_params, expected_params);
  17524. }
  17525. TEST(PathParamsTest, FragmentMismatch) {
  17526. const auto pattern = "/users/:id/";
  17527. detail::PathParamsMatcher matcher(pattern);
  17528. Request request;
  17529. request.path = "/admins/24/";
  17530. ASSERT_FALSE(matcher.match(request));
  17531. }
  17532. TEST(PathParamsTest, ExtraFragments) {
  17533. const auto pattern = "/users/:id";
  17534. detail::PathParamsMatcher matcher(pattern);
  17535. Request request;
  17536. request.path = "/users/42/subscriptions";
  17537. ASSERT_FALSE(matcher.match(request));
  17538. }
  17539. TEST(PathParamsTest, MissingTrailingParam) {
  17540. const auto pattern = "/users/:id";
  17541. detail::PathParamsMatcher matcher(pattern);
  17542. Request request;
  17543. request.path = "/users";
  17544. ASSERT_FALSE(matcher.match(request));
  17545. }
  17546. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17547. const auto pattern = "/users/:id/subscriptions";
  17548. detail::PathParamsMatcher matcher(pattern);
  17549. Request request;
  17550. request.path = "/users/subscriptions";
  17551. ASSERT_FALSE(matcher.match(request));
  17552. }
  17553. TEST(PathParamsTest, MultipleParams) {
  17554. const auto pattern = "/users/:userid/subscriptions/:subid";
  17555. detail::PathParamsMatcher matcher(pattern);
  17556. Request request;
  17557. request.path = "/users/42/subscriptions/2";
  17558. ASSERT_TRUE(matcher.match(request));
  17559. std::unordered_map<std::string, std::string> expected_params = {
  17560. {"userid", "42"}, {"subid", "2"}};
  17561. EXPECT_EQ(request.path_params, expected_params);
  17562. }
  17563. TEST(PathParamsTest, SequenceOfParams) {
  17564. const auto pattern = "/values/:x/:y/:z";
  17565. detail::PathParamsMatcher matcher(pattern);
  17566. Request request;
  17567. request.path = "/values/1/2/3";
  17568. ASSERT_TRUE(matcher.match(request));
  17569. std::unordered_map<std::string, std::string> expected_params = {
  17570. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17571. EXPECT_EQ(request.path_params, expected_params);
  17572. }
  17573. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17574. const auto pattern = "/prefix:suffix";
  17575. detail::PathParamsMatcher matcher(pattern);
  17576. Request request;
  17577. request.path = "/prefix:suffix";
  17578. ASSERT_TRUE(matcher.match(request));
  17579. const std::unordered_map<std::string, std::string> expected_params = {};
  17580. EXPECT_EQ(request.path_params, expected_params);
  17581. }
  17582. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17583. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17584. // calling thread's stack on a long enough path for a quantified pattern;
  17585. // RegexMatcher must refuse to run regex matching on paths beyond
  17586. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17587. detail::RegexMatcher matcher("/files/(.*)");
  17588. Request within_limit;
  17589. within_limit.path = "/files/" + std::string(10, 'A');
  17590. EXPECT_TRUE(matcher.match(within_limit));
  17591. Request over_limit;
  17592. over_limit.path =
  17593. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17594. EXPECT_FALSE(matcher.match(over_limit));
  17595. }
  17596. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17597. Server svr;
  17598. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17599. res.set_content("ok", "text/plain");
  17600. });
  17601. auto port = svr.bind_to_any_port(HOST);
  17602. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17603. auto se = detail::scope_exit([&] {
  17604. svr.stop();
  17605. thread.join();
  17606. ASSERT_FALSE(svr.is_running());
  17607. });
  17608. svr.wait_until_ready();
  17609. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17610. // request URI limit; this used to be able to crash the process.
  17611. std::string path =
  17612. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17613. std::string req = "GET " + path +
  17614. " HTTP/1.1\r\n"
  17615. "Host: " +
  17616. std::string(HOST) + ":" + std::to_string(port) +
  17617. "\r\n"
  17618. "Connection: close\r\n"
  17619. "\r\n";
  17620. std::string response;
  17621. ASSERT_TRUE(send_request(5, req, &response, port));
  17622. EXPECT_NE(std::string::npos, response.find("404"));
  17623. }
  17624. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17625. Server svr;
  17626. auto handler = [](const Request & /*req*/, Response &res) {
  17627. res.set_content("hit", "text/plain");
  17628. };
  17629. // No regex metacharacter, so this one is compared literally
  17630. svr.Get("/literal/route", handler);
  17631. // '.' is a regex metacharacter, so this one must keep regex semantics
  17632. svr.Get("/a.c", handler);
  17633. auto port = svr.bind_to_any_port(HOST);
  17634. std::thread t([&]() { svr.listen_after_bind(); });
  17635. auto se = detail::scope_exit([&] {
  17636. svr.stop();
  17637. t.join();
  17638. ASSERT_FALSE(svr.is_running());
  17639. });
  17640. svr.wait_until_ready();
  17641. Client cli(HOST, port);
  17642. struct {
  17643. const char *path;
  17644. int status;
  17645. } cases[] = {
  17646. {"/literal/route", StatusCode::OK_200},
  17647. {"/literal/routes", StatusCode::NotFound_404},
  17648. {"/literal/rout", StatusCode::NotFound_404},
  17649. {"/abc", StatusCode::OK_200},
  17650. {"/a.c", StatusCode::OK_200},
  17651. };
  17652. for (const auto &x : cases) {
  17653. auto res = cli.Get(x.path);
  17654. ASSERT_TRUE(res) << x.path;
  17655. EXPECT_EQ(x.status, res->status) << x.path;
  17656. }
  17657. }
  17658. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17659. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17660. // from exhausting the stack, so it must only constrain routes that actually
  17661. // run a regular expression. A literal route is matched by comparison and
  17662. // stays usable at any length.
  17663. Server svr;
  17664. const std::string pattern =
  17665. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17666. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17667. res.set_content("hit", "text/plain");
  17668. });
  17669. auto port = svr.bind_to_any_port(HOST);
  17670. std::thread t([&]() { svr.listen_after_bind(); });
  17671. auto se = detail::scope_exit([&] {
  17672. svr.stop();
  17673. t.join();
  17674. ASSERT_FALSE(svr.is_running());
  17675. });
  17676. svr.wait_until_ready();
  17677. Client cli(HOST, port);
  17678. auto res = cli.Get(pattern);
  17679. ASSERT_TRUE(res);
  17680. EXPECT_EQ(StatusCode::OK_200, res->status);
  17681. }
  17682. TEST(ParseUrlTest, VariousPatterns) {
  17683. {
  17684. detail::UrlComponents uc;
  17685. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17686. EXPECT_EQ("http", uc.scheme);
  17687. EXPECT_EQ("example.com", uc.host);
  17688. EXPECT_EQ("8080", uc.port);
  17689. EXPECT_EQ("/path", uc.path);
  17690. EXPECT_EQ("?q=1", uc.query);
  17691. }
  17692. {
  17693. detail::UrlComponents uc;
  17694. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17695. EXPECT_EQ("https", uc.scheme);
  17696. EXPECT_EQ("example.com", uc.host);
  17697. EXPECT_TRUE(uc.port.empty());
  17698. EXPECT_EQ("/path", uc.path);
  17699. }
  17700. {
  17701. detail::UrlComponents uc;
  17702. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17703. EXPECT_EQ("::1", uc.host);
  17704. EXPECT_EQ("8080", uc.port);
  17705. EXPECT_EQ("/path", uc.path);
  17706. }
  17707. {
  17708. detail::UrlComponents uc;
  17709. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17710. }
  17711. {
  17712. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17713. // the path while the connection still targets the bracketed host.
  17714. detail::UrlComponents uc;
  17715. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17716. }
  17717. {
  17718. detail::UrlComponents uc;
  17719. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17720. }
  17721. {
  17722. detail::UrlComponents uc;
  17723. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17724. EXPECT_EQ("::1", uc.host);
  17725. EXPECT_TRUE(uc.port.empty());
  17726. EXPECT_EQ("/path", uc.path);
  17727. }
  17728. {
  17729. detail::UrlComponents uc;
  17730. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17731. EXPECT_TRUE(uc.scheme.empty());
  17732. EXPECT_EQ("example.com", uc.host);
  17733. EXPECT_EQ("/path", uc.path);
  17734. EXPECT_EQ("?q=1", uc.query);
  17735. }
  17736. {
  17737. detail::UrlComponents uc;
  17738. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17739. EXPECT_TRUE(uc.host.empty());
  17740. EXPECT_EQ("/path", uc.path);
  17741. EXPECT_EQ("?q=1", uc.query);
  17742. }
  17743. {
  17744. detail::UrlComponents uc;
  17745. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17746. EXPECT_EQ("example.com", uc.host);
  17747. EXPECT_EQ("8080", uc.port);
  17748. }
  17749. {
  17750. // Unix socket path — must not be parsed as host
  17751. detail::UrlComponents uc;
  17752. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17753. EXPECT_TRUE(uc.host.empty());
  17754. }
  17755. {
  17756. detail::UrlComponents uc;
  17757. ASSERT_TRUE(detail::parse_url("", uc));
  17758. EXPECT_TRUE(uc.host.empty());
  17759. EXPECT_TRUE(uc.path.empty());
  17760. }
  17761. {
  17762. detail::UrlComponents uc;
  17763. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17764. }
  17765. {
  17766. detail::UrlComponents uc;
  17767. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17768. }
  17769. {
  17770. // Accepted by parse_url; callers restrict to http/https
  17771. detail::UrlComponents uc;
  17772. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17773. EXPECT_EQ("ftp", uc.scheme);
  17774. }
  17775. {
  17776. detail::UrlComponents uc;
  17777. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17778. }
  17779. {
  17780. detail::UrlComponents uc;
  17781. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17782. }
  17783. }
  17784. TEST(ParseUrlTest, FragmentHandling) {
  17785. {
  17786. detail::UrlComponents uc;
  17787. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17788. EXPECT_EQ("/path", uc.path);
  17789. EXPECT_TRUE(uc.query.empty());
  17790. }
  17791. {
  17792. detail::UrlComponents uc;
  17793. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17794. EXPECT_TRUE(uc.path.empty());
  17795. EXPECT_TRUE(uc.query.empty());
  17796. }
  17797. }
  17798. TEST(ParseUrlTest, UserinfoHandling) {
  17799. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17800. // parsers would see evil.com as the host.
  17801. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17802. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17803. for (auto url : urls) {
  17804. detail::UrlComponents uc;
  17805. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17806. }
  17807. }
  17808. TEST(ParseUrlTest, IPv6EdgeCases) {
  17809. {
  17810. detail::UrlComponents uc;
  17811. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17812. EXPECT_TRUE(uc.scheme.empty());
  17813. EXPECT_EQ("::1", uc.host);
  17814. EXPECT_EQ("8080", uc.port);
  17815. }
  17816. {
  17817. // Zone ID '%25' is not in [a-fA-F0-9:]
  17818. detail::UrlComponents uc;
  17819. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17820. }
  17821. }
  17822. TEST(ParseUrlTest, SchemeEdgeCases) {
  17823. {
  17824. detail::UrlComponents uc;
  17825. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17826. }
  17827. {
  17828. detail::UrlComponents uc;
  17829. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17830. }
  17831. {
  17832. detail::UrlComponents uc;
  17833. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17834. }
  17835. }
  17836. TEST(ParseUrlTest, PortEdgeCases) {
  17837. {
  17838. detail::UrlComponents uc;
  17839. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17840. EXPECT_TRUE(uc.port.empty());
  17841. EXPECT_EQ("/path", uc.path);
  17842. }
  17843. {
  17844. // parse_url accepts any port string; validation is done by parse_port
  17845. detail::UrlComponents uc;
  17846. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17847. EXPECT_EQ("abc", uc.port);
  17848. }
  17849. }
  17850. TEST(ParseUrlTest, WebSocketPatterns) {
  17851. {
  17852. detail::UrlComponents uc;
  17853. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17854. EXPECT_EQ("ws", uc.scheme);
  17855. EXPECT_EQ("echo.example.com", uc.host);
  17856. EXPECT_EQ("8080", uc.port);
  17857. EXPECT_EQ("/ws", uc.path);
  17858. }
  17859. {
  17860. detail::UrlComponents uc;
  17861. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17862. EXPECT_EQ("wss", uc.scheme);
  17863. EXPECT_EQ("echo.example.com", uc.host);
  17864. EXPECT_TRUE(uc.port.empty());
  17865. EXPECT_EQ("/ws", uc.path);
  17866. }
  17867. }
  17868. TEST(ParseUrlTest, QueryOnly) {
  17869. detail::UrlComponents uc;
  17870. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17871. EXPECT_TRUE(uc.host.empty());
  17872. EXPECT_TRUE(uc.path.empty());
  17873. EXPECT_EQ("?q=1&r=2", uc.query);
  17874. }
  17875. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17876. detail::UrlComponents uc;
  17877. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17878. EXPECT_TRUE(uc.scheme.empty());
  17879. EXPECT_EQ("example.com", uc.host);
  17880. EXPECT_EQ("443", uc.port);
  17881. EXPECT_EQ("/path", uc.path);
  17882. }
  17883. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17884. // If ipv6 regex working, regex match codepath is taken.
  17885. // else port will default to 80 in Client impl
  17886. int clientImplMagicPort = 80;
  17887. int port = 4321;
  17888. // above ports must be different to avoid false negative
  17889. EXPECT_NE(clientImplMagicPort, port);
  17890. std::string ipV6TestURL = "http://[ff06::c3]";
  17891. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17892. CLIENT_PRIVATE_KEY_FILE);
  17893. EXPECT_EQ(cli.port(), port);
  17894. }
  17895. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17896. auto file_path = "./www/dir/index.html";
  17897. auto dir_path = "./www/dir";
  17898. detail::FileStat stat_file(file_path);
  17899. EXPECT_TRUE(stat_file.is_file());
  17900. EXPECT_FALSE(stat_file.is_dir());
  17901. detail::FileStat stat_dir(dir_path);
  17902. EXPECT_FALSE(stat_dir.is_file());
  17903. EXPECT_TRUE(stat_dir.is_dir());
  17904. }
  17905. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17906. // IPv4 with default HTTP port (80)
  17907. EXPECT_EQ("example.com",
  17908. detail::make_host_and_port_string("example.com", 80, false));
  17909. // IPv4 with default HTTPS port (443)
  17910. EXPECT_EQ("example.com",
  17911. detail::make_host_and_port_string("example.com", 443, true));
  17912. // IPv4 with non-default HTTP port
  17913. EXPECT_EQ("example.com:8080",
  17914. detail::make_host_and_port_string("example.com", 8080, false));
  17915. // IPv4 with non-default HTTPS port
  17916. EXPECT_EQ("example.com:8443",
  17917. detail::make_host_and_port_string("example.com", 8443, true));
  17918. // IPv6 with default HTTP port (80)
  17919. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17920. // IPv6 with default HTTPS port (443)
  17921. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17922. // IPv6 with non-default HTTP port
  17923. EXPECT_EQ("[::1]:8080",
  17924. detail::make_host_and_port_string("::1", 8080, false));
  17925. // IPv6 with non-default HTTPS port
  17926. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17927. // IPv6 full address with default port
  17928. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17929. detail::make_host_and_port_string(
  17930. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17931. // IPv6 full address with non-default port
  17932. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17933. detail::make_host_and_port_string(
  17934. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17935. // IPv6 localhost with non-default port
  17936. EXPECT_EQ("[::1]:3000",
  17937. detail::make_host_and_port_string("::1", 3000, false));
  17938. // IPv6 with zone ID (link-local address) with default port
  17939. EXPECT_EQ("[fe80::1%eth0]",
  17940. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17941. // IPv6 with zone ID (link-local address) with non-default port
  17942. EXPECT_EQ("[fe80::1%eth0]:8080",
  17943. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17944. // Edge case: Port 443 with is_ssl=false (should add port)
  17945. EXPECT_EQ("example.com:443",
  17946. detail::make_host_and_port_string("example.com", 443, false));
  17947. // Edge case: Port 80 with is_ssl=true (should add port)
  17948. EXPECT_EQ("example.com:80",
  17949. detail::make_host_and_port_string("example.com", 80, true));
  17950. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17951. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17952. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17953. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17954. // Security fix: Already bracketed IPv6 should not get double brackets
  17955. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17956. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17957. EXPECT_EQ("[::1]:8080",
  17958. detail::make_host_and_port_string("[::1]", 8080, false));
  17959. EXPECT_EQ("[2001:db8::1]:8080",
  17960. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17961. EXPECT_EQ("[fe80::1%eth0]",
  17962. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17963. EXPECT_EQ("[fe80::1%eth0]:8080",
  17964. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17965. // Edge case: Empty host (should return as-is)
  17966. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17967. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17968. // This is a known limitation but shouldn't crash
  17969. EXPECT_EQ("[host:name]",
  17970. detail::make_host_and_port_string("host:name", 80, false));
  17971. // Port number edge cases (no validation, but should not crash)
  17972. EXPECT_EQ("example.com:0",
  17973. detail::make_host_and_port_string("example.com", 0, false));
  17974. EXPECT_EQ("example.com:-1",
  17975. detail::make_host_and_port_string("example.com", -1, false));
  17976. EXPECT_EQ("example.com:65535",
  17977. detail::make_host_and_port_string("example.com", 65535, false));
  17978. EXPECT_EQ("example.com:65536",
  17979. detail::make_host_and_port_string("example.com", 65536, false));
  17980. }
  17981. #ifdef CPPHTTPLIB_SSL_ENABLED
  17982. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17983. httplib::SSLClient cli("roblox.com", 443);
  17984. cli.set_follow_location(true);
  17985. auto res = cli.Get("/");
  17986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17987. EXPECT_EQ(StatusCode::OK_200, res->status);
  17988. }
  17989. #endif
  17990. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17991. Server svr;
  17992. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17993. EXPECT_EQ(res.status, 400);
  17994. });
  17995. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17996. auto se = detail::scope_exit([&] {
  17997. svr.stop();
  17998. thread.join();
  17999. ASSERT_FALSE(svr.is_running());
  18000. });
  18001. svr.wait_until_ready();
  18002. Client cli(HOST, PORT);
  18003. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18004. }
  18005. TEST(InvalidHeaderCharsTest, is_field_name) {
  18006. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18007. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18008. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18009. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18010. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18011. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18012. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18013. EXPECT_FALSE(detail::fields::is_field_name(""));
  18014. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18015. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18016. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18017. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18018. }
  18019. TEST(InvalidHeaderCharsTest, is_field_value) {
  18020. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18021. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18022. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18023. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18024. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18025. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18026. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18027. EXPECT_TRUE(detail::fields::is_field_value(""));
  18028. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18029. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18030. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18031. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18032. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18033. }
  18034. TEST(InvalidHeaderCharsTest, OnServer) {
  18035. Server svr;
  18036. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18037. std::string header = "Not Set";
  18038. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18039. res.set_header(header, "value");
  18040. res.set_content("Page Content Page Content", "text/plain");
  18041. });
  18042. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18043. std::string header = "Not Set";
  18044. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18045. res.set_header("X-Test", header);
  18046. res.set_content("Page Content Page Content", "text/plain");
  18047. });
  18048. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18049. auto se = detail::scope_exit([&] {
  18050. svr.stop();
  18051. thread.join();
  18052. ASSERT_FALSE(svr.is_running());
  18053. });
  18054. svr.wait_until_ready();
  18055. Client cli(HOST, PORT);
  18056. {
  18057. auto res = cli.Get(
  18058. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18060. EXPECT_EQ("Page Content Page Content", res->body);
  18061. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18062. }
  18063. {
  18064. auto res = cli.Get(
  18065. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18067. EXPECT_EQ("Page Content Page Content", res->body);
  18068. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18069. }
  18070. }
  18071. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18072. auto handled = false;
  18073. Server svr;
  18074. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18075. thread t = thread([&] { svr.listen(HOST, PORT); });
  18076. auto se = detail::scope_exit([&] {
  18077. svr.stop();
  18078. t.join();
  18079. ASSERT_FALSE(svr.is_running());
  18080. ASSERT_FALSE(handled);
  18081. });
  18082. svr.wait_until_ready();
  18083. auto req = "POST /test HTTP/1.1\r\n"
  18084. "Content-Length: x\r\n"
  18085. "\r\n";
  18086. std::string response;
  18087. ASSERT_TRUE(send_request(1, req, &response));
  18088. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18089. response.substr(0, response.find("\r\n")));
  18090. }
  18091. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18092. // case-insensitive, and a server that receives a 100-continue expectation in
  18093. // an HTTP/1.0 request MUST ignore it.
  18094. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18095. std::string response;
  18096. ASSERT_TRUE(send_request(1, req, &response, port));
  18097. *got_100 = response.find("100 Continue") != std::string::npos;
  18098. }
  18099. class ExpectTokenTest : public ::testing::Test {
  18100. protected:
  18101. void SetUp() override {
  18102. svr_.Post("/p", [](const Request &, Response &res) {
  18103. res.set_content("ok", "text/plain");
  18104. });
  18105. port_ = svr_.bind_to_any_port(HOST);
  18106. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18107. svr_.wait_until_ready();
  18108. }
  18109. void TearDown() override {
  18110. svr_.stop();
  18111. if (thread_.joinable()) { thread_.join(); }
  18112. }
  18113. std::string request(const char *version, const char *expect_value) const {
  18114. return std::string("POST /p ") + version +
  18115. "\r\n"
  18116. "Host: localhost\r\n"
  18117. "Content-Length: 2\r\n"
  18118. "Connection: close\r\n"
  18119. "Expect: " +
  18120. expect_value +
  18121. "\r\n"
  18122. "\r\n"
  18123. "hi";
  18124. }
  18125. Server svr_;
  18126. int port_ = 0;
  18127. thread thread_;
  18128. };
  18129. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18130. bool got_100 = false;
  18131. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18132. EXPECT_TRUE(got_100);
  18133. }
  18134. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18135. bool got_100 = true;
  18136. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18137. EXPECT_FALSE(got_100);
  18138. }
  18139. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18140. bool got_100 = false;
  18141. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18142. EXPECT_TRUE(got_100);
  18143. }
  18144. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18145. bool got_100 = false;
  18146. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18147. EXPECT_TRUE(got_100);
  18148. }
  18149. // `100 Continue` is sent only when the server starts reading the body, so a
  18150. // request rejected before that never invites the client to send it. The
  18151. // requests below carry the expectation but withhold the body, as a client
  18152. // waiting for `100 Continue` would.
  18153. // A POST that expects `100 Continue` and withholds its two-byte body.
  18154. static std::string expect_headers_only(const std::string &path) {
  18155. return "POST " + path +
  18156. " HTTP/1.1\r\n"
  18157. "Host: localhost\r\n"
  18158. "Content-Length: 2\r\n"
  18159. "Expect: 100-continue\r\n"
  18160. "\r\n";
  18161. }
  18162. class ExpectLazyContinueTest : public ::testing::Test {
  18163. protected:
  18164. void SetUp() override {
  18165. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18166. if (req.path == "/pre-routing") {
  18167. res.status = StatusCode::Unauthorized_401;
  18168. return Server::HandlerResponse::Handled;
  18169. }
  18170. return Server::HandlerResponse::Unhandled;
  18171. });
  18172. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18173. if (req.matched_route == "/pre-request") {
  18174. res.status = StatusCode::Forbidden_403;
  18175. return Server::HandlerResponse::Handled;
  18176. }
  18177. return Server::HandlerResponse::Unhandled;
  18178. });
  18179. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18180. res.set_content("ok", "text/plain");
  18181. });
  18182. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18183. res.set_content("ok", "text/plain");
  18184. });
  18185. svr_.Post("/reader-used", [](const Request &, Response &res,
  18186. const ContentReader &content_reader) {
  18187. std::string body;
  18188. content_reader([&](const char *data, size_t len) {
  18189. body.append(data, len);
  18190. return true;
  18191. });
  18192. res.set_content(body, "text/plain");
  18193. });
  18194. svr_.Post("/reader-unused",
  18195. [](const Request &, Response &res, const ContentReader &) {
  18196. res.set_content("ignored", "text/plain");
  18197. });
  18198. port_ = svr_.bind_to_any_port(HOST);
  18199. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18200. svr_.wait_until_ready();
  18201. }
  18202. void TearDown() override {
  18203. svr_.stop();
  18204. if (thread_.joinable()) { thread_.join(); }
  18205. }
  18206. // Sends `req` and reads until the server closes the connection. Returns
  18207. // false if the read had to wait for the client-side timeout instead.
  18208. bool send_until_closed(const std::string &req, std::string *resp) const {
  18209. auto start = std::chrono::steady_clock::now();
  18210. if (!send_request(3, req, resp, port_)) { return false; }
  18211. auto elapsed = std::chrono::steady_clock::now() - start;
  18212. return elapsed < std::chrono::seconds(2);
  18213. }
  18214. // The final response comes without `100 Continue`, and the server closes
  18215. // the connection since the body may or may not follow.
  18216. void expect_final_without_interim(const std::string &path,
  18217. const char *status_line) const {
  18218. std::string resp;
  18219. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18220. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18221. EXPECT_EQ(0u, resp.find(status_line));
  18222. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18223. }
  18224. Server svr_;
  18225. int port_ = 0;
  18226. thread thread_;
  18227. };
  18228. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18229. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18230. }
  18231. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18232. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18233. }
  18234. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18235. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18236. }
  18237. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18238. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18239. }
  18240. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18241. // The body follows once `100 Continue` has had time to arrive.
  18242. auto req = expect_headers_only("/reader-used");
  18243. req.insert(req.size() - 2, "Connection: close\r\n");
  18244. std::string resp;
  18245. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18246. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18247. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18248. EXPECT_NE(std::string::npos, resp.find("hi"));
  18249. }
  18250. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18251. // Large enough for the client to add `Expect: 100-continue` itself.
  18252. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18253. std::atomic<bool> body_sent{false};
  18254. Client cli(HOST, port_);
  18255. auto res = cli.Post(
  18256. "/pre-request", length,
  18257. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18258. body_sent = true;
  18259. std::string chunk(len, 'x');
  18260. sink.write(chunk.data(), chunk.size());
  18261. return true;
  18262. },
  18263. "application/octet-stream");
  18264. ASSERT_TRUE(res);
  18265. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18266. EXPECT_FALSE(body_sent);
  18267. }
  18268. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18269. Server svr;
  18270. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18271. return StatusCode::ExpectationFailed_417;
  18272. });
  18273. svr.Post("/p", [](const Request &, Response &res) {
  18274. res.set_content("ok", "text/plain");
  18275. });
  18276. auto port = svr.bind_to_any_port(HOST);
  18277. thread t = thread([&] { svr.listen_after_bind(); });
  18278. auto se = detail::scope_exit([&] {
  18279. svr.stop();
  18280. t.join();
  18281. });
  18282. svr.wait_until_ready();
  18283. std::string resp;
  18284. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18285. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18286. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18287. // Exactly one response: the route handler must not run after the 417.
  18288. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18289. }
  18290. #ifndef _WIN32
  18291. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18292. static constexpr char reject[] = "Unauthorized";
  18293. static constexpr char accept[] = "Upload accepted";
  18294. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18295. Server svr;
  18296. svr.set_expect_100_continue_handler(
  18297. [](const Request & /*req*/, Response &res) {
  18298. res.status = StatusCode::Unauthorized_401;
  18299. res.set_content(reject, "text/plain");
  18300. return res.status;
  18301. });
  18302. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18303. res.set_content(accept, "text/plain");
  18304. });
  18305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18306. auto se = detail::scope_exit([&] {
  18307. svr.stop();
  18308. thread.join();
  18309. ASSERT_FALSE(svr.is_running());
  18310. });
  18311. svr.wait_until_ready();
  18312. {
  18313. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18314. curl_easy_init(), &curl_easy_cleanup};
  18315. ASSERT_NE(curl, nullptr);
  18316. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18317. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18318. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18319. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18320. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18321. &curl_slist_free_all};
  18322. ASSERT_NE(list, nullptr);
  18323. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18324. struct read_data {
  18325. uint64_t read_size;
  18326. uint64_t total_size;
  18327. } data = {0, total_size};
  18328. using read_callback_t =
  18329. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18330. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18331. void *userdata) -> size_t {
  18332. read_data *d = (read_data *)userdata;
  18333. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18334. std::fill_n(ptr, size * nmemb, 'A');
  18335. d->read_size += size * nmemb;
  18336. return size * nmemb;
  18337. };
  18338. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18339. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18340. std::vector<char> buffer;
  18341. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18342. using write_callback_t =
  18343. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18344. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18345. void *userdata) -> size_t {
  18346. std::vector<char> *buf = (std::vector<char> *)userdata;
  18347. buf->reserve(buf->size() + size * nmemb + 1);
  18348. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18349. return size * nmemb;
  18350. };
  18351. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18352. {
  18353. const auto res = curl_easy_perform(curl.get());
  18354. ASSERT_EQ(res, CURLE_OK);
  18355. }
  18356. {
  18357. auto response_code = long{};
  18358. const auto res =
  18359. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18360. ASSERT_EQ(res, CURLE_OK);
  18361. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18362. }
  18363. {
  18364. auto dl = curl_off_t{};
  18365. const auto res =
  18366. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18367. ASSERT_EQ(res, CURLE_OK);
  18368. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18369. }
  18370. {
  18371. buffer.push_back('\0');
  18372. ASSERT_STRCASEEQ(buffer.data(), reject);
  18373. }
  18374. }
  18375. }
  18376. #endif
  18377. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18378. // Regression test for #2458.
  18379. //
  18380. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18381. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18382. // ticket can make the client socket spuriously readable during the
  18383. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18384. // the client withholds the body and then blocks reading a response that never
  18385. // comes, failing with `Failed to read connection`.
  18386. //
  18387. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18388. // within the timeout. This raw OpenSSL server deliberately never sends
  18389. // `100 Continue`; the client must still deliver the body and receive 200.
  18390. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18391. signal(SIGPIPE, SIG_IGN);
  18392. const auto port = PORT + 4;
  18393. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18394. ASSERT_NE(srv, INVALID_SOCKET);
  18395. int opt = 1;
  18396. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18397. sockaddr_in addr{};
  18398. addr.sin_family = AF_INET;
  18399. addr.sin_port = htons(static_cast<uint16_t>(port));
  18400. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18401. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18402. ASSERT_EQ(0, ::listen(srv, 1));
  18403. std::atomic<size_t> server_body_bytes{0};
  18404. auto server_thread = std::thread([&] {
  18405. sockaddr_in cli_addr{};
  18406. socklen_t cli_len = sizeof(cli_addr);
  18407. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18408. if (cli == INVALID_SOCKET) { return; }
  18409. // Bound the lifetime of the server side so a buggy client (which never
  18410. // sends the body) cannot make this thread block forever on join.
  18411. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18412. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18413. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18414. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18415. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18416. SSL *ssl = SSL_new(ctx);
  18417. SSL_set_fd(ssl, static_cast<int>(cli));
  18418. if (SSL_accept(ssl) > 0) {
  18419. // Read the request headers. Reading here also flushes the TLS 1.3
  18420. // session tickets to the client. Deliberately do NOT send
  18421. // `100 Continue`.
  18422. std::string buf;
  18423. char tmp[1024];
  18424. while (buf.find("\r\n\r\n") == std::string::npos) {
  18425. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18426. if (n <= 0) { break; }
  18427. buf.append(tmp, static_cast<size_t>(n));
  18428. }
  18429. // A correct client sends the body now; count what arrives.
  18430. auto pos = buf.find("\r\n\r\n");
  18431. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18432. while (body < 4096) {
  18433. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18434. if (n <= 0) { break; }
  18435. body += static_cast<size_t>(n);
  18436. }
  18437. server_body_bytes = body;
  18438. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18439. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18440. SSL_shutdown(ssl);
  18441. }
  18442. SSL_free(ssl);
  18443. detail::close_socket(cli);
  18444. SSL_CTX_free(ctx);
  18445. });
  18446. auto se = detail::scope_exit([&] {
  18447. server_thread.join();
  18448. detail::close_socket(srv);
  18449. });
  18450. SSLClient cli("127.0.0.1", port);
  18451. cli.enable_server_certificate_verification(false);
  18452. cli.set_connection_timeout(5, 0);
  18453. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18454. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18455. std::string body(4096, 'A');
  18456. auto res = cli.Put("/api/test", body, "application/json");
  18457. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18458. EXPECT_EQ(StatusCode::OK_200, res->status);
  18459. EXPECT_EQ(body.size(), server_body_bytes.load());
  18460. }
  18461. #endif
  18462. template <typename S, typename C>
  18463. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18464. svr.Get("/stream", [&](const Request &, Response &res) {
  18465. auto data = new std::string("01234567890123456789");
  18466. res.set_content_provider(
  18467. data->size(), "text/plain",
  18468. [&, data](size_t offset, size_t length, DataSink &sink) {
  18469. const size_t DATA_CHUNK_SIZE = 4;
  18470. const auto &d = *data;
  18471. std::this_thread::sleep_for(std::chrono::seconds(1));
  18472. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18473. return true;
  18474. },
  18475. [data](bool success) {
  18476. EXPECT_FALSE(success);
  18477. delete data;
  18478. });
  18479. });
  18480. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18481. auto i = new size_t(0);
  18482. res.set_content_provider(
  18483. "text/plain",
  18484. [i](size_t, DataSink &sink) {
  18485. if (*i < 5) {
  18486. std::this_thread::sleep_for(std::chrono::seconds(1));
  18487. sink.write("abcd", 4);
  18488. (*i)++;
  18489. } else {
  18490. sink.done();
  18491. }
  18492. return true;
  18493. },
  18494. [i](bool success) {
  18495. EXPECT_FALSE(success);
  18496. delete i;
  18497. });
  18498. });
  18499. svr.Get("/chunked", [&](const Request &, Response &res) {
  18500. auto i = new size_t(0);
  18501. res.set_chunked_content_provider(
  18502. "text/plain",
  18503. [i](size_t, DataSink &sink) {
  18504. if (*i < 5) {
  18505. std::this_thread::sleep_for(std::chrono::seconds(1));
  18506. sink.os << "abcd";
  18507. (*i)++;
  18508. } else {
  18509. sink.done();
  18510. }
  18511. return true;
  18512. },
  18513. [i](bool success) {
  18514. EXPECT_FALSE(success);
  18515. delete i;
  18516. });
  18517. });
  18518. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18519. auto se = detail::scope_exit([&] {
  18520. svr.stop();
  18521. listen_thread.join();
  18522. ASSERT_FALSE(svr.is_running());
  18523. });
  18524. svr.wait_until_ready();
  18525. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18526. {
  18527. auto start = std::chrono::steady_clock::now();
  18528. auto res = cli.Get("/stream");
  18529. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18530. std::chrono::steady_clock::now() - start)
  18531. .count();
  18532. ASSERT_FALSE(res);
  18533. EXPECT_EQ(Error::Read, res.error());
  18534. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18535. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18536. }
  18537. {
  18538. auto start = std::chrono::steady_clock::now();
  18539. auto res = cli.Get("/stream_without_length");
  18540. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18541. std::chrono::steady_clock::now() - start)
  18542. .count();
  18543. ASSERT_FALSE(res);
  18544. EXPECT_EQ(Error::Read, res.error());
  18545. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18546. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18547. }
  18548. {
  18549. auto start = std::chrono::steady_clock::now();
  18550. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18551. EXPECT_EQ("abcd", string(data, data_length));
  18552. return true;
  18553. });
  18554. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18555. std::chrono::steady_clock::now() - start)
  18556. .count();
  18557. ASSERT_FALSE(res);
  18558. EXPECT_EQ(Error::Read, res.error());
  18559. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18560. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18561. }
  18562. }
  18563. TEST(MaxTimeoutTest, ContentStream) {
  18564. time_t timeout = 2000;
  18565. time_t threshold = 200;
  18566. Server svr;
  18567. Client cli("localhost", PORT);
  18568. max_timeout_test(svr, cli, timeout, threshold);
  18569. }
  18570. #ifdef CPPHTTPLIB_SSL_ENABLED
  18571. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18572. time_t timeout = 2000;
  18573. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18575. SSLClient cli("localhost", PORT);
  18576. cli.enable_server_certificate_verification(false);
  18577. max_timeout_test(svr, cli, timeout, threshold);
  18578. }
  18579. #endif
  18580. class EventDispatcher {
  18581. public:
  18582. EventDispatcher() {}
  18583. bool wait_event(DataSink *sink) {
  18584. unique_lock<mutex> lk(m_);
  18585. int id = id_;
  18586. // Wait with timeout to prevent hanging if client disconnects
  18587. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18588. [&] { return cid_ == id; })) {
  18589. return false; // Timeout occurred
  18590. }
  18591. sink->write(message_.data(), message_.size());
  18592. return true;
  18593. }
  18594. void send_event(const string &message) {
  18595. lock_guard<mutex> lk(m_);
  18596. cid_ = id_++;
  18597. message_ = message;
  18598. cv_.notify_all();
  18599. }
  18600. private:
  18601. mutex m_;
  18602. condition_variable cv_;
  18603. atomic_int id_{0};
  18604. atomic_int cid_{-1};
  18605. string message_;
  18606. };
  18607. TEST(ClientInThreadTest, Issue2068) {
  18608. EventDispatcher ed;
  18609. Server svr;
  18610. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18611. res.set_chunked_content_provider("text/event-stream",
  18612. [&](size_t /*offset*/, DataSink &sink) {
  18613. return ed.wait_event(&sink);
  18614. });
  18615. });
  18616. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18617. svr.wait_until_ready();
  18618. thread event_thread([&] {
  18619. int id = 0;
  18620. while (svr.is_running()) {
  18621. this_thread::sleep_for(chrono::milliseconds(500));
  18622. std::stringstream ss;
  18623. ss << "data: " << id << "\n\n";
  18624. ed.send_event(ss.str());
  18625. id++;
  18626. }
  18627. });
  18628. auto se = detail::scope_exit([&] {
  18629. svr.stop();
  18630. listen_thread.join();
  18631. event_thread.join();
  18632. ASSERT_FALSE(svr.is_running());
  18633. });
  18634. {
  18635. auto client = detail::make_unique<Client>(HOST, PORT);
  18636. client->set_read_timeout(std::chrono::minutes(10));
  18637. std::atomic<bool> stop{false};
  18638. std::thread t([&] {
  18639. client->Get("/event1",
  18640. [&](const char *, size_t) -> bool { return !stop; });
  18641. });
  18642. std::this_thread::sleep_for(std::chrono::seconds(2));
  18643. stop = true;
  18644. client->stop();
  18645. t.join();
  18646. // Reset client after thread has finished
  18647. client.reset();
  18648. }
  18649. }
  18650. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18651. auto handled = false;
  18652. Server svr;
  18653. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18654. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18655. auto se = detail::scope_exit([&] {
  18656. svr.stop();
  18657. t.join();
  18658. ASSERT_FALSE(svr.is_running());
  18659. ASSERT_FALSE(handled);
  18660. });
  18661. svr.wait_until_ready();
  18662. // Two Content-Length headers with different values — must be rejected
  18663. auto req = "POST /test HTTP/1.1\r\n"
  18664. "Content-Length: 5\r\n"
  18665. "Content-Length: 10\r\n"
  18666. "\r\n"
  18667. "hello";
  18668. std::string response;
  18669. ASSERT_TRUE(send_request(1, req, &response));
  18670. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18671. response.substr(0, response.find("\r\n")));
  18672. }
  18673. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18674. auto handled = false;
  18675. Server svr;
  18676. svr.Post("/test", [&](const Request &, Response &res) {
  18677. handled = true;
  18678. res.set_content("ok", "text/plain");
  18679. });
  18680. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18681. auto se = detail::scope_exit([&] {
  18682. svr.stop();
  18683. t.join();
  18684. ASSERT_FALSE(svr.is_running());
  18685. ASSERT_TRUE(handled);
  18686. });
  18687. svr.wait_until_ready();
  18688. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18689. auto req = "POST /test HTTP/1.1\r\n"
  18690. "Host: localhost\r\n"
  18691. "Content-Length: 5\r\n"
  18692. "Content-Length: 5\r\n"
  18693. "\r\n"
  18694. "hello";
  18695. std::string response;
  18696. ASSERT_TRUE(send_request(1, req, &response));
  18697. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18698. }
  18699. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18700. Server svr;
  18701. svr.Get("/test", [](const Request &, Response &res) {
  18702. res.set_content("ok", "text/plain");
  18703. });
  18704. auto port = svr.bind_to_any_port(HOST);
  18705. thread t = thread([&] { svr.listen_after_bind(); });
  18706. auto se = detail::scope_exit([&] {
  18707. svr.stop();
  18708. t.join();
  18709. ASSERT_FALSE(svr.is_running());
  18710. });
  18711. svr.wait_until_ready();
  18712. auto status_line = [&](const std::string &host_lines) {
  18713. std::string res;
  18714. send_request(
  18715. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18716. &res, port);
  18717. return res.substr(0, res.find("\r\n"));
  18718. };
  18719. const char *accepted[] = {
  18720. "Host: localhost\r\n",
  18721. "Host: a.example:8080\r\n",
  18722. "Host: my_service\r\n",
  18723. "Host: [::1]:8080\r\n",
  18724. "Host: [fe80::1%25eth0]\r\n",
  18725. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18726. };
  18727. for (auto host_lines : accepted) {
  18728. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18729. }
  18730. const char *rejected[] = {
  18731. "Host: a.example\r\nHost: b.example\r\n",
  18732. "Host: a.example\r\nHost: a.example\r\n",
  18733. "Host: a@b.example\r\n",
  18734. "Host: a.example/b\r\n",
  18735. "Host: a.example\\b\r\n",
  18736. "Host: a.example?b\r\n",
  18737. "Host: a.example#b\r\n",
  18738. "Host: a.example b.example\r\n",
  18739. };
  18740. for (auto host_lines : rejected) {
  18741. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18742. << host_lines;
  18743. }
  18744. }
  18745. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18746. Server svr;
  18747. svr.Get("/", [](const Request &req, Response &res) {
  18748. EXPECT_EQ(2U, req.trailers.size());
  18749. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18750. // Denied
  18751. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18752. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18753. // Accepted
  18754. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18755. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18756. EXPECT_TRUE(req.has_trailer("X-World"));
  18757. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18758. res.set_content("ok", "text/plain");
  18759. });
  18760. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18761. auto se = detail::scope_exit([&] {
  18762. svr.stop();
  18763. t.join();
  18764. ASSERT_FALSE(svr.is_running());
  18765. });
  18766. svr.wait_until_ready();
  18767. const std::string req = "GET / HTTP/1.1\r\n"
  18768. "Transfer-Encoding: chunked\r\n"
  18769. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18770. "\r\n"
  18771. "0\r\n"
  18772. "Content-Length: 10\r\n"
  18773. "Host: internal.local\r\n"
  18774. "Content-Type: malicious/content\r\n"
  18775. "Cookie: any\r\n"
  18776. "Set-Cookie: any\r\n"
  18777. "X-Forwarded-For: attacker.com\r\n"
  18778. "X-Real-Ip: 1.1.1.1\r\n"
  18779. "X-Hello: hello\r\n"
  18780. "X-World: world\r\n"
  18781. "\r\n";
  18782. std::string res;
  18783. ASSERT_TRUE(send_request(1, req, &res));
  18784. }
  18785. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18786. // several field lines, and the combined value is what has to be parsed. A
  18787. // Trailer field split across lines therefore declares every name it lists;
  18788. // reading only the first line silently drops the trailers the later lines
  18789. // declare. The prohibited-trailer filter still applies to every line.
  18790. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18791. Server svr;
  18792. size_t observed_trailer_count = 0;
  18793. std::string observed_hello;
  18794. std::string observed_world;
  18795. bool observed_content_length = true;
  18796. svr.Get("/", [&](const Request &req, Response &res) {
  18797. observed_trailer_count = req.trailers.size();
  18798. observed_hello = req.get_trailer_value("X-Hello");
  18799. observed_world = req.get_trailer_value("X-World");
  18800. observed_content_length = req.has_trailer("Content-Length");
  18801. res.set_content("ok", "text/plain");
  18802. });
  18803. auto port = svr.bind_to_any_port(HOST);
  18804. thread t = thread([&]() { svr.listen_after_bind(); });
  18805. auto se = detail::scope_exit([&] {
  18806. svr.stop();
  18807. t.join();
  18808. ASSERT_FALSE(svr.is_running());
  18809. });
  18810. svr.wait_until_ready();
  18811. const std::string req = "GET / HTTP/1.1\r\n"
  18812. "Host: localhost\r\n"
  18813. "Transfer-Encoding: chunked\r\n"
  18814. "Trailer: X-Hello\r\n"
  18815. "Trailer: X-World, Content-Length\r\n"
  18816. "\r\n"
  18817. "0\r\n"
  18818. "X-Hello: hello\r\n"
  18819. "X-World: world\r\n"
  18820. "Content-Length: 10\r\n"
  18821. "\r\n";
  18822. std::string res;
  18823. ASSERT_TRUE(send_request(1, req, &res, port));
  18824. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18825. // Accepted: both field lines contribute to the declared set
  18826. EXPECT_EQ(2U, observed_trailer_count);
  18827. EXPECT_EQ(observed_hello, "hello");
  18828. EXPECT_EQ(observed_world, "world");
  18829. // Denied: a prohibited name stays prohibited on a later field line
  18830. EXPECT_FALSE(observed_content_length);
  18831. }
  18832. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18833. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18834. // unbounded run of fields that are never declared, because the counter would
  18835. // only advance for declared fields.
  18836. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18837. Server svr;
  18838. bool handler_called = false;
  18839. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18840. handler_called = true;
  18841. res.set_content("ok", "text/plain");
  18842. });
  18843. auto port = svr.bind_to_any_port(HOST);
  18844. thread t = thread([&]() { svr.listen_after_bind(); });
  18845. auto se = detail::scope_exit([&] {
  18846. svr.stop();
  18847. t.join();
  18848. ASSERT_FALSE(svr.is_running());
  18849. });
  18850. svr.wait_until_ready();
  18851. // Declare nothing, then send far more undeclared trailer fields than the
  18852. // header-count limit. Parsing must stop and reject the request rather than
  18853. // read every line.
  18854. std::string req = "GET / HTTP/1.1\r\n"
  18855. "Transfer-Encoding: chunked\r\n"
  18856. "\r\n"
  18857. "0\r\n";
  18858. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18859. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18860. }
  18861. req += "\r\n";
  18862. std::string res;
  18863. ASSERT_TRUE(send_request(1, req, &res, port));
  18864. // The request is rejected before the handler runs.
  18865. EXPECT_FALSE(handler_called);
  18866. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18867. }
  18868. // The set of declared trailer names is capped so a peer cannot grow it without
  18869. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18870. // declared past the cap is not honored, even if the field is actually sent.
  18871. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18872. Server svr;
  18873. // One name inside the cap and one past it, so the test tracks the cap rather
  18874. // than a fixed count.
  18875. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18876. const std::string within_cap_name = "X-T-0";
  18877. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18878. bool observed_within_cap = false;
  18879. bool observed_past_cap = false;
  18880. svr.Get("/", [&](const Request &req, Response &res) {
  18881. observed_within_cap = req.has_trailer(within_cap_name);
  18882. observed_past_cap = req.has_trailer(past_cap_name);
  18883. res.set_content("ok", "text/plain");
  18884. });
  18885. auto port = svr.bind_to_any_port(HOST);
  18886. thread t = thread([&]() { svr.listen_after_bind(); });
  18887. auto se = detail::scope_exit([&] {
  18888. svr.stop();
  18889. t.join();
  18890. ASSERT_FALSE(svr.is_running());
  18891. });
  18892. svr.wait_until_ready();
  18893. // Declare more trailer names than the cap in a single Trailer field, then
  18894. // actually send the first (within the cap) and the last (past it).
  18895. std::string trailer_decl = "Trailer: ";
  18896. for (int i = 0; i < declared_count; i++) {
  18897. if (i != 0) { trailer_decl += ", "; }
  18898. trailer_decl += "X-T-" + std::to_string(i);
  18899. }
  18900. trailer_decl += "\r\n";
  18901. const std::string req = "GET / HTTP/1.1\r\n"
  18902. "Host: localhost\r\n"
  18903. "Transfer-Encoding: chunked\r\n" +
  18904. trailer_decl +
  18905. "\r\n"
  18906. "0\r\n" +
  18907. within_cap_name + ": a\r\n" + past_cap_name +
  18908. ": b\r\n"
  18909. "\r\n";
  18910. std::string res;
  18911. ASSERT_TRUE(send_request(1, req, &res, port));
  18912. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18913. // A name within the cap is honored; one declared past the cap is dropped.
  18914. EXPECT_TRUE(observed_within_cap);
  18915. EXPECT_FALSE(observed_past_cap);
  18916. }
  18917. // A direct client that is not listed in trusted_proxies must not be able to
  18918. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18919. // the peer address on the actual TCP connection determines whether the
  18920. // header is honored.
  18921. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18922. Server svr;
  18923. // Deliberately does NOT include the loopback address the test client
  18924. // actually connects from, so the direct connection is not a trusted proxy.
  18925. svr.set_trusted_proxies({"203.0.113.66"});
  18926. std::string observed_remote_addr;
  18927. svr.Get("/ip", [&](const Request &req, Response &res) {
  18928. observed_remote_addr = req.remote_addr;
  18929. res.set_content("ok", "text/plain");
  18930. });
  18931. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18932. auto se = detail::scope_exit([&] {
  18933. svr.stop();
  18934. t.join();
  18935. ASSERT_FALSE(svr.is_running());
  18936. });
  18937. svr.wait_until_ready();
  18938. Client cli(HOST, PORT);
  18939. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18941. EXPECT_EQ(StatusCode::OK_200, res->status);
  18942. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18943. // ignored entirely and the real connection-level address retained.
  18944. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18945. observed_remote_addr == "127.0.0.1");
  18946. }
  18947. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18948. Server svr;
  18949. std::string observed_remote_addr;
  18950. std::string observed_xff;
  18951. svr.Get("/ip", [&](const Request &req, Response &res) {
  18952. observed_remote_addr = req.remote_addr;
  18953. observed_xff = req.get_header_value("X-Forwarded-For");
  18954. res.set_content("ok", "text/plain");
  18955. });
  18956. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18957. auto se = detail::scope_exit([&] {
  18958. svr.stop();
  18959. t.join();
  18960. ASSERT_FALSE(svr.is_running());
  18961. });
  18962. svr.wait_until_ready();
  18963. Client cli(HOST, PORT);
  18964. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18966. EXPECT_EQ(StatusCode::OK_200, res->status);
  18967. EXPECT_EQ(observed_xff, "203.0.113.66");
  18968. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18969. observed_remote_addr == "127.0.0.1");
  18970. }
  18971. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18972. Server svr;
  18973. svr.set_trusted_proxies({"203.0.113.66"});
  18974. std::string observed_remote_addr;
  18975. std::string observed_xff;
  18976. svr.Get("/ip", [&](const Request &req, Response &res) {
  18977. observed_remote_addr = req.remote_addr;
  18978. observed_xff = req.get_header_value("X-Forwarded-For");
  18979. res.set_content("ok", "text/plain");
  18980. });
  18981. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18982. auto se = detail::scope_exit([&] {
  18983. svr.stop();
  18984. t.join();
  18985. ASSERT_FALSE(svr.is_running());
  18986. });
  18987. svr.wait_until_ready();
  18988. Client cli(HOST, PORT);
  18989. auto res = cli.Get("/ip");
  18990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18991. EXPECT_EQ(StatusCode::OK_200, res->status);
  18992. EXPECT_EQ(observed_xff, "");
  18993. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18994. observed_remote_addr == "127.0.0.1");
  18995. }
  18996. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18997. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18998. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18999. Server svr;
  19000. svr.set_trusted_proxies({"127.0.0.1"});
  19001. svr.Get("/ip", [](const Request &req, Response &res) {
  19002. res.set_content(req.remote_addr, "text/plain");
  19003. });
  19004. auto port = svr.bind_to_any_port("::");
  19005. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19006. thread t = thread([&] { svr.listen_after_bind(); });
  19007. auto se = detail::scope_exit([&] {
  19008. svr.stop();
  19009. t.join();
  19010. ASSERT_FALSE(svr.is_running());
  19011. });
  19012. svr.wait_until_ready();
  19013. Client cli("127.0.0.1", port);
  19014. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19016. EXPECT_EQ("198.51.100.23", res->body);
  19017. }
  19018. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19019. Server svr;
  19020. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19021. svr.Get("/ip", [](const Request &req, Response &res) {
  19022. res.set_content(req.remote_addr, "text/plain");
  19023. });
  19024. auto port = svr.bind_to_any_port(HOST);
  19025. ASSERT_GT(port, 0);
  19026. thread t = thread([&] { svr.listen_after_bind(); });
  19027. auto se = detail::scope_exit([&] {
  19028. svr.stop();
  19029. t.join();
  19030. ASSERT_FALSE(svr.is_running());
  19031. });
  19032. svr.wait_until_ready();
  19033. Client cli(HOST, port);
  19034. auto res = cli.Get(
  19035. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19037. EXPECT_EQ("198.51.100.23", res->body);
  19038. }
  19039. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19040. Server svr;
  19041. // Include the loopback address the test client actually connects from, so
  19042. // the direct connection itself is recognized as the trusted proxy hop.
  19043. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19044. std::string observed_remote_addr;
  19045. std::string observed_xff;
  19046. svr.Get("/ip", [&](const Request &req, Response &res) {
  19047. observed_remote_addr = req.remote_addr;
  19048. observed_xff = req.get_header_value("X-Forwarded-For");
  19049. res.set_content("ok", "text/plain");
  19050. });
  19051. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19052. auto se = detail::scope_exit([&] {
  19053. svr.stop();
  19054. t.join();
  19055. ASSERT_FALSE(svr.is_running());
  19056. });
  19057. svr.wait_until_ready();
  19058. Client cli(HOST, PORT);
  19059. auto res = cli.Get(
  19060. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19062. EXPECT_EQ(StatusCode::OK_200, res->status);
  19063. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19064. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19065. }
  19066. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19067. Server svr;
  19068. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19069. std::string observed_remote_addr;
  19070. std::string observed_xff;
  19071. svr.Get("/ip", [&](const Request &req, Response &res) {
  19072. observed_remote_addr = req.remote_addr;
  19073. observed_xff = req.get_header_value("X-Forwarded-For");
  19074. res.set_content("ok", "text/plain");
  19075. });
  19076. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19077. auto se = detail::scope_exit([&] {
  19078. svr.stop();
  19079. t.join();
  19080. ASSERT_FALSE(svr.is_running());
  19081. });
  19082. svr.wait_until_ready();
  19083. Client cli(HOST, PORT);
  19084. auto res = cli.Get(
  19085. "/ip",
  19086. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19088. EXPECT_EQ(StatusCode::OK_200, res->status);
  19089. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19090. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19091. }
  19092. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19093. Server svr;
  19094. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19095. std::string observed_remote_addr;
  19096. std::string observed_xff;
  19097. svr.Get("/ip", [&](const Request &req, Response &res) {
  19098. observed_remote_addr = req.remote_addr;
  19099. observed_xff = req.get_header_value("X-Forwarded-For");
  19100. res.set_content("ok", "text/plain");
  19101. });
  19102. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19103. auto se = detail::scope_exit([&] {
  19104. svr.stop();
  19105. t.join();
  19106. ASSERT_FALSE(svr.is_running());
  19107. });
  19108. svr.wait_until_ready();
  19109. Client cli(HOST, PORT);
  19110. auto res = cli.Get(
  19111. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19113. EXPECT_EQ(StatusCode::OK_200, res->status);
  19114. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19115. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19116. // and must not be selected.
  19117. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19118. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19119. }
  19120. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19121. Server svr;
  19122. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19123. std::string observed_remote_addr;
  19124. svr.Get("/ip", [&](const Request &req, Response &res) {
  19125. observed_remote_addr = req.remote_addr;
  19126. res.set_content("ok", "text/plain");
  19127. });
  19128. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19129. auto se = detail::scope_exit([&] {
  19130. svr.stop();
  19131. t.join();
  19132. ASSERT_FALSE(svr.is_running());
  19133. });
  19134. svr.wait_until_ready();
  19135. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19136. // a forged address and the trusted proxy's own address; the forged value must
  19137. // not win over the address the trusted proxy actually recorded.
  19138. Client cli(HOST, PORT);
  19139. auto res = cli.Get(
  19140. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19142. EXPECT_EQ(StatusCode::OK_200, res->status);
  19143. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19144. }
  19145. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19146. Server svr;
  19147. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19148. std::string observed_remote_addr;
  19149. std::string observed_xff;
  19150. svr.Get("/ip", [&](const Request &req, Response &res) {
  19151. observed_remote_addr = req.remote_addr;
  19152. observed_xff = req.get_header_value("X-Forwarded-For");
  19153. res.set_content("ok", "text/plain");
  19154. });
  19155. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19156. auto se = detail::scope_exit([&] {
  19157. svr.stop();
  19158. t.join();
  19159. ASSERT_FALSE(svr.is_running());
  19160. });
  19161. svr.wait_until_ready();
  19162. Client cli(HOST, PORT);
  19163. auto res = cli.Get(
  19164. "/ip",
  19165. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19167. EXPECT_EQ(StatusCode::OK_200, res->status);
  19168. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19169. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19170. }
  19171. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19172. Server svr;
  19173. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19174. std::string observed_remote_addr;
  19175. std::string observed_xff;
  19176. svr.Get("/ip", [&](const Request &req, Response &res) {
  19177. observed_remote_addr = req.remote_addr;
  19178. observed_xff = req.get_header_value("X-Forwarded-For");
  19179. res.set_content("ok", "text/plain");
  19180. });
  19181. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19182. auto se = detail::scope_exit([&] {
  19183. svr.stop();
  19184. t.join();
  19185. ASSERT_FALSE(svr.is_running());
  19186. });
  19187. svr.wait_until_ready();
  19188. std::string raw_req =
  19189. "GET /ip HTTP/1.1\r\n"
  19190. "Host: localhost\r\n"
  19191. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19192. "Connection: close\r\n"
  19193. "\r\n";
  19194. std::string out;
  19195. ASSERT_TRUE(send_request(5, raw_req, &out));
  19196. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19197. // Header parser trims surrounding whitespace of the header value
  19198. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19199. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19200. }
  19201. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19202. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19203. // their own X-Forwarded-For as a separate field line rather than extending the
  19204. // one the client sent, so every occurrence has to be taken into account.
  19205. // Reading only the first one hands back the address the client chose.
  19206. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19207. Server svr;
  19208. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19209. std::string observed_remote_addr;
  19210. size_t observed_xff_count = 0;
  19211. svr.Get("/ip", [&](const Request &req, Response &res) {
  19212. observed_remote_addr = req.remote_addr;
  19213. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19214. res.set_content("ok", "text/plain");
  19215. });
  19216. auto port = svr.bind_to_any_port(HOST);
  19217. thread t = thread([&]() { svr.listen_after_bind(); });
  19218. auto se = detail::scope_exit([&] {
  19219. svr.stop();
  19220. t.join();
  19221. ASSERT_FALSE(svr.is_running());
  19222. });
  19223. svr.wait_until_ready();
  19224. // The client supplies the first field line; the trusted proxy appends the
  19225. // address it observed as a second one.
  19226. std::string raw_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, 192.0.2.45\r\n"
  19230. "Connection: close\r\n"
  19231. "\r\n";
  19232. std::string out;
  19233. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19234. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19235. EXPECT_EQ(observed_xff_count, 2U);
  19236. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19237. // The same chain spread over one field line per hop derives the same client
  19238. // address, i.e. the split and the comma-joined representations agree.
  19239. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19240. "Host: localhost\r\n"
  19241. "X-Forwarded-For: 1.2.3.4\r\n"
  19242. "X-Forwarded-For: 198.51.100.23\r\n"
  19243. "X-Forwarded-For: 192.0.2.45\r\n"
  19244. "Connection: close\r\n"
  19245. "\r\n";
  19246. out.clear();
  19247. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19248. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19249. EXPECT_EQ(observed_xff_count, 3U);
  19250. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19251. }
  19252. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19253. // crash the server (it used to call front() on an empty vector inside
  19254. // get_client_ip). The connection-level remote address must be retained instead.
  19255. static void run_malformed_xff_test(const std::string &xff_value) {
  19256. Server svr;
  19257. svr.set_trusted_proxies({"192.0.2.45"});
  19258. std::string observed_remote_addr;
  19259. svr.Get("/ip", [&](const Request &req, Response &res) {
  19260. observed_remote_addr = req.remote_addr;
  19261. res.set_content("ok", "text/plain");
  19262. });
  19263. int port = 0;
  19264. thread t = thread([&]() {
  19265. port = svr.bind_to_any_port(HOST);
  19266. svr.listen_after_bind();
  19267. });
  19268. auto se = detail::scope_exit([&] {
  19269. svr.stop();
  19270. t.join();
  19271. ASSERT_FALSE(svr.is_running());
  19272. });
  19273. svr.wait_until_ready();
  19274. Client cli(HOST, port);
  19275. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19277. EXPECT_EQ(StatusCode::OK_200, res->status);
  19278. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19279. observed_remote_addr == "127.0.0.1");
  19280. }
  19281. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19282. run_malformed_xff_test("");
  19283. }
  19284. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19285. run_malformed_xff_test(",");
  19286. }
  19287. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19288. run_malformed_xff_test(", , ,");
  19289. }
  19290. // The same rule applies to Accept: a request whose acceptable types are spread
  19291. // over several field lines must be negotiated against all of them.
  19292. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19293. // case-insensitive connection options. Comparing the whole field value against
  19294. // one option misses a client that sends several of them, and misses every
  19295. // casing but the one written in the comparison.
  19296. //
  19297. // Sends req, reads the response, then reuses the same socket for a second
  19298. // request to find out whether the server kept the connection.
  19299. static void probe_connection_reuse(int port, const std::string &req,
  19300. bool *announced_close, bool *reusable) {
  19301. auto error = Error::Success;
  19302. auto sock = detail::create_client_socket(
  19303. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19304. /*connection_timeout_sec=*/5, 0,
  19305. /*read_timeout_sec=*/1, 0,
  19306. /*write_timeout_sec=*/5, 0, std::string(), error);
  19307. ASSERT_NE(sock, INVALID_SOCKET);
  19308. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19309. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19310. "Host: localhost\r\n"
  19311. "Connection: close\r\n"
  19312. "\r\n";
  19313. std::string first_response;
  19314. std::string second_response;
  19315. detail::process_client_socket(
  19316. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19317. [&](Stream &strm) {
  19318. if (strm.write(req.data(), req.size()) !=
  19319. static_cast<ssize_t>(req.size())) {
  19320. return false;
  19321. }
  19322. char buf[512];
  19323. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19324. // Headers plus the two-byte body of the handler below
  19325. while (reader.getline()) {
  19326. first_response += reader.ptr();
  19327. if (first_response.find("ok") != std::string::npos) { break; }
  19328. }
  19329. if (strm.write(second.data(), second.size()) !=
  19330. static_cast<ssize_t>(second.size())) {
  19331. return true;
  19332. }
  19333. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19334. while (reader2.getline()) {
  19335. second_response += reader2.ptr();
  19336. if (second_response.find("ok") != std::string::npos) { break; }
  19337. }
  19338. return true;
  19339. });
  19340. *announced_close =
  19341. first_response.find("Connection: close") != std::string::npos;
  19342. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19343. }
  19344. class ConnectionTokenTest : public ::testing::Test {
  19345. protected:
  19346. void SetUp() override {
  19347. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19348. res.set_content("ok", "text/plain");
  19349. });
  19350. port_ = svr_.bind_to_any_port(HOST);
  19351. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19352. svr_.wait_until_ready();
  19353. }
  19354. void TearDown() override {
  19355. svr_.stop();
  19356. if (thread_.joinable()) { thread_.join(); }
  19357. }
  19358. Server svr_;
  19359. int port_ = 0;
  19360. thread thread_;
  19361. };
  19362. // "close" alongside another option still closes the connection, and the
  19363. // response says so rather than leaving the peer to discover it.
  19364. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  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, close\r\n"
  19371. "\r\n",
  19372. &announced_close, &reusable);
  19373. EXPECT_TRUE(announced_close);
  19374. EXPECT_FALSE(reusable);
  19375. }
  19376. // "close" split over two field lines is the same list, so it is honored too.
  19377. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19378. bool announced_close = false;
  19379. bool reusable = true;
  19380. probe_connection_reuse(port_,
  19381. "GET /keepalive HTTP/1.1\r\n"
  19382. "Host: localhost\r\n"
  19383. "Connection: keep-alive\r\n"
  19384. "Connection: close\r\n"
  19385. "\r\n",
  19386. &announced_close, &reusable);
  19387. EXPECT_TRUE(announced_close);
  19388. EXPECT_FALSE(reusable);
  19389. }
  19390. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19391. // keep-alive in the spelling everyone actually sends keeps its connection.
  19392. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19393. bool announced_close = false;
  19394. bool reusable = false;
  19395. probe_connection_reuse(port_,
  19396. "GET /keepalive HTTP/1.0\r\n"
  19397. "Host: localhost\r\n"
  19398. "Connection: keep-alive\r\n"
  19399. "\r\n",
  19400. &announced_close, &reusable);
  19401. EXPECT_FALSE(announced_close);
  19402. EXPECT_TRUE(reusable);
  19403. }
  19404. // A token the value merely contains is not the token itself.
  19405. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19406. bool announced_close = false;
  19407. bool reusable = false;
  19408. probe_connection_reuse(port_,
  19409. "GET /keepalive HTTP/1.1\r\n"
  19410. "Host: localhost\r\n"
  19411. "Connection: notclose\r\n"
  19412. "\r\n",
  19413. &announced_close, &reusable);
  19414. EXPECT_FALSE(announced_close);
  19415. EXPECT_TRUE(reusable);
  19416. }
  19417. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19418. Server svr;
  19419. std::vector<std::string> observed_types;
  19420. svr.Get("/", [&](const Request &req, Response &res) {
  19421. observed_types = req.accept_content_types;
  19422. res.set_content("ok", "text/plain");
  19423. });
  19424. auto port = svr.bind_to_any_port(HOST);
  19425. thread t = thread([&]() { svr.listen_after_bind(); });
  19426. auto se = detail::scope_exit([&] {
  19427. svr.stop();
  19428. t.join();
  19429. ASSERT_FALSE(svr.is_running());
  19430. });
  19431. svr.wait_until_ready();
  19432. Client cli(HOST, port);
  19433. Headers headers;
  19434. headers.emplace("Accept", "text/plain;q=0.5");
  19435. headers.emplace("Accept", "application/json");
  19436. auto res = cli.Get("/", headers);
  19437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19438. EXPECT_EQ(StatusCode::OK_200, res->status);
  19439. // Sorted by q-value, so the second field line's type comes first
  19440. ASSERT_EQ(2U, observed_types.size());
  19441. EXPECT_EQ("application/json", observed_types[0]);
  19442. EXPECT_EQ("text/plain", observed_types[1]);
  19443. }
  19444. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19445. // empty field line must not contribute a bare comma to the combined value.
  19446. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19447. Server svr;
  19448. std::vector<std::string> observed_types;
  19449. svr.Get("/", [&](const Request &req, Response &res) {
  19450. observed_types = req.accept_content_types;
  19451. res.set_content("ok", "text/plain");
  19452. });
  19453. auto port = svr.bind_to_any_port(HOST);
  19454. thread t = thread([&]() { svr.listen_after_bind(); });
  19455. auto se = detail::scope_exit([&] {
  19456. svr.stop();
  19457. t.join();
  19458. ASSERT_FALSE(svr.is_running());
  19459. });
  19460. svr.wait_until_ready();
  19461. // Empty first field line, then a real one
  19462. std::string raw_req = "GET / HTTP/1.1\r\n"
  19463. "Host: localhost\r\n"
  19464. "Accept:\r\n"
  19465. "Accept: application/json\r\n"
  19466. "Connection: close\r\n"
  19467. "\r\n";
  19468. std::string out;
  19469. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19470. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19471. ASSERT_EQ(1U, observed_types.size());
  19472. EXPECT_EQ("application/json", observed_types[0]);
  19473. }
  19474. // The skip in get_combined_header_value() is what keeps an empty field line
  19475. // from contributing a bare comma. Only a trailing empty field line exercises
  19476. // it: a leading one is already covered by the "combined is still empty" check,
  19477. // and parse_accept_header() now ignores the empty element either way, so the
  19478. // request-level test above can no longer tell the two apart.
  19479. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19480. Headers headers;
  19481. headers.emplace("Accept", "text/html");
  19482. headers.emplace("Accept", "");
  19483. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19484. headers.clear();
  19485. headers.emplace("Accept", "");
  19486. headers.emplace("Accept", "application/json");
  19487. EXPECT_EQ("application/json",
  19488. detail::get_combined_header_value(headers, "Accept"));
  19489. }
  19490. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19491. // An encoding offered on a later Accept-Encoding field line is still offered.
  19492. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19493. Server svr;
  19494. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19495. res.set_content(std::string(1024, 'x'), "text/plain");
  19496. });
  19497. auto port = svr.bind_to_any_port(HOST);
  19498. thread t = thread([&]() { svr.listen_after_bind(); });
  19499. auto se = detail::scope_exit([&] {
  19500. svr.stop();
  19501. t.join();
  19502. ASSERT_FALSE(svr.is_running());
  19503. });
  19504. svr.wait_until_ready();
  19505. Client cli(HOST, port);
  19506. cli.set_decompress(false);
  19507. Headers headers;
  19508. headers.emplace("Accept-Encoding", "identity");
  19509. headers.emplace("Accept-Encoding", "gzip");
  19510. auto res = cli.Get("/", headers);
  19511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19512. EXPECT_EQ(StatusCode::OK_200, res->status);
  19513. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19514. }
  19515. #endif
  19516. #ifndef _WIN32
  19517. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19518. Server svr;
  19519. svr.Post("/post", [&](const Request &req, Response &res) {
  19520. res.set_content(req.body, "text/plain");
  19521. });
  19522. svr.Put("/put", [&](const Request &req, Response &res) {
  19523. res.set_content(req.body, "text/plain");
  19524. });
  19525. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19526. res.set_content(req.body, "text/plain");
  19527. });
  19528. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19529. res.set_content(req.body, "text/plain");
  19530. });
  19531. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19532. auto se = detail::scope_exit([&] {
  19533. svr.stop();
  19534. t.join();
  19535. ASSERT_FALSE(svr.is_running());
  19536. });
  19537. svr.wait_until_ready();
  19538. std::string resp;
  19539. // POST without Content-Length
  19540. ASSERT_TRUE(send_request(5,
  19541. "POST /post HTTP/1.1\r\n"
  19542. "Host: localhost\r\n"
  19543. "Connection: close\r\n"
  19544. "\r\n",
  19545. &resp));
  19546. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19547. // PUT without Content-Length
  19548. resp.clear();
  19549. ASSERT_TRUE(send_request(5,
  19550. "PUT /put HTTP/1.1\r\n"
  19551. "Host: localhost\r\n"
  19552. "Connection: close\r\n"
  19553. "\r\n",
  19554. &resp));
  19555. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19556. // PATCH without Content-Length
  19557. resp.clear();
  19558. ASSERT_TRUE(send_request(5,
  19559. "PATCH /patch HTTP/1.1\r\n"
  19560. "Host: localhost\r\n"
  19561. "Connection: close\r\n"
  19562. "\r\n",
  19563. &resp));
  19564. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19565. // DELETE without Content-Length
  19566. resp.clear();
  19567. ASSERT_TRUE(send_request(5,
  19568. "DELETE /delete HTTP/1.1\r\n"
  19569. "Host: localhost\r\n"
  19570. "Connection: close\r\n"
  19571. "\r\n",
  19572. &resp));
  19573. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19574. }
  19575. #endif
  19576. //==============================================================================
  19577. // open_stream() Tests
  19578. //==============================================================================
  19579. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19580. std::string result;
  19581. char buf[8192];
  19582. ssize_t n;
  19583. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19584. result.append(buf, static_cast<size_t>(n));
  19585. }
  19586. return result;
  19587. }
  19588. // Mock stream for unit tests
  19589. class MockStream : public Stream {
  19590. public:
  19591. std::string data;
  19592. size_t pos = 0;
  19593. ssize_t error_after = -1; // -1 = no error
  19594. explicit MockStream(const std::string &d, ssize_t err = -1)
  19595. : data(d), error_after(err) {}
  19596. bool is_readable() const override { return true; }
  19597. bool wait_readable() const override { return true; }
  19598. bool wait_writable() const override { return true; }
  19599. ssize_t read(char *ptr, size_t size) override {
  19600. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19601. if (pos >= data.size()) return 0;
  19602. size_t limit =
  19603. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19604. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19605. std::memcpy(ptr, data.data() + pos, to_read);
  19606. pos += to_read;
  19607. return static_cast<ssize_t>(to_read);
  19608. }
  19609. ssize_t write(const char *, size_t) override { return -1; }
  19610. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19611. ip = "127.0.0.1";
  19612. port = 0;
  19613. }
  19614. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19615. ip = "127.0.0.1";
  19616. port = 0;
  19617. }
  19618. socket_t socket() const override { return INVALID_SOCKET; }
  19619. time_t duration() const override { return 0; }
  19620. };
  19621. TEST(StreamHandleTest, Basic) {
  19622. ClientImpl::StreamHandle handle;
  19623. EXPECT_FALSE(handle.is_valid());
  19624. handle.response = detail::make_unique<Response>();
  19625. handle.error = Error::Connection;
  19626. EXPECT_FALSE(handle.is_valid());
  19627. handle.error = Error::Success;
  19628. EXPECT_TRUE(handle.is_valid());
  19629. }
  19630. TEST(BodyReaderTest, Basic) {
  19631. MockStream stream("Hello, World!");
  19632. detail::BodyReader reader;
  19633. reader.stream = &stream;
  19634. reader.content_length = 13;
  19635. char buf[32];
  19636. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19637. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19638. EXPECT_TRUE(reader.eof);
  19639. }
  19640. TEST(BodyReaderTest, NoStream) {
  19641. detail::BodyReader reader;
  19642. char buf[32];
  19643. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19644. EXPECT_EQ(Error::Connection, reader.last_error);
  19645. }
  19646. TEST(BodyReaderTest, Error) {
  19647. MockStream stream("Hello, World!", 5);
  19648. detail::BodyReader reader;
  19649. reader.stream = &stream;
  19650. reader.content_length = 13;
  19651. char buf[32];
  19652. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19653. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19654. EXPECT_EQ(Error::Read, reader.last_error);
  19655. }
  19656. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19657. // Mock-based StreamHandle tests relying on private internals are removed.
  19658. class OpenStreamTest : public ::testing::Test {
  19659. protected:
  19660. void SetUp() override {
  19661. svr_.Get("/hello", [](const Request &, Response &res) {
  19662. res.set_content("Hello World!", "text/plain");
  19663. });
  19664. svr_.Get("/large", [](const Request &, Response &res) {
  19665. res.set_content(std::string(10000, 'X'), "text/plain");
  19666. });
  19667. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19668. res.set_content("Hello World!", "image/jpeg");
  19669. res.set_header("Content-Encoding", "UTF-8");
  19670. });
  19671. svr_.Get("/chunked", [](const Request &, Response &res) {
  19672. res.set_chunked_content_provider("text/plain",
  19673. [](size_t offset, DataSink &sink) {
  19674. if (offset < 15) {
  19675. sink.write("chunk", 5);
  19676. return true;
  19677. }
  19678. sink.done();
  19679. return true;
  19680. });
  19681. });
  19682. svr_.Get("/compressible", [](const Request &, Response &res) {
  19683. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19684. DataSink &sink) {
  19685. if (offset < 100 * 1024) {
  19686. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19687. sink.write(chunk.data(), chunk.size());
  19688. return true;
  19689. }
  19690. sink.done();
  19691. return true;
  19692. });
  19693. });
  19694. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19695. [](const Request & /*req*/, Response &res) {
  19696. auto i = new int(0);
  19697. res.set_header("Trailer", "Content-Length, X-Allowed");
  19698. res.set_chunked_content_provider(
  19699. "text/plain",
  19700. [i](size_t /*offset*/, DataSink &sink) {
  19701. switch (*i) {
  19702. case 0: sink.os << "123"; break;
  19703. case 1: sink.os << "456"; break;
  19704. case 2: sink.os << "789"; break;
  19705. case 3: {
  19706. sink.done_with_trailer(
  19707. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19708. } break;
  19709. }
  19710. (*i)++;
  19711. return true;
  19712. },
  19713. [i](bool success) {
  19714. EXPECT_TRUE(success);
  19715. delete i;
  19716. });
  19717. });
  19718. // Echo headers endpoint for header-related tests
  19719. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19720. std::string body;
  19721. for (const auto &h : req.headers) {
  19722. body.append(h.first);
  19723. body.push_back(':');
  19724. body.append(h.second);
  19725. body.push_back('\n');
  19726. }
  19727. res.set_content(body, "text/plain");
  19728. });
  19729. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19730. std::string body;
  19731. for (const auto &h : req.headers) {
  19732. body.append(h.first);
  19733. body.push_back(':');
  19734. body.append(h.second);
  19735. body.push_back('\n');
  19736. }
  19737. res.set_content(body, "text/plain");
  19738. });
  19739. port_ = svr_.bind_to_any_port("127.0.0.1");
  19740. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19741. svr_.wait_until_ready();
  19742. }
  19743. void TearDown() override {
  19744. svr_.stop();
  19745. if (thread_.joinable()) thread_.join();
  19746. }
  19747. Server svr_;
  19748. std::thread thread_;
  19749. int port_ = 0;
  19750. };
  19751. TEST_F(OpenStreamTest, Basic) {
  19752. Client cli("127.0.0.1", port_);
  19753. auto handle = cli.open_stream("GET", "/hello");
  19754. EXPECT_TRUE(handle.is_valid());
  19755. EXPECT_EQ("Hello World!", read_all(handle));
  19756. }
  19757. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19758. Client cli("127.0.0.1", port_);
  19759. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19760. ASSERT_TRUE(handle.is_valid());
  19761. EXPECT_EQ("Hello World!", read_all(handle));
  19762. }
  19763. TEST_F(OpenStreamTest, SmallBuffer) {
  19764. Client cli("127.0.0.1", port_);
  19765. auto handle = cli.open_stream("GET", "/hello");
  19766. std::string result;
  19767. char buf[4];
  19768. ssize_t n;
  19769. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19770. result.append(buf, static_cast<size_t>(n));
  19771. EXPECT_EQ("Hello World!", result);
  19772. }
  19773. TEST_F(OpenStreamTest, DefaultHeaders) {
  19774. Client cli("127.0.0.1", port_);
  19775. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19776. {
  19777. auto handle = cli.open_stream("GET", "/echo-headers");
  19778. ASSERT_TRUE(handle.is_valid());
  19779. auto body = read_all(handle);
  19780. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19781. std::string::npos);
  19782. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19783. std::string::npos);
  19784. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19785. }
  19786. // open_stream POST with body and no explicit content_type should NOT add
  19787. // text/plain Content-Type (behavior differs from non-streaming path), but
  19788. // should include Content-Length
  19789. {
  19790. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19791. ASSERT_TRUE(handle.is_valid());
  19792. auto body = read_all(handle);
  19793. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19794. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19795. }
  19796. // open_stream POST with explicit Content-Type should preserve it
  19797. {
  19798. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19799. {{"Content-Type", "application/custom"}},
  19800. "{}", "application/custom");
  19801. ASSERT_TRUE(handle.is_valid());
  19802. auto body = read_all(handle);
  19803. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19804. }
  19805. // User-specified User-Agent must not be overwritten for stream API
  19806. {
  19807. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19808. {{"User-Agent", "MyAgent/1.2"}});
  19809. ASSERT_TRUE(handle.is_valid());
  19810. auto body = read_all(handle);
  19811. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19812. }
  19813. }
  19814. TEST_F(OpenStreamTest, Large) {
  19815. Client cli("127.0.0.1", port_);
  19816. auto handle = cli.open_stream("GET", "/large");
  19817. EXPECT_EQ(10000u, read_all(handle).size());
  19818. }
  19819. TEST_F(OpenStreamTest, ConnectionError) {
  19820. Client cli("127.0.0.1", 9999);
  19821. auto handle = cli.open_stream("GET", "/hello");
  19822. EXPECT_FALSE(handle.is_valid());
  19823. }
  19824. TEST_F(OpenStreamTest, Chunked) {
  19825. Client cli("127.0.0.1", port_);
  19826. auto handle = cli.open_stream("GET", "/chunked");
  19827. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19828. "Transfer-Encoding") == "chunked");
  19829. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19830. }
  19831. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19832. Client cli("127.0.0.1", port_);
  19833. auto handle =
  19834. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19835. ASSERT_TRUE(handle.is_valid());
  19836. // Consume body to allow trailers to be received/parsed
  19837. auto body = read_all(handle);
  19838. // Explicitly parse trailers (ensure trailers are available for assertion)
  19839. handle.parse_trailers_if_needed();
  19840. EXPECT_EQ(std::string("123456789"), body);
  19841. // The response should include a Trailer header declaring both names
  19842. ASSERT_TRUE(handle.response);
  19843. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19844. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19845. handle.response->get_header_value("Trailer"));
  19846. // Prohibited trailer must not be present
  19847. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19848. // Allowed trailer should be present
  19849. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19850. EXPECT_EQ(std::string("yes"),
  19851. handle.response->get_trailer_value("X-Allowed"));
  19852. // Verify trailers are NOT present as regular headers
  19853. EXPECT_EQ(std::string(""),
  19854. handle.response->get_header_value("Content-Length"));
  19855. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19856. }
  19857. // Accepts one connection on an OS-assigned port, which it hands over through
  19858. // port_promise, reads the request head and sends back response. after_send,
  19859. // if given, runs on the connection before it is closed.
  19860. static std::thread
  19861. serve_single_response(std::promise<int> &port_promise,
  19862. const std::string &response,
  19863. std::function<void(socket_t)> after_send = nullptr) {
  19864. return std::thread([&port_promise, response, after_send] {
  19865. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19866. default_socket_options(srv);
  19867. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19868. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19869. sockaddr_in addr{};
  19870. addr.sin_family = AF_INET;
  19871. addr.sin_port = htons(0); // Let OS assign a free port
  19872. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19873. int opt = 1;
  19874. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19875. #ifdef _WIN32
  19876. reinterpret_cast<const char *>(&opt),
  19877. #else
  19878. &opt,
  19879. #endif
  19880. sizeof(opt));
  19881. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19882. ::listen(srv, 1) != 0) {
  19883. port_promise.set_value(-1);
  19884. detail::close_socket(srv);
  19885. return;
  19886. }
  19887. socklen_t addr_len = sizeof(addr);
  19888. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19889. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19890. sockaddr_in cli_addr{};
  19891. socklen_t cli_len = sizeof(cli_addr);
  19892. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19893. if (cli != INVALID_SOCKET) {
  19894. // Read the complete HTTP request (until the blank line that terminates
  19895. // headers) before sending the response. If the server closes the socket
  19896. // while the client's request data is still unread in the kernel receive
  19897. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19898. // connection on both sides: it discards the client's receive buffer
  19899. // (which already holds our response) and causes any in-progress write on
  19900. // the client to fail with ECONNRESET. Reading all request data first
  19901. // ensures close() emits a graceful FIN.
  19902. {
  19903. char rbuf[256];
  19904. std::string req;
  19905. while (req.find("\r\n\r\n") == std::string::npos) {
  19906. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19907. if (n <= 0) { break; }
  19908. req.append(rbuf, static_cast<size_t>(n));
  19909. }
  19910. }
  19911. ::send(cli,
  19912. #ifdef _WIN32
  19913. static_cast<const char *>(response.c_str()),
  19914. static_cast<int>(response.size()),
  19915. #else
  19916. response.c_str(), response.size(),
  19917. #endif
  19918. 0);
  19919. if (after_send) { after_send(cli); }
  19920. detail::close_socket(cli);
  19921. }
  19922. detail::close_socket(srv);
  19923. });
  19924. }
  19925. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19926. #ifndef _WIN32
  19927. signal(SIGPIPE, SIG_IGN);
  19928. #endif
  19929. std::promise<int> port_promise;
  19930. auto port_future = port_promise.get_future();
  19931. auto server_thread =
  19932. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19933. "Content-Type: text/plain\r\n"
  19934. "Content-Length: not-a-number\r\n"
  19935. "Connection: close\r\n"
  19936. "\r\n"
  19937. "hello");
  19938. auto port = port_future.get();
  19939. ASSERT_GT(port, 0);
  19940. Client cli("127.0.0.1", port);
  19941. auto handle = cli.open_stream("GET", "/");
  19942. EXPECT_FALSE(handle.is_valid());
  19943. server_thread.join();
  19944. }
  19945. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19946. #ifndef _WIN32
  19947. signal(SIGPIPE, SIG_IGN);
  19948. #endif
  19949. std::promise<int> port_promise;
  19950. auto port_future = port_promise.get_future();
  19951. auto server_thread = serve_single_response(
  19952. port_promise, "HTTP/1.1 200 OK\r\n"
  19953. "Content-Type: text/plain\r\n"
  19954. "Content-Length: 99999999999999999999999999\r\n"
  19955. "Connection: close\r\n"
  19956. "\r\n"
  19957. "hello");
  19958. auto port = port_future.get();
  19959. ASSERT_GT(port, 0);
  19960. // Historically std::stoull would throw std::out_of_range here and crash
  19961. // the process, then parsing silently clamped to a bogus framing length and
  19962. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19963. // so the stream fails to open, matching the not-a-number case above. The
  19964. // process still must NOT terminate.
  19965. Client cli("127.0.0.1", port);
  19966. auto handle = cli.open_stream("GET", "/");
  19967. EXPECT_FALSE(handle.is_valid());
  19968. server_thread.join();
  19969. }
  19970. // Serves `response` to the single request `fn` makes with a fresh client.
  19971. template <typename Fn>
  19972. static void with_single_response(const std::string &response, Fn fn) {
  19973. #ifndef _WIN32
  19974. signal(SIGPIPE, SIG_IGN);
  19975. #endif
  19976. std::promise<int> port_promise;
  19977. auto port_future = port_promise.get_future();
  19978. auto server_thread = serve_single_response(port_promise, response);
  19979. auto se = detail::scope_exit([&] { server_thread.join(); });
  19980. auto port = port_future.get();
  19981. ASSERT_GT(port, 0);
  19982. Client cli("127.0.0.1", port);
  19983. fn(cli);
  19984. }
  19985. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19986. // Neither Content-Length nor chunked: the body ends at the close
  19987. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19988. "Connection: close\r\n"
  19989. "\r\n"
  19990. "hello";
  19991. with_single_response(close_delimited, [](Client &cli) {
  19992. auto handle = cli.open_stream("GET", "/");
  19993. ASSERT_TRUE(handle.is_valid());
  19994. EXPECT_EQ("hello", read_all(handle));
  19995. EXPECT_FALSE(handle.has_read_error());
  19996. });
  19997. // A close before the end of the Content-Length is still an error
  19998. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19999. "Content-Length: 10\r\n"
  20000. "\r\n"
  20001. "hello";
  20002. with_single_response(short_content_length, [](Client &cli) {
  20003. auto handle = cli.open_stream("GET", "/");
  20004. ASSERT_TRUE(handle.is_valid());
  20005. read_all(handle);
  20006. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20007. });
  20008. // So is a close before the last chunk
  20009. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20010. "Transfer-Encoding: chunked\r\n"
  20011. "\r\n"
  20012. "5\r\nhello\r\n";
  20013. with_single_response(short_chunked, [](Client &cli) {
  20014. auto handle = cli.open_stream("GET", "/");
  20015. ASSERT_TRUE(handle.is_valid());
  20016. read_all(handle);
  20017. EXPECT_TRUE(handle.has_read_error());
  20018. });
  20019. }
  20020. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20021. const char *responses[] = {
  20022. "HTTP/1.1 103 Early Hints\r\n"
  20023. "Link: </style.css>; rel=preload\r\n"
  20024. "\r\n"
  20025. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20026. "HTTP/1.1 100 Continue\r\n"
  20027. "X-Note: interim\r\n"
  20028. "\r\n"
  20029. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20030. };
  20031. for (auto response : responses) {
  20032. with_single_response(response, [](Client &cli) {
  20033. auto res = cli.Get("/");
  20034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20035. EXPECT_EQ(StatusCode::OK_200, res->status);
  20036. EXPECT_EQ("ok", res->body);
  20037. });
  20038. }
  20039. }
  20040. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20041. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20042. const std::string final_response =
  20043. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20044. std::string interims;
  20045. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20046. interims += interim;
  20047. }
  20048. with_single_response(interims + final_response, [](Client &cli) {
  20049. auto res = cli.Get("/");
  20050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20051. EXPECT_EQ("ok", res->body);
  20052. });
  20053. with_single_response(interims + interim + final_response, [](Client &cli) {
  20054. auto res = cli.Get("/");
  20055. ASSERT_FALSE(res);
  20056. EXPECT_EQ(Error::Read, res.error());
  20057. });
  20058. }
  20059. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20060. #ifndef _WIN32
  20061. signal(SIGPIPE, SIG_IGN);
  20062. #endif
  20063. // The server answers the head without asking for the body. Bytes it then
  20064. // reads on the connection would be taken for the body the request declared.
  20065. auto closed_by_client = false;
  20066. std::promise<int> port_promise;
  20067. auto server_thread = serve_single_response(
  20068. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20069. [&](socket_t sock) {
  20070. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20071. char buf[256];
  20072. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20073. });
  20074. Client cli("127.0.0.1", port_promise.get_future().get());
  20075. cli.set_keep_alive(true);
  20076. cli.set_read_timeout(1, 0);
  20077. // Long enough for the client to send Expect: 100-continue.
  20078. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20080. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20081. cli.Get("/second");
  20082. server_thread.join();
  20083. EXPECT_TRUE(closed_by_client);
  20084. }
  20085. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20086. // Long enough for the client to send Expect: 100-continue
  20087. with_single_response(
  20088. "HTTP/1.1 103 Early Hints\r\n"
  20089. "Link: </style.css>; rel=preload\r\n"
  20090. "\r\n"
  20091. "HTTP/1.1 401 Unauthorized\r\n"
  20092. "Content-Length: 0\r\n\r\n",
  20093. [](Client &cli) {
  20094. cli.set_read_timeout(2, 0);
  20095. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20097. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20098. });
  20099. }
  20100. #ifdef CPPHTTPLIB_SSL_ENABLED
  20101. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20102. #ifndef _WIN32
  20103. signal(SIGPIPE, SIG_IGN);
  20104. #endif
  20105. auto reused = false;
  20106. std::promise<int> port_promise;
  20107. auto server_thread = serve_single_response(
  20108. port_promise,
  20109. "HTTP/1.1 401 Unauthorized\r\n"
  20110. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20111. "Content-Length: 0\r\n\r\n",
  20112. [&](socket_t sock) {
  20113. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20114. char buf[256];
  20115. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20116. });
  20117. Client cli("127.0.0.1", port_promise.get_future().get());
  20118. cli.set_keep_alive(true);
  20119. cli.set_digest_auth("user", "pass");
  20120. cli.set_read_timeout(1, 0);
  20121. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20122. server_thread.join();
  20123. EXPECT_FALSE(reused);
  20124. }
  20125. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20126. // Any other answer to CONNECT would read as the origin's response.
  20127. struct {
  20128. const char *response;
  20129. bool passed_on;
  20130. } cases[] = {
  20131. {"HTTP/1.1 201 Created\r\n"
  20132. "Set-Cookie: session=from-proxy\r\n"
  20133. "Content-Length: 0\r\n\r\n",
  20134. false},
  20135. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20136. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20137. "Content-Length: 0\r\n\r\n",
  20138. true},
  20139. };
  20140. for (const auto &c : cases) {
  20141. std::promise<int> port_promise;
  20142. auto server_thread = serve_single_response(port_promise, c.response);
  20143. SSLClient cli("example.com", 443);
  20144. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20145. auto res = cli.Get("/");
  20146. server_thread.join();
  20147. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20148. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20149. if (res) {
  20150. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20151. }
  20152. }
  20153. }
  20154. #endif
  20155. // Records the client's error logger calls as "error METHOD path", or
  20156. // "error null" for a call without a request
  20157. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20158. return [&log](const Error &err, const Request *req) {
  20159. log.push_back(to_string(err) + " " +
  20160. (req ? req->method + " " + req->path : "null"));
  20161. };
  20162. }
  20163. // A failed request is reported once, with the request the caller made
  20164. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20165. Server svr;
  20166. svr.Get("/big", [](const Request &, Response &res) {
  20167. res.set_content(std::string(100000, 'b'), "text/plain");
  20168. });
  20169. auto port = svr.bind_to_any_port(HOST);
  20170. std::thread t([&]() { svr.listen_after_bind(); });
  20171. auto se = detail::scope_exit([&] {
  20172. svr.stop();
  20173. t.join();
  20174. });
  20175. svr.wait_until_ready();
  20176. Client cli(HOST, port);
  20177. std::vector<std::string> log;
  20178. cli.set_error_logger(record_errors(log));
  20179. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20180. cli.Get("/big", [](const char *, size_t) { return false; });
  20181. EXPECT_EQ(expected, log);
  20182. log.clear();
  20183. cli.Get("/big", [](size_t, size_t) { return false; });
  20184. EXPECT_EQ(expected, log);
  20185. }
  20186. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20187. // Fails while the body is read
  20188. auto broken = [](const Request &, Response &res) {
  20189. res.set_content_provider(10, "text/plain",
  20190. [](size_t, size_t, DataSink &) { return false; });
  20191. };
  20192. Server other;
  20193. other.Get("/broken", broken);
  20194. auto other_port = other.bind_to_any_port(HOST);
  20195. std::thread other_t([&]() { other.listen_after_bind(); });
  20196. auto other_se = detail::scope_exit([&] {
  20197. other.stop();
  20198. other_t.join();
  20199. });
  20200. other.wait_until_ready();
  20201. Server svr;
  20202. svr.Get("/broken", broken);
  20203. svr.Get("/same-origin",
  20204. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20205. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20206. res.set_redirect("http://" + std::string(HOST) + ":" +
  20207. std::to_string(other_port) + "/broken");
  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. cli.set_follow_location(true);
  20218. std::vector<std::string> log;
  20219. cli.set_error_logger(record_errors(log));
  20220. for (auto path : {"/same-origin", "/cross-origin"}) {
  20221. log.clear();
  20222. auto res = cli.Get(path);
  20223. ASSERT_FALSE(res);
  20224. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20225. log);
  20226. }
  20227. }
  20228. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20229. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20230. std::vector<std::string> log;
  20231. cli.set_error_logger(record_errors(log));
  20232. auto handle = cli.open_stream("GET", "/x");
  20233. EXPECT_FALSE(handle.is_valid());
  20234. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20235. log);
  20236. });
  20237. }
  20238. #ifdef CPPHTTPLIB_SSL_ENABLED
  20239. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20240. // Not a TLS server, so the handshake fails. It waits for a request line in
  20241. // the handshake bytes, so a short read timeout lets it close quickly.
  20242. Server svr;
  20243. svr.set_read_timeout(0, 100000);
  20244. svr.Get("/x", [](const Request &, Response &res) {
  20245. res.set_content("x", "text/plain");
  20246. });
  20247. auto port = svr.bind_to_any_port(HOST);
  20248. std::thread t([&]() { svr.listen_after_bind(); });
  20249. auto se = detail::scope_exit([&] {
  20250. svr.stop();
  20251. t.join();
  20252. });
  20253. svr.wait_until_ready();
  20254. std::vector<std::string> log;
  20255. SSLClient cli(HOST, port);
  20256. cli.enable_server_certificate_verification(false);
  20257. cli.set_error_logger(record_errors(log));
  20258. auto res = cli.Get("/x");
  20259. ASSERT_FALSE(res);
  20260. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20261. log.clear();
  20262. auto handle = cli.open_stream("GET", "/x");
  20263. EXPECT_FALSE(handle.is_valid());
  20264. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20265. log.clear();
  20266. SSLClient no_ca(HOST, port);
  20267. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20268. no_ca.set_error_logger(record_errors(log));
  20269. res = no_ca.Get("/x");
  20270. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20271. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20272. }
  20273. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20274. #ifndef _WIN32
  20275. signal(SIGPIPE, SIG_IGN);
  20276. #endif
  20277. // Refused, answered with a challenge, or closed without an answer
  20278. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20279. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20280. "Content-Length: 0\r\n\r\n",
  20281. ""}) {
  20282. std::promise<int> port_promise;
  20283. auto server_thread = serve_single_response(port_promise, response);
  20284. SSLClient cli("example.com", 443);
  20285. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20286. std::vector<std::string> log;
  20287. cli.set_error_logger(record_errors(log));
  20288. auto res = cli.Get("/");
  20289. server_thread.join();
  20290. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20291. << response;
  20292. }
  20293. }
  20294. #endif
  20295. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20296. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20297. // the chunked coding and drop Content-Length, so a front-end that trusts
  20298. // Content-Length would disagree about where the body ends (response
  20299. // smuggling). The client must reject such a response.
  20300. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20301. for (const char *te : {"chunked", "gzip, chunked"}) {
  20302. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20303. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20304. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20305. "5\r\nhello\r\n0\r\n\r\n";
  20306. with_single_response(response, [&](Client &cli) {
  20307. auto res = cli.Get("/");
  20308. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20309. EXPECT_EQ(Error::Read, res.error()) << te;
  20310. });
  20311. with_single_response(response, [&](Client &cli) {
  20312. auto handle = cli.open_stream("GET", "/");
  20313. EXPECT_FALSE(handle.is_valid()) << te;
  20314. EXPECT_EQ(Error::Read, handle.error) << te;
  20315. });
  20316. }
  20317. }
  20318. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20319. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20320. // closing the connection (unlike a request, which must be rejected).
  20321. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20322. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20323. "Transfer-Encoding: chunked\r\n"
  20324. "Connection: close\r\n"
  20325. "\r\n"
  20326. "5\r\nhello\r\n0\r\n\r\n",
  20327. "HTTP/1.1 200 OK\r\n"
  20328. "Transfer-Encoding: gzip\r\n"
  20329. "Connection: close\r\n"
  20330. "\r\n"
  20331. "hello"}) {
  20332. with_single_response(response, [&](Client &cli) {
  20333. auto res = cli.Get("/");
  20334. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20335. EXPECT_EQ("hello", res->body);
  20336. });
  20337. with_single_response(response, [&](Client &cli) {
  20338. auto handle = cli.open_stream("GET", "/");
  20339. ASSERT_TRUE(handle.is_valid()) << response;
  20340. EXPECT_EQ("hello", read_all(handle));
  20341. });
  20342. }
  20343. }
  20344. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20345. // framing headers describe nothing to read and must not be rejected.
  20346. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20347. const std::string framing = "Content-Length: 5\r\n"
  20348. "Transfer-Encoding: chunked\r\n"
  20349. "Connection: close\r\n"
  20350. "\r\n";
  20351. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20352. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20353. });
  20354. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20355. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20356. });
  20357. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20358. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20359. with_single_response(response, [&](Client &cli) {
  20360. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20361. });
  20362. with_single_response(response, [&](Client &cli) {
  20363. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20364. });
  20365. }
  20366. }
  20367. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20368. // header section, so a stream opened on one has nothing to read, whatever
  20369. // framing or coding headers it carries.
  20370. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20371. struct Case {
  20372. const char *method;
  20373. const char *status;
  20374. };
  20375. // A reader of the declared body reports an early close when nothing
  20376. // follows, and hands back what does.
  20377. struct Framing {
  20378. const char *headers;
  20379. const char *after;
  20380. };
  20381. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20382. Case{"GET", "304 Not Modified"}}) {
  20383. for (const auto &f :
  20384. {Framing{"Content-Length: 5\r\n", ""},
  20385. Framing{"Content-Length: 5\r\n", "hello"},
  20386. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20387. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20388. // Not decoded, so a build without Brotli opens it too
  20389. Framing{"Content-Encoding: br\r\n", ""}}) {
  20390. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20391. "Connection: close\r\n"
  20392. "\r\n" +
  20393. f.after;
  20394. with_single_response(response, [&](Client &cli) {
  20395. auto handle = cli.open_stream(c.method, "/");
  20396. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20397. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20398. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20399. });
  20400. }
  20401. }
  20402. }
  20403. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20404. // response, is faulty framing, so the connection is not reused after it.
  20405. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20406. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20407. "Content-Length: 0\r\n"
  20408. "Transfer-Encoding: chunked\r\n"
  20409. "\r\n"
  20410. "5\r\nhello\r\n0\r\n\r\n",
  20411. "HTTP/1.0 200 Connection established\r\n"
  20412. "Connection: keep-alive\r\n"
  20413. "Transfer-Encoding: chunked\r\n"
  20414. "\r\n"
  20415. "5\r\nhello\r\n0\r\n\r\n"}) {
  20416. with_single_response(response, [&](Client &cli) {
  20417. cli.set_keep_alive(true);
  20418. auto res = cli.Get("/");
  20419. ASSERT_TRUE(res) << response;
  20420. EXPECT_EQ("hello", res->body);
  20421. EXPECT_FALSE(cli.is_socket_open()) << response;
  20422. });
  20423. }
  20424. }
  20425. // A payload max length of 0 means no limit, however the body is framed.
  20426. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20427. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20428. "Transfer-Encoding: chunked\r\n"
  20429. "\r\n"
  20430. "5\r\nhello\r\n0\r\n\r\n",
  20431. "HTTP/1.1 200 OK\r\n"
  20432. "Connection: close\r\n"
  20433. "\r\n"
  20434. "hello"}) {
  20435. with_single_response(response, [&](Client &cli) {
  20436. cli.set_payload_max_length(0);
  20437. auto res = cli.Get("/");
  20438. ASSERT_TRUE(res) << response;
  20439. EXPECT_EQ("hello", res->body) << response;
  20440. });
  20441. }
  20442. }
  20443. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20444. Server svr;
  20445. svr.set_payload_max_length(0);
  20446. svr.Post("/echo", [](const Request &req, Response &res) {
  20447. res.set_content(req.body, "text/plain");
  20448. });
  20449. auto port = svr.bind_to_any_port(HOST);
  20450. thread t = thread([&] { svr.listen_after_bind(); });
  20451. auto se = detail::scope_exit([&] {
  20452. svr.stop();
  20453. t.join();
  20454. ASSERT_FALSE(svr.is_running());
  20455. });
  20456. svr.wait_until_ready();
  20457. Client cli(HOST, port);
  20458. auto res = cli.Post(
  20459. "/echo",
  20460. [](size_t /*offset*/, DataSink &sink) {
  20461. sink.write("hello", 5);
  20462. sink.done();
  20463. return true;
  20464. },
  20465. "text/plain");
  20466. ASSERT_TRUE(res);
  20467. EXPECT_EQ(StatusCode::OK_200, res->status);
  20468. EXPECT_EQ("hello", res->body);
  20469. }
  20470. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20471. TEST_F(OpenStreamTest, Gzip) {
  20472. Client cli("127.0.0.1", port_);
  20473. auto handle = cli.open_stream("GET", "/compressible", {},
  20474. {{"Accept-Encoding", "gzip"}});
  20475. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20476. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20477. }
  20478. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20479. Client cli("127.0.0.1", port_);
  20480. auto handle =
  20481. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20482. {{"Accept-Encoding", "gzip"}});
  20483. ASSERT_TRUE(handle.is_valid());
  20484. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20485. EXPECT_EQ("123456789", read_all(handle));
  20486. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20487. }
  20488. #endif
  20489. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20490. TEST_F(OpenStreamTest, Brotli) {
  20491. Client cli("127.0.0.1", port_);
  20492. auto handle =
  20493. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20494. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20495. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20496. }
  20497. #endif
  20498. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20499. TEST_F(OpenStreamTest, Zstd) {
  20500. Client cli("127.0.0.1", port_);
  20501. auto handle = cli.open_stream("GET", "/compressible", {},
  20502. {{"Accept-Encoding", "zstd"}});
  20503. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20504. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20505. }
  20506. #endif
  20507. #ifdef CPPHTTPLIB_SSL_ENABLED
  20508. class SSLOpenStreamTest : public ::testing::Test {
  20509. protected:
  20510. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20511. void SetUp() override {
  20512. svr_.Get("/hello", [](const Request &, Response &res) {
  20513. res.set_content("Hello SSL World!", "text/plain");
  20514. });
  20515. svr_.Get("/chunked", [](const Request &, Response &res) {
  20516. res.set_chunked_content_provider("text/plain",
  20517. [](size_t offset, DataSink &sink) {
  20518. if (offset < 15) {
  20519. sink.write("chunk", 5);
  20520. return true;
  20521. }
  20522. sink.done();
  20523. return true;
  20524. });
  20525. });
  20526. svr_.Post("/echo", [](const Request &req, Response &res) {
  20527. res.set_content(req.body, req.get_header_value("Content-Type"));
  20528. });
  20529. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20530. std::string body = req.body;
  20531. res.set_chunked_content_provider(
  20532. "text/plain", [body](size_t offset, DataSink &sink) {
  20533. if (offset < body.size()) {
  20534. sink.write(body.data() + offset, body.size() - offset);
  20535. }
  20536. sink.done();
  20537. return true;
  20538. });
  20539. });
  20540. port_ = svr_.bind_to_any_port("127.0.0.1");
  20541. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20542. svr_.wait_until_ready();
  20543. }
  20544. void TearDown() override {
  20545. svr_.stop();
  20546. if (thread_.joinable()) thread_.join();
  20547. }
  20548. SSLServer svr_;
  20549. std::thread thread_;
  20550. int port_ = 0;
  20551. };
  20552. TEST_F(SSLOpenStreamTest, Basic) {
  20553. SSLClient cli("127.0.0.1", port_);
  20554. cli.enable_server_certificate_verification(false);
  20555. auto handle = cli.open_stream("GET", "/hello");
  20556. ASSERT_TRUE(handle.is_valid());
  20557. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20558. }
  20559. TEST_F(SSLOpenStreamTest, Chunked) {
  20560. SSLClient cli("127.0.0.1", port_);
  20561. cli.enable_server_certificate_verification(false);
  20562. auto handle = cli.open_stream("GET", "/chunked");
  20563. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20564. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20565. "Transfer-Encoding") == "chunked");
  20566. auto body = read_all(handle);
  20567. EXPECT_EQ("chunkchunkchunk", body);
  20568. }
  20569. TEST_F(SSLOpenStreamTest, Post) {
  20570. SSLClient cli("127.0.0.1", port_);
  20571. cli.enable_server_certificate_verification(false);
  20572. auto handle =
  20573. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20574. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20575. EXPECT_EQ(200, handle.response->status);
  20576. auto body = read_all(handle);
  20577. EXPECT_EQ("Hello SSL POST", body);
  20578. }
  20579. TEST_F(SSLOpenStreamTest, PostChunked) {
  20580. SSLClient cli("127.0.0.1", port_);
  20581. cli.enable_server_certificate_verification(false);
  20582. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20583. "Chunked SSL Data", "text/plain");
  20584. ASSERT_TRUE(handle.is_valid());
  20585. EXPECT_EQ(200, handle.response->status);
  20586. auto body = read_all(handle);
  20587. EXPECT_EQ("Chunked SSL Data", body);
  20588. }
  20589. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20590. // Content-Length is terminated by the server closing the connection. When the
  20591. // SSL peer sends a close_notify after the body, the client must treat it as a
  20592. // clean EOF and return a successful response rather than an error.
  20593. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20594. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20595. ASSERT_TRUE(svr.is_valid());
  20596. svr.set_keep_alive_max_count(1);
  20597. const std::string expected_body = "Hello from connection-close response!";
  20598. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20599. res.set_content_provider("text/plain",
  20600. [&](size_t offset, DataSink &sink) -> bool {
  20601. if (offset < expected_body.size()) {
  20602. sink.write(expected_body.data() + offset,
  20603. expected_body.size() - offset);
  20604. }
  20605. sink.done();
  20606. return true;
  20607. });
  20608. });
  20609. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20610. auto se = detail::scope_exit([&] {
  20611. svr.stop();
  20612. listen_thread.join();
  20613. ASSERT_FALSE(svr.is_running());
  20614. });
  20615. svr.wait_until_ready();
  20616. SSLClient cli(HOST, PORT);
  20617. cli.enable_server_certificate_verification(false);
  20618. auto res = cli.Get("/no-content-length");
  20619. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20620. EXPECT_EQ(StatusCode::OK_200, res->status);
  20621. EXPECT_EQ(expected_body, res->body);
  20622. }
  20623. #endif // CPPHTTPLIB_SSL_ENABLED
  20624. //==============================================================================
  20625. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20626. // results for various scenarios.
  20627. //==============================================================================
  20628. TEST(ParityTest, GetVsOpenStream) {
  20629. Server svr;
  20630. const std::string path = "/parity";
  20631. const std::string content = "Parity test content: hello world";
  20632. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20633. res.set_content(content, "text/plain");
  20634. });
  20635. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20636. auto se = detail::scope_exit([&] {
  20637. svr.stop();
  20638. t.join();
  20639. ASSERT_FALSE(svr.is_running());
  20640. });
  20641. svr.wait_until_ready();
  20642. Client cli(HOST, PORT);
  20643. // Non-stream path
  20644. auto r1 = cli.Get(path);
  20645. ASSERT_TRUE(r1);
  20646. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20647. // Stream path
  20648. auto h = cli.open_stream("GET", path);
  20649. ASSERT_TRUE(h.is_valid());
  20650. EXPECT_EQ(r1->body, read_all(h));
  20651. }
  20652. // Helper to compress data with provided compressor type T
  20653. template <typename Compressor>
  20654. static std::string compress_payload_for_parity(const std::string &in) {
  20655. std::string out;
  20656. Compressor compressor;
  20657. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20658. [&](const char *data, size_t n) {
  20659. out.append(data, n);
  20660. return true;
  20661. });
  20662. EXPECT_TRUE(ok);
  20663. return out;
  20664. }
  20665. // Helper function for compression parity tests
  20666. template <typename Compressor>
  20667. static void test_compression_parity(const std::string &original,
  20668. const std::string &path,
  20669. const std::string &encoding) {
  20670. const std::string compressed =
  20671. compress_payload_for_parity<Compressor>(original);
  20672. Server svr;
  20673. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20674. res.set_content(compressed, "application/octet-stream");
  20675. res.set_header("Content-Encoding", encoding);
  20676. });
  20677. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20678. auto se = detail::scope_exit([&] {
  20679. svr.stop();
  20680. t.join();
  20681. ASSERT_FALSE(svr.is_running());
  20682. });
  20683. svr.wait_until_ready();
  20684. Client cli(HOST, PORT);
  20685. // Non-streaming
  20686. {
  20687. auto res = cli.Get(path);
  20688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20689. EXPECT_EQ(StatusCode::OK_200, res->status);
  20690. EXPECT_EQ(original, res->body);
  20691. }
  20692. // Streaming
  20693. {
  20694. auto h = cli.open_stream("GET", path);
  20695. ASSERT_TRUE(h.is_valid());
  20696. EXPECT_EQ(original, read_all(h));
  20697. }
  20698. }
  20699. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20700. TEST(ParityTest, Gzip) {
  20701. test_compression_parity<detail::gzip_compressor>(
  20702. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20703. }
  20704. #endif
  20705. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20706. TEST(ParityTest, Brotli) {
  20707. test_compression_parity<detail::brotli_compressor>(
  20708. "Hello, brotli parity test payload", "/parity-br", "br");
  20709. }
  20710. #endif
  20711. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20712. TEST(ParityTest, Zstd) {
  20713. test_compression_parity<detail::zstd_compressor>(
  20714. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20715. }
  20716. #endif
  20717. //==============================================================================
  20718. // New Stream API Tests
  20719. //==============================================================================
  20720. inline std::string read_body(httplib::stream::Result &result) {
  20721. std::string body;
  20722. while (result.next()) {
  20723. body.append(result.data(), result.size());
  20724. }
  20725. return body;
  20726. }
  20727. TEST(ClientConnectionTest, Basic) {
  20728. httplib::ClientConnection conn;
  20729. EXPECT_FALSE(conn.is_open());
  20730. conn.sock = 1;
  20731. EXPECT_TRUE(conn.is_open());
  20732. httplib::ClientConnection conn2(std::move(conn));
  20733. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20734. conn2.sock = INVALID_SOCKET;
  20735. }
  20736. // Unified test server for all stream::* tests
  20737. class StreamApiTest : public ::testing::Test {
  20738. protected:
  20739. void SetUp() override {
  20740. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20741. res.set_content("Hello World!", "text/plain");
  20742. });
  20743. svr_.Get("/echo-params",
  20744. [](const httplib::Request &req, httplib::Response &res) {
  20745. std::string r;
  20746. for (const auto &p : req.params) {
  20747. if (!r.empty()) r += "&";
  20748. r += p.first + "=" + p.second;
  20749. }
  20750. res.set_content(r, "text/plain");
  20751. });
  20752. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20753. res.set_content(req.body, req.get_header_value("Content-Type"));
  20754. });
  20755. svr_.Post("/echo-headers",
  20756. [](const httplib::Request &req, httplib::Response &res) {
  20757. std::string r;
  20758. for (const auto &h : req.headers)
  20759. r += h.first + ": " + h.second + "\n";
  20760. res.set_content(r, "text/plain");
  20761. });
  20762. svr_.Post("/echo-params",
  20763. [](const httplib::Request &req, httplib::Response &res) {
  20764. std::string r = "params:";
  20765. for (const auto &p : req.params)
  20766. r += p.first + "=" + p.second + ";";
  20767. res.set_content(r + " body:" + req.body, "text/plain");
  20768. });
  20769. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20770. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20771. });
  20772. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20773. res.set_content("PUT:" + req.body, "text/plain");
  20774. });
  20775. svr_.Patch("/echo",
  20776. [](const httplib::Request &req, httplib::Response &res) {
  20777. res.set_content("PATCH:" + req.body, "text/plain");
  20778. });
  20779. svr_.Delete(
  20780. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20781. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20782. "text/plain");
  20783. });
  20784. svr_.Get("/head-test",
  20785. [](const httplib::Request &, httplib::Response &res) {
  20786. res.set_content("body for HEAD", "text/plain");
  20787. });
  20788. svr_.Options("/options",
  20789. [](const httplib::Request &, httplib::Response &res) {
  20790. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20791. });
  20792. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20793. svr_.wait_until_ready();
  20794. }
  20795. void TearDown() override {
  20796. svr_.stop();
  20797. if (thread_.joinable()) thread_.join();
  20798. }
  20799. httplib::Server svr_;
  20800. std::thread thread_;
  20801. };
  20802. // stream::Get tests
  20803. TEST_F(StreamApiTest, GetBasic) {
  20804. httplib::Client cli(HOST, PORT);
  20805. auto result = httplib::stream::Get(cli, "/hello");
  20806. ASSERT_TRUE(result.is_valid());
  20807. EXPECT_EQ(200, result.status());
  20808. EXPECT_EQ("Hello World!", read_body(result));
  20809. }
  20810. TEST_F(StreamApiTest, GetWithParams) {
  20811. httplib::Client cli(HOST, PORT);
  20812. httplib::Params params{{"foo", "bar"}};
  20813. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20814. ASSERT_TRUE(result.is_valid());
  20815. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20816. }
  20817. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20818. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20819. httplib::Client cli(HOST, PORT);
  20820. cli.set_payload_max_length(0);
  20821. auto result = httplib::stream::Get(cli, "/hello");
  20822. ASSERT_TRUE(result.is_valid());
  20823. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20824. EXPECT_EQ("Hello World!", read_body(result));
  20825. }
  20826. #endif
  20827. TEST_F(StreamApiTest, GetConnectionError) {
  20828. httplib::Client cli(HOST, 9999);
  20829. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20830. }
  20831. TEST_F(StreamApiTest, Get404) {
  20832. httplib::Client cli(HOST, PORT);
  20833. auto result = httplib::stream::Get(cli, "/nonexistent");
  20834. EXPECT_TRUE(result.is_valid());
  20835. EXPECT_EQ(404, result.status());
  20836. }
  20837. // stream::Post tests
  20838. TEST_F(StreamApiTest, PostBasic) {
  20839. httplib::Client cli(HOST, PORT);
  20840. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20841. "application/json");
  20842. ASSERT_TRUE(result.is_valid());
  20843. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20844. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20845. }
  20846. TEST_F(StreamApiTest, PostWithHeaders) {
  20847. httplib::Client cli(HOST, PORT);
  20848. httplib::Headers headers{{"X-Custom", "value"}};
  20849. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20850. "text/plain");
  20851. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20852. }
  20853. TEST_F(StreamApiTest, PostWithParams) {
  20854. httplib::Client cli(HOST, PORT);
  20855. httplib::Params params{{"k", "v"}};
  20856. auto result =
  20857. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20858. auto body = read_body(result);
  20859. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20860. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20861. }
  20862. TEST_F(StreamApiTest, PostLarge) {
  20863. httplib::Client cli(HOST, PORT);
  20864. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20865. size_t total = 0;
  20866. while (result.next()) {
  20867. total += result.size();
  20868. }
  20869. EXPECT_EQ(100u * 1024u, total);
  20870. }
  20871. // stream::Put/Patch tests
  20872. TEST_F(StreamApiTest, PutAndPatch) {
  20873. httplib::Client cli(HOST, PORT);
  20874. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20875. EXPECT_EQ("PUT:test", read_body(put));
  20876. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20877. EXPECT_EQ("PATCH:test", read_body(patch));
  20878. }
  20879. // stream::Delete tests
  20880. TEST_F(StreamApiTest, Delete) {
  20881. httplib::Client cli(HOST, PORT);
  20882. auto del1 = httplib::stream::Delete(cli, "/resource");
  20883. EXPECT_EQ("Deleted", read_body(del1));
  20884. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20885. EXPECT_EQ("Deleted:data", read_body(del2));
  20886. }
  20887. // stream::Head/Options tests
  20888. TEST_F(StreamApiTest, HeadAndOptions) {
  20889. httplib::Client cli(HOST, PORT);
  20890. auto head = httplib::stream::Head(cli, "/head-test");
  20891. EXPECT_TRUE(head.is_valid());
  20892. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20893. auto opts = httplib::stream::Options(cli, "/options");
  20894. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20895. }
  20896. // SSL stream::* tests
  20897. #ifdef CPPHTTPLIB_SSL_ENABLED
  20898. class SSLStreamApiTest : public ::testing::Test {
  20899. protected:
  20900. void SetUp() override {
  20901. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20902. res.set_content("Hello SSL!", "text/plain");
  20903. });
  20904. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20905. res.set_content(req.body, "text/plain");
  20906. });
  20907. port_ = svr_.bind_to_any_port("127.0.0.1");
  20908. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20909. svr_.wait_until_ready();
  20910. }
  20911. void TearDown() override {
  20912. svr_.stop();
  20913. if (thread_.joinable()) thread_.join();
  20914. }
  20915. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20916. std::thread thread_;
  20917. int port_ = 0;
  20918. };
  20919. TEST_F(SSLStreamApiTest, GetAndPost) {
  20920. httplib::SSLClient cli("127.0.0.1", port_);
  20921. cli.enable_server_certificate_verification(false);
  20922. auto get = httplib::stream::Get(cli, "/hello");
  20923. EXPECT_EQ("Hello SSL!", read_body(get));
  20924. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20925. EXPECT_EQ("test", read_body(post));
  20926. }
  20927. #endif
  20928. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20929. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20930. // BodyReader
  20931. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20932. // Test that read timeout during streaming is detected
  20933. // Use a large content-length response where server delays mid-stream
  20934. Server svr;
  20935. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20936. // Send a large response with delay in the middle
  20937. res.set_content_provider(
  20938. 1000, // content_length
  20939. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20940. if (offset < 100) {
  20941. // Send first 100 bytes immediately
  20942. std::string data(100, 'A');
  20943. sink.write(data.c_str(), data.size());
  20944. return true;
  20945. }
  20946. // Then delay longer than client timeout
  20947. std::this_thread::sleep_for(std::chrono::seconds(3));
  20948. std::string data(900, 'B');
  20949. sink.write(data.c_str(), data.size());
  20950. return true;
  20951. });
  20952. });
  20953. auto port = 8091;
  20954. std::thread t([&]() { svr.listen("localhost", port); });
  20955. svr.wait_until_ready();
  20956. Client cli("localhost", port);
  20957. cli.set_read_timeout(1, 0); // 1 second timeout
  20958. auto handle = cli.open_stream("GET", "/slow-stream");
  20959. ASSERT_TRUE(handle.is_valid());
  20960. char buf[256];
  20961. ssize_t total = 0;
  20962. ssize_t n;
  20963. bool got_error = false;
  20964. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20965. total += n;
  20966. }
  20967. if (n < 0) {
  20968. got_error = true;
  20969. // Should be timeout or read error
  20970. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20971. handle.get_read_error() == Error::Read)
  20972. << "Actual error: " << to_string(handle.get_read_error());
  20973. }
  20974. // Either we got an error, or we got less data than expected
  20975. EXPECT_TRUE(got_error || total < 1000)
  20976. << "Expected timeout but got all " << total << " bytes";
  20977. svr.stop();
  20978. t.join();
  20979. }
  20980. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20981. // Test connection closed detection via BodyReader
  20982. Server svr;
  20983. std::atomic<bool> close_now{false};
  20984. svr.Get("/will-close", [&](const Request &, Response &res) {
  20985. res.set_content_provider(
  20986. 10000, // Large content_length that we won't fully send
  20987. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20988. if (offset < 100) {
  20989. std::string data(100, 'X');
  20990. sink.write(data.c_str(), data.size());
  20991. return true;
  20992. }
  20993. // Wait for signal then abort
  20994. while (!close_now) {
  20995. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20996. }
  20997. return false; // Abort - server will close connection
  20998. });
  20999. });
  21000. auto port = 8092;
  21001. std::thread t([&]() { svr.listen("localhost", port); });
  21002. svr.wait_until_ready();
  21003. Client cli("localhost", port);
  21004. auto handle = cli.open_stream("GET", "/will-close");
  21005. ASSERT_TRUE(handle.is_valid());
  21006. char buf[256];
  21007. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21008. EXPECT_GT(n, 0) << "First read should succeed";
  21009. // Signal server to close
  21010. close_now = true;
  21011. // Keep reading until error or EOF
  21012. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21013. // Keep reading
  21014. }
  21015. // Should get an error since content_length wasn't satisfied
  21016. if (n < 0) {
  21017. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21018. handle.get_read_error() == Error::Read)
  21019. << "Actual error: " << to_string(handle.get_read_error());
  21020. }
  21021. svr.stop();
  21022. t.join();
  21023. }
  21024. #ifdef CPPHTTPLIB_SSL_ENABLED
  21025. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21026. // Test that read timeout during SSL streaming is detected
  21027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21028. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21029. res.set_content_provider(
  21030. 1000, "text/plain",
  21031. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21032. if (offset < 100) {
  21033. std::string data(100, 'A');
  21034. sink.write(data.c_str(), data.size());
  21035. return true;
  21036. }
  21037. std::this_thread::sleep_for(std::chrono::seconds(3));
  21038. std::string data(900, 'B');
  21039. sink.write(data.c_str(), data.size());
  21040. return true;
  21041. });
  21042. });
  21043. auto port = 8093;
  21044. std::thread t([&]() { svr.listen("localhost", port); });
  21045. svr.wait_until_ready();
  21046. SSLClient cli("localhost", port);
  21047. cli.enable_server_certificate_verification(false);
  21048. cli.set_read_timeout(1, 0); // 1 second timeout
  21049. auto handle = cli.open_stream("GET", "/slow-stream");
  21050. ASSERT_TRUE(handle.is_valid());
  21051. char buf[256];
  21052. ssize_t total = 0;
  21053. ssize_t n;
  21054. bool got_error = false;
  21055. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21056. total += n;
  21057. }
  21058. if (n < 0) {
  21059. got_error = true;
  21060. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21061. handle.get_read_error() == Error::Read)
  21062. << "Actual error: " << to_string(handle.get_read_error());
  21063. }
  21064. EXPECT_TRUE(got_error || total < 1000)
  21065. << "Expected timeout but got all " << total << " bytes";
  21066. svr.stop();
  21067. t.join();
  21068. }
  21069. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21070. // Test SSL connection closed detection
  21071. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21072. std::atomic<bool> close_now{false};
  21073. svr.Get("/will-close", [&](const Request &, Response &res) {
  21074. res.set_content_provider(
  21075. 10000, "text/plain",
  21076. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21077. if (offset < 100) {
  21078. std::string data(100, 'X');
  21079. sink.write(data.c_str(), data.size());
  21080. return true;
  21081. }
  21082. while (!close_now) {
  21083. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21084. }
  21085. return false;
  21086. });
  21087. });
  21088. auto port = 8094;
  21089. std::thread t([&]() { svr.listen("localhost", port); });
  21090. svr.wait_until_ready();
  21091. SSLClient cli("localhost", port);
  21092. cli.enable_server_certificate_verification(false);
  21093. auto handle = cli.open_stream("GET", "/will-close");
  21094. ASSERT_TRUE(handle.is_valid());
  21095. char buf[256];
  21096. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21097. EXPECT_GT(n, 0);
  21098. // Signal server to close
  21099. close_now = true;
  21100. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21101. // Keep reading
  21102. }
  21103. if (n < 0) {
  21104. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21105. handle.get_read_error() == Error::Read)
  21106. << "Actual error: " << to_string(handle.get_read_error());
  21107. }
  21108. svr.stop();
  21109. t.join();
  21110. }
  21111. #endif
  21112. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21113. using namespace httplib;
  21114. // Create a test file
  21115. const char *fname = "etag_testfile.txt";
  21116. const char *content = "etag-content";
  21117. {
  21118. std::ofstream ofs(fname);
  21119. ofs << content;
  21120. ASSERT_TRUE(ofs.good());
  21121. }
  21122. Server svr;
  21123. svr.set_mount_point("/static", ".");
  21124. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21125. svr.wait_until_ready();
  21126. Client cli(HOST, PORT);
  21127. // First request: should get 200 with ETag header
  21128. auto res1 = cli.Get("/static/etag_testfile.txt");
  21129. ASSERT_TRUE(res1);
  21130. ASSERT_EQ(200, res1->status);
  21131. ASSERT_TRUE(res1->has_header("ETag"));
  21132. std::string etag = res1->get_header_value("ETag");
  21133. EXPECT_FALSE(etag.empty());
  21134. // Verify ETag format: W/"hex-hex"
  21135. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21136. EXPECT_EQ('W', etag[0]);
  21137. EXPECT_EQ('/', etag[1]);
  21138. EXPECT_EQ('"', etag[2]);
  21139. EXPECT_EQ('"', etag.back());
  21140. // Exact match: expect 304 Not Modified
  21141. Headers h2 = {{"If-None-Match", etag}};
  21142. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21143. ASSERT_TRUE(res2);
  21144. EXPECT_EQ(304, res2->status);
  21145. // Wildcard match: expect 304 Not Modified
  21146. Headers h3 = {{"If-None-Match", "*"}};
  21147. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21148. ASSERT_TRUE(res3);
  21149. EXPECT_EQ(304, res3->status);
  21150. // Non-matching ETag: expect 200
  21151. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21152. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21153. ASSERT_TRUE(res4);
  21154. EXPECT_EQ(200, res4->status);
  21155. // Multiple ETags with one matching: expect 304
  21156. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21157. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21158. ASSERT_TRUE(res5);
  21159. EXPECT_EQ(304, res5->status);
  21160. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21161. // that equivalent to the single comma-separated list above, so the match on
  21162. // the second line must still be found.
  21163. Headers h6;
  21164. h6.emplace("If-None-Match", "W/\"other\"");
  21165. h6.emplace("If-None-Match", etag);
  21166. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21167. ASSERT_TRUE(res6);
  21168. EXPECT_EQ(304, res6->status);
  21169. svr.stop();
  21170. t.join();
  21171. std::remove(fname);
  21172. }
  21173. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21174. using namespace httplib;
  21175. Server svr;
  21176. svr.set_mount_point("/static", ".");
  21177. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21178. svr.wait_until_ready();
  21179. Client cli(HOST, PORT);
  21180. // Send If-None-Match: * to a non-existent file
  21181. Headers h = {{"If-None-Match", "*"}};
  21182. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21184. EXPECT_EQ(404, res->status);
  21185. svr.stop();
  21186. t.join();
  21187. }
  21188. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21189. using namespace httplib;
  21190. // Create a test file
  21191. const char *fname = "etag_boundary_testfile.txt";
  21192. const char *content = "boundary-test";
  21193. {
  21194. std::ofstream ofs(fname);
  21195. ofs << content;
  21196. ASSERT_TRUE(ofs.good());
  21197. }
  21198. Server svr;
  21199. svr.set_mount_point("/static", ".");
  21200. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21201. svr.wait_until_ready();
  21202. Client cli(HOST, PORT);
  21203. // Get the actual ETag
  21204. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21205. ASSERT_TRUE(res1);
  21206. ASSERT_EQ(200, res1->status);
  21207. ASSERT_TRUE(res1->has_header("ETag"));
  21208. std::string etag = res1->get_header_value("ETag");
  21209. // Test 1: Very long ETag value (longer than actual ETag)
  21210. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21211. Headers h1 = {{"If-None-Match", "W/"
  21212. "\"very-long-etag-value-that-is-much-longer-"
  21213. "than-the-actual-etag-value\""}};
  21214. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21215. ASSERT_TRUE(res2);
  21216. EXPECT_EQ(200, res2->status); // Should not match
  21217. // Test 2: Long string followed by wildcard
  21218. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21219. // string)
  21220. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21221. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21222. ASSERT_TRUE(res3);
  21223. EXPECT_EQ(304, res3->status); // Should match on "*"
  21224. // Test 3: Wildcard followed by long string
  21225. // Should match on "*" immediately and return 304
  21226. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21227. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21228. ASSERT_TRUE(res4);
  21229. EXPECT_EQ(304, res4->status); // Should match on "*"
  21230. // Test 4: Multiple long non-matching values
  21231. // Should NOT match and return 200 (test that all comparisons are safe)
  21232. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21233. "W/\"second-long-non-matching-value\", "
  21234. "W/\"third-long-non-matching-value\""}};
  21235. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21236. ASSERT_TRUE(res5);
  21237. EXPECT_EQ(200, res5->status); // Should not match
  21238. // Test 5: Single character that is not "*" (edge case)
  21239. Headers h5 = {{"If-None-Match", "X"}};
  21240. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21241. ASSERT_TRUE(res6);
  21242. EXPECT_EQ(200, res6->status); // Should not match
  21243. svr.stop();
  21244. t.join();
  21245. std::remove(fname);
  21246. }
  21247. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21248. using namespace httplib;
  21249. // Create a test file
  21250. const char *fname = "ims_testfile.txt";
  21251. const char *content = "if-modified-since-test";
  21252. {
  21253. std::ofstream ofs(fname);
  21254. ofs << content;
  21255. ASSERT_TRUE(ofs.good());
  21256. }
  21257. Server svr;
  21258. svr.set_mount_point("/static", ".");
  21259. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21260. svr.wait_until_ready();
  21261. Client cli(HOST, PORT);
  21262. // First request: should get 200 with Last-Modified header
  21263. auto res1 = cli.Get("/static/ims_testfile.txt");
  21264. ASSERT_TRUE(res1);
  21265. ASSERT_EQ(200, res1->status);
  21266. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21267. std::string last_modified = res1->get_header_value("Last-Modified");
  21268. EXPECT_FALSE(last_modified.empty());
  21269. // If-Modified-Since with same time: expect 304
  21270. Headers h2 = {{"If-Modified-Since", last_modified}};
  21271. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21272. ASSERT_TRUE(res2);
  21273. EXPECT_EQ(304, res2->status);
  21274. // If-Modified-Since with future time: expect 304
  21275. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21276. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21277. ASSERT_TRUE(res3);
  21278. EXPECT_EQ(304, res3->status);
  21279. // If-Modified-Since with past time: expect 200
  21280. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21281. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21282. ASSERT_TRUE(res4);
  21283. EXPECT_EQ(200, res4->status);
  21284. // If-None-Match takes precedence over If-Modified-Since
  21285. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21286. ASSERT_TRUE(res1->has_header("ETag"));
  21287. std::string etag = res1->get_header_value("ETag");
  21288. Headers h5 = {{"If-None-Match", etag},
  21289. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21290. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21291. ASSERT_TRUE(res5);
  21292. EXPECT_EQ(304, res5->status);
  21293. svr.stop();
  21294. t.join();
  21295. std::remove(fname);
  21296. }
  21297. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21298. using namespace httplib;
  21299. Server svr;
  21300. // Endpoint that returns compressible content
  21301. svr.Get("/compressible", [](const Request &, Response &res) {
  21302. // Return a large enough body to trigger compression
  21303. std::string body(1000, 'a');
  21304. res.set_content(body, "text/plain");
  21305. });
  21306. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21307. svr.wait_until_ready();
  21308. Client cli(HOST, PORT);
  21309. // Request with gzip support: should get Vary header when compressed
  21310. cli.set_compress(true);
  21311. auto res1 = cli.Get("/compressible");
  21312. ASSERT_TRUE(res1);
  21313. EXPECT_EQ(200, res1->status);
  21314. // If Content-Encoding is set, Vary should also be set
  21315. if (res1->has_header("Content-Encoding")) {
  21316. EXPECT_TRUE(res1->has_header("Vary"));
  21317. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21318. }
  21319. // Request without Accept-Encoding header: should not have compression
  21320. Headers h_no_compress;
  21321. auto res2 = cli.Get("/compressible", h_no_compress);
  21322. ASSERT_TRUE(res2);
  21323. EXPECT_EQ(200, res2->status);
  21324. // Verify Vary header is present when compression is applied
  21325. // (the exact behavior depends on server configuration)
  21326. svr.stop();
  21327. t.join();
  21328. }
  21329. TEST(ETagTest, IfRangeWithETag) {
  21330. using namespace httplib;
  21331. // Create a test file with known content
  21332. const char *fname = "if_range_testfile.txt";
  21333. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21334. {
  21335. std::ofstream ofs(fname);
  21336. ofs << content;
  21337. ASSERT_TRUE(ofs.good());
  21338. }
  21339. Server svr;
  21340. svr.set_mount_point("/static", ".");
  21341. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21342. svr.wait_until_ready();
  21343. Client cli(HOST, PORT);
  21344. // First request: get ETag
  21345. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21346. ASSERT_TRUE(res1);
  21347. ASSERT_EQ(200, res1->status);
  21348. ASSERT_TRUE(res1->has_header("ETag"));
  21349. std::string etag = res1->get_header_value("ETag");
  21350. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21351. // Since our server generates weak ETags (W/"..."), If-Range with our
  21352. // ETag should NOT result in partial content - it should return full content.
  21353. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21354. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21355. ASSERT_TRUE(res2);
  21356. // Weak ETag in If-Range -> full content (200), not partial (206)
  21357. EXPECT_EQ(200, res2->status);
  21358. EXPECT_EQ(content, res2->body);
  21359. EXPECT_FALSE(res2->has_header("Content-Range"));
  21360. // Range request with non-matching If-Range (ETag): should get 200 (full
  21361. // content)
  21362. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21363. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21364. ASSERT_TRUE(res3);
  21365. EXPECT_EQ(200, res3->status);
  21366. EXPECT_EQ(content, res3->body);
  21367. EXPECT_FALSE(res3->has_header("Content-Range"));
  21368. // Range request with strong ETag (hypothetical - our server doesn't generate
  21369. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21370. // should return full content)
  21371. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21372. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21373. ASSERT_TRUE(res4);
  21374. EXPECT_EQ(200, res4->status);
  21375. EXPECT_EQ(content, res4->body);
  21376. EXPECT_FALSE(res4->has_header("Content-Range"));
  21377. svr.stop();
  21378. t.join();
  21379. std::remove(fname);
  21380. }
  21381. TEST(ETagTest, IfRangeWithDate) {
  21382. using namespace httplib;
  21383. // Create a test file
  21384. const char *fname = "if_range_date_testfile.txt";
  21385. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21386. {
  21387. std::ofstream ofs(fname);
  21388. ofs << content;
  21389. ASSERT_TRUE(ofs.good());
  21390. }
  21391. Server svr;
  21392. svr.set_mount_point("/static", ".");
  21393. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21394. svr.wait_until_ready();
  21395. Client cli(HOST, PORT);
  21396. // First request: get Last-Modified
  21397. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21398. ASSERT_TRUE(res1);
  21399. ASSERT_EQ(200, res1->status);
  21400. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21401. std::string last_modified = res1->get_header_value("Last-Modified");
  21402. // Range request with matching If-Range (date): should get 206
  21403. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21404. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21405. ASSERT_TRUE(res2);
  21406. EXPECT_EQ(206, res2->status);
  21407. EXPECT_EQ("FGHIJ", res2->body);
  21408. // Range request with old If-Range date: should get 200 (full content)
  21409. Headers h3 = {{"Range", "bytes=5-9"},
  21410. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21411. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21412. ASSERT_TRUE(res3);
  21413. EXPECT_EQ(200, res3->status);
  21414. EXPECT_EQ(content, res3->body);
  21415. // Range request with future If-Range date: should get 206
  21416. Headers h4 = {{"Range", "bytes=0-4"},
  21417. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21418. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21419. ASSERT_TRUE(res4);
  21420. EXPECT_EQ(206, res4->status);
  21421. EXPECT_EQ("ABCDE", res4->body);
  21422. svr.stop();
  21423. t.join();
  21424. std::remove(fname);
  21425. }
  21426. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21427. using namespace httplib;
  21428. const char *fname = "etag_malformed.txt";
  21429. const char *content = "malformed-etag";
  21430. {
  21431. std::ofstream ofs(fname);
  21432. ofs << content;
  21433. ASSERT_TRUE(ofs.good());
  21434. }
  21435. Server svr;
  21436. svr.set_mount_point("/static", ".");
  21437. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21438. svr.wait_until_ready();
  21439. Client cli(HOST, PORT);
  21440. // baseline: should get 200 and an ETag
  21441. auto res1 = cli.Get("/static/etag_malformed.txt");
  21442. ASSERT_TRUE(res1);
  21443. ASSERT_EQ(200, res1->status);
  21444. ASSERT_TRUE(res1->has_header("ETag"));
  21445. // Malformed ETag value (missing quotes) should be treated as non-matching
  21446. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21447. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21448. ASSERT_TRUE(res_bad);
  21449. EXPECT_EQ(200, res_bad->status);
  21450. // Whitespace-only header value should be considered invalid / non-matching
  21451. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21452. "Host: localhost\r\n"
  21453. "If-None-Match: \r\n"
  21454. "Connection: close\r\n"
  21455. "\r\n";
  21456. std::string out;
  21457. ASSERT_TRUE(send_request(5, raw_req, &out));
  21458. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21459. svr.stop();
  21460. t.join();
  21461. std::remove(fname);
  21462. }
  21463. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21464. using namespace httplib;
  21465. const char *fname = "ims_invalid_format.txt";
  21466. const char *content = "ims-bad-format";
  21467. {
  21468. std::ofstream ofs(fname);
  21469. ofs << content;
  21470. ASSERT_TRUE(ofs.good());
  21471. }
  21472. Server svr;
  21473. svr.set_mount_point("/static", ".");
  21474. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21475. svr.wait_until_ready();
  21476. Client cli(HOST, PORT);
  21477. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21478. ASSERT_TRUE(res1);
  21479. ASSERT_EQ(200, res1->status);
  21480. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21481. // If-Modified-Since with invalid format should not result in 304
  21482. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21483. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21484. ASSERT_TRUE(res_bad);
  21485. EXPECT_EQ(200, res_bad->status);
  21486. // If-Range with invalid date format should be treated as mismatch -> full
  21487. // content (200)
  21488. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21489. {"If-Range", "invalid-date"}};
  21490. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21491. ASSERT_TRUE(res_ifrange);
  21492. EXPECT_EQ(200, res_ifrange->status);
  21493. svr.stop();
  21494. t.join();
  21495. std::remove(fname);
  21496. }
  21497. TEST(ETagTest, IfRangeWithMalformedETag) {
  21498. using namespace httplib;
  21499. const char *fname = "ifrange_malformed.txt";
  21500. const std::string content = "0123456789";
  21501. {
  21502. std::ofstream ofs(fname);
  21503. ofs << content;
  21504. ASSERT_TRUE(ofs.good());
  21505. }
  21506. Server svr;
  21507. svr.set_mount_point("/static", ".");
  21508. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21509. svr.wait_until_ready();
  21510. Client cli(HOST, PORT);
  21511. // First request: get ETag
  21512. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21513. ASSERT_TRUE(res1);
  21514. ASSERT_EQ(200, res1->status);
  21515. ASSERT_TRUE(res1->has_header("ETag"));
  21516. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21517. // full content (200)
  21518. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21519. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21520. ASSERT_TRUE(res2);
  21521. EXPECT_EQ(200, res2->status);
  21522. EXPECT_EQ(content, res2->body);
  21523. svr.stop();
  21524. t.join();
  21525. std::remove(fname);
  21526. }
  21527. TEST(ETagTest, ExtremeLargeDateValues) {
  21528. using namespace httplib;
  21529. const char *fname = "ims_extreme_date.txt";
  21530. const char *content = "ims-extreme-date";
  21531. {
  21532. std::ofstream ofs(fname);
  21533. ofs << content;
  21534. ASSERT_TRUE(ofs.good());
  21535. }
  21536. Server svr;
  21537. svr.set_mount_point("/static", ".");
  21538. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21539. svr.wait_until_ready();
  21540. Client cli(HOST, PORT);
  21541. auto res1 = cli.Get(std::string("/static/") + fname);
  21542. ASSERT_TRUE(res1);
  21543. ASSERT_EQ(200, res1->status);
  21544. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21545. // Extremely large year that may overflow date parsing routines.
  21546. Headers h_large_date = {
  21547. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21548. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21549. ASSERT_TRUE(res_bad);
  21550. // Expect server to treat this as invalid/mismatch and return full content
  21551. EXPECT_EQ(200, res_bad->status);
  21552. // If-Range with extremely large date should be treated as mismatch -> full
  21553. // content (200)
  21554. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21555. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21556. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21557. ASSERT_TRUE(res_ifrange);
  21558. EXPECT_EQ(200, res_ifrange->status);
  21559. svr.stop();
  21560. t.join();
  21561. std::remove(fname);
  21562. }
  21563. TEST(ETagTest, NegativeFileModificationTime) {
  21564. using namespace httplib;
  21565. const char *fname = "ims_negative_mtime.txt";
  21566. const std::string content = "negative-mtime";
  21567. {
  21568. std::ofstream ofs(fname);
  21569. ofs << content;
  21570. ASSERT_TRUE(ofs.good());
  21571. }
  21572. // Try to set file mtime to a negative value. This may fail on some
  21573. // platforms/filesystems; if it fails, the test will still verify server
  21574. // behaves safely by performing a regular conditional request.
  21575. #if defined(__APPLE__) || defined(__linux__)
  21576. bool set_negative = false;
  21577. do {
  21578. struct timeval times[2];
  21579. // access time: now
  21580. times[0].tv_sec = time(nullptr);
  21581. times[0].tv_usec = 0;
  21582. // modification time: negative (e.g., -1)
  21583. times[1].tv_sec = -1;
  21584. times[1].tv_usec = 0;
  21585. if (utimes(fname, times) == 0) { set_negative = true; }
  21586. } while (0);
  21587. #else
  21588. bool set_negative = false;
  21589. #endif
  21590. Server svr;
  21591. svr.set_mount_point("/static", ".");
  21592. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21593. svr.wait_until_ready();
  21594. Client cli(HOST, PORT);
  21595. auto res1 = cli.Get(std::string("/static/") + fname);
  21596. ASSERT_TRUE(res1);
  21597. ASSERT_EQ(200, res1->status);
  21598. bool has_last_modified = res1->has_header("Last-Modified");
  21599. std::string last_modified;
  21600. if (has_last_modified) {
  21601. last_modified = res1->get_header_value("Last-Modified");
  21602. }
  21603. if (set_negative) {
  21604. // If we successfully set a negative mtime, ensure server returns a
  21605. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21606. // with an old date and ensure server handles it without crash.
  21607. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21608. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21609. ASSERT_TRUE(res2);
  21610. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21611. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21612. } else {
  21613. // Could not set negative mtime on this platform; fall back to verifying
  21614. // that normal invalid/malformed dates are treated safely (non-304).
  21615. Headers h_bad_date = {
  21616. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21617. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21618. ASSERT_TRUE(res_bad);
  21619. EXPECT_EQ(200, res_bad->status);
  21620. }
  21621. svr.stop();
  21622. t.join();
  21623. std::remove(fname);
  21624. }
  21625. //==============================================================================
  21626. // Integration Tests with Server
  21627. //==============================================================================
  21628. class SSEIntegrationTest : public ::testing::Test {
  21629. protected:
  21630. void SetUp() override {
  21631. stop_server_.store(false);
  21632. events_.clear();
  21633. server_ = httplib::detail::make_unique<Server>();
  21634. setup_server();
  21635. start_server();
  21636. }
  21637. void TearDown() override {
  21638. stop_server_.store(true);
  21639. event_cv_.notify_all();
  21640. server_->stop();
  21641. if (server_thread_.joinable()) { server_thread_.join(); }
  21642. }
  21643. void setup_server() {
  21644. // Simple SSE endpoint
  21645. server_->Get("/events", [this](const Request &req, Response &res) {
  21646. auto last_id = req.get_header_value("Last-Event-ID");
  21647. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21648. res.set_chunked_content_provider(
  21649. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21650. std::unique_lock<std::mutex> lock(event_mutex_);
  21651. if (event_cv_.wait_for(
  21652. lock, std::chrono::milliseconds(200), [this] {
  21653. return !events_.empty() || stop_server_.load();
  21654. })) {
  21655. if (stop_server_.load()) { return false; }
  21656. if (!events_.empty()) {
  21657. std::string event = events_.front();
  21658. events_.erase(events_.begin());
  21659. sink.write(event.data(), event.size());
  21660. return true;
  21661. }
  21662. }
  21663. return !stop_server_.load();
  21664. });
  21665. });
  21666. // Endpoint that returns error
  21667. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21668. res.status = 500;
  21669. res.set_content("Internal Server Error", "text/plain");
  21670. });
  21671. // Endpoint for custom event types
  21672. server_->Get("/custom-events", [](const Request &, Response &res) {
  21673. res.set_chunked_content_provider(
  21674. "text/event-stream", [](size_t offset, DataSink &sink) {
  21675. if (offset == 0) {
  21676. std::string event = "event: update\ndata: updated\n\n"
  21677. "event: delete\ndata: deleted\n\n";
  21678. sink.write(event.data(), event.size());
  21679. }
  21680. return false; // End stream after sending
  21681. });
  21682. });
  21683. }
  21684. void start_server() {
  21685. port_ = server_->bind_to_any_port(HOST);
  21686. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21687. // Wait for server to start
  21688. while (!server_->is_running()) {
  21689. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21690. }
  21691. }
  21692. int get_port() const { return port_; }
  21693. void send_event(const std::string &event) {
  21694. std::lock_guard<std::mutex> lock(event_mutex_);
  21695. events_.push_back(event);
  21696. event_cv_.notify_all();
  21697. }
  21698. std::unique_ptr<Server> server_;
  21699. std::thread server_thread_;
  21700. std::mutex event_mutex_;
  21701. std::condition_variable event_cv_;
  21702. std::vector<std::string> events_;
  21703. std::atomic<bool> stop_server_{false};
  21704. std::string last_received_event_id_;
  21705. int port_ = 0;
  21706. };
  21707. //==============================================================================
  21708. // SSE Parsing Tests
  21709. //==============================================================================
  21710. class SSEParsingTest : public SSEIntegrationTest {
  21711. protected:
  21712. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21713. // A trailing sentinel event tells when the whole stream has been parsed.
  21714. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21715. auto body = stream + "event: end\ndata: end\n\n";
  21716. server_->Get("/parse", [body](const Request &, Response &res) {
  21717. res.set_content(body, "text/event-stream");
  21718. });
  21719. return collect("/parse");
  21720. }
  21721. // Runs SSEClient against path until an "end" event arrives and returns the
  21722. // messages dispatched before it
  21723. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21724. Client client(HOST, get_port());
  21725. sse::SSEClient sse(client, path);
  21726. std::mutex mutex;
  21727. std::condition_variable cv;
  21728. std::vector<sse::SSEMessage> messages;
  21729. auto done = false;
  21730. sse.on_message([&](const sse::SSEMessage &msg) {
  21731. std::lock_guard<std::mutex> lock(mutex);
  21732. // Ignore a replay from a reconnect that races with stop()
  21733. if (!done) { messages.push_back(msg); }
  21734. });
  21735. sse.on_event("end", [&](const sse::SSEMessage &) {
  21736. std::lock_guard<std::mutex> lock(mutex);
  21737. done = true;
  21738. cv.notify_all();
  21739. });
  21740. sse.set_reconnect_interval(100);
  21741. sse.start_async();
  21742. {
  21743. std::unique_lock<std::mutex> lock(mutex);
  21744. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21745. }
  21746. sse.stop();
  21747. EXPECT_TRUE(done);
  21748. return messages;
  21749. }
  21750. };
  21751. TEST_F(SSEParsingTest, SingleLineData) {
  21752. auto msgs = parse("data: hello\n\n");
  21753. ASSERT_EQ(msgs.size(), 1u);
  21754. EXPECT_EQ(msgs[0].data, "hello");
  21755. EXPECT_EQ(msgs[0].event, "message");
  21756. }
  21757. TEST_F(SSEParsingTest, MultiLineData) {
  21758. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21759. ASSERT_EQ(msgs.size(), 1u);
  21760. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21761. }
  21762. TEST_F(SSEParsingTest, CustomEventType) {
  21763. auto msgs = parse("event: update\ndata: payload\n\n");
  21764. ASSERT_EQ(msgs.size(), 1u);
  21765. EXPECT_EQ(msgs[0].event, "update");
  21766. EXPECT_EQ(msgs[0].data, "payload");
  21767. }
  21768. TEST_F(SSEParsingTest, EventIdHandling) {
  21769. auto msgs = parse("id: 12345\ndata: test\n\n");
  21770. ASSERT_EQ(msgs.size(), 1u);
  21771. EXPECT_EQ(msgs[0].id, "12345");
  21772. }
  21773. TEST_F(SSEParsingTest, EmptyEventId) {
  21774. auto msgs = parse("id:\ndata: test\n\n");
  21775. ASSERT_EQ(msgs.size(), 1u);
  21776. EXPECT_EQ(msgs[0].id, "");
  21777. }
  21778. TEST_F(SSEParsingTest, CommentsIgnored) {
  21779. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21780. ASSERT_EQ(msgs.size(), 1u);
  21781. EXPECT_EQ(msgs[0].data, "hello");
  21782. EXPECT_EQ(msgs[0].event, "message");
  21783. }
  21784. TEST_F(SSEParsingTest, ColonInValue) {
  21785. auto msgs = parse("data: hello:world:test\n\n");
  21786. ASSERT_EQ(msgs.size(), 1u);
  21787. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21788. }
  21789. TEST_F(SSEParsingTest, FieldNameOnly) {
  21790. // A line without a colon is a field name with an empty value
  21791. auto msgs = parse("data\n\n");
  21792. ASSERT_EQ(msgs.size(), 1u);
  21793. EXPECT_EQ(msgs[0].data, "");
  21794. }
  21795. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21796. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21797. ASSERT_EQ(msgs.size(), 1u);
  21798. EXPECT_EQ(msgs[0].event, "update");
  21799. EXPECT_EQ(msgs[0].data, "hello");
  21800. }
  21801. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21802. auto msgs = parse("data\r\n\r\n");
  21803. ASSERT_EQ(msgs.size(), 1u);
  21804. EXPECT_EQ(msgs[0].data, "");
  21805. }
  21806. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21807. auto msgs = parse("event: update\rdata: hello\r\r");
  21808. ASSERT_EQ(msgs.size(), 1u);
  21809. EXPECT_EQ(msgs[0].event, "update");
  21810. EXPECT_EQ(msgs[0].data, "hello");
  21811. }
  21812. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21813. // Chunk boundaries fall inside every \r\n and right before the first one
  21814. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21815. "\n\r", "\nevent: end\ndata: end\n\n"};
  21816. server_->Get("/split", [chunks](const Request &, Response &res) {
  21817. auto i = std::make_shared<size_t>(0);
  21818. res.set_chunked_content_provider(
  21819. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21820. if (*i == chunks.size()) {
  21821. sink.done();
  21822. } else {
  21823. sink.write(chunks[*i].data(), chunks[*i].size());
  21824. (*i)++;
  21825. }
  21826. return true;
  21827. });
  21828. });
  21829. auto msgs = collect("/split");
  21830. ASSERT_EQ(msgs.size(), 1u);
  21831. EXPECT_EQ(msgs[0].event, "update");
  21832. EXPECT_EQ(msgs[0].data, "hello");
  21833. }
  21834. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21835. // Only a BOM at the start of the stream is ignored
  21836. auto msgs = parse("\xEF\xBB\xBF"
  21837. "data: first\n\n"
  21838. "\xEF\xBB\xBF"
  21839. "data: second\n\n");
  21840. ASSERT_EQ(msgs.size(), 1u);
  21841. EXPECT_EQ(msgs[0].data, "first");
  21842. }
  21843. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21844. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21845. ASSERT_EQ(msgs.size(), 1u);
  21846. EXPECT_EQ(msgs[0].data, "hello");
  21847. EXPECT_EQ(msgs[0].event, "message");
  21848. }
  21849. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21850. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21851. ASSERT_EQ(msgs.size(), 2u);
  21852. EXPECT_EQ(msgs[0].data, "hello");
  21853. EXPECT_EQ(msgs[1].data, "hello");
  21854. }
  21855. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21856. // An event without data is not dispatched, and its type must not leak
  21857. // into the next event
  21858. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21859. ASSERT_EQ(msgs.size(), 1u);
  21860. EXPECT_EQ(msgs[0].event, "message");
  21861. EXPECT_EQ(msgs[0].data, "hello");
  21862. }
  21863. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21864. // Also when the empty field replaces an earlier type
  21865. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21866. ASSERT_EQ(msgs.size(), 2u);
  21867. EXPECT_EQ(msgs[0].event, "message");
  21868. EXPECT_EQ(msgs[1].event, "message");
  21869. }
  21870. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21871. // The first connection sends only an id; the second echoes back the
  21872. // Last-Event-ID it was reconnected with
  21873. std::atomic<int> connection_count{0};
  21874. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21875. if (connection_count++ == 0) {
  21876. res.set_content("id: 42\n\n", "text/event-stream");
  21877. } else {
  21878. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21879. "\n\nevent: end\ndata: end\n\n",
  21880. "text/event-stream");
  21881. }
  21882. });
  21883. auto msgs = collect("/id-only");
  21884. ASSERT_EQ(msgs.size(), 1u);
  21885. EXPECT_EQ(msgs[0].data, "42");
  21886. }
  21887. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21888. // The first connection sets an id and then clears it with an empty one; the
  21889. // second reports whether it was reconnected with a Last-Event-ID
  21890. std::atomic<int> connection_count{0};
  21891. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21892. if (connection_count++ == 0) {
  21893. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21894. "text/event-stream");
  21895. } else {
  21896. res.set_content(
  21897. std::string("data: ") +
  21898. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21899. "\n\nevent: end\ndata: end\n\n",
  21900. "text/event-stream");
  21901. }
  21902. });
  21903. auto msgs = collect("/id-clear");
  21904. ASSERT_EQ(msgs.size(), 3u);
  21905. EXPECT_EQ(msgs[0].id, "1");
  21906. EXPECT_EQ(msgs[1].id, "");
  21907. EXPECT_EQ(msgs[2].data, "not sent");
  21908. }
  21909. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21910. // The first connection sets an id and then sends ids that cannot be carried
  21911. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21912. // with
  21913. std::atomic<int> connection_count{0};
  21914. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21915. if (connection_count++ == 0) {
  21916. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21917. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21918. "text/event-stream");
  21919. } else {
  21920. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21921. "\n\nevent: end\ndata: end\n\n",
  21922. "text/event-stream");
  21923. }
  21924. });
  21925. auto msgs = collect("/id-unsendable");
  21926. ASSERT_EQ(msgs.size(), 1u);
  21927. EXPECT_EQ(msgs[0].data, "42");
  21928. }
  21929. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21930. auto msgs = parse("event: notification\nid: evt-42\n"
  21931. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21932. ASSERT_EQ(msgs.size(), 1u);
  21933. EXPECT_EQ(msgs[0].event, "notification");
  21934. EXPECT_EQ(msgs[0].id, "evt-42");
  21935. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21936. }
  21937. TEST(SSEMessageTest, Clear) {
  21938. sse::SSEMessage msg;
  21939. msg.event = "custom";
  21940. msg.data = "some data";
  21941. msg.id = "123";
  21942. msg.clear();
  21943. EXPECT_EQ(msg.event, "message");
  21944. EXPECT_EQ(msg.data, "");
  21945. EXPECT_EQ(msg.id, "");
  21946. }
  21947. //==============================================================================
  21948. // SSE Integration Tests
  21949. //==============================================================================
  21950. // Test: Successful connection and on_open callback
  21951. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21952. // Add a simple endpoint that sends one event and closes
  21953. server_->Get("/simple-event", [](const Request &, Response &res) {
  21954. res.set_chunked_content_provider(
  21955. "text/event-stream", [](size_t offset, DataSink &sink) {
  21956. if (offset == 0) {
  21957. std::string event = "data: hello\n\n";
  21958. sink.write(event.data(), event.size());
  21959. }
  21960. return false; // Close stream after sending
  21961. });
  21962. });
  21963. Client client("localhost", get_port());
  21964. sse::SSEClient sse(client, "/simple-event");
  21965. std::atomic<bool> open_called{false};
  21966. std::atomic<bool> message_received{false};
  21967. sse.on_open([&open_called]() { open_called.store(true); });
  21968. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21969. if (msg.data == "hello") { message_received.store(true); }
  21970. });
  21971. sse.set_reconnect_interval(100);
  21972. sse.set_max_reconnect_attempts(1);
  21973. // Start async
  21974. sse.start_async();
  21975. // Wait for message to be processed
  21976. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21977. sse.stop();
  21978. EXPECT_TRUE(open_called.load());
  21979. EXPECT_TRUE(message_received.load());
  21980. }
  21981. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21982. // A data line that never ends.
  21983. server_->Get("/endless-line", [](const Request &, Response &res) {
  21984. res.set_chunked_content_provider(
  21985. "text/event-stream", [](size_t offset, DataSink &sink) {
  21986. if (offset == 0) { sink.write("data: ", 6); }
  21987. std::string chunk(64 * 1024, 'A');
  21988. return sink.write(chunk.data(), chunk.size());
  21989. });
  21990. });
  21991. Client client("localhost", get_port());
  21992. sse::SSEClient sse(client, "/endless-line");
  21993. std::atomic<bool> too_long{false};
  21994. sse.on_error([&](Error err) {
  21995. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21996. });
  21997. sse.set_max_reconnect_attempts(1);
  21998. sse.start_async();
  21999. for (int i = 0; i < 500 && !too_long; i++) {
  22000. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22001. }
  22002. sse.stop();
  22003. EXPECT_TRUE(too_long);
  22004. }
  22005. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22006. // Far more in all than the client's payload limit below.
  22007. server_->Get("/many-events", [](const Request &, Response &res) {
  22008. res.set_chunked_content_provider(
  22009. "text/event-stream", [](size_t offset, DataSink &sink) {
  22010. if (offset == 0) {
  22011. std::string events;
  22012. for (int i = 0; i < 1000; i++) {
  22013. events += "data: message\n\n";
  22014. }
  22015. sink.write(events.data(), events.size());
  22016. }
  22017. return false;
  22018. });
  22019. });
  22020. Client client("localhost", get_port());
  22021. client.set_payload_max_length(1024);
  22022. sse::SSEClient sse(client, "/many-events");
  22023. std::atomic<int> messages{0};
  22024. std::atomic<bool> too_large{false};
  22025. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22026. sse.on_error([&](Error err) {
  22027. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22028. });
  22029. sse.set_max_reconnect_attempts(1);
  22030. sse.start_async();
  22031. for (int i = 0; i < 500 && messages < 1000; i++) {
  22032. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22033. }
  22034. sse.stop();
  22035. EXPECT_GE(messages.load(), 1000);
  22036. EXPECT_FALSE(too_large);
  22037. }
  22038. // Test: on_message callback
  22039. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22040. // Endpoint that sends multiple events then closes
  22041. server_->Get("/multi-event", [](const Request &, Response &res) {
  22042. res.set_chunked_content_provider(
  22043. "text/event-stream", [](size_t offset, DataSink &sink) {
  22044. if (offset == 0) {
  22045. std::string events = "data: message1\n\ndata: message2\n\n";
  22046. sink.write(events.data(), events.size());
  22047. }
  22048. return false;
  22049. });
  22050. });
  22051. Client client("localhost", get_port());
  22052. sse::SSEClient sse(client, "/multi-event");
  22053. std::vector<std::string> received_messages;
  22054. std::mutex messages_mutex;
  22055. sse.on_message([&](const sse::SSEMessage &msg) {
  22056. std::lock_guard<std::mutex> lock(messages_mutex);
  22057. received_messages.push_back(msg.data);
  22058. });
  22059. sse.set_reconnect_interval(100);
  22060. sse.set_max_reconnect_attempts(1);
  22061. sse.start_async();
  22062. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22063. sse.stop();
  22064. std::lock_guard<std::mutex> lock(messages_mutex);
  22065. EXPECT_GE(received_messages.size(), 2u);
  22066. if (received_messages.size() >= 2) {
  22067. EXPECT_EQ(received_messages[0], "message1");
  22068. EXPECT_EQ(received_messages[1], "message2");
  22069. }
  22070. }
  22071. // Test: on_event for specific types
  22072. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22073. Client client("localhost", get_port());
  22074. sse::SSEClient sse(client, "/custom-events");
  22075. std::atomic<bool> update_received{false};
  22076. std::atomic<bool> delete_received{false};
  22077. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22078. if (msg.data == "updated") { update_received.store(true); }
  22079. });
  22080. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22081. if (msg.data == "deleted") { delete_received.store(true); }
  22082. });
  22083. sse.set_max_reconnect_attempts(1);
  22084. sse.start_async();
  22085. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22086. sse.stop();
  22087. EXPECT_TRUE(update_received.load());
  22088. EXPECT_TRUE(delete_received.load());
  22089. }
  22090. // Test: on_error callback on connection failure
  22091. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22092. // Connect to a non-existent port
  22093. Client client("localhost", 59999);
  22094. sse::SSEClient sse(client, "/events");
  22095. std::atomic<bool> error_called{false};
  22096. Error received_error = Error::Success;
  22097. sse.on_error([&](Error err) {
  22098. error_called.store(true);
  22099. received_error = err;
  22100. });
  22101. sse.set_reconnect_interval(50);
  22102. sse.set_max_reconnect_attempts(1);
  22103. sse.start_async();
  22104. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22105. sse.stop();
  22106. EXPECT_TRUE(error_called.load());
  22107. EXPECT_NE(received_error, Error::Success);
  22108. }
  22109. // Test: Last-Event-ID header sent on reconnect
  22110. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22111. // Endpoint that sends event with ID
  22112. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22113. res.set_chunked_content_provider(
  22114. "text/event-stream", [](size_t offset, DataSink &sink) {
  22115. if (offset == 0) {
  22116. std::string event = "id: evt-123\ndata: test\n\n";
  22117. sink.write(event.data(), event.size());
  22118. }
  22119. return false;
  22120. });
  22121. });
  22122. Client client("localhost", get_port());
  22123. sse::SSEClient sse(client, "/event-with-id");
  22124. std::atomic<bool> id_received{false};
  22125. sse.on_message([&](const sse::SSEMessage &msg) {
  22126. if (!msg.id.empty()) { id_received.store(true); }
  22127. });
  22128. sse.set_reconnect_interval(100);
  22129. sse.set_max_reconnect_attempts(1);
  22130. sse.start_async();
  22131. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22132. sse.stop();
  22133. EXPECT_TRUE(id_received.load());
  22134. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22135. }
  22136. // Test: Manual stop
  22137. TEST_F(SSEIntegrationTest, ManualStop) {
  22138. // Endpoint that sends one event and stays open briefly. The server outlives
  22139. // this test body, so the provider uses the fixture's flag, not a local.
  22140. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22141. res.set_chunked_content_provider(
  22142. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22143. if (offset == 0) {
  22144. std::string event = "data: connected\n\n";
  22145. sink.write(event.data(), event.size());
  22146. }
  22147. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22148. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22149. }
  22150. return false;
  22151. });
  22152. });
  22153. Client client("localhost", get_port());
  22154. sse::SSEClient sse(client, "/stay-open");
  22155. std::atomic<bool> connected{false};
  22156. sse.on_open([&connected]() { connected.store(true); });
  22157. sse.set_reconnect_interval(100);
  22158. sse.set_max_reconnect_attempts(1);
  22159. sse.start_async();
  22160. // Wait for connection to establish
  22161. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22162. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22163. }
  22164. EXPECT_TRUE(connected.load());
  22165. EXPECT_TRUE(sse.is_connected());
  22166. // Signal handler to stop
  22167. stop_server_.store(true);
  22168. // Stop SSE client
  22169. sse.stop();
  22170. EXPECT_FALSE(sse.is_connected());
  22171. }
  22172. // Sends one event, then nothing until stop is set
  22173. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22174. return [&stop](const Request &, Response &res) {
  22175. res.set_chunked_content_provider(
  22176. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22177. if (offset == 0) {
  22178. std::string event = "data: hello\n\n";
  22179. sink.write(event.data(), event.size());
  22180. }
  22181. while (!stop.load()) {
  22182. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22183. }
  22184. return false;
  22185. });
  22186. };
  22187. }
  22188. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22189. static void check_stop_interrupts_blocked_read(Client &client) {
  22190. client.set_read_timeout(30, 0);
  22191. for (auto by_destructor : {false, true}) {
  22192. std::atomic<bool> received{false};
  22193. std::chrono::steady_clock::time_point start;
  22194. {
  22195. sse::SSEClient sse(client, "/idle-stream");
  22196. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22197. sse.start_async();
  22198. for (int i = 0; i < 500 && !received.load(); ++i) {
  22199. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22200. }
  22201. ASSERT_TRUE(received.load());
  22202. // Let the client block in the next read
  22203. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22204. start = std::chrono::steady_clock::now();
  22205. if (!by_destructor) { sse.stop(); }
  22206. }
  22207. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22208. std::chrono::seconds(2));
  22209. }
  22210. }
  22211. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22212. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22213. Client client("localhost", get_port());
  22214. check_stop_interrupts_blocked_read(client);
  22215. }
  22216. #ifdef CPPHTTPLIB_SSL_ENABLED
  22217. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22219. std::atomic<bool> done{false};
  22220. svr.Get("/idle-stream", idle_event_stream(done));
  22221. auto port = svr.bind_to_any_port(HOST);
  22222. std::thread t([&] { svr.listen_after_bind(); });
  22223. auto se = detail::scope_exit([&] {
  22224. done.store(true);
  22225. svr.stop();
  22226. t.join();
  22227. });
  22228. svr.wait_until_ready();
  22229. Client client("https://localhost:" + std::to_string(port));
  22230. client.enable_server_certificate_verification(false);
  22231. check_stop_interrupts_blocked_read(client);
  22232. }
  22233. #endif
  22234. // Test: SSEClient with custom headers
  22235. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22236. // Setup a server endpoint that checks for custom header
  22237. std::atomic<bool> header_received{false};
  22238. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22239. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22240. header_received.store(true);
  22241. }
  22242. res.set_chunked_content_provider("text/event-stream",
  22243. [](size_t, DataSink &) { return false; });
  22244. });
  22245. Client client("localhost", get_port());
  22246. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22247. sse::SSEClient sse(client, "/header-check", headers);
  22248. sse.set_max_reconnect_attempts(1);
  22249. sse.start_async();
  22250. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22251. sse.stop();
  22252. EXPECT_TRUE(header_received.load());
  22253. }
  22254. // Test: Reconnect interval configuration
  22255. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22256. Client client("localhost", get_port());
  22257. sse::SSEClient sse(client, "/events");
  22258. auto &result = sse.set_reconnect_interval(500);
  22259. // Builder pattern should return reference to self
  22260. EXPECT_EQ(&result, &sse);
  22261. }
  22262. // Test: Max reconnect attempts
  22263. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22264. // Connect to non-existent port to force reconnects
  22265. Client client("localhost", 59998);
  22266. sse::SSEClient sse(client, "/events");
  22267. std::atomic<int> error_count{0};
  22268. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22269. sse.set_reconnect_interval(50);
  22270. sse.set_max_reconnect_attempts(2);
  22271. auto start = std::chrono::steady_clock::now();
  22272. sse.start(); // Blocking call
  22273. auto end = std::chrono::steady_clock::now();
  22274. // Should have stopped after 2 failed attempts
  22275. EXPECT_GE(error_count.load(), 2);
  22276. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22277. auto duration =
  22278. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22279. #ifdef _WIN32
  22280. // Windows is much slower for socket connection failures
  22281. EXPECT_LT(duration.count(), 7000);
  22282. #else
  22283. EXPECT_LT(duration.count(), 1000);
  22284. #endif
  22285. }
  22286. // Test: Multi-line data in integration
  22287. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22288. // Endpoint with multi-line data
  22289. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22290. res.set_chunked_content_provider(
  22291. "text/event-stream", [](size_t offset, DataSink &sink) {
  22292. if (offset == 0) {
  22293. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22294. sink.write(event.data(), event.size());
  22295. }
  22296. return false;
  22297. });
  22298. });
  22299. Client client("localhost", get_port());
  22300. sse::SSEClient sse(client, "/multiline-data");
  22301. std::string received_data;
  22302. std::mutex data_mutex;
  22303. sse.on_message([&](const sse::SSEMessage &msg) {
  22304. std::lock_guard<std::mutex> lock(data_mutex);
  22305. received_data = msg.data;
  22306. });
  22307. sse.set_reconnect_interval(100);
  22308. sse.set_max_reconnect_attempts(1);
  22309. sse.start_async();
  22310. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22311. sse.stop();
  22312. std::lock_guard<std::mutex> lock(data_mutex);
  22313. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22314. }
  22315. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22316. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22317. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22318. DataSink &sink) {
  22319. if (offset == 0) {
  22320. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22321. sink.write(events.data(), events.size());
  22322. }
  22323. return false;
  22324. });
  22325. });
  22326. Client client("localhost", get_port());
  22327. sse::SSEClient sse(client, "/empty-data-lines");
  22328. std::mutex mutex;
  22329. std::condition_variable cv;
  22330. std::vector<std::string> received;
  22331. sse.on_message([&](const sse::SSEMessage &msg) {
  22332. std::lock_guard<std::mutex> lock(mutex);
  22333. received.push_back(msg.data);
  22334. cv.notify_all();
  22335. });
  22336. sse.set_max_reconnect_attempts(1);
  22337. sse.start_async();
  22338. {
  22339. std::unique_lock<std::mutex> lock(mutex);
  22340. cv.wait_for(lock, std::chrono::seconds(2),
  22341. [&] { return received.size() >= 3; });
  22342. }
  22343. sse.stop();
  22344. ASSERT_GE(received.size(), 3u);
  22345. EXPECT_EQ(received[0], "");
  22346. EXPECT_EQ(received[1], "\nhello");
  22347. EXPECT_EQ(received[2], "");
  22348. }
  22349. // Test: Auto-reconnect after server disconnection
  22350. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22351. std::atomic<int> connection_count{0};
  22352. std::atomic<int> message_count{0};
  22353. // Endpoint that sends one event and closes, forcing reconnect
  22354. server_->Get("/reconnect-test",
  22355. [&connection_count](const Request &, Response &res) {
  22356. connection_count.fetch_add(1);
  22357. res.set_chunked_content_provider(
  22358. "text/event-stream", [](size_t offset, DataSink &sink) {
  22359. if (offset == 0) {
  22360. std::string event = "data: hello\n\n";
  22361. sink.write(event.data(), event.size());
  22362. }
  22363. return false; // Close connection after sending
  22364. });
  22365. });
  22366. Client client("localhost", get_port());
  22367. sse::SSEClient sse(client, "/reconnect-test");
  22368. sse.on_message([&message_count](const sse::SSEMessage &) {
  22369. message_count.fetch_add(1);
  22370. });
  22371. sse.set_reconnect_interval(100);
  22372. sse.set_max_reconnect_attempts(3);
  22373. sse.start_async();
  22374. // Wait long enough for multiple reconnects
  22375. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22376. sse.stop();
  22377. // Should have connected multiple times (initial + reconnects)
  22378. EXPECT_GE(connection_count.load(), 2);
  22379. // Should have received messages from multiple connections
  22380. EXPECT_GE(message_count.load(), 2);
  22381. }
  22382. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22383. std::atomic<int> connection_count{0};
  22384. // Neither Content-Length nor chunked: the close ends the stream
  22385. server_->Get("/close-delimited",
  22386. [&connection_count](const Request &, Response &res) {
  22387. connection_count.fetch_add(1);
  22388. res.set_content_provider(
  22389. "text/event-stream", [](size_t offset, DataSink &sink) {
  22390. if (offset == 0) {
  22391. std::string event = "data: hello\n\n";
  22392. sink.write(event.data(), event.size());
  22393. } else {
  22394. sink.done();
  22395. }
  22396. return true;
  22397. });
  22398. });
  22399. Client client("localhost", get_port());
  22400. sse::SSEClient sse(client, "/close-delimited");
  22401. std::atomic<int> error_count{0};
  22402. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22403. sse.set_reconnect_interval(100);
  22404. sse.start_async();
  22405. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22406. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22407. }
  22408. sse.stop();
  22409. // Reconnects as after any end of the stream, but reports no error
  22410. EXPECT_GE(connection_count.load(), 2);
  22411. EXPECT_EQ(0, error_count.load());
  22412. }
  22413. // Test: A retry field that is not all ASCII digits is ignored
  22414. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22415. std::atomic<int> connection_count{0};
  22416. server_->Get("/bad-retry",
  22417. [&connection_count](const Request &, Response &res) {
  22418. connection_count.fetch_add(1);
  22419. res.set_chunked_content_provider(
  22420. "text/event-stream", [](size_t offset, DataSink &sink) {
  22421. if (offset == 0) {
  22422. std::string event = "retry: -1\ndata: hello\n\n";
  22423. sink.write(event.data(), event.size());
  22424. }
  22425. return false;
  22426. });
  22427. });
  22428. Client client("localhost", get_port());
  22429. sse::SSEClient sse(client, "/bad-retry");
  22430. sse.set_reconnect_interval(10000);
  22431. sse.start_async();
  22432. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22433. sse.stop();
  22434. EXPECT_EQ(connection_count.load(), 1);
  22435. }
  22436. // Test: A retry field of all ASCII digits sets the reconnection time
  22437. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22438. std::mutex mutex;
  22439. std::condition_variable cv;
  22440. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22441. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22442. {
  22443. std::lock_guard<std::mutex> lock(mutex);
  22444. connected_at.push_back(std::chrono::steady_clock::now());
  22445. cv.notify_all();
  22446. }
  22447. res.set_chunked_content_provider(
  22448. "text/event-stream", [](size_t offset, DataSink &sink) {
  22449. if (offset == 0) {
  22450. std::string event = "retry: 0\ndata: hello\n\n";
  22451. sink.write(event.data(), event.size());
  22452. }
  22453. return false;
  22454. });
  22455. });
  22456. Client client("localhost", get_port());
  22457. sse::SSEClient sse(client, "/zero-retry");
  22458. sse.set_reconnect_interval(10000);
  22459. sse.start_async();
  22460. {
  22461. std::unique_lock<std::mutex> lock(mutex);
  22462. cv.wait_for(lock, std::chrono::seconds(5),
  22463. [&] { return connected_at.size() >= 2; });
  22464. }
  22465. sse.stop();
  22466. // The server-supplied interval is applied, but never below 100ms, so
  22467. // "retry: 0" does not cause a busy reconnect loop
  22468. std::lock_guard<std::mutex> lock(mutex);
  22469. ASSERT_GE(connected_at.size(), 2u);
  22470. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22471. connected_at[1] - connected_at[0])
  22472. .count();
  22473. EXPECT_GE(interval_ms, 100);
  22474. }
  22475. // Test: Last-Event-ID sent on reconnect
  22476. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22477. std::atomic<int> connection_count{0};
  22478. std::vector<std::string> received_last_event_ids;
  22479. std::mutex id_mutex;
  22480. // Endpoint that checks Last-Event-ID header and sends event with ID
  22481. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22482. int conn = connection_count.fetch_add(1);
  22483. // Capture the Last-Event-ID header from each connection
  22484. {
  22485. std::lock_guard<std::mutex> lock(id_mutex);
  22486. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22487. }
  22488. res.set_chunked_content_provider(
  22489. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22490. if (offset == 0) {
  22491. std::string event =
  22492. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22493. sink.write(event.data(), event.size());
  22494. }
  22495. return false;
  22496. });
  22497. });
  22498. Client client("localhost", get_port());
  22499. sse::SSEClient sse(client, "/reconnect-with-id");
  22500. sse.set_reconnect_interval(100);
  22501. sse.set_max_reconnect_attempts(3);
  22502. sse.start_async();
  22503. // Wait for at least 2 connections
  22504. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22505. sse.stop();
  22506. // Verify behavior
  22507. std::lock_guard<std::mutex> lock(id_mutex);
  22508. EXPECT_GE(received_last_event_ids.size(), 2u);
  22509. // First connection should have no Last-Event-ID
  22510. if (!received_last_event_ids.empty()) {
  22511. EXPECT_EQ(received_last_event_ids[0], "");
  22512. }
  22513. // Second connection should have Last-Event-ID from first connection
  22514. if (received_last_event_ids.size() >= 2) {
  22515. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22516. }
  22517. }
  22518. // Test: set_headers updates headers used on reconnect
  22519. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22520. std::vector<std::string> received_tokens;
  22521. std::mutex token_mutex;
  22522. // Endpoint that captures Authorization header
  22523. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22524. {
  22525. std::lock_guard<std::mutex> lock(token_mutex);
  22526. received_tokens.push_back(req.get_header_value("Authorization"));
  22527. }
  22528. res.set_chunked_content_provider(
  22529. "text/event-stream", [](size_t offset, DataSink &sink) {
  22530. if (offset == 0) {
  22531. std::string event = "data: hello\n\n";
  22532. sink.write(event.data(), event.size());
  22533. }
  22534. return false; // Close connection to trigger reconnect
  22535. });
  22536. });
  22537. Client client("localhost", get_port());
  22538. Headers headers = {{"Authorization", "Bearer old-token"}};
  22539. sse::SSEClient sse(client, "/auth-check", headers);
  22540. // Update headers on each successful connection
  22541. sse.on_open(
  22542. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22543. sse.set_reconnect_interval(100);
  22544. sse.set_max_reconnect_attempts(3);
  22545. sse.start_async();
  22546. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22547. sse.stop();
  22548. std::lock_guard<std::mutex> lock(token_mutex);
  22549. ASSERT_GE(received_tokens.size(), 2u);
  22550. // First connection uses original header
  22551. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22552. // Second connection uses updated header from set_headers
  22553. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22554. }
  22555. // Test: 401 allows reconnection (so on_error can refresh headers)
  22556. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22557. std::atomic<int> connection_count{0};
  22558. // Endpoint: returns 401 on first attempt, 200 on second
  22559. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22560. int conn = connection_count.fetch_add(1);
  22561. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22562. res.status = StatusCode::Unauthorized_401;
  22563. res.set_content("Unauthorized", "text/plain");
  22564. return;
  22565. }
  22566. res.set_chunked_content_provider(
  22567. "text/event-stream", [](size_t offset, DataSink &sink) {
  22568. if (offset == 0) {
  22569. std::string event = "data: authenticated\n\n";
  22570. sink.write(event.data(), event.size());
  22571. }
  22572. return false;
  22573. });
  22574. });
  22575. Client client("localhost", get_port());
  22576. Headers headers = {{"Authorization", "Bearer expired"}};
  22577. sse::SSEClient sse(client, "/auth-retry", headers);
  22578. std::atomic<bool> message_received{false};
  22579. // Refresh token on error
  22580. sse.on_error(
  22581. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22582. sse.on_message([&](const sse::SSEMessage &msg) {
  22583. if (msg.data == "authenticated") { message_received.store(true); }
  22584. });
  22585. sse.set_reconnect_interval(100);
  22586. sse.set_max_reconnect_attempts(3);
  22587. sse.start_async();
  22588. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22589. sse.stop();
  22590. // Should have reconnected after 401 and succeeded with new token
  22591. EXPECT_GE(connection_count.load(), 2);
  22592. EXPECT_TRUE(message_received.load());
  22593. }
  22594. TEST(Issue2318Test, EmptyHostString) {
  22595. {
  22596. httplib::Client cli_empty("", PORT);
  22597. auto res = cli_empty.Get("/");
  22598. ASSERT_FALSE(res);
  22599. EXPECT_EQ(httplib::Error::Connection, res.error());
  22600. }
  22601. {
  22602. httplib::Client cli(" ", PORT);
  22603. auto res = cli.Get("/");
  22604. ASSERT_FALSE(res);
  22605. EXPECT_EQ(httplib::Error::Connection, res.error());
  22606. }
  22607. }
  22608. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22609. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22610. Server svr;
  22611. // Set a small payload limit (1KB)
  22612. svr.set_payload_max_length(1024);
  22613. svr.Post("/test", [&](const Request &req, Response &res) {
  22614. res.set_content("Body size: " + std::to_string(req.body.size()),
  22615. "text/plain");
  22616. });
  22617. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22618. auto se = detail::scope_exit([&] {
  22619. svr.stop();
  22620. listen_thread.join();
  22621. });
  22622. svr.wait_until_ready();
  22623. // Create data that compresses well but exceeds limit when decompressed
  22624. // 8KB of repeated null bytes compresses to a very small size
  22625. std::string original_data(8 * 1024, '\0');
  22626. // Compress the data using gzip
  22627. std::string compressed_data;
  22628. detail::gzip_compressor compressor;
  22629. compressor.compress(original_data.data(), original_data.size(), true,
  22630. [&](const char *data, size_t size) {
  22631. compressed_data.append(data, size);
  22632. return true;
  22633. });
  22634. // Verify compression worked (compressed should be much smaller)
  22635. ASSERT_LT(compressed_data.size(), original_data.size());
  22636. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22637. // Send compressed data with Content-Encoding: gzip
  22638. Client cli(HOST, PORT);
  22639. Headers headers = {{"Content-Encoding", "gzip"}};
  22640. auto res =
  22641. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22642. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22644. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22645. }
  22646. #endif
  22647. // ============================================================================
  22648. // OpenSSL-Specific Tests
  22649. // ============================================================================
  22650. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22651. X509 *readCertificate(const std::string &strFileName) {
  22652. std::ifstream inStream(strFileName);
  22653. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22654. std::istreambuf_iterator<char>());
  22655. if (strCertPEM.empty()) return (nullptr);
  22656. BIO *pbCert = BIO_new(BIO_s_mem());
  22657. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22658. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22659. BIO_free(pbCert);
  22660. return (pCert);
  22661. }
  22662. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22663. std::ifstream inStream(strFileName);
  22664. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22665. std::istreambuf_iterator<char>());
  22666. if (strPrivateKeyPEM.empty()) return (nullptr);
  22667. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22668. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22669. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22670. BIO_free(pbPrivKey);
  22671. return (pPrivateKey);
  22672. }
  22673. TEST(BindServerTest, UpdateCerts) {
  22674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22675. int port = svr.bind_to_any_port("0.0.0.0");
  22676. ASSERT_TRUE(svr.is_valid());
  22677. ASSERT_TRUE(port > 0);
  22678. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22679. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22680. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22681. ASSERT_TRUE(cert != nullptr);
  22682. ASSERT_TRUE(ca_cert != nullptr);
  22683. ASSERT_TRUE(key != nullptr);
  22684. X509_STORE *cert_store = X509_STORE_new();
  22685. X509_STORE_add_cert(cert_store, ca_cert);
  22686. // svr.update_certs(cert, key, cert_store); // deprecated
  22687. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22688. CLIENT_CA_CERT_FILE);
  22689. ASSERT_TRUE(svr.is_valid());
  22690. svr.stop();
  22691. X509_STORE_free(cert_store);
  22692. X509_free(cert);
  22693. X509_free(ca_cert);
  22694. EVP_PKEY_free(key);
  22695. }
  22696. // Test that update_certs() updates client CA list correctly
  22697. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22698. // Start with file-based constructor
  22699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22700. ASSERT_TRUE(svr.is_valid());
  22701. // Initially no client CA list should be set
  22702. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22703. ASSERT_TRUE(ssl_ctx != nullptr);
  22704. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22705. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22706. // Now update with client CA (PEM string)
  22707. std::string cert_pem, key_pem, ca_pem;
  22708. read_file(SERVER_CERT_FILE, cert_pem);
  22709. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22710. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22711. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22712. ASSERT_TRUE(svr.is_valid());
  22713. // Now client CA list should be set
  22714. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22715. ASSERT_TRUE(ca_list_after != nullptr);
  22716. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22717. }
  22718. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22719. // Test that the file-path SSLServer constructor properly sets the client CA
  22720. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22721. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22722. ASSERT_TRUE(svr.is_valid());
  22723. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22724. ASSERT_TRUE(ssl_ctx != nullptr);
  22725. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22726. ASSERT_TRUE(ca_list != nullptr);
  22727. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22728. }
  22729. #endif
  22730. // ============================================================================
  22731. // MbedTLS-Specific Tests
  22732. // ============================================================================
  22733. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22734. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22735. using namespace httplib::tls;
  22736. // Track if callback was invoked
  22737. bool callback_invoked = false;
  22738. // The callback receives void* ctx which is actually MbedTlsContext*
  22739. // We can access the mbedtls_ssl_config via the context
  22740. auto setup_callback = [&callback_invoked](void *ctx) {
  22741. callback_invoked = true;
  22742. // Cast to MbedTlsContext* to access the ssl config
  22743. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22744. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22745. // Use static variables to hold certificate data (simplified for test)
  22746. static mbedtls_x509_crt own_cert;
  22747. static mbedtls_pk_context own_key;
  22748. static mbedtls_x509_crt ca_chain;
  22749. static bool initialized = false;
  22750. if (!initialized) {
  22751. mbedtls_x509_crt_init(&own_cert);
  22752. mbedtls_pk_init(&own_key);
  22753. mbedtls_x509_crt_init(&ca_chain);
  22754. // Load server certificate
  22755. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22756. return false;
  22757. }
  22758. // Load server private key.
  22759. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22760. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22761. #if MBEDTLS_VERSION_MAJOR == 3
  22762. ,
  22763. mbedtls_ctr_drbg_random, nullptr
  22764. #endif
  22765. ) != 0) {
  22766. return false;
  22767. }
  22768. // Load CA chain for client verification
  22769. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22770. return false;
  22771. }
  22772. initialized = true;
  22773. }
  22774. // Configure the SSL config
  22775. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22776. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22777. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22778. // Set minimum TLS version using mbedTLS native API
  22779. #if MBEDTLS_VERSION_MAJOR >= 3
  22780. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22781. #else
  22782. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22783. MBEDTLS_SSL_MINOR_VERSION_3);
  22784. #endif
  22785. return true;
  22786. };
  22787. SSLServer svr(setup_callback);
  22788. ASSERT_TRUE(svr.is_valid());
  22789. ASSERT_TRUE(callback_invoked);
  22790. svr.Get("/test", [&](const Request &req, Response &res) {
  22791. res.set_content("test", "text/plain");
  22792. auto cert = req.peer_cert();
  22793. ASSERT_TRUE(static_cast<bool>(cert));
  22794. auto common_name = cert.subject_cn();
  22795. EXPECT_EQ("Common Name", common_name);
  22796. });
  22797. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22798. auto se = detail::scope_exit([&] {
  22799. svr.stop();
  22800. t.join();
  22801. ASSERT_FALSE(svr.is_running());
  22802. });
  22803. svr.wait_until_ready();
  22804. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22805. cli.enable_server_certificate_verification(false);
  22806. cli.set_connection_timeout(30);
  22807. auto res = cli.Get("/test");
  22808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22809. ASSERT_EQ(StatusCode::OK_200, res->status);
  22810. }
  22811. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22812. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22813. // keep-alive SSL session, which reads through that config in
  22814. // mbedtls_ssl_close_notify.
  22815. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22817. ASSERT_TRUE(svr.is_valid());
  22818. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22819. res.set_content("test", "text/plain");
  22820. });
  22821. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22822. auto se = detail::scope_exit([&] {
  22823. svr.stop();
  22824. t.join();
  22825. ASSERT_FALSE(svr.is_running());
  22826. });
  22827. svr.wait_until_ready();
  22828. {
  22829. SSLClient cli(HOST, PORT);
  22830. cli.enable_server_certificate_verification(false);
  22831. cli.set_keep_alive(true);
  22832. auto res = cli.Get("/test");
  22833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22834. ASSERT_EQ(StatusCode::OK_200, res->status);
  22835. // cli is destructed here with the keep-alive SSL session still open.
  22836. }
  22837. }
  22838. #endif
  22839. // WebSocket Tests
  22840. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22841. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22842. // defining the meaning of these bits has been negotiated.
  22843. auto make_frame = [](uint8_t first_byte) {
  22844. std::string frame;
  22845. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22846. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22847. frame += "Hello";
  22848. return frame;
  22849. };
  22850. // RSV1 set (0x40)
  22851. {
  22852. detail::BufferStream strm;
  22853. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22854. ws::Opcode opcode;
  22855. std::string payload;
  22856. bool fin;
  22857. EXPECT_EQ(
  22858. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22859. ws::impl::FrameRead::Fail);
  22860. }
  22861. // RSV2 set (0x20)
  22862. {
  22863. detail::BufferStream strm;
  22864. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22865. ws::Opcode opcode;
  22866. std::string payload;
  22867. bool fin;
  22868. EXPECT_EQ(
  22869. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22870. ws::impl::FrameRead::Fail);
  22871. }
  22872. // RSV3 set (0x10)
  22873. {
  22874. detail::BufferStream strm;
  22875. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22876. ws::Opcode opcode;
  22877. std::string payload;
  22878. bool fin;
  22879. EXPECT_EQ(
  22880. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22881. ws::impl::FrameRead::Fail);
  22882. }
  22883. // No RSV bits set - should succeed
  22884. {
  22885. detail::BufferStream strm;
  22886. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22887. ws::Opcode opcode;
  22888. std::string payload;
  22889. bool fin;
  22890. EXPECT_EQ(
  22891. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22892. ws::impl::FrameRead::Ok);
  22893. EXPECT_EQ(ws::Opcode::Text, opcode);
  22894. EXPECT_EQ("Hello", payload);
  22895. EXPECT_TRUE(fin);
  22896. }
  22897. }
  22898. TEST(WebSocketTest, ControlFrameValidation) {
  22899. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22900. // payload length <= 125.
  22901. // Ping with FIN=0 - must be rejected
  22902. {
  22903. detail::BufferStream strm;
  22904. std::string frame;
  22905. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22906. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22907. strm.write(frame.data(), frame.size());
  22908. ws::Opcode opcode;
  22909. std::string payload;
  22910. bool fin;
  22911. EXPECT_EQ(
  22912. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22913. ws::impl::FrameRead::Fail);
  22914. }
  22915. // Close with FIN=0 - must be rejected
  22916. {
  22917. detail::BufferStream strm;
  22918. std::string frame;
  22919. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22920. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22921. strm.write(frame.data(), frame.size());
  22922. ws::Opcode opcode;
  22923. std::string payload;
  22924. bool fin;
  22925. EXPECT_EQ(
  22926. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22927. ws::impl::FrameRead::Fail);
  22928. }
  22929. // Ping with payload_len=126 (extended length) - must be rejected
  22930. {
  22931. detail::BufferStream strm;
  22932. std::string frame;
  22933. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22934. frame += static_cast<char>(126); // payload_len=126 (>125)
  22935. frame += static_cast<char>(0x00); // extended length high byte
  22936. frame += static_cast<char>(126); // extended length low byte
  22937. frame += std::string(126, 'x');
  22938. strm.write(frame.data(), frame.size());
  22939. ws::Opcode opcode;
  22940. std::string payload;
  22941. bool fin;
  22942. EXPECT_EQ(
  22943. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22944. ws::impl::FrameRead::Fail);
  22945. }
  22946. // Ping with FIN=1 and payload_len=125 - should succeed
  22947. {
  22948. detail::BufferStream strm;
  22949. std::string frame;
  22950. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22951. frame += static_cast<char>(125); // payload_len=125
  22952. frame += std::string(125, 'x');
  22953. strm.write(frame.data(), frame.size());
  22954. ws::Opcode opcode;
  22955. std::string payload;
  22956. bool fin;
  22957. EXPECT_EQ(
  22958. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22959. ws::impl::FrameRead::Ok);
  22960. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22961. EXPECT_EQ(125u, payload.size());
  22962. EXPECT_TRUE(fin);
  22963. }
  22964. }
  22965. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22966. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22967. // length MUST be 0.
  22968. // MSB set - must be rejected
  22969. {
  22970. detail::BufferStream strm;
  22971. std::string frame;
  22972. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22973. frame += static_cast<char>(127); // 64-bit extended length
  22974. frame += static_cast<char>(0x80); // MSB set (invalid)
  22975. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22976. strm.write(frame.data(), frame.size());
  22977. ws::Opcode opcode;
  22978. std::string payload;
  22979. bool fin;
  22980. EXPECT_EQ(
  22981. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22982. ws::impl::FrameRead::Fail);
  22983. }
  22984. // MSB clear - should pass length parsing (will be rejected by max_len,
  22985. // but that's a different check; use a small length to verify)
  22986. {
  22987. detail::BufferStream strm;
  22988. std::string frame;
  22989. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22990. frame += static_cast<char>(127); // 64-bit extended length
  22991. frame += std::string(7, '\0'); // high bytes = 0
  22992. frame += static_cast<char>(0x03); // length = 3
  22993. frame += "abc";
  22994. strm.write(frame.data(), frame.size());
  22995. ws::Opcode opcode;
  22996. std::string payload;
  22997. bool fin;
  22998. EXPECT_EQ(
  22999. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23000. ws::impl::FrameRead::Ok);
  23001. EXPECT_EQ(ws::Opcode::Text, opcode);
  23002. EXPECT_EQ("abc", payload);
  23003. }
  23004. }
  23005. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23006. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23007. // Valid UTF-8
  23008. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23009. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23010. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23011. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23012. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23013. // Invalid UTF-8
  23014. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23015. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23016. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23017. EXPECT_FALSE(
  23018. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23019. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23020. }
  23021. TEST(WebSocketTest, ConnectAndDisconnect) {
  23022. Server svr;
  23023. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23024. std::string msg;
  23025. while (ws.read(msg)) {}
  23026. });
  23027. auto port = svr.bind_to_any_port(HOST);
  23028. std::thread t([&]() { svr.listen_after_bind(); });
  23029. svr.wait_until_ready();
  23030. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23031. auto res = client.connect();
  23032. ASSERT_TRUE(res);
  23033. EXPECT_EQ(Error::Success, res.error());
  23034. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23035. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23036. EXPECT_TRUE(client.is_open());
  23037. client.close();
  23038. EXPECT_FALSE(client.is_open());
  23039. svr.stop();
  23040. t.join();
  23041. }
  23042. TEST(WebSocketTest, ValidURL) {
  23043. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23044. EXPECT_TRUE(ws1.is_valid());
  23045. ws::WebSocketClient ws2("ws://example.com/path");
  23046. EXPECT_TRUE(ws2.is_valid());
  23047. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23048. EXPECT_TRUE(ws3.is_valid());
  23049. #ifdef CPPHTTPLIB_SSL_ENABLED
  23050. ws::WebSocketClient wss1("wss://example.com/path");
  23051. EXPECT_TRUE(wss1.is_valid());
  23052. ws::WebSocketClient wss2("wss://example.com:443/path");
  23053. EXPECT_TRUE(wss2.is_valid());
  23054. #endif
  23055. }
  23056. TEST(WebSocketTest, InvalidURL) {
  23057. // No scheme
  23058. ws::WebSocketClient ws1("localhost:8080/path");
  23059. EXPECT_FALSE(ws1.is_valid());
  23060. // No path
  23061. ws::WebSocketClient ws2("ws://localhost:8080");
  23062. EXPECT_FALSE(ws2.is_valid());
  23063. // Empty string
  23064. ws::WebSocketClient ws3("");
  23065. EXPECT_FALSE(ws3.is_valid());
  23066. // Missing host
  23067. ws::WebSocketClient ws4("ws://:8080/path");
  23068. EXPECT_FALSE(ws4.is_valid());
  23069. // Port number overflow — should not crash
  23070. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23071. EXPECT_FALSE(ws5.is_valid());
  23072. // Port out of range
  23073. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23074. EXPECT_FALSE(ws6.is_valid());
  23075. }
  23076. TEST(WebSocketTest, UnsupportedScheme) {
  23077. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23078. ws::WebSocketClient ws1("http://localhost:8080/path");
  23079. EXPECT_FALSE(ws1.is_valid());
  23080. ws::WebSocketClient ws2("https://localhost:8080/path");
  23081. EXPECT_FALSE(ws2.is_valid());
  23082. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23083. EXPECT_FALSE(ws3.is_valid());
  23084. #else
  23085. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23086. std::invalid_argument);
  23087. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23088. std::invalid_argument);
  23089. #endif
  23090. }
  23091. TEST(WebSocketTest, ConnectWhenInvalid) {
  23092. ws::WebSocketClient ws("not a valid url");
  23093. EXPECT_FALSE(ws.is_valid());
  23094. auto res = ws.connect();
  23095. EXPECT_FALSE(res);
  23096. EXPECT_EQ(Error::Connection, res.error());
  23097. EXPECT_EQ(-1, res.status());
  23098. }
  23099. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23100. // Grab a port that is free, then close it again so nothing listens there
  23101. Server svr;
  23102. auto port = svr.bind_to_any_port(HOST);
  23103. svr.stop();
  23104. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23105. auto res = client.connect();
  23106. ASSERT_FALSE(res);
  23107. EXPECT_EQ(Error::Connection, res.error());
  23108. EXPECT_EQ(-1, res.status());
  23109. }
  23110. TEST(WebSocketTest, DefaultPort) {
  23111. ws::WebSocketClient ws1("ws://example.com/path");
  23112. EXPECT_TRUE(ws1.is_valid());
  23113. // ws:// defaults to port 80 (verified by successful parse)
  23114. #ifdef CPPHTTPLIB_SSL_ENABLED
  23115. ws::WebSocketClient ws2("wss://example.com/path");
  23116. EXPECT_TRUE(ws2.is_valid());
  23117. // wss:// defaults to port 443 (verified by successful parse)
  23118. #endif
  23119. }
  23120. TEST(WebSocketTest, IPv6LiteralAddress) {
  23121. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23122. EXPECT_TRUE(ws1.is_valid());
  23123. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23124. EXPECT_TRUE(ws2.is_valid());
  23125. }
  23126. TEST(WebSocketTest, ComplexPath) {
  23127. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23128. EXPECT_TRUE(ws1.is_valid());
  23129. ws::WebSocketClient ws2("ws://localhost:8080/");
  23130. EXPECT_TRUE(ws2.is_valid());
  23131. }
  23132. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23133. Server svr;
  23134. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23135. std::string msg;
  23136. while (ws.read(msg)) {}
  23137. });
  23138. auto port = svr.bind_to_any_port(HOST);
  23139. std::thread t([&]() { svr.listen_after_bind(); });
  23140. svr.wait_until_ready();
  23141. auto another_host = "example.com";
  23142. auto wrong_ip = "192.0.2.1";
  23143. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23144. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23145. ASSERT_TRUE(client.connect());
  23146. EXPECT_TRUE(client.is_open());
  23147. client.close();
  23148. svr.stop();
  23149. t.join();
  23150. }
  23151. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23152. Server svr;
  23153. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23154. std::string msg;
  23155. while (ws.read(msg)) {}
  23156. });
  23157. auto port = svr.bind_to_any_port(HOST);
  23158. std::thread t([&]() { svr.listen_after_bind(); });
  23159. svr.wait_until_ready();
  23160. auto wrong_ip = "192.0.2.1";
  23161. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23162. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23163. client.set_connection_timeout(1);
  23164. client.set_read_timeout(1);
  23165. client.set_write_timeout(1);
  23166. EXPECT_FALSE(client.connect());
  23167. EXPECT_FALSE(client.is_open());
  23168. svr.stop();
  23169. t.join();
  23170. }
  23171. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23172. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23173. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23174. // (RFC 6761) is only a map key and the Host header value.
  23175. auto host = "target.invalid";
  23176. Server svr;
  23177. std::string received_host;
  23178. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23179. received_host = req.get_header_value("Host");
  23180. std::string msg;
  23181. while (ws.read(msg)) {}
  23182. });
  23183. auto port = svr.bind_to_any_port(HOST);
  23184. std::thread t([&]() { svr.listen_after_bind(); });
  23185. // ASSERT_* below returns from the test body, which would leave t joinable
  23186. // and make ~thread call std::terminate.
  23187. auto se = detail::scope_exit([&] {
  23188. svr.stop();
  23189. if (t.joinable()) { t.join(); }
  23190. });
  23191. svr.wait_until_ready();
  23192. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23193. std::to_string(port) + "/ws");
  23194. client.set_hostname_addr_map({{host, HOST}});
  23195. ASSERT_TRUE(client.connect());
  23196. EXPECT_TRUE(client.is_open());
  23197. client.close();
  23198. svr.stop();
  23199. t.join();
  23200. // The mapping only redirects the connection; the identity stays host_.
  23201. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23202. }
  23203. class WebSocketIntegrationTest : public ::testing::Test {
  23204. protected:
  23205. void SetUp() override {
  23206. server_ = httplib::detail::make_unique<Server>();
  23207. setup_server();
  23208. start_server();
  23209. }
  23210. void TearDown() override {
  23211. server_->stop();
  23212. if (server_thread_.joinable()) { server_thread_.join(); }
  23213. }
  23214. void setup_server() {
  23215. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23216. std::string msg;
  23217. ws::ReadResult ret;
  23218. while ((ret = ws.read(msg))) {
  23219. if (ret == ws::Binary) {
  23220. ws.send(msg.data(), msg.size());
  23221. } else {
  23222. ws.send(msg);
  23223. }
  23224. }
  23225. });
  23226. server_->WebSocket("/ws-echo-string",
  23227. [](const Request &, ws::WebSocket &ws) {
  23228. std::string msg;
  23229. while (ws.read(msg)) {
  23230. ws.send("echo: " + msg);
  23231. }
  23232. });
  23233. server_->WebSocket(
  23234. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23235. // Echo back request metadata
  23236. ws.send("path:" + req.path);
  23237. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23238. std::string msg;
  23239. while (ws.read(msg)) {}
  23240. });
  23241. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23242. std::string msg;
  23243. ws.read(msg); // wait for a message
  23244. ws.close();
  23245. });
  23246. server_->WebSocket("/ws-close-status",
  23247. [](const Request &, ws::WebSocket &ws) {
  23248. std::string msg;
  23249. ws.read(msg); // wait for a message
  23250. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23251. });
  23252. server_->WebSocket(
  23253. "/ws-subprotocol",
  23254. [](const Request &, ws::WebSocket &ws) {
  23255. std::string msg;
  23256. while (ws.read(msg)) {
  23257. ws.send(msg);
  23258. }
  23259. },
  23260. [](const std::vector<std::string> &protocols) -> std::string {
  23261. for (const auto &p : protocols) {
  23262. if (p == "graphql-ws") { return p; }
  23263. }
  23264. return "";
  23265. });
  23266. server_->WebSocket(
  23267. "/ws-subprotocol-unoffered",
  23268. [](const Request &, ws::WebSocket &ws) {
  23269. std::string msg;
  23270. while (ws.read(msg)) {
  23271. ws.send(msg);
  23272. }
  23273. },
  23274. [](const std::vector<std::string> &) -> std::string {
  23275. return "admin";
  23276. });
  23277. }
  23278. void start_server() {
  23279. port_ = server_->bind_to_any_port(HOST);
  23280. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23281. server_->wait_until_ready();
  23282. }
  23283. std::unique_ptr<Server> server_;
  23284. std::thread server_thread_;
  23285. int port_ = 0;
  23286. };
  23287. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23288. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23289. "/ws-echo");
  23290. ASSERT_TRUE(client.connect());
  23291. ASSERT_TRUE(client.is_open());
  23292. ASSERT_TRUE(client.send("Hello WebSocket"));
  23293. std::string msg;
  23294. EXPECT_EQ(ws::Text, client.read(msg));
  23295. EXPECT_EQ("Hello WebSocket", msg);
  23296. client.close();
  23297. }
  23298. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23299. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23300. "/ws-echo");
  23301. ASSERT_TRUE(client.connect());
  23302. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23303. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23304. std::string msg;
  23305. EXPECT_EQ(ws::Binary, client.read(msg));
  23306. EXPECT_EQ(binary_data, msg);
  23307. client.close();
  23308. }
  23309. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23310. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23311. "/ws-echo");
  23312. ASSERT_TRUE(client.connect());
  23313. for (int i = 0; i < 10; i++) {
  23314. auto text = "message " + std::to_string(i);
  23315. ASSERT_TRUE(client.send(text));
  23316. std::string msg;
  23317. ASSERT_TRUE(client.read(msg));
  23318. EXPECT_EQ(text, msg);
  23319. }
  23320. client.close();
  23321. }
  23322. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23323. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23324. "/ws-close");
  23325. ASSERT_TRUE(client.connect());
  23326. // Send a message to trigger the server to close
  23327. ASSERT_TRUE(client.send("trigger close"));
  23328. // The server will close, so read should return false
  23329. std::string msg;
  23330. EXPECT_FALSE(client.read(msg));
  23331. EXPECT_FALSE(client.is_open());
  23332. }
  23333. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23334. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23335. "/ws-echo");
  23336. ASSERT_TRUE(client.connect());
  23337. // 128KB message
  23338. std::string large_data(128 * 1024, 'X');
  23339. ASSERT_TRUE(client.send(large_data));
  23340. std::string msg;
  23341. ASSERT_TRUE(client.read(msg));
  23342. EXPECT_EQ(large_data, msg);
  23343. client.close();
  23344. }
  23345. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23346. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23347. "/ws-echo");
  23348. ASSERT_TRUE(client.connect());
  23349. const int num_threads = 4;
  23350. std::vector<std::thread> threads;
  23351. std::atomic<int> send_count{0};
  23352. for (int t = 0; t < num_threads; t++) {
  23353. threads.emplace_back([&client, &send_count, t]() {
  23354. for (int i = 0; i < 5; i++) {
  23355. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23356. if (client.send(text)) { send_count++; }
  23357. }
  23358. });
  23359. }
  23360. for (auto &th : threads) {
  23361. th.join();
  23362. }
  23363. int received = 0;
  23364. std::string msg;
  23365. while (received < send_count.load()) {
  23366. if (!client.read(msg)) { break; }
  23367. received++;
  23368. }
  23369. EXPECT_EQ(send_count.load(), received);
  23370. client.close();
  23371. }
  23372. TEST_F(WebSocketIntegrationTest, ReadString) {
  23373. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23374. "/ws-echo-string");
  23375. ASSERT_TRUE(client.connect());
  23376. ASSERT_TRUE(client.send("hello"));
  23377. std::string msg;
  23378. ASSERT_TRUE(client.read(msg));
  23379. EXPECT_EQ("echo: hello", msg);
  23380. ASSERT_TRUE(client.send("world"));
  23381. ASSERT_TRUE(client.read(msg));
  23382. EXPECT_EQ("echo: world", msg);
  23383. client.close();
  23384. }
  23385. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23386. Headers headers = {{"X-Test-Header", "test-value"}};
  23387. ws::WebSocketClient client(
  23388. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23389. ASSERT_TRUE(client.connect());
  23390. std::string msg;
  23391. ASSERT_TRUE(client.read(msg));
  23392. EXPECT_EQ("path:/ws-request-info", msg);
  23393. ASSERT_TRUE(client.read(msg));
  23394. EXPECT_EQ("header:test-value", msg);
  23395. client.close();
  23396. }
  23397. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23398. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23399. "/ws-echo");
  23400. client.set_read_timeout(1, 0); // 1 second
  23401. ASSERT_TRUE(client.connect());
  23402. // Don't send anything — server echo handler waits for a message, so read()
  23403. // should time out. The connection survives it: nothing was consumed.
  23404. std::string msg;
  23405. EXPECT_EQ(client.read(msg), ws::Timeout);
  23406. EXPECT_TRUE(client.is_open());
  23407. // And it is still usable afterwards.
  23408. EXPECT_TRUE(client.send("after timeout"));
  23409. EXPECT_EQ(client.read(msg), ws::Text);
  23410. EXPECT_EQ(msg, "after timeout");
  23411. }
  23412. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23413. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23414. "/ws-echo");
  23415. client.set_read_timeout(1, 0);
  23416. ASSERT_TRUE(client.connect());
  23417. ASSERT_TRUE(client.send("first"));
  23418. std::string msg;
  23419. ASSERT_EQ(client.read(msg), ws::Text);
  23420. ASSERT_EQ(msg, "first");
  23421. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23422. // not be used with a read timeout: it would reprocess the previous message.
  23423. EXPECT_EQ(client.read(msg), ws::Timeout);
  23424. EXPECT_EQ(msg, "first");
  23425. }
  23426. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23427. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23428. "/ws-echo");
  23429. ASSERT_TRUE(client.connect());
  23430. // Setting it once the connection is open reaches the live stream, not just
  23431. // the seed for the next connect().
  23432. client.set_read_timeout(1, 0);
  23433. std::string msg;
  23434. EXPECT_EQ(client.read(msg), ws::Timeout);
  23435. EXPECT_TRUE(client.is_open());
  23436. }
  23437. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23438. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23439. "/ws-echo");
  23440. client.set_read_timeout(5, 0);
  23441. ASSERT_TRUE(client.connect());
  23442. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23443. // The server should reject it and close the connection.
  23444. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23445. client.send(oversized);
  23446. // The server's read() should have failed due to payload limit,
  23447. // so our read() should return false (connection closed).
  23448. std::string msg;
  23449. EXPECT_FALSE(client.read(msg));
  23450. }
  23451. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23452. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23453. "/ws-echo");
  23454. client.set_read_timeout(10, 0);
  23455. ASSERT_TRUE(client.connect());
  23456. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23457. // This should succeed.
  23458. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23459. ASSERT_TRUE(client.send(at_limit));
  23460. std::string msg;
  23461. ASSERT_TRUE(client.read(msg));
  23462. EXPECT_EQ(at_limit.size(), msg.size());
  23463. client.close();
  23464. }
  23465. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23466. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23467. "/nonexistent");
  23468. auto res = client.connect();
  23469. EXPECT_FALSE(res);
  23470. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23471. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23472. EXPECT_FALSE(client.is_open());
  23473. }
  23474. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23475. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23476. "/ws-echo");
  23477. ASSERT_TRUE(client.connect());
  23478. ASSERT_TRUE(client.send(""));
  23479. std::string msg;
  23480. EXPECT_EQ(ws::Text, client.read(msg));
  23481. EXPECT_EQ("", msg);
  23482. client.close();
  23483. }
  23484. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23485. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23486. "/ws-echo");
  23487. // First connection
  23488. ASSERT_TRUE(client.connect());
  23489. ASSERT_TRUE(client.send("first"));
  23490. std::string msg;
  23491. ASSERT_TRUE(client.read(msg));
  23492. EXPECT_EQ("first", msg);
  23493. client.close();
  23494. EXPECT_FALSE(client.is_open());
  23495. // Reconnect using the same client object
  23496. ASSERT_TRUE(client.connect());
  23497. ASSERT_TRUE(client.is_open());
  23498. ASSERT_TRUE(client.send("second"));
  23499. ASSERT_TRUE(client.read(msg));
  23500. EXPECT_EQ("second", msg);
  23501. client.close();
  23502. }
  23503. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23504. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23505. "/ws-close-status");
  23506. ASSERT_TRUE(client.connect());
  23507. // Trigger the server to close with GoingAway status
  23508. ASSERT_TRUE(client.send("trigger"));
  23509. // read() should return false after receiving the close frame
  23510. std::string msg;
  23511. EXPECT_FALSE(client.read(msg));
  23512. EXPECT_FALSE(client.is_open());
  23513. }
  23514. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23515. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23516. "/ws-echo");
  23517. ASSERT_TRUE(client.connect());
  23518. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23519. EXPECT_FALSE(client.is_open());
  23520. }
  23521. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23522. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23523. ws::WebSocketClient client(
  23524. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23525. ASSERT_TRUE(client.connect());
  23526. // Server should have selected graphql-ws
  23527. EXPECT_EQ("graphql-ws", client.subprotocol());
  23528. client.close();
  23529. }
  23530. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23531. Headers headers;
  23532. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23533. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23534. ws::WebSocketClient client(
  23535. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23536. ASSERT_TRUE(client.connect());
  23537. // The offer on the second field line counts too, so graphql-ws is selected
  23538. EXPECT_EQ("graphql-ws", client.subprotocol());
  23539. client.close();
  23540. }
  23541. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23542. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23543. ws::WebSocketClient client(
  23544. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23545. ASSERT_TRUE(client.connect());
  23546. // Server should not have selected any subprotocol
  23547. EXPECT_TRUE(client.subprotocol().empty());
  23548. client.close();
  23549. }
  23550. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23551. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23552. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23553. "/ws-subprotocol-unoffered",
  23554. headers);
  23555. ASSERT_TRUE(client.connect());
  23556. EXPECT_TRUE(client.subprotocol().empty());
  23557. client.close();
  23558. }
  23559. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23560. // Connect without requesting any subprotocol
  23561. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23562. "/ws-subprotocol");
  23563. ASSERT_TRUE(client.connect());
  23564. EXPECT_TRUE(client.subprotocol().empty());
  23565. client.close();
  23566. }
  23567. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23568. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23569. "/ws-echo");
  23570. client.set_tcp_nodelay(true);
  23571. client.set_connection_timeout(3, 0);
  23572. bool socket_options_called = false;
  23573. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23574. ASSERT_TRUE(client.connect());
  23575. ASSERT_TRUE(client.is_open());
  23576. EXPECT_TRUE(socket_options_called);
  23577. ASSERT_TRUE(client.send("hello"));
  23578. std::string msg;
  23579. auto result = client.read(msg);
  23580. EXPECT_EQ(result, ws::ReadResult::Text);
  23581. EXPECT_EQ(msg, "hello");
  23582. client.close();
  23583. }
  23584. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23585. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23586. "/ws-echo");
  23587. client.set_connection_timeout(std::chrono::seconds(3));
  23588. client.set_write_timeout(std::chrono::seconds(3));
  23589. // A sub-second remainder exercises the seconds/microseconds split.
  23590. client.set_read_timeout(std::chrono::milliseconds(1500));
  23591. ASSERT_TRUE(client.connect());
  23592. auto start = std::chrono::steady_clock::now();
  23593. std::string msg;
  23594. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23595. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23596. std::chrono::steady_clock::now() - start)
  23597. .count();
  23598. // Above 1s so that dropping the microseconds half of the split fails here.
  23599. // Ignoring the setter altogether would not reach this line at all: a client
  23600. // waits forever by default.
  23601. EXPECT_GE(elapsed, 1400);
  23602. EXPECT_LT(elapsed, 30000);
  23603. }
  23604. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23605. Server svr;
  23606. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23607. if (!req.has_header("Authorization")) {
  23608. res.status = StatusCode::Unauthorized_401;
  23609. res.set_content("Unauthorized", "text/plain");
  23610. return Server::HandlerResponse::Handled;
  23611. }
  23612. return Server::HandlerResponse::Unhandled;
  23613. });
  23614. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23615. std::string msg;
  23616. while (ws.read(msg)) {
  23617. ws.send(msg);
  23618. }
  23619. });
  23620. auto port = svr.bind_to_any_port("localhost");
  23621. std::thread t([&]() { svr.listen_after_bind(); });
  23622. svr.wait_until_ready();
  23623. // Without Authorization header - should be rejected before upgrade
  23624. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23625. EXPECT_FALSE(client1.connect());
  23626. // The rejection is framed like any other HTTP response
  23627. {
  23628. Client cli("localhost", port);
  23629. Headers headers = {{"Upgrade", "websocket"},
  23630. {"Connection", "Upgrade"},
  23631. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23632. {"Sec-WebSocket-Version", "13"}};
  23633. auto res = cli.Get("/ws", headers);
  23634. ASSERT_TRUE(res);
  23635. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23636. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23637. EXPECT_EQ("Unauthorized", res->body);
  23638. }
  23639. // With Authorization header - should succeed
  23640. Headers headers = {{"Authorization", "Bearer token123"}};
  23641. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23642. headers);
  23643. ASSERT_TRUE(client2.connect());
  23644. ASSERT_TRUE(client2.send("hello"));
  23645. std::string msg;
  23646. ASSERT_TRUE(client2.read(msg));
  23647. EXPECT_EQ("hello", msg);
  23648. client2.close();
  23649. svr.stop();
  23650. t.join();
  23651. }
  23652. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23653. Server svr;
  23654. std::atomic<int> pre_routing_calls{0};
  23655. std::atomic<int> pre_request_calls{0};
  23656. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23657. pre_routing_calls++;
  23658. if (req.path == "/handled") {
  23659. res.set_content("handled", "text/plain");
  23660. return Server::HandlerResponse::Handled;
  23661. }
  23662. return Server::HandlerResponse::Unhandled;
  23663. });
  23664. svr.set_pre_request_handler([&](const Request &, Response &) {
  23665. pre_request_calls++;
  23666. return Server::HandlerResponse::Unhandled;
  23667. });
  23668. svr.Get("/http", [](const Request &, Response &res) {
  23669. res.set_content("http", "text/plain");
  23670. });
  23671. svr.WebSocket("/ws",
  23672. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23673. auto port = svr.bind_to_any_port("localhost");
  23674. std::thread t([&]() { svr.listen_after_bind(); });
  23675. auto se = detail::scope_exit([&] {
  23676. svr.stop();
  23677. t.join();
  23678. });
  23679. svr.wait_until_ready();
  23680. Headers upgrade = {{"Upgrade", "websocket"},
  23681. {"Connection", "Upgrade"},
  23682. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23683. {"Sec-WebSocket-Version", "13"}};
  23684. auto get = [&](const char *path) {
  23685. pre_routing_calls = 0;
  23686. return Client("localhost", port).Get(path, upgrade);
  23687. };
  23688. // No WebSocket route, but an HTTP one
  23689. auto res = get("/http");
  23690. ASSERT_TRUE(res);
  23691. EXPECT_EQ(StatusCode::OK_200, res->status);
  23692. EXPECT_EQ("http", res->body);
  23693. EXPECT_EQ(1, pre_routing_calls);
  23694. EXPECT_EQ(1, pre_request_calls);
  23695. // No route at all
  23696. res = get("/none");
  23697. ASSERT_TRUE(res);
  23698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23699. EXPECT_EQ(1, pre_routing_calls);
  23700. // Answered by the pre-routing handler
  23701. res = get("/handled");
  23702. ASSERT_TRUE(res);
  23703. EXPECT_EQ(StatusCode::OK_200, res->status);
  23704. EXPECT_EQ("handled", res->body);
  23705. EXPECT_EQ(1, pre_routing_calls);
  23706. // A WebSocket route
  23707. pre_routing_calls = 0;
  23708. pre_request_calls = 0;
  23709. {
  23710. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23711. "/ws");
  23712. ASSERT_TRUE(client.connect());
  23713. std::string msg;
  23714. ASSERT_TRUE(client.read(msg));
  23715. EXPECT_EQ("ws", msg);
  23716. client.close();
  23717. }
  23718. EXPECT_EQ(1, pre_routing_calls);
  23719. EXPECT_EQ(1, pre_request_calls);
  23720. }
  23721. // An upgrade request answered by a hook leaves its body unread, so that body
  23722. // must not be served as the next request on the connection.
  23723. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23724. Server svr;
  23725. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23726. if (req.path == "/pre-routing") {
  23727. res.set_content("pre-routing", "text/plain");
  23728. return Server::HandlerResponse::Handled;
  23729. }
  23730. return Server::HandlerResponse::Unhandled;
  23731. });
  23732. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23733. if (req.matched_route == "/pre-request") {
  23734. res.set_content("pre-request", "text/plain");
  23735. return Server::HandlerResponse::Handled;
  23736. }
  23737. return Server::HandlerResponse::Unhandled;
  23738. });
  23739. svr.Get("/smuggled", [](const Request &, Response &res) {
  23740. res.set_content("smuggled", "text/plain");
  23741. });
  23742. svr.WebSocket("/pre-request",
  23743. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23744. auto port = svr.bind_to_any_port(HOST);
  23745. std::thread t([&]() { svr.listen_after_bind(); });
  23746. auto se = detail::scope_exit([&] {
  23747. svr.stop();
  23748. t.join();
  23749. });
  23750. svr.wait_until_ready();
  23751. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23752. for (auto path : {"/pre-routing", "/pre-request"}) {
  23753. std::string req = std::string("GET ") + path +
  23754. " HTTP/1.1\r\n"
  23755. "Host: localhost\r\n"
  23756. "Upgrade: websocket\r\n"
  23757. "Connection: Upgrade\r\n"
  23758. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23759. "Sec-WebSocket-Version: 13\r\n"
  23760. "Content-Length: " +
  23761. std::to_string(body.size()) + "\r\n\r\n" + body;
  23762. std::string res;
  23763. ASSERT_TRUE(send_request(5, req, &res, port));
  23764. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23765. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23766. // Only one response, and the body was not served as a request
  23767. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23768. }
  23769. }
  23770. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23771. Server svr;
  23772. std::atomic<int> pre_request_calls{0};
  23773. std::atomic<bool> route_matched{false};
  23774. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23775. pre_request_calls++;
  23776. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23777. if (req.get_header_value("Authorization") != "Bearer token123") {
  23778. res.status = StatusCode::Unauthorized_401;
  23779. res.set_content("Unauthorized", "text/plain");
  23780. return Server::HandlerResponse::Handled;
  23781. }
  23782. return Server::HandlerResponse::Unhandled;
  23783. });
  23784. std::atomic<bool> handler_called{false};
  23785. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23786. handler_called = true;
  23787. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23788. });
  23789. auto port = svr.bind_to_any_port("localhost");
  23790. std::thread t([&]() { svr.listen_after_bind(); });
  23791. svr.wait_until_ready();
  23792. // Without Authorization header - should be rejected before upgrade
  23793. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23794. "/ws/1");
  23795. EXPECT_FALSE(client1.connect());
  23796. EXPECT_FALSE(handler_called);
  23797. EXPECT_EQ(1, pre_request_calls);
  23798. EXPECT_TRUE(route_matched);
  23799. // The rejection is an ordinary HTTP response, not a protocol switch
  23800. {
  23801. Client cli("localhost", port);
  23802. Headers headers = {{"Upgrade", "websocket"},
  23803. {"Connection", "Upgrade"},
  23804. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23805. {"Sec-WebSocket-Version", "13"}};
  23806. auto res = cli.Get("/ws/1", headers);
  23807. ASSERT_TRUE(res);
  23808. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23809. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23810. EXPECT_EQ("Unauthorized", res->body);
  23811. }
  23812. EXPECT_FALSE(handler_called);
  23813. // With Authorization header - should succeed
  23814. Headers headers = {{"Authorization", "Bearer token123"}};
  23815. ws::WebSocketClient client2(
  23816. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23817. ASSERT_TRUE(client2.connect());
  23818. std::string msg;
  23819. ASSERT_TRUE(client2.read(msg));
  23820. EXPECT_EQ("/ws/:id 2", msg);
  23821. EXPECT_TRUE(handler_called);
  23822. client2.close();
  23823. svr.stop();
  23824. t.join();
  23825. }
  23826. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23827. Server svr;
  23828. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23829. // A read timeout is how a handler gets control back. Without it, a handler
  23830. // parked in read() can never write on the connection it is reading.
  23831. ws.set_read_timeout(std::chrono::milliseconds(100));
  23832. std::string msg;
  23833. while (ws.is_open()) {
  23834. auto r = ws.read(msg);
  23835. if (r == httplib::ws::Timeout) {
  23836. ws.send("tick");
  23837. continue;
  23838. }
  23839. if (r == httplib::ws::Fail) { break; }
  23840. ws.send(msg);
  23841. }
  23842. });
  23843. auto port = svr.bind_to_any_port("localhost");
  23844. std::thread t([&]() { svr.listen_after_bind(); });
  23845. svr.wait_until_ready();
  23846. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23847. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23848. ASSERT_TRUE(client.connect());
  23849. // The client sends nothing, so anything it receives came out of the
  23850. // handler's timeout path.
  23851. std::string msg;
  23852. ASSERT_EQ(client.read(msg), ws::Text);
  23853. EXPECT_EQ("tick", msg);
  23854. client.close();
  23855. svr.stop();
  23856. t.join();
  23857. }
  23858. // Stream::read may return fewer bytes than asked for. This is that contract at
  23859. // its worst -- one byte per call -- which is what a frame header straddling a
  23860. // read buffer's boundary looks like to the frame parser.
  23861. class WsByteAtATimeStream : public Stream {
  23862. public:
  23863. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23864. bool is_readable() const override { return true; }
  23865. bool wait_readable() const override { return true; }
  23866. bool wait_writable() const override { return true; }
  23867. ssize_t read(char *ptr, size_t size) override {
  23868. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23869. *ptr = data_[pos_++];
  23870. return 1;
  23871. }
  23872. ssize_t write(const char *, size_t size) override {
  23873. return static_cast<ssize_t>(size);
  23874. }
  23875. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23876. ip = "127.0.0.1";
  23877. port = 0;
  23878. }
  23879. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23880. ip = "127.0.0.1";
  23881. port = 0;
  23882. }
  23883. socket_t socket() const override { return INVALID_SOCKET; }
  23884. time_t duration() const override { return 0; }
  23885. private:
  23886. std::string data_;
  23887. size_t pos_ = 0;
  23888. };
  23889. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23890. // The payload uses the 16-bit extended length, so the header, the length
  23891. // and the mask key are all multi-byte fields here. Each used to be read
  23892. // with a single read() call, which fails as soon as one is split. The
  23893. // payload is also a little over one read chunk, so it is read in two.
  23894. std::string body;
  23895. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23896. body += static_cast<char>(i % 251);
  23897. }
  23898. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23899. std::string frame;
  23900. frame += static_cast<char>(0x81); // FIN + Text
  23901. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23902. frame += static_cast<char>(body.size() >> 8);
  23903. frame += static_cast<char>(body.size() & 0xff);
  23904. for (size_t i = 0; i < 4; i++) {
  23905. frame += static_cast<char>(mask[i]);
  23906. }
  23907. for (size_t i = 0; i < body.size(); i++) {
  23908. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23909. }
  23910. WsByteAtATimeStream strm(frame);
  23911. ws::Opcode opcode;
  23912. std::string payload;
  23913. bool fin = false;
  23914. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23915. /*expect_masked=*/true, body.size()),
  23916. ws::impl::FrameRead::Ok);
  23917. EXPECT_TRUE(fin);
  23918. EXPECT_EQ(opcode, ws::Opcode::Text);
  23919. EXPECT_EQ(payload, body);
  23920. }
  23921. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23922. std::string body(2000, 'x');
  23923. std::string frame;
  23924. frame += static_cast<char>(0x82); // FIN + Binary
  23925. frame += static_cast<char>(126); // 16-bit length follows
  23926. frame += static_cast<char>(body.size() >> 8);
  23927. frame += static_cast<char>(body.size() & 0xff);
  23928. frame += body;
  23929. detail::BufferStream strm;
  23930. strm.write(frame.data(), frame.size());
  23931. ws::Opcode opcode;
  23932. std::string payload;
  23933. bool fin;
  23934. EXPECT_EQ(
  23935. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23936. ws::impl::FrameRead::Ok);
  23937. EXPECT_EQ(body, payload);
  23938. }
  23939. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23940. // The header announces the largest payload allowed, and only 3 bytes of it
  23941. // ever arrive.
  23942. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23943. std::string frame;
  23944. frame += static_cast<char>(0x82); // FIN + Binary
  23945. frame += static_cast<char>(127); // 64-bit length follows
  23946. for (int shift = 56; shift >= 0; shift -= 8) {
  23947. frame += static_cast<char>((len >> shift) & 0xff);
  23948. }
  23949. frame += "abc";
  23950. detail::BufferStream strm;
  23951. strm.write(frame.data(), frame.size());
  23952. ws::Opcode opcode;
  23953. std::string payload;
  23954. bool fin;
  23955. EXPECT_EQ(
  23956. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23957. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23958. ws::impl::FrameRead::Fail);
  23959. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23960. }
  23961. TEST(WebSocketTest, QueryStringInHandshake) {
  23962. Server svr;
  23963. std::mutex mtx;
  23964. std::string received_target;
  23965. std::string received_token;
  23966. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23967. {
  23968. std::lock_guard<std::mutex> lock(mtx);
  23969. received_target = req.target;
  23970. if (req.has_param("token")) {
  23971. received_token = req.get_param_value("token");
  23972. }
  23973. }
  23974. std::string msg;
  23975. while (ws.read(msg)) {
  23976. ws.send(msg);
  23977. }
  23978. });
  23979. auto port = svr.bind_to_any_port("localhost");
  23980. std::thread t([&]() { svr.listen_after_bind(); });
  23981. svr.wait_until_ready();
  23982. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23983. "/ws?token=ABC&session=123");
  23984. ASSERT_TRUE(client.connect());
  23985. // Round-trip ensures the handler has run and captured the request.
  23986. ASSERT_TRUE(client.send("hello"));
  23987. std::string msg;
  23988. ASSERT_TRUE(client.read(msg));
  23989. EXPECT_EQ("hello", msg);
  23990. client.close();
  23991. {
  23992. std::lock_guard<std::mutex> lock(mtx);
  23993. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23994. EXPECT_EQ("ABC", received_token);
  23995. }
  23996. svr.stop();
  23997. t.join();
  23998. }
  23999. // Run a handshake against a throwaway server and hand the request the server
  24000. // received back to the caller, so tests can assert on the headers the client
  24001. // actually put on the wire.
  24002. static void capture_websocket_handshake_request(
  24003. const Headers &client_headers,
  24004. std::function<void(const Request &, int port)> verify) {
  24005. Server svr;
  24006. std::mutex mtx;
  24007. Request received;
  24008. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24009. {
  24010. std::lock_guard<std::mutex> lock(mtx);
  24011. received = req;
  24012. }
  24013. std::string msg;
  24014. while (ws.read(msg)) {
  24015. ws.send(msg);
  24016. }
  24017. });
  24018. auto port = svr.bind_to_any_port("localhost");
  24019. std::thread t([&]() { svr.listen_after_bind(); });
  24020. auto se = detail::scope_exit([&] {
  24021. svr.stop();
  24022. t.join();
  24023. });
  24024. svr.wait_until_ready();
  24025. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24026. client_headers);
  24027. ASSERT_TRUE(client.connect());
  24028. ASSERT_TRUE(client.send("hello"));
  24029. std::string msg;
  24030. ASSERT_TRUE(client.read(msg));
  24031. client.close();
  24032. {
  24033. std::lock_guard<std::mutex> lock(mtx);
  24034. verify(received, port);
  24035. }
  24036. }
  24037. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24038. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24039. // Non-default port must be present in the Host header. Default ports
  24040. // (80/443) are omitted; that logic is covered by
  24041. // MakeHostAndPortStringTest.
  24042. EXPECT_EQ("localhost:" + std::to_string(port),
  24043. req.get_header_value("Host"));
  24044. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24045. req.get_header_value("User-Agent"));
  24046. EXPECT_FALSE(req.has_header("Accept"));
  24047. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24048. EXPECT_FALSE(req.has_header("Content-Length"));
  24049. });
  24050. }
  24051. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24052. capture_websocket_handshake_request(
  24053. {{"Host", "example.com"},
  24054. {"User-Agent", "custom-agent"},
  24055. {"X-Custom", "value"}},
  24056. [](const Request &req, int) {
  24057. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24058. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24059. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24060. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24061. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24062. });
  24063. }
  24064. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24065. capture_websocket_handshake_request(
  24066. {{"Upgrade", "bogus"},
  24067. {"Connection", "close"},
  24068. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24069. {"Sec-WebSocket-Version", "8"}},
  24070. [](const Request &req, int) {
  24071. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24072. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24073. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24074. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24075. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24076. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24077. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24078. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24079. req.get_header_value("Sec-WebSocket-Key"));
  24080. });
  24081. }
  24082. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24083. // A header the client refuses to send must abort the handshake before any
  24084. // part of it reaches the wire; a lone request line would otherwise sit in
  24085. // the peer's buffer as a truncated request.
  24086. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24087. ASSERT_NE(INVALID_SOCKET, srv);
  24088. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24089. sockaddr_in addr{};
  24090. addr.sin_family = AF_INET;
  24091. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24092. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24093. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24094. ASSERT_EQ(0, ::listen(srv, 1));
  24095. sockaddr_in bound{};
  24096. socklen_t bound_len = sizeof(bound);
  24097. ASSERT_EQ(
  24098. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24099. auto port = ntohs(bound.sin_port);
  24100. ssize_t received = -1;
  24101. std::thread t([&] {
  24102. // Bound every blocking call so a regression fails the test with a bad
  24103. // value instead of hanging the suite.
  24104. fd_set rfds;
  24105. FD_ZERO(&rfds);
  24106. FD_SET(srv, &rfds);
  24107. timeval tv{5, 0};
  24108. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24109. 0) {
  24110. return;
  24111. }
  24112. sockaddr_in cli_addr{};
  24113. socklen_t cli_len = sizeof(cli_addr);
  24114. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24115. if (cli == INVALID_SOCKET) { return; }
  24116. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24117. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24118. char buf[4096];
  24119. received = ::recv(cli, buf, sizeof(buf), 0);
  24120. });
  24121. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24122. // connect() has already shut the socket down by the time it returns false,
  24123. // so the peer sees EOF without waiting for the client to be destroyed.
  24124. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24125. {{"X-Bad", "a\r\nInjected: 1"}});
  24126. EXPECT_FALSE(client.connect());
  24127. t.join();
  24128. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24129. EXPECT_EQ(0, received);
  24130. }
  24131. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24132. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24133. // contains "upgrade" as a substring is a different token and must not
  24134. // start a WebSocket handshake.
  24135. auto make_request = [](const std::vector<std::string> &connection_values) {
  24136. Request req;
  24137. req.method = "GET";
  24138. req.headers.emplace("Upgrade", "websocket");
  24139. for (const auto &value : connection_values) {
  24140. req.headers.emplace("Connection", value);
  24141. }
  24142. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24143. req.headers.emplace("Sec-WebSocket-Version", "13");
  24144. return req;
  24145. };
  24146. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24147. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24148. EXPECT_TRUE(
  24149. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24150. EXPECT_TRUE(
  24151. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24152. EXPECT_TRUE(
  24153. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24154. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24155. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24156. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24157. EXPECT_FALSE(
  24158. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24159. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24160. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24161. }
  24162. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24163. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24164. // asks recipients to match each protocol-name case-insensitively, and RFC
  24165. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24166. // client naming websocket alongside another protocol, or on a second field
  24167. // line, is offering websocket; a value that merely contains "websocket" as a
  24168. // substring is a different protocol name and is not.
  24169. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24170. Request req;
  24171. req.method = "GET";
  24172. for (const auto &value : upgrade_values) {
  24173. req.headers.emplace("Upgrade", value);
  24174. }
  24175. req.headers.emplace("Connection", "Upgrade");
  24176. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24177. req.headers.emplace("Sec-WebSocket-Version", "13");
  24178. return req;
  24179. };
  24180. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24181. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24182. EXPECT_TRUE(
  24183. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24184. EXPECT_TRUE(
  24185. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24186. EXPECT_TRUE(
  24187. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24188. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24189. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24190. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24191. EXPECT_FALSE(
  24192. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24193. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24194. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24195. }
  24196. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24197. Server svr;
  24198. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24199. auto port = svr.bind_to_any_port("localhost");
  24200. std::thread t([&]() { svr.listen_after_bind(); });
  24201. auto se = detail::scope_exit([&] {
  24202. svr.stop();
  24203. t.join();
  24204. });
  24205. svr.wait_until_ready();
  24206. Headers headers = {{"Upgrade", "websocket"},
  24207. {"Connection", "notupgrade"},
  24208. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24209. {"Sec-WebSocket-Version", "13"}};
  24210. Client cli("localhost", port);
  24211. auto res = cli.Get("/ws", headers);
  24212. // The route exists only as a WebSocket route, so a request that fails the
  24213. // handshake check falls through to ordinary routing.
  24214. ASSERT_TRUE(res);
  24215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24216. }
  24217. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24218. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24219. // Connection value is the only thing left for the client to reject.
  24220. Server svr;
  24221. svr.Get("/ws", [](const Request &req, Response &res) {
  24222. res.status = StatusCode::SwitchingProtocol_101;
  24223. res.set_header("Upgrade", "websocket");
  24224. res.set_header("Connection", "notupgrade");
  24225. res.set_header("Sec-WebSocket-Accept",
  24226. detail::websocket_accept_key(
  24227. req.get_header_value("Sec-WebSocket-Key")));
  24228. });
  24229. auto port = svr.bind_to_any_port("localhost");
  24230. std::thread t([&]() { svr.listen_after_bind(); });
  24231. auto se = detail::scope_exit([&] {
  24232. svr.stop();
  24233. t.join();
  24234. });
  24235. svr.wait_until_ready();
  24236. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24237. auto res = client.connect();
  24238. EXPECT_FALSE(res);
  24239. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24240. EXPECT_FALSE(client.is_open());
  24241. }
  24242. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24243. Server svr;
  24244. svr.Get("/ws", [](const Request &req, Response &res) {
  24245. res.status = StatusCode::SwitchingProtocol_101;
  24246. res.set_header("Upgrade", "websocket");
  24247. res.set_header("Connection", "Upgrade");
  24248. res.set_header("Sec-WebSocket-Accept",
  24249. detail::websocket_accept_key(
  24250. req.get_header_value("Sec-WebSocket-Key")));
  24251. res.set_header("Sec-WebSocket-Protocol", "admin");
  24252. });
  24253. auto port = svr.bind_to_any_port("localhost");
  24254. std::thread t([&]() { svr.listen_after_bind(); });
  24255. auto se = detail::scope_exit([&] {
  24256. svr.stop();
  24257. t.join();
  24258. });
  24259. svr.wait_until_ready();
  24260. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24261. // Server selects a subprotocol the client never offered
  24262. {
  24263. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24264. ws::WebSocketClient client(url, headers);
  24265. auto res = client.connect();
  24266. EXPECT_FALSE(res);
  24267. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24268. EXPECT_FALSE(client.is_open());
  24269. EXPECT_TRUE(client.subprotocol().empty());
  24270. }
  24271. // Client offered none but the server named one anyway
  24272. {
  24273. ws::WebSocketClient client(url);
  24274. auto res = client.connect();
  24275. EXPECT_FALSE(res);
  24276. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24277. EXPECT_FALSE(client.is_open());
  24278. EXPECT_TRUE(client.subprotocol().empty());
  24279. }
  24280. }
  24281. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24282. // The socket path doubles as the URL host, so it must not contain '/'.
  24283. const char *shard = getenv("GTEST_SHARD_INDEX");
  24284. const std::string sock_path =
  24285. shard ? std::string("httplib-ws-") + shard + ".sock"
  24286. : std::string("httplib-ws.sock");
  24287. std::remove(sock_path.c_str());
  24288. Server svr;
  24289. std::mutex mtx;
  24290. std::string received_host;
  24291. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24292. {
  24293. std::lock_guard<std::mutex> lock(mtx);
  24294. received_host = req.get_header_value("Host");
  24295. }
  24296. std::string msg;
  24297. while (ws.read(msg)) {
  24298. ws.send(msg);
  24299. }
  24300. });
  24301. svr.set_address_family(AF_UNIX);
  24302. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24303. auto se = detail::scope_exit([&] {
  24304. svr.stop();
  24305. t.join();
  24306. std::remove(sock_path.c_str());
  24307. });
  24308. svr.wait_until_ready();
  24309. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24310. client.set_address_family(AF_UNIX);
  24311. ASSERT_TRUE(client.connect());
  24312. ASSERT_TRUE(client.send("hello"));
  24313. std::string msg;
  24314. ASSERT_TRUE(client.read(msg));
  24315. client.close();
  24316. {
  24317. std::lock_guard<std::mutex> lock(mtx);
  24318. // There is no host:port for a Unix socket, so the same "localhost"
  24319. // placeholder the HTTP client uses is expected.
  24320. EXPECT_EQ("localhost", received_host);
  24321. }
  24322. }
  24323. // Two threads must never parse WebSocket frames from the same stream.
  24324. // close() used to read the peer's Close reply with its own frame read, so it
  24325. // raced a reader thread that was in the middle of a payload: the payload loop
  24326. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24327. // so bytes taken by close() were replaced with bytes from further along the
  24328. // stream. The message kept its length and silently changed content.
  24329. //
  24330. // The raw peer below sends a frame header plus part of the payload, waits for
  24331. // the handler to call close(), and only then sends the rest. Whichever thread
  24332. // would win the race for those bytes, the message must arrive intact, because
  24333. // close() must not touch the stream while read() owns it.
  24334. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24335. #ifndef _WIN32
  24336. signal(SIGPIPE, SIG_IGN);
  24337. #endif
  24338. const size_t payload_len = 120; // fits the 7-bit length field
  24339. const size_t prefix_len = 8;
  24340. const int attempts = 8;
  24341. std::string expected(payload_len, '\0');
  24342. for (size_t i = 0; i < payload_len; i++) {
  24343. expected[i] = static_cast<char>('a' + i % 26);
  24344. }
  24345. std::atomic<bool> peer_stalled{false};
  24346. std::atomic<bool> handler_done{false};
  24347. std::mutex received_mutex;
  24348. std::vector<std::string> received;
  24349. // Bound every wait, so a regression fails the test instead of hanging the
  24350. // suite.
  24351. auto wait_for = [](const std::atomic<bool> &flag) {
  24352. for (int i = 0; i < 500 && !flag; i++) {
  24353. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24354. }
  24355. };
  24356. Server svr;
  24357. svr.set_websocket_ping_interval(0);
  24358. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24359. std::thread reader([&]() {
  24360. std::string msg;
  24361. while (ws.read(msg)) {
  24362. std::lock_guard<std::mutex> guard(received_mutex);
  24363. received.push_back(msg);
  24364. }
  24365. });
  24366. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24367. // inside read_websocket_frame() when close() runs.
  24368. wait_for(peer_stalled);
  24369. ws.close();
  24370. reader.join();
  24371. handler_done = true;
  24372. });
  24373. auto port = svr.bind_to_any_port("127.0.0.1");
  24374. std::thread t([&]() { svr.listen_after_bind(); });
  24375. auto se = detail::scope_exit([&] {
  24376. svr.stop();
  24377. t.join();
  24378. });
  24379. svr.wait_until_ready();
  24380. auto send_bytes = [](socket_t s, const std::string &data) {
  24381. #ifdef _WIN32
  24382. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24383. #else
  24384. auto n = ::send(s, data.data(), data.size(), 0);
  24385. #endif
  24386. return n == static_cast<decltype(n)>(data.size());
  24387. };
  24388. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24389. // Every length used here fits the 7-bit length field.
  24390. auto masked_header = [](uint8_t first_byte, size_t len) {
  24391. std::string h;
  24392. h += static_cast<char>(first_byte);
  24393. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24394. h.append(4, '\0'); // mask key
  24395. return h;
  24396. };
  24397. for (int attempt = 0; attempt < attempts; attempt++) {
  24398. peer_stalled = false;
  24399. handler_done = false;
  24400. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24401. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24402. auto se_sock = detail::scope_exit([&] {
  24403. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24404. });
  24405. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24406. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24407. sockaddr_in addr{};
  24408. addr.sin_family = AF_INET;
  24409. addr.sin_port = htons(static_cast<uint16_t>(port));
  24410. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24411. ASSERT_EQ(
  24412. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24413. << "attempt " << attempt;
  24414. ASSERT_TRUE(send_bytes(sock,
  24415. "GET /ws HTTP/1.1\r\n"
  24416. "Host: 127.0.0.1\r\n"
  24417. "Upgrade: websocket\r\n"
  24418. "Connection: Upgrade\r\n"
  24419. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24420. "Sec-WebSocket-Version: 13\r\n"
  24421. "\r\n"))
  24422. << "attempt " << attempt;
  24423. std::string response;
  24424. while (response.find("\r\n\r\n") == std::string::npos) {
  24425. char buf[512];
  24426. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24427. if (n <= 0) { break; }
  24428. response.append(buf, static_cast<size_t>(n));
  24429. }
  24430. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24431. << "attempt " << attempt;
  24432. // Send the header of a Binary message but only the first prefix_len bytes
  24433. // of its payload, leaving the reader thread stalled inside the payload.
  24434. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24435. expected.substr(0, prefix_len)))
  24436. << "attempt " << attempt;
  24437. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24438. peer_stalled = true;
  24439. // Let close() send its Close frame and park in its own read before the
  24440. // rest of the payload arrives, so both threads are waiting for it.
  24441. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24442. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24443. close_frame += static_cast<char>(0x03); // status 1000
  24444. close_frame += static_cast<char>(0xE8);
  24445. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24446. << "attempt " << attempt;
  24447. // Closing the peer releases the reader thread even on the buggy path,
  24448. // where it waits for bytes another thread already consumed.
  24449. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24450. detail::close_socket(sock);
  24451. sock = INVALID_SOCKET;
  24452. wait_for(handler_done);
  24453. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24454. }
  24455. std::lock_guard<std::mutex> guard(received_mutex);
  24456. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24457. << "a message in flight when close() ran was dropped";
  24458. for (size_t i = 0; i < received.size(); i++) {
  24459. EXPECT_EQ(expected, received[i]) << "message " << i;
  24460. }
  24461. }
  24462. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24463. // returning the socket, or INVALID_SOCKET.
  24464. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24465. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24466. if (sock == INVALID_SOCKET) { return sock; }
  24467. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24468. sockaddr_in addr{};
  24469. addr.sin_family = AF_INET;
  24470. addr.sin_port = htons(static_cast<uint16_t>(port));
  24471. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24472. std::string req = "GET " + path +
  24473. " HTTP/1.1\r\n"
  24474. "Host: 127.0.0.1\r\n"
  24475. "Upgrade: websocket\r\n"
  24476. "Connection: Upgrade\r\n"
  24477. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24478. "Sec-WebSocket-Version: 13\r\n"
  24479. "\r\n";
  24480. std::string res;
  24481. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24482. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24483. static_cast<ssize_t>(req.size())) {
  24484. char c;
  24485. while (res.find("\r\n\r\n") == std::string::npos &&
  24486. ::recv(sock, &c, 1, 0) == 1) {
  24487. res += c;
  24488. }
  24489. }
  24490. if (res.find(" 101 ") == std::string::npos) {
  24491. detail::close_socket(sock);
  24492. return INVALID_SOCKET;
  24493. }
  24494. return sock;
  24495. }
  24496. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24497. // The payload must fit the 7-bit length field.
  24498. static std::string masked_frame(uint8_t first_byte,
  24499. const std::string &payload) {
  24500. std::string f;
  24501. f += static_cast<char>(first_byte);
  24502. f += static_cast<char>(0x80 | payload.size());
  24503. f.append(4, '\0');
  24504. return f + payload;
  24505. }
  24506. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24507. std::atomic<bool> done{false};
  24508. std::string received;
  24509. Server svr;
  24510. svr.set_websocket_ping_interval(0);
  24511. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24512. std::string msg;
  24513. if (ws.read(msg) == ws::Binary) { received = msg; }
  24514. done = true;
  24515. });
  24516. auto port = svr.bind_to_any_port("127.0.0.1");
  24517. std::thread t([&]() { svr.listen_after_bind(); });
  24518. auto se = detail::scope_exit([&] {
  24519. svr.stop();
  24520. t.join();
  24521. });
  24522. svr.wait_until_ready();
  24523. auto sock = connect_raw_websocket(port, "/ws");
  24524. ASSERT_NE(INVALID_SOCKET, sock);
  24525. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24526. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24527. masked_frame(0x89, "p") + // FIN + Ping
  24528. masked_frame(0x80, "lo"); // FIN + Continuation
  24529. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24530. for (int i = 0; i < 500 && !done; i++) {
  24531. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24532. }
  24533. ASSERT_TRUE(done);
  24534. EXPECT_EQ("Hello", received);
  24535. // The Ping between the fragments is answered with a Pong.
  24536. char pong[3];
  24537. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24538. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24539. }
  24540. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24541. Server svr;
  24542. svr.set_websocket_ping_interval(-1);
  24543. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24544. std::string msg;
  24545. while (ws.read(msg)) {}
  24546. });
  24547. auto port = svr.bind_to_any_port("127.0.0.1");
  24548. std::thread t([&]() { svr.listen_after_bind(); });
  24549. auto se = detail::scope_exit([&] {
  24550. svr.stop();
  24551. t.join();
  24552. });
  24553. svr.wait_until_ready();
  24554. auto sock = connect_raw_websocket(port, "/ws");
  24555. ASSERT_NE(INVALID_SOCKET, sock);
  24556. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24557. // Nothing comes while the client stays quiet.
  24558. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24559. char c;
  24560. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24561. }
  24562. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24563. // and that has to end a read() already waiting on the peer, on every platform.
  24564. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24565. // The peer sends no pings, and its handler never calls read(), which is
  24566. // where pongs are written.
  24567. std::mutex mutex;
  24568. std::condition_variable cv;
  24569. auto release = false;
  24570. svr.set_websocket_ping_interval(0);
  24571. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24572. std::unique_lock<std::mutex> lock(mutex);
  24573. cv.wait(lock, [&] { return release; });
  24574. });
  24575. auto port = svr.bind_to_any_port(HOST);
  24576. std::thread t([&]() { svr.listen_after_bind(); });
  24577. auto se = detail::scope_exit([&] {
  24578. {
  24579. std::lock_guard<std::mutex> lock(mutex);
  24580. release = true;
  24581. }
  24582. cv.notify_all();
  24583. svr.stop();
  24584. t.join();
  24585. });
  24586. svr.wait_until_ready();
  24587. ws::WebSocketClient client(std::string(scheme) +
  24588. "://localhost:" + std::to_string(port) + "/ws");
  24589. #ifdef CPPHTTPLIB_SSL_ENABLED
  24590. client.enable_server_certificate_verification(false);
  24591. #endif
  24592. // A ping a second, given up on after two go unanswered: about 3s
  24593. client.set_websocket_ping_interval(1);
  24594. client.set_websocket_max_missed_pongs(2);
  24595. // Well past that, so that a read the timeout ends instead stands out
  24596. client.set_read_timeout(10);
  24597. ASSERT_TRUE(client.connect());
  24598. auto start = std::chrono::steady_clock::now();
  24599. std::string msg;
  24600. EXPECT_EQ(ws::Fail, client.read(msg));
  24601. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24602. std::chrono::steady_clock::now() - start)
  24603. .count(),
  24604. 6000);
  24605. EXPECT_FALSE(client.is_open());
  24606. }
  24607. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24608. Server svr;
  24609. check_pong_timeout_ends_read(svr, "ws");
  24610. }
  24611. #ifdef CPPHTTPLIB_SSL_ENABLED
  24612. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24613. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24614. ASSERT_TRUE(svr.is_valid());
  24615. check_pong_timeout_ends_read(svr, "wss");
  24616. }
  24617. #endif
  24618. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24619. Server svr;
  24620. svr.set_websocket_ping_interval(0);
  24621. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24622. std::string msg;
  24623. while (ws.read(msg)) {}
  24624. });
  24625. auto port = svr.bind_to_any_port("127.0.0.1");
  24626. std::thread t([&]() { svr.listen_after_bind(); });
  24627. auto se = detail::scope_exit([&] {
  24628. svr.stop();
  24629. t.join();
  24630. });
  24631. svr.wait_until_ready();
  24632. // Each Close payload and the reply it should get: an echo when valid, 1002
  24633. // otherwise.
  24634. std::vector<std::pair<std::string, std::string>> cases = {
  24635. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24636. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24637. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24638. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24639. };
  24640. // Also between the fragments of a message.
  24641. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24642. for (const auto &c : cases) {
  24643. auto sock = connect_raw_websocket(port, "/ws");
  24644. ASSERT_NE(INVALID_SOCKET, sock);
  24645. auto frames = prefix + masked_frame(0x88, c.first);
  24646. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24647. std::string reply;
  24648. char buf[256];
  24649. while (reply.size() < 2 + c.second.size()) {
  24650. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24651. if (n <= 0) { break; }
  24652. reply.append(buf, static_cast<size_t>(n));
  24653. }
  24654. detail::close_socket(sock);
  24655. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24656. c.second,
  24657. reply);
  24658. }
  24659. }
  24660. }
  24661. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24662. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24663. protected:
  24664. void SetUp() override {
  24665. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24666. SERVER_PRIVATE_KEY_FILE);
  24667. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24668. std::string msg;
  24669. ws::ReadResult ret;
  24670. while ((ret = ws.read(msg))) {
  24671. if (ret == ws::Binary) {
  24672. ws.send(msg.data(), msg.size());
  24673. } else {
  24674. ws.send(msg);
  24675. }
  24676. }
  24677. });
  24678. port_ = server_->bind_to_any_port(HOST);
  24679. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24680. server_->wait_until_ready();
  24681. }
  24682. void TearDown() override {
  24683. server_->stop();
  24684. if (server_thread_.joinable()) { server_thread_.join(); }
  24685. }
  24686. std::unique_ptr<SSLServer> server_;
  24687. std::thread server_thread_;
  24688. int port_ = 0;
  24689. };
  24690. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24691. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24692. {
  24693. ws::WebSocketClient client(url);
  24694. client.enable_server_certificate_verification(false);
  24695. auto calls = 0;
  24696. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24697. calls++;
  24698. return false;
  24699. });
  24700. EXPECT_FALSE(client.connect());
  24701. EXPECT_GT(calls, 0);
  24702. }
  24703. {
  24704. ws::WebSocketClient client(url);
  24705. client.enable_server_certificate_verification(false);
  24706. client.set_session_verifier([](tls::session_t) {
  24707. return SSLVerifierResponse::CertificateRejected;
  24708. });
  24709. EXPECT_FALSE(client.connect());
  24710. }
  24711. {
  24712. ws::WebSocketClient client(url);
  24713. client.enable_server_certificate_verification(false);
  24714. client.set_session_verifier([](tls::session_t) {
  24715. return SSLVerifierResponse::CertificateAccepted;
  24716. });
  24717. EXPECT_TRUE(client.connect());
  24718. }
  24719. }
  24720. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24721. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24722. "/ws-echo");
  24723. client.enable_server_certificate_verification(false);
  24724. ASSERT_TRUE(client.connect());
  24725. ASSERT_TRUE(client.is_open());
  24726. ASSERT_TRUE(client.send("Hello WSS"));
  24727. std::string msg;
  24728. EXPECT_EQ(ws::Text, client.read(msg));
  24729. EXPECT_EQ("Hello WSS", msg);
  24730. client.close();
  24731. }
  24732. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24733. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24734. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24735. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24736. // client (without calling close() first) is the only path that runs
  24737. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24738. // bug exactly.
  24739. //
  24740. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24741. // when linked against an instrumented libssl; run under Valgrind to catch it
  24742. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24743. // suite (the freed session otherwise stalls on the close handshake) — this test
  24744. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24745. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24746. {
  24747. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24748. "/ws-echo");
  24749. client.enable_server_certificate_verification(false);
  24750. client.set_read_timeout(2, 0);
  24751. client.set_write_timeout(2, 0);
  24752. ASSERT_TRUE(client.connect());
  24753. ASSERT_TRUE(client.is_open());
  24754. ASSERT_TRUE(client.send("still open"));
  24755. // Intentionally do NOT call client.close(): leaving scope runs
  24756. // shutdown_and_close() with the WebSocket still open, which must send the
  24757. // close frame while the TLS session is still alive.
  24758. }
  24759. }
  24760. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24761. // shutdown_and_close() at the start of connect(), reproducing the same
  24762. // use-after-free within the test body rather than at scope exit. The second
  24763. // connect must succeed and echo, proving the close handshake ran over a live
  24764. // session. See the note above about memory-tool requirements.
  24765. TEST_F(WebSocketSSLIntegrationTest,
  24766. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24767. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24768. "/ws-echo");
  24769. client.enable_server_certificate_verification(false);
  24770. client.set_read_timeout(2, 0);
  24771. client.set_write_timeout(2, 0);
  24772. ASSERT_TRUE(client.connect());
  24773. ASSERT_TRUE(client.is_open());
  24774. ASSERT_TRUE(client.send("still open"));
  24775. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24776. // the still-open connection, which must not touch a freed TLS session.
  24777. ASSERT_TRUE(client.connect());
  24778. ASSERT_TRUE(client.is_open());
  24779. ASSERT_TRUE(client.send("after reconnect"));
  24780. std::string msg;
  24781. EXPECT_EQ(ws::Text, client.read(msg));
  24782. EXPECT_EQ("after reconnect", msg);
  24783. client.close();
  24784. }
  24785. #endif
  24786. #ifdef CPPHTTPLIB_SSL_ENABLED
  24787. class WebSocketSSLCATest : public ::testing::Test {
  24788. protected:
  24789. void SetUp() override {
  24790. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24791. SERVER_PRIVATE_KEY_FILE);
  24792. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24793. std::string msg;
  24794. while (ws.read(msg)) {
  24795. ws.send(msg);
  24796. }
  24797. });
  24798. port_ = server_->bind_to_any_port("127.0.0.1");
  24799. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24800. server_->wait_until_ready();
  24801. }
  24802. void TearDown() override {
  24803. server_->stop();
  24804. if (server_thread_.joinable()) { server_thread_.join(); }
  24805. }
  24806. std::string url() const {
  24807. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24808. }
  24809. std::unique_ptr<SSLServer> server_;
  24810. std::thread server_thread_;
  24811. int port_ = 0;
  24812. };
  24813. // A custom CA loaded as PEM verifies the server with full certificate
  24814. // verification enabled
  24815. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24816. ws::WebSocketClient client(url());
  24817. std::string cert;
  24818. read_file(SERVER_CERT2_FILE, cert);
  24819. client.load_ca_cert_store(cert.c_str(), cert.size());
  24820. ASSERT_TRUE(client.connect());
  24821. ASSERT_TRUE(client.send("hello"));
  24822. std::string msg;
  24823. EXPECT_EQ(ws::Text, client.read(msg));
  24824. EXPECT_EQ("hello", msg);
  24825. client.close();
  24826. }
  24827. // A custom CA that does not cover the server must fail verification (the
  24828. // custom CA is exclusive; system certs are not loaded alongside it)
  24829. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24830. ws::WebSocketClient client(url());
  24831. std::string cert;
  24832. read_file(CLIENT_CA_CERT_FILE, cert);
  24833. client.load_ca_cert_store(cert.c_str(), cert.size());
  24834. auto res = client.connect();
  24835. ASSERT_FALSE(res);
  24836. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24837. EXPECT_EQ(-1, res.status());
  24838. EXPECT_NE(0u, res.ssl_backend_error());
  24839. }
  24840. // The same CA as a file path rather than PEM in memory
  24841. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24842. ws::WebSocketClient client(url());
  24843. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24844. ASSERT_TRUE(client.connect());
  24845. ASSERT_TRUE(client.send("hello"));
  24846. std::string msg;
  24847. EXPECT_EQ(ws::Text, client.read(msg));
  24848. EXPECT_EQ("hello", msg);
  24849. client.close();
  24850. }
  24851. // ...and a CA file that does not cover the server still fails, so it is the
  24852. // path above that decides the outcome
  24853. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24854. ws::WebSocketClient client(url());
  24855. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24856. ASSERT_FALSE(client.connect());
  24857. }
  24858. // Regression test: reconnecting with a native custom CA store used to reuse
  24859. // a store handle the previous TLS context had already freed (use-after-free
  24860. // under the OpenSSL backend). The context now lives as long as the client.
  24861. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24862. ws::WebSocketClient client(url());
  24863. std::string cert;
  24864. read_file(SERVER_CERT2_FILE, cert);
  24865. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24866. ASSERT_TRUE(client.connect());
  24867. client.close();
  24868. ASSERT_TRUE(client.connect());
  24869. ASSERT_TRUE(client.send("again"));
  24870. std::string msg;
  24871. EXPECT_EQ(ws::Text, client.read(msg));
  24872. EXPECT_EQ("again", msg);
  24873. client.close();
  24874. }
  24875. // Regression test: a certificate with a trusted chain but no identity match
  24876. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24877. // verification entirely for IP hosts, so this connection succeeded there.
  24878. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24879. // chain verification while the identity check must still fail.
  24880. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24881. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24882. ASSERT_TRUE(svr.is_valid());
  24883. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24884. std::string msg;
  24885. while (ws.read(msg)) {
  24886. ws.send(msg);
  24887. }
  24888. });
  24889. auto port = svr.bind_to_any_port("127.0.0.1");
  24890. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24891. auto se = detail::scope_exit([&] {
  24892. svr.stop();
  24893. t.join();
  24894. });
  24895. svr.wait_until_ready();
  24896. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24897. "/echo");
  24898. std::string cert;
  24899. read_file(SERVER_CERT_FILE, cert);
  24900. client.load_ca_cert_store(cert.c_str(), cert.size());
  24901. ASSERT_FALSE(client.connect());
  24902. }
  24903. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24904. // SNI, so nothing binds the host name to the TLS session. These bind the
  24905. // server to "localhost" instead, the only shape that exercises the SNI and
  24906. // hostname-verification path with certificate verification left enabled.
  24907. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24908. protected:
  24909. void Start(const char *cert_file) {
  24910. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24911. SERVER_PRIVATE_KEY_FILE);
  24912. ASSERT_TRUE(server_->is_valid());
  24913. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24914. std::string msg;
  24915. while (ws.read(msg)) {
  24916. ws.send(msg);
  24917. }
  24918. });
  24919. port_ = server_->bind_to_any_port("localhost");
  24920. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24921. server_->wait_until_ready();
  24922. }
  24923. void TearDown() override {
  24924. if (server_) { server_->stop(); }
  24925. if (server_thread_.joinable()) { server_thread_.join(); }
  24926. }
  24927. std::string url() const {
  24928. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24929. }
  24930. std::unique_ptr<SSLServer> server_;
  24931. std::thread server_thread_;
  24932. int port_ = 0;
  24933. };
  24934. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24935. // out and the connection is usable
  24936. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24937. Start(SERVER_CERT2_FILE);
  24938. ws::WebSocketClient client(url());
  24939. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24940. ASSERT_TRUE(client.connect());
  24941. ASSERT_TRUE(client.send("hello"));
  24942. std::string msg;
  24943. EXPECT_EQ(ws::Text, client.read(msg));
  24944. EXPECT_EQ("hello", msg);
  24945. client.close();
  24946. }
  24947. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24948. // while the identity check must still reject "localhost"
  24949. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24950. Start(SERVER_CERT_FILE);
  24951. ws::WebSocketClient client(url());
  24952. client.set_ca_cert_path(SERVER_CERT_FILE);
  24953. auto res = client.connect();
  24954. ASSERT_FALSE(res);
  24955. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24956. EXPECT_EQ(-1, res.status());
  24957. }
  24958. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24959. // disabled: the chain is still checked, only the identity check is skipped
  24960. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24961. Start(SERVER_CERT_FILE);
  24962. ws::WebSocketClient client(url());
  24963. client.set_ca_cert_path(SERVER_CERT_FILE);
  24964. client.enable_server_hostname_verification(false);
  24965. ASSERT_TRUE(client.connect());
  24966. ASSERT_TRUE(client.send("hello"));
  24967. std::string msg;
  24968. EXPECT_EQ(ws::Text, client.read(msg));
  24969. EXPECT_EQ("hello", msg);
  24970. client.close();
  24971. }
  24972. // A CA that did not sign the server certificate fails the chain, even though
  24973. // the name would match
  24974. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24975. Start(SERVER_CERT2_FILE);
  24976. ws::WebSocketClient client(url());
  24977. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24978. ASSERT_FALSE(client.connect());
  24979. }
  24980. // With verification disabled, neither the chain nor the name is checked
  24981. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24982. Start(SERVER_CERT_FILE);
  24983. ws::WebSocketClient client(url());
  24984. client.enable_server_certificate_verification(false);
  24985. ASSERT_TRUE(client.connect());
  24986. ASSERT_TRUE(client.send("hello"));
  24987. std::string msg;
  24988. EXPECT_EQ(ws::Text, client.read(msg));
  24989. EXPECT_EQ("hello", msg);
  24990. client.close();
  24991. }
  24992. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24993. protected:
  24994. void SetUp() override {
  24995. server_ = httplib::detail::make_unique<SSLServer>(
  24996. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24997. ASSERT_TRUE(server_->is_valid());
  24998. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24999. std::string msg;
  25000. while (ws.read(msg)) {
  25001. ws.send(msg);
  25002. }
  25003. });
  25004. port_ = server_->bind_to_any_port("localhost");
  25005. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25006. server_->wait_until_ready();
  25007. }
  25008. void TearDown() override {
  25009. server_->stop();
  25010. if (server_thread_.joinable()) { server_thread_.join(); }
  25011. }
  25012. std::string url() const {
  25013. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25014. }
  25015. void ConnectWithClientCert(const std::string &client_cert_file,
  25016. const std::string &client_private_key_file,
  25017. const char *private_key_password) {
  25018. std::string cert_pem, key_pem;
  25019. read_file(client_cert_file, cert_pem);
  25020. read_file(client_private_key_file, key_pem);
  25021. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25022. key_pem.c_str(), key_pem.size(),
  25023. private_key_password};
  25024. ConnectWithPem(pem);
  25025. }
  25026. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25027. ws::WebSocketClient client(url(), pem);
  25028. ASSERT_TRUE(client.is_valid());
  25029. client.enable_server_certificate_verification(false);
  25030. ASSERT_TRUE(client.connect());
  25031. ASSERT_TRUE(client.send("hello"));
  25032. std::string msg;
  25033. EXPECT_EQ(ws::Text, client.read(msg));
  25034. EXPECT_EQ("hello", msg);
  25035. client.close();
  25036. }
  25037. std::unique_ptr<SSLServer> server_;
  25038. std::thread server_thread_;
  25039. int port_ = 0;
  25040. };
  25041. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25042. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25043. }
  25044. // Control for the tests above: the fixture's server really does require a
  25045. // client certificate, so it is the PEM the constructor installed that decides
  25046. // the outcome.
  25047. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25048. ws::WebSocketClient client(url());
  25049. ASSERT_TRUE(client.is_valid());
  25050. client.enable_server_certificate_verification(false);
  25051. EXPECT_FALSE(client.connect());
  25052. }
  25053. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25054. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25055. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25056. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25057. }
  25058. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25059. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25060. std::string cert_pem, key_pem;
  25061. read_file(CLIENT_CERT_FILE, cert_pem);
  25062. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25063. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25064. std::vector<char> key(key_pem.begin(), key_pem.end());
  25065. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25066. key.size(), nullptr};
  25067. ConnectWithPem(pem);
  25068. }
  25069. #endif
  25070. #if !defined(_WIN32)
  25071. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25072. auto secret_dir = std::string("./symlink_test_secret");
  25073. auto served_dir = std::string("./symlink_test_served");
  25074. auto secret_file = secret_dir + "/secret.txt";
  25075. auto symlink_path = served_dir + "/escape";
  25076. // Setup: create directories and files
  25077. mkdir(secret_dir.c_str(), 0755);
  25078. mkdir(served_dir.c_str(), 0755);
  25079. {
  25080. std::ofstream ofs(secret_file);
  25081. ofs << "SECRET_DATA";
  25082. }
  25083. // Create symlink using absolute path so it resolves correctly
  25084. #ifdef PATH_MAX
  25085. char abs_secret[PATH_MAX];
  25086. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25087. #else
  25088. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25089. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25090. ASSERT_NE(nullptr, abs_secret);
  25091. #endif
  25092. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25093. auto se = detail::scope_exit([&] {
  25094. unlink(symlink_path.c_str());
  25095. unlink(secret_file.c_str());
  25096. rmdir(served_dir.c_str());
  25097. rmdir(secret_dir.c_str());
  25098. });
  25099. Server svr;
  25100. svr.set_mount_point("/", served_dir);
  25101. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25102. auto se2 = detail::scope_exit([&] {
  25103. svr.stop();
  25104. listen_thread.join();
  25105. });
  25106. svr.wait_until_ready();
  25107. Client cli("localhost", PORT);
  25108. // Symlink pointing outside base dir should be blocked
  25109. auto res = cli.Get("/escape/secret.txt");
  25110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25111. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25112. }
  25113. #endif
  25114. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25115. // "GET /smuggled" request), reads the first response, and only then sends the
  25116. // embedded request as the body. Returns how many times /smuggled ran.
  25117. //
  25118. // The body is sent AFTER receiving the first response (as in the original
  25119. // PoC) so that the stream_line_reader cannot buffer it together with the
  25120. // headers of the first request.
  25121. static int count_smuggled_requests(const std::string &outer_head,
  25122. std::string &first_response) {
  25123. Server svr;
  25124. svr.set_mount_point("/", "./www");
  25125. std::atomic<int> smuggled_count(0);
  25126. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25127. smuggled_count++;
  25128. res.set_content("oops", "text/plain");
  25129. });
  25130. svr.Post("/post", [&](const Request &req, Response &res) {
  25131. res.set_content(req.body, "text/plain");
  25132. });
  25133. auto port = svr.bind_to_any_port("localhost");
  25134. thread t = thread([&] { svr.listen_after_bind(); });
  25135. auto se = detail::scope_exit([&] {
  25136. svr.stop();
  25137. t.join();
  25138. });
  25139. svr.wait_until_ready();
  25140. auto error = Error::Success;
  25141. auto sock = detail::create_client_socket(
  25142. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25143. /*connection_timeout_sec=*/2, 0,
  25144. /*read_timeout_sec=*/2, 0,
  25145. /*write_timeout_sec=*/2, 0, std::string(), error);
  25146. EXPECT_NE(INVALID_SOCKET, sock);
  25147. if (sock == INVALID_SOCKET) { return -1; }
  25148. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25149. // The "smuggled" request will be sent as the body of the outer request
  25150. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25151. "Host: localhost\r\n"
  25152. "Connection: close\r\n"
  25153. "\r\n";
  25154. auto head = outer_head;
  25155. auto len = std::to_string(smuggled.size());
  25156. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25157. pos = head.find("{len}", pos + len.size())) {
  25158. head.replace(pos, 5, len);
  25159. }
  25160. // Step 1: Send only the outer request headers (no body yet)
  25161. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25162. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25163. // Step 2: Read the first response
  25164. char buf[4096];
  25165. for (;;) {
  25166. auto n = recv(sock, buf, sizeof(buf), 0);
  25167. if (n <= 0) break;
  25168. first_response.append(buf, static_cast<size_t>(n));
  25169. // Stop once we have a complete response (headers + body)
  25170. auto hdr_end = first_response.find("\r\n\r\n");
  25171. if (hdr_end != std::string::npos) {
  25172. // Check for Content-Length to know when the body is complete
  25173. auto cl_pos = first_response.find("Content-Length:");
  25174. if (cl_pos != std::string::npos) {
  25175. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25176. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25177. auto cl = std::stoul(
  25178. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25179. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25180. } else {
  25181. break; // No Content-Length, assume headers-only response
  25182. }
  25183. }
  25184. }
  25185. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25186. // vulnerable server the keep-alive loop reads this as a second request. The
  25187. // server may already have closed the connection, so the result is ignored.
  25188. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25189. // Half-close so that a server which drained the body sees EOF and closes,
  25190. // instead of the read below waiting for the read timeout.
  25191. #ifdef _WIN32
  25192. ::shutdown(sock, SD_SEND);
  25193. #else
  25194. ::shutdown(sock, SHUT_WR);
  25195. #endif
  25196. // Step 4: Read until the server closes the connection
  25197. for (;;) {
  25198. auto n = recv(sock, buf, sizeof(buf), 0);
  25199. if (n <= 0) break;
  25200. }
  25201. return smuggled_count.load();
  25202. }
  25203. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25204. // A GET request with Content-Length to a static file handler must have its
  25205. // body drained before the keep-alive connection is reused. Otherwise the
  25206. // unread body bytes are interpreted as the next HTTP request.
  25207. std::string first_response;
  25208. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25209. "Host: localhost\r\n"
  25210. "Content-Length: {len}\r\n"
  25211. "\r\n",
  25212. first_response));
  25213. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25214. }
  25215. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25216. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25217. // be answered with 400 and the connection closed. Treating it as "no body"
  25218. // leaves the body to be parsed as the next request.
  25219. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25220. const char *targets[] = {
  25221. "GET /file", // handler that never reads the body
  25222. "GET /not-found", // no handler matches (404)
  25223. "POST /post", // handler that reads the body
  25224. };
  25225. for (auto target : targets) {
  25226. for (auto value : values) {
  25227. std::string first_response;
  25228. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25229. " HTTP/1.1\r\n"
  25230. "Host: localhost\r\n"
  25231. "Content-Length: " +
  25232. value + "\r\n\r\n",
  25233. first_response))
  25234. << target << " with Content-Length: " << value;
  25235. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25236. << target << " with Content-Length: " << value;
  25237. }
  25238. }
  25239. }
  25240. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25241. // A 400 for an unparseable request line leaves the rest of the message
  25242. // unread, so the connection must be closed rather than reused.
  25243. std::string first_response;
  25244. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25245. "Host: localhost\r\n"
  25246. "Content-Length: {len}\r\n"
  25247. "\r\n",
  25248. first_response));
  25249. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25250. }
  25251. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25252. // Same as above for a header block that fails to parse.
  25253. std::string first_response;
  25254. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25255. "Host: localhost\r\n"
  25256. "Bad Header\r\n"
  25257. "Content-Length: {len}\r\n"
  25258. "\r\n",
  25259. first_response));
  25260. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25261. }
  25262. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25263. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25264. // server must not read another request on that connection, even when the
  25265. // request had no body to drain.
  25266. std::string first_response;
  25267. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25268. "Host: localhost\r\n"
  25269. "\r\n",
  25270. first_response));
  25271. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25272. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25273. }
  25274. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25275. // A content reader that stops early leaves the stream inside the body.
  25276. // Draining the whole Content-Length from there, or reading the body again,
  25277. // reads into the next request, and whatever follows is parsed as a request
  25278. // of its own.
  25279. Server svr;
  25280. std::atomic<int> smuggled_count(0);
  25281. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25282. svr.Post("/upload", [](const Request &req, Response &res,
  25283. const ContentReader &content_reader) {
  25284. // Stop at the last chunk, so the whole body has been read however it
  25285. // arrives.
  25286. auto length = req.get_header_value_u64("Content-Length");
  25287. size_t total = 0;
  25288. auto consumed = content_reader([&](const char *, size_t n) {
  25289. total += n;
  25290. return total < length;
  25291. });
  25292. EXPECT_FALSE(consumed);
  25293. if (req.has_param("retry")) {
  25294. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25295. }
  25296. // Replace the 400 the aborted read set, which would close the connection.
  25297. res.set_redirect("/done");
  25298. });
  25299. auto port = svr.bind_to_any_port(HOST);
  25300. thread t = thread([&] { svr.listen_after_bind(); });
  25301. auto se = detail::scope_exit([&] {
  25302. svr.stop();
  25303. t.join();
  25304. });
  25305. svr.wait_until_ready();
  25306. // A front end sees the second request as a POST whose body is the GET. The
  25307. // first body is as long as the POST's headers, so draining it again reads
  25308. // exactly those and leaves the GET to be parsed next.
  25309. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25310. "Host: localhost\r\n"
  25311. "\r\n";
  25312. std::string second_head = "POST /post HTTP/1.1\r\n"
  25313. "Host: localhost\r\n"
  25314. "Content-Length: " +
  25315. std::to_string(inner.size()) +
  25316. "\r\n"
  25317. "\r\n";
  25318. for (auto target : {"/upload", "/upload?retry"}) {
  25319. smuggled_count = 0;
  25320. std::string request = "POST " + std::string(target) +
  25321. " HTTP/1.1\r\n"
  25322. "Host: localhost\r\n"
  25323. "Content-Length: " +
  25324. std::to_string(second_head.size()) +
  25325. "\r\n"
  25326. "\r\n" +
  25327. std::string(second_head.size(), 'A') + second_head +
  25328. inner;
  25329. std::string response;
  25330. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25331. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25332. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25333. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25334. EXPECT_EQ(0, smuggled_count.load()) << target;
  25335. }
  25336. }
  25337. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25338. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25339. // must be rejected with 400 Bad Request.
  25340. Server svr;
  25341. svr.Post("/test", [&](const Request &, Response &res) {
  25342. res.set_content("ok", "text/plain");
  25343. });
  25344. thread t = thread([&] { svr.listen(HOST, PORT); });
  25345. auto se = detail::scope_exit([&] {
  25346. svr.stop();
  25347. t.join();
  25348. ASSERT_FALSE(svr.is_running());
  25349. });
  25350. svr.wait_until_ready();
  25351. // Exact "chunked"
  25352. {
  25353. auto req = "POST /test HTTP/1.1\r\n"
  25354. "Host: localhost\r\n"
  25355. "Content-Length: 5\r\n"
  25356. "Transfer-Encoding: chunked\r\n"
  25357. "Connection: close\r\n"
  25358. "\r\n"
  25359. "hello";
  25360. std::string response;
  25361. ASSERT_TRUE(send_request(1, req, &response));
  25362. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25363. response.substr(0, response.find("\r\n")));
  25364. }
  25365. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25366. {
  25367. auto req = "POST /test HTTP/1.1\r\n"
  25368. "Host: localhost\r\n"
  25369. "Content-Length: 5\r\n"
  25370. "Transfer-Encoding: gzip, chunked\r\n"
  25371. "Connection: close\r\n"
  25372. "\r\n"
  25373. "hello";
  25374. std::string response;
  25375. ASSERT_TRUE(send_request(1, req, &response));
  25376. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25377. response.substr(0, response.find("\r\n")));
  25378. }
  25379. }
  25380. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25381. Server svr;
  25382. svr.Post("/test", [&](const Request &, Response &res) {
  25383. res.set_content("ok", "text/plain");
  25384. });
  25385. thread t = thread([&] { svr.listen(HOST, PORT); });
  25386. auto se = detail::scope_exit([&] {
  25387. svr.stop();
  25388. t.join();
  25389. ASSERT_FALSE(svr.is_running());
  25390. });
  25391. svr.wait_until_ready();
  25392. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25393. // length cannot be determined, so the server must answer 400 and close
  25394. // rather than treat the request as bodyless and leave the body in the
  25395. // socket for the next request to pick up.
  25396. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25397. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25398. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25399. std::string response;
  25400. ASSERT_TRUE(send_request(1, req, &response));
  25401. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25402. response.substr(0, response.find("\r\n")))
  25403. << transfer_encoding;
  25404. }
  25405. // RFC 9110 5.3: the codings may also be split across several
  25406. // Transfer-Encoding lines, which combine in the order they were received.
  25407. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25408. // just like the single-line "chunked, gzip" above.
  25409. {
  25410. auto req = "POST /test HTTP/1.1\r\n"
  25411. "Host: localhost\r\n"
  25412. "Transfer-Encoding: chunked\r\n"
  25413. "Transfer-Encoding: gzip\r\n"
  25414. "\r\n"
  25415. "0\r\n\r\n";
  25416. std::string response;
  25417. ASSERT_TRUE(send_request(1, req, &response));
  25418. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25419. response.substr(0, response.find("\r\n")));
  25420. }
  25421. // A sequence ending in chunked stays valid.
  25422. auto req = "POST /test HTTP/1.1\r\n"
  25423. "Host: localhost\r\n"
  25424. "Transfer-Encoding: gzip, chunked\r\n"
  25425. "Connection: close\r\n"
  25426. "\r\n"
  25427. "0\r\n\r\n";
  25428. std::string response;
  25429. ASSERT_TRUE(send_request(1, req, &response));
  25430. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  25431. // ...including when it is spread over several lines.
  25432. auto split_req = "POST /test HTTP/1.1\r\n"
  25433. "Host: localhost\r\n"
  25434. "Transfer-Encoding: gzip\r\n"
  25435. "Transfer-Encoding: chunked\r\n"
  25436. "Connection: close\r\n"
  25437. "\r\n"
  25438. "0\r\n\r\n";
  25439. std::string split_response;
  25440. ASSERT_TRUE(send_request(1, split_req, &split_response));
  25441. EXPECT_EQ("HTTP/1.1 200 OK",
  25442. split_response.substr(0, split_response.find("\r\n")));
  25443. }
  25444. // Regression for issue #2450: a DELETE without Content-Length on a
  25445. // keep-alive connection must not let the post-response drain consume the
  25446. // next request's bytes.
  25447. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25448. Server svr;
  25449. std::atomic<int> delete_count(0);
  25450. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25451. delete_count++;
  25452. res.status = StatusCode::NoContent_204;
  25453. });
  25454. auto port = svr.bind_to_any_port(HOST);
  25455. thread t = thread([&] { svr.listen_after_bind(); });
  25456. auto se = detail::scope_exit([&] {
  25457. svr.stop();
  25458. t.join();
  25459. });
  25460. svr.wait_until_ready();
  25461. auto error = Error::Success;
  25462. auto sock = detail::create_client_socket(
  25463. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25464. /*connection_timeout_sec=*/2, 0,
  25465. /*read_timeout_sec=*/2, 0,
  25466. /*write_timeout_sec=*/2, 0, std::string(), error);
  25467. ASSERT_NE(INVALID_SOCKET, sock);
  25468. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25469. auto send_request_and_read_response = [&](const std::string &req,
  25470. std::string &out) -> bool {
  25471. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25472. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25473. char buf[4096];
  25474. for (;;) {
  25475. auto n = recv(sock, buf, sizeof(buf), 0);
  25476. if (n <= 0) { return !out.empty(); }
  25477. out.append(buf, static_cast<size_t>(n));
  25478. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25479. }
  25480. };
  25481. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25482. "Host: localhost\r\n"
  25483. "\r\n";
  25484. std::string resp1;
  25485. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25486. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25487. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25488. "Host: localhost\r\n"
  25489. "Connection: close\r\n"
  25490. "\r\n";
  25491. std::string resp2;
  25492. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25493. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25494. EXPECT_EQ(2, delete_count.load());
  25495. }
  25496. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25497. Server svr;
  25498. svr.Post("/ingest", [&](const Request &, Response &res,
  25499. const ContentReader &content_reader) {
  25500. auto consumed = content_reader([](const char *, size_t) { return false; });
  25501. EXPECT_FALSE(consumed);
  25502. res.status = StatusCode::Conflict_409;
  25503. res.set_header("Connection", "close");
  25504. });
  25505. auto port = svr.bind_to_any_port(HOST);
  25506. thread t = thread([&] { svr.listen_after_bind(); });
  25507. auto se = detail::scope_exit([&] {
  25508. svr.stop();
  25509. t.join();
  25510. });
  25511. svr.wait_until_ready();
  25512. auto error = Error::Success;
  25513. auto sock = detail::create_client_socket(
  25514. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25515. /*connection_timeout_sec=*/2, 0,
  25516. /*read_timeout_sec=*/1, 0,
  25517. /*write_timeout_sec=*/2, 0, std::string(), error);
  25518. ASSERT_NE(INVALID_SOCKET, sock);
  25519. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25520. std::string request = "POST /ingest HTTP/1.1\r\n"
  25521. "Host: localhost\r\n"
  25522. "Transfer-Encoding: chunked\r\n"
  25523. "\r\n"
  25524. "4\r\n"
  25525. "data\r\n";
  25526. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25527. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25528. std::string response;
  25529. ssize_t received = 0;
  25530. do {
  25531. char buf[4096];
  25532. received = recv(sock, buf, sizeof(buf), 0);
  25533. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25534. } while (received > 0);
  25535. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25536. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25537. EXPECT_EQ(0, received);
  25538. }
  25539. namespace no_proxy_test {
  25540. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25541. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25542. // calling listen().
  25543. class ScopedServer {
  25544. public:
  25545. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25546. ~ScopedServer() {
  25547. svr_.stop();
  25548. if (th_.joinable()) { th_.join(); }
  25549. }
  25550. Server &svr() { return svr_; }
  25551. int port() const { return port_; }
  25552. void listen() {
  25553. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25554. svr_.wait_until_ready();
  25555. }
  25556. private:
  25557. Server svr_;
  25558. std::thread th_;
  25559. int port_ = 0;
  25560. };
  25561. class ProxyAndTargetServers {
  25562. public:
  25563. ProxyAndTargetServers() {
  25564. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25565. proxy_hits_++;
  25566. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25567. res.set_content("via-proxy", "text/plain");
  25568. });
  25569. target_.Get(".*", [this](const Request &req, Response &res) {
  25570. target_hits_++;
  25571. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25572. res.set_content("direct", "text/plain");
  25573. });
  25574. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25575. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25576. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25577. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25578. proxy_mock_.wait_until_ready();
  25579. target_.wait_until_ready();
  25580. }
  25581. ~ProxyAndTargetServers() {
  25582. proxy_mock_.stop();
  25583. target_.stop();
  25584. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25585. if (target_thread_.joinable()) { target_thread_.join(); }
  25586. }
  25587. Server &proxy_mock() { return proxy_mock_; }
  25588. Server &target() { return target_; }
  25589. int proxy_port() const { return proxy_port_; }
  25590. int target_port() const { return target_port_; }
  25591. int proxy_hits() const { return proxy_hits_.load(); }
  25592. int target_hits() const { return target_hits_.load(); }
  25593. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25594. void reset_counters() {
  25595. proxy_hits_ = 0;
  25596. target_hits_ = 0;
  25597. last_had_proxy_authz_ = false;
  25598. }
  25599. private:
  25600. Server proxy_mock_;
  25601. Server target_;
  25602. std::thread proxy_thread_;
  25603. std::thread target_thread_;
  25604. int proxy_port_ = 0;
  25605. int target_port_ = 0;
  25606. std::atomic<int> proxy_hits_{0};
  25607. std::atomic<int> target_hits_{0};
  25608. std::atomic<bool> last_had_proxy_authz_{false};
  25609. };
  25610. inline std::unique_ptr<Client> make_client(const std::string &host,
  25611. ProxyAndTargetServers &s) {
  25612. auto cli = detail::make_unique<Client>(host, s.target_port());
  25613. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25614. cli->set_proxy("127.0.0.1", s.proxy_port());
  25615. return cli;
  25616. }
  25617. } // namespace no_proxy_test
  25618. using no_proxy_test::make_client;
  25619. using no_proxy_test::ProxyAndTargetServers;
  25620. // A stream request carries the credentials a buffered request does
  25621. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25622. no_proxy_test::ScopedServer origin;
  25623. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25624. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25625. });
  25626. origin.listen();
  25627. Client cli("127.0.0.1", origin.port());
  25628. cli.set_basic_auth("user", "pass");
  25629. auto handle = cli.open_stream("GET", "/x");
  25630. ASSERT_TRUE(handle.is_valid());
  25631. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25632. Client bearer("127.0.0.1", origin.port());
  25633. bearer.set_bearer_token_auth("tok");
  25634. auto handle2 = bearer.open_stream("GET", "/x");
  25635. ASSERT_TRUE(handle2.is_valid());
  25636. EXPECT_EQ("Bearer tok", read_all(handle2));
  25637. }
  25638. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25639. // takes its own credentials, as for a buffered request
  25640. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25641. std::string target, authz, proxy_authz;
  25642. no_proxy_test::ScopedServer proxy;
  25643. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25644. target = req.target;
  25645. authz = req.get_header_value("Authorization");
  25646. proxy_authz = req.get_header_value("Proxy-Authorization");
  25647. res.set_content("ok", "text/plain");
  25648. });
  25649. proxy.listen();
  25650. Client cli("origin.example", 8080);
  25651. cli.set_proxy("127.0.0.1", proxy.port());
  25652. cli.set_proxy_basic_auth("puser", "ppass");
  25653. cli.set_basic_auth("user", "pass");
  25654. auto handle = cli.open_stream("GET", "/x");
  25655. ASSERT_TRUE(handle.is_valid());
  25656. EXPECT_EQ("ok", read_all(handle));
  25657. EXPECT_EQ("http://origin.example:8080/x", target);
  25658. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25659. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25660. }
  25661. TEST(NoProxyTest, ExactHostnameBypasses) {
  25662. ProxyAndTargetServers s;
  25663. auto cli = make_client("example.com", s);
  25664. cli->set_no_proxy({"example.com"});
  25665. auto res = cli->Get("/");
  25666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25667. EXPECT_EQ(0, s.proxy_hits());
  25668. EXPECT_EQ(1, s.target_hits());
  25669. }
  25670. TEST(NoProxyTest, SubdomainBypasses) {
  25671. ProxyAndTargetServers s;
  25672. auto cli = make_client("foo.example.com", s);
  25673. cli->set_no_proxy({"example.com"});
  25674. auto res = cli->Get("/");
  25675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25676. EXPECT_EQ(0, s.proxy_hits());
  25677. EXPECT_EQ(1, s.target_hits());
  25678. }
  25679. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25680. // Regression guard: "evilexample.com" must not be considered a subdomain
  25681. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25682. // check would let traffic bypass the proxy and leak credentials direct
  25683. // to the attacker host.
  25684. ProxyAndTargetServers s;
  25685. auto cli = make_client("evilexample.com", s);
  25686. cli->set_no_proxy({"example.com"});
  25687. auto res = cli->Get("/");
  25688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25689. EXPECT_GE(s.proxy_hits(), 1);
  25690. EXPECT_EQ(0, s.target_hits());
  25691. }
  25692. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25693. ProxyAndTargetServers s;
  25694. auto cli = make_client("example.com.evil.com", s);
  25695. cli->set_no_proxy({"example.com"});
  25696. auto res = cli->Get("/");
  25697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25698. EXPECT_GE(s.proxy_hits(), 1);
  25699. EXPECT_EQ(0, s.target_hits());
  25700. }
  25701. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25702. ProxyAndTargetServers s;
  25703. auto cli = make_client("example.com", s);
  25704. cli->set_no_proxy({".example.com"});
  25705. auto res = cli->Get("/");
  25706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25707. EXPECT_EQ(0, s.proxy_hits());
  25708. EXPECT_EQ(1, s.target_hits());
  25709. }
  25710. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25711. ProxyAndTargetServers s;
  25712. auto cli = make_client("Example.COM", s);
  25713. cli->set_no_proxy({"EXAMPLE.com"});
  25714. auto res = cli->Get("/");
  25715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25716. EXPECT_EQ(0, s.proxy_hits());
  25717. EXPECT_EQ(1, s.target_hits());
  25718. }
  25719. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25720. ProxyAndTargetServers s;
  25721. auto cli = make_client("example.com.", s);
  25722. cli->set_no_proxy({"example.com"});
  25723. auto res = cli->Get("/");
  25724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25725. EXPECT_EQ(0, s.proxy_hits());
  25726. EXPECT_EQ(1, s.target_hits());
  25727. }
  25728. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25729. // Trailing dots must be normalized on BOTH sides — host and entry.
  25730. // An implementation that only strips the host-side trailing dot would
  25731. // fail to match host "example.com" against entry "example.com." because
  25732. // a literal substring search would compare 11 chars against 12.
  25733. ProxyAndTargetServers s;
  25734. auto cli = make_client("example.com", s);
  25735. cli->set_no_proxy({"example.com."});
  25736. auto res = cli->Get("/");
  25737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25738. EXPECT_EQ(0, s.proxy_hits());
  25739. EXPECT_EQ(1, s.target_hits());
  25740. }
  25741. TEST(NoProxyTest, WildcardBypassesEverything) {
  25742. ProxyAndTargetServers s;
  25743. auto cli = make_client("anything.invalid.test", s);
  25744. cli->set_no_proxy({"*"});
  25745. auto res = cli->Get("/");
  25746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25747. EXPECT_EQ(0, s.proxy_hits());
  25748. EXPECT_EQ(1, s.target_hits());
  25749. }
  25750. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25751. ProxyAndTargetServers s;
  25752. Client cli("127.0.0.1", s.target_port());
  25753. cli.set_proxy("127.0.0.1", s.proxy_port());
  25754. cli.set_no_proxy({"127.0.0.1"});
  25755. auto res = cli.Get("/");
  25756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25757. EXPECT_EQ(0, s.proxy_hits());
  25758. EXPECT_EQ(1, s.target_hits());
  25759. }
  25760. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25761. ProxyAndTargetServers s;
  25762. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25763. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25764. cli.set_proxy("127.0.0.1", s.proxy_port());
  25765. cli.set_no_proxy({"::1"});
  25766. auto res = cli.Get("/");
  25767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25768. EXPECT_EQ(0, s.proxy_hits());
  25769. EXPECT_EQ(1, s.target_hits());
  25770. }
  25771. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25772. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25773. // must still be recognized as IPv6 for CIDR matching. Implementations
  25774. // that detect IPv6 only when the host begins with '[' would parse the
  25775. // host as a hostname and miss the match.
  25776. ProxyAndTargetServers s;
  25777. Client cli("fe80::1", s.target_port());
  25778. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25779. cli.set_proxy("127.0.0.1", s.proxy_port());
  25780. cli.set_no_proxy({"fe80::/10"});
  25781. auto res = cli.Get("/");
  25782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25783. EXPECT_EQ(0, s.proxy_hits());
  25784. EXPECT_EQ(1, s.target_hits());
  25785. }
  25786. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25787. ProxyAndTargetServers s;
  25788. Client cli("::1", s.target_port());
  25789. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25790. cli.set_proxy("127.0.0.1", s.proxy_port());
  25791. cli.set_no_proxy({"[::1]"});
  25792. auto res = cli.Get("/");
  25793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25794. EXPECT_EQ(0, s.proxy_hits());
  25795. EXPECT_EQ(1, s.target_hits());
  25796. }
  25797. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25798. ProxyAndTargetServers s;
  25799. Client cli("fe80::1", s.target_port());
  25800. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25801. cli.set_proxy("127.0.0.1", s.proxy_port());
  25802. cli.set_no_proxy({"[fe80::]/10"});
  25803. auto res = cli.Get("/");
  25804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25805. EXPECT_EQ(0, s.proxy_hits());
  25806. EXPECT_EQ(1, s.target_hits());
  25807. }
  25808. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25809. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25810. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25811. // tricks via address-family conversion.
  25812. ProxyAndTargetServers s;
  25813. Client cli("::ffff:127.0.0.1", s.target_port());
  25814. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25815. cli.set_proxy("127.0.0.1", s.proxy_port());
  25816. cli.set_no_proxy({"127.0.0.1"});
  25817. auto res = cli.Get("/");
  25818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25819. EXPECT_GE(s.proxy_hits(), 1);
  25820. EXPECT_EQ(0, s.target_hits());
  25821. }
  25822. TEST(NoProxyTest, IPv4CidrMatch) {
  25823. ProxyAndTargetServers s;
  25824. Client cli("127.0.0.1", s.target_port());
  25825. cli.set_proxy("127.0.0.1", s.proxy_port());
  25826. cli.set_no_proxy({"127.0.0.0/8"});
  25827. auto res = cli.Get("/");
  25828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25829. EXPECT_EQ(0, s.proxy_hits());
  25830. EXPECT_EQ(1, s.target_hits());
  25831. }
  25832. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25833. ProxyAndTargetServers s;
  25834. Client cli("127.0.0.1", s.target_port());
  25835. cli.set_proxy("127.0.0.1", s.proxy_port());
  25836. cli.set_no_proxy({"10.0.0.0/8"});
  25837. auto res = cli.Get("/");
  25838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25839. EXPECT_GE(s.proxy_hits(), 1);
  25840. EXPECT_EQ(0, s.target_hits());
  25841. }
  25842. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25843. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25844. // IPv4 target matches.
  25845. ProxyAndTargetServers s;
  25846. Client cli("127.0.0.1", s.target_port());
  25847. cli.set_proxy("127.0.0.1", s.proxy_port());
  25848. cli.set_no_proxy({"0.0.0.0/0"});
  25849. auto res = cli.Get("/");
  25850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25851. EXPECT_EQ(0, s.proxy_hits());
  25852. EXPECT_EQ(1, s.target_hits());
  25853. }
  25854. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25855. ProxyAndTargetServers s;
  25856. Client cli("127.0.0.1", s.target_port());
  25857. cli.set_proxy("127.0.0.1", s.proxy_port());
  25858. cli.set_no_proxy({"127.0.0.1"});
  25859. auto res = cli.Get("/");
  25860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25861. EXPECT_EQ(0, s.proxy_hits());
  25862. EXPECT_EQ(1, s.target_hits());
  25863. }
  25864. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25865. ProxyAndTargetServers s;
  25866. Client cli("127.0.0.1", s.target_port());
  25867. cli.set_proxy("127.0.0.1", s.proxy_port());
  25868. cli.set_no_proxy({"127.0.0.0/33"});
  25869. auto res = cli.Get("/");
  25870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25871. EXPECT_GE(s.proxy_hits(), 1);
  25872. EXPECT_EQ(0, s.target_hits());
  25873. }
  25874. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25875. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25876. ProxyAndTargetServers s;
  25877. Client cli("127.0.0.1", s.target_port());
  25878. cli.set_proxy("127.0.0.1", s.proxy_port());
  25879. cli.set_no_proxy({"127.0.0.1/"});
  25880. auto res = cli.Get("/");
  25881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25882. EXPECT_GE(s.proxy_hits(), 1);
  25883. EXPECT_EQ(0, s.target_hits());
  25884. }
  25885. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25886. ProxyAndTargetServers s;
  25887. auto cli = make_client("internal.corp", s);
  25888. cli->set_proxy_basic_auth("u", "p");
  25889. cli->set_no_proxy({"internal.corp"});
  25890. auto res = cli->Get("/");
  25891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25892. EXPECT_EQ(1, s.target_hits());
  25893. EXPECT_EQ(0, s.proxy_hits());
  25894. EXPECT_FALSE(s.last_had_proxy_authz())
  25895. << "Proxy-Authorization must not be sent direct to the target";
  25896. }
  25897. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25898. ProxyAndTargetServers s;
  25899. auto cli = make_client("public.example", s);
  25900. cli->set_proxy_basic_auth("u", "p");
  25901. cli->set_no_proxy({"internal.corp"}); // does not match
  25902. auto res = cli->Get("/");
  25903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25904. EXPECT_GE(s.proxy_hits(), 1);
  25905. EXPECT_TRUE(s.last_had_proxy_authz());
  25906. }
  25907. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25908. std::atomic<int> hits{0};
  25909. std::atomic<int> hits_with_authz{0};
  25910. no_proxy_test::ScopedServer proxy_mock;
  25911. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25912. hits++;
  25913. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25914. if (req.target.find("/redir") != std::string::npos) {
  25915. res.set_redirect("http://other.example/landed");
  25916. } else {
  25917. res.set_content("via-proxy", "text/plain");
  25918. }
  25919. });
  25920. proxy_mock.listen();
  25921. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25922. hits = 0;
  25923. hits_with_authz = 0;
  25924. Client cli("public.example", 80);
  25925. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25926. cli.set_proxy_basic_auth(c.first, c.second);
  25927. cli.set_follow_location(true);
  25928. // The redirect to another host goes through the proxy as well
  25929. auto res = cli.Get("/redir");
  25930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25931. EXPECT_EQ(2, hits.load());
  25932. EXPECT_EQ(2, hits_with_authz.load());
  25933. }
  25934. }
  25935. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25936. ProxyAndTargetServers s;
  25937. auto cli = make_client("anything.test", s);
  25938. auto res = cli->Get("/");
  25939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25940. EXPECT_GE(s.proxy_hits(), 1);
  25941. EXPECT_EQ(0, s.target_hits());
  25942. }
  25943. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25944. ProxyAndTargetServers s;
  25945. auto cli = make_client("example.com", s);
  25946. cli->set_no_proxy({"example.com:8080"});
  25947. auto res = cli->Get("/");
  25948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25949. EXPECT_GE(s.proxy_hits(), 1);
  25950. EXPECT_EQ(0, s.target_hits());
  25951. }
  25952. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25953. ProxyAndTargetServers s;
  25954. auto cli = make_client("anything.test", s);
  25955. cli->set_no_proxy({"", " ", "\t"});
  25956. auto res = cli->Get("/");
  25957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25958. EXPECT_GE(s.proxy_hits(), 1);
  25959. EXPECT_EQ(0, s.target_hits());
  25960. }
  25961. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25962. // An entry with leading/trailing whitespace must still match — env-style
  25963. // values are commonly pasted with stray spaces and an implementation
  25964. // that feeds the raw token directly to inet_pton would fail to match
  25965. // valid CIDRs because of the spaces.
  25966. ProxyAndTargetServers s;
  25967. Client cli("127.0.0.1", s.target_port());
  25968. cli.set_proxy("127.0.0.1", s.proxy_port());
  25969. cli.set_no_proxy({" 127.0.0.0/8 "});
  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, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25976. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25977. // go direct and must NOT carry Proxy-Authorization.
  25978. std::atomic<int> proxy_hits{0};
  25979. std::atomic<int> target_hits{0};
  25980. std::atomic<bool> target_saw_authz{false};
  25981. no_proxy_test::ScopedServer proxy_mock, target;
  25982. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25983. proxy_hits++;
  25984. res.status = 302;
  25985. res.set_header("Location", "http://127.0.0.1:" +
  25986. std::to_string(target.port()) + "/landed");
  25987. });
  25988. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25989. target_hits++;
  25990. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25991. res.set_content("direct", "text/plain");
  25992. });
  25993. proxy_mock.listen();
  25994. target.listen();
  25995. Client cli("public.example", target.port());
  25996. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25997. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25998. cli.set_proxy_basic_auth("u", "p");
  25999. cli.set_no_proxy({"127.0.0.1"});
  26000. cli.set_follow_location(true);
  26001. auto res = cli.Get("/redir");
  26002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26003. EXPECT_GE(proxy_hits.load(), 1);
  26004. EXPECT_GE(target_hits.load(), 1);
  26005. EXPECT_FALSE(target_saw_authz.load());
  26006. }
  26007. #ifdef CPPHTTPLIB_SSL_ENABLED
  26008. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26009. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26010. // proxy creds would be sent to the (possibly hostile) origin.
  26011. std::atomic<int> target_hits{0};
  26012. std::atomic<bool> target_saw_proxy_authz{false};
  26013. no_proxy_test::ScopedServer target;
  26014. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26015. target_hits++;
  26016. if (req.has_header("Proxy-Authorization")) {
  26017. target_saw_proxy_authz = true;
  26018. }
  26019. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26020. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26021. "nonce=\"abc\", algorithm=MD5");
  26022. });
  26023. target.listen();
  26024. // The proxy address is set to the target's port: the bypass MUST kick in;
  26025. // if it doesn't, the test still routes "via proxy" to the same server and
  26026. // the Proxy-Authorization assertion below catches the leak.
  26027. Client cli("evil.example", target.port());
  26028. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26029. cli.set_proxy("127.0.0.1", target.port());
  26030. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26031. cli.set_no_proxy({"evil.example"});
  26032. auto res = cli.Get("/x");
  26033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26034. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26035. EXPECT_EQ(1, target_hits.load());
  26036. EXPECT_FALSE(target_saw_proxy_authz.load());
  26037. }
  26038. #endif
  26039. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26040. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26041. std::atomic<int> proxy_hits{0};
  26042. std::atomic<int> bypass_hits{0};
  26043. std::atomic<bool> proxy_saw_c_url{false};
  26044. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26045. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26046. proxy_hits++;
  26047. if (req.path.find("/start") != std::string::npos) {
  26048. res.status = 302;
  26049. res.set_header("Location", "http://127.0.0.1:" +
  26050. std::to_string(bypass_server.port()) +
  26051. "/middle");
  26052. return;
  26053. }
  26054. if (req.path.find("/end") != std::string::npos) {
  26055. proxy_saw_c_url = true;
  26056. res.set_content("c-via-proxy", "text/plain");
  26057. return;
  26058. }
  26059. res.set_content("unexpected", "text/plain");
  26060. });
  26061. // public.example's "advertised" port is arbitrary (the request never lands
  26062. // there — it goes through the proxy), but use a dynamic value to stay
  26063. // friendly with sharded parallel runs.
  26064. int public_port = bypass_server.port();
  26065. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26066. bypass_hits++;
  26067. res.status = 302;
  26068. res.set_header("Location", "http://public.example:" +
  26069. std::to_string(public_port) + "/end");
  26070. });
  26071. proxy_mock.listen();
  26072. bypass_server.listen();
  26073. Client cli("public.example", public_port);
  26074. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26075. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26076. cli.set_no_proxy({"127.0.0.1"});
  26077. cli.set_follow_location(true);
  26078. auto res = cli.Get("/start");
  26079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26080. EXPECT_EQ(StatusCode::OK_200, res->status);
  26081. EXPECT_EQ("c-via-proxy", res->body);
  26082. EXPECT_GE(proxy_hits.load(), 2);
  26083. EXPECT_GE(bypass_hits.load(), 1);
  26084. EXPECT_TRUE(proxy_saw_c_url.load());
  26085. }
  26086. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26087. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26088. // request reconnects to the correct endpoint.
  26089. std::atomic<int> proxy_hits{0};
  26090. std::atomic<int> target_hits{0};
  26091. no_proxy_test::ScopedServer proxy_mock, target;
  26092. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26093. proxy_hits++;
  26094. res.set_content("via-proxy", "text/plain");
  26095. });
  26096. target.svr().Get(".*", [&](const Request &, Response &res) {
  26097. target_hits++;
  26098. res.set_content("direct", "text/plain");
  26099. });
  26100. proxy_mock.listen();
  26101. target.listen();
  26102. Client cli("public.example", target.port());
  26103. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26104. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26105. cli.set_keep_alive(true);
  26106. auto res1 = cli.Get("/a");
  26107. ASSERT_TRUE(res1);
  26108. EXPECT_EQ("via-proxy", res1->body);
  26109. EXPECT_EQ(1, proxy_hits.load());
  26110. EXPECT_EQ(0, target_hits.load());
  26111. cli.set_no_proxy({"public.example"});
  26112. auto res2 = cli.Get("/b");
  26113. ASSERT_TRUE(res2);
  26114. EXPECT_EQ("direct", res2->body);
  26115. EXPECT_EQ(1, proxy_hits.load());
  26116. EXPECT_EQ(1, target_hits.load());
  26117. }
  26118. // Forward declarations (see the base64_encode note).
  26119. namespace httplib {
  26120. namespace detail {
  26121. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26122. int shutdown_socket(socket_t sock) noexcept;
  26123. } // namespace detail
  26124. } // namespace httplib
  26125. namespace proxy_tunnel_test {
  26126. const char *const kTunnelEstablished =
  26127. "HTTP/1.1 200 Connection established\r\n\r\n";
  26128. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26129. using ConnectReply = std::function<std::string(const std::string &head)>;
  26130. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26131. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26132. class ScopedConnectProxy {
  26133. public:
  26134. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26135. : forward_port_(forward_port), reply_(std::move(reply)) {
  26136. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26137. if (listen_sock_ == INVALID_SOCKET) { return; }
  26138. auto a = loopback(0);
  26139. auto addr = reinterpret_cast<sockaddr *>(&a);
  26140. socklen_t alen = sizeof(a);
  26141. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26142. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26143. ::listen(listen_sock_, 4) != 0) {
  26144. return;
  26145. }
  26146. port_ = ntohs(a.sin_port);
  26147. th_ = std::thread([this] { run(); });
  26148. }
  26149. ~ScopedConnectProxy() {
  26150. if (th_.joinable()) {
  26151. stop_ = true;
  26152. auto wake = connect_to(port_);
  26153. th_.join();
  26154. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26155. }
  26156. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26157. }
  26158. int port() const { return port_; }
  26159. int connect_hits() const { return connect_hits_.load(); }
  26160. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26161. std::string connect_request() const {
  26162. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26163. return connect_request_;
  26164. }
  26165. private:
  26166. static sockaddr_in loopback(int port) {
  26167. sockaddr_in a{};
  26168. a.sin_family = AF_INET;
  26169. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26170. a.sin_port = htons(static_cast<unsigned short>(port));
  26171. return a;
  26172. }
  26173. static socket_t connect_to(int port) {
  26174. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26175. if (sock == INVALID_SOCKET) { return sock; }
  26176. auto a = loopback(port);
  26177. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26178. detail::close_socket(sock);
  26179. return INVALID_SOCKET;
  26180. }
  26181. return sock;
  26182. }
  26183. static bool send_all(socket_t sock, const char *data, size_t size) {
  26184. while (size > 0) {
  26185. auto n = detail::send_socket(sock, data, size, 0);
  26186. if (n <= 0) { return false; }
  26187. data += n;
  26188. size -= static_cast<size_t>(n);
  26189. }
  26190. return true;
  26191. }
  26192. void run() {
  26193. for (;;) {
  26194. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26195. if (stop_) {
  26196. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26197. return;
  26198. }
  26199. if (client == INVALID_SOCKET) { continue; }
  26200. serve(client);
  26201. detail::close_socket(client);
  26202. }
  26203. }
  26204. void serve(socket_t client) {
  26205. std::string head;
  26206. char buf[2048];
  26207. while (head.find("\r\n\r\n") == std::string::npos) {
  26208. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26209. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26210. if (n <= 0) { return; }
  26211. head.append(buf, static_cast<size_t>(n));
  26212. }
  26213. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26214. connect_hits_++;
  26215. {
  26216. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26217. connect_request_ = head;
  26218. }
  26219. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26220. if (!send_all(client, res.data(), res.size()) ||
  26221. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26222. return;
  26223. }
  26224. auto origin = connect_to(forward_port_);
  26225. if (origin == INVALID_SOCKET) { return; }
  26226. // When either side stops, shut both down so the other pump returns too.
  26227. auto pump = [&](socket_t from, socket_t to) {
  26228. char b[8192];
  26229. for (;;) {
  26230. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26231. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26232. }
  26233. detail::shutdown_socket(client);
  26234. detail::shutdown_socket(origin);
  26235. };
  26236. std::thread up([&] { pump(client, origin); });
  26237. pump(origin, client);
  26238. up.join();
  26239. detail::close_socket(origin);
  26240. }
  26241. int forward_port_;
  26242. ConnectReply reply_;
  26243. socket_t listen_sock_ = INVALID_SOCKET;
  26244. int port_ = 0;
  26245. std::thread th_;
  26246. std::atomic<bool> stop_{false};
  26247. std::atomic<int> connect_hits_{0};
  26248. mutable std::mutex connect_request_mutex_;
  26249. std::string connect_request_;
  26250. };
  26251. } // namespace proxy_tunnel_test
  26252. #ifdef CPPHTTPLIB_SSL_ENABLED
  26253. namespace proxy_tunnel_test {
  26254. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26255. class ScopedSSLServer {
  26256. public:
  26257. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26258. port_ = svr_.bind_to_any_port("127.0.0.1");
  26259. }
  26260. ~ScopedSSLServer() {
  26261. svr_.stop();
  26262. if (th_.joinable()) { th_.join(); }
  26263. }
  26264. SSLServer &svr() { return svr_; }
  26265. int port() const { return port_; }
  26266. void listen() {
  26267. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26268. svr_.wait_until_ready();
  26269. }
  26270. private:
  26271. SSLServer svr_;
  26272. std::thread th_;
  26273. int port_ = 0;
  26274. };
  26275. // Sends one request through the CONNECT proxy to the TLS origin with a
  26276. // credential configured for each hop, and checks that each credential reaches
  26277. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26278. // origin's (every header in origin_headers) on the tunnelled request.
  26279. void CredentialsStayWithTheirHop(
  26280. const std::function<void(SSLClient &)> &set_credentials,
  26281. const std::string &scheme,
  26282. const std::vector<std::string> &origin_headers = {"Authorization"},
  26283. bool stream = false) {
  26284. std::atomic<int> origin_hits{0};
  26285. std::atomic<bool> origin_saw_proxy_authz{false};
  26286. std::atomic<bool> origin_saw_headers{false};
  26287. ScopedSSLServer origin;
  26288. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26289. origin_hits++;
  26290. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26291. origin_saw_headers =
  26292. std::all_of(origin_headers.begin(), origin_headers.end(),
  26293. [&](const std::string &h) { return req.has_header(h); });
  26294. res.set_content("ok", "text/plain");
  26295. });
  26296. origin.listen();
  26297. ScopedConnectProxy proxy(origin.port());
  26298. ASSERT_NE(0, proxy.port());
  26299. // Pinned to 127.0.0.1 for the same reason as the test below.
  26300. SSLClient cli("127.0.0.1", origin.port());
  26301. cli.enable_server_certificate_verification(false);
  26302. cli.set_proxy("127.0.0.1", proxy.port());
  26303. set_credentials(cli);
  26304. if (stream) {
  26305. auto handle = cli.open_stream("GET", "/x");
  26306. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26307. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26308. } else {
  26309. auto res = cli.Get("/x");
  26310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26311. EXPECT_EQ(StatusCode::OK_200, res->status);
  26312. }
  26313. EXPECT_EQ(1, origin_hits.load());
  26314. EXPECT_EQ(1, proxy.connect_hits());
  26315. EXPECT_TRUE(origin_saw_headers.load());
  26316. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26317. << "Proxy-Authorization must not be sent inside the tunnel";
  26318. auto connect_req = proxy.connect_request();
  26319. EXPECT_NE(std::string::npos,
  26320. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26321. for (const auto &h : origin_headers) {
  26322. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26323. << h << " must not be sent to the proxy on CONNECT";
  26324. }
  26325. }
  26326. } // namespace proxy_tunnel_test
  26327. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26328. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26329. [](SSLClient &cli) {
  26330. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26331. cli.set_basic_auth("origin-user", "origin-pass");
  26332. },
  26333. "Basic");
  26334. }
  26335. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26336. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26337. [](SSLClient &cli) {
  26338. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26339. cli.set_basic_auth("origin-user", "origin-pass");
  26340. },
  26341. "Basic", {"Authorization"}, true);
  26342. }
  26343. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26344. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26345. [](SSLClient &cli) {
  26346. cli.set_proxy_bearer_token_auth("proxy-token");
  26347. cli.set_bearer_token_auth("origin-token");
  26348. },
  26349. "Bearer");
  26350. }
  26351. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26352. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26353. [](SSLClient &cli) {
  26354. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26355. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26356. {"Cookie", "sid=origin-session"},
  26357. {"X-Api-Key", "origin-key"}});
  26358. },
  26359. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26360. }
  26361. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26362. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26363. // retry; otherwise proxy creds would be sent to the origin.
  26364. std::atomic<int> origin_hits{0};
  26365. std::atomic<bool> origin_saw_proxy_authz{false};
  26366. proxy_tunnel_test::ScopedSSLServer origin;
  26367. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26368. origin_hits++;
  26369. if (req.has_header("Proxy-Authorization")) {
  26370. origin_saw_proxy_authz = true;
  26371. }
  26372. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26373. res.set_header("Proxy-Authenticate",
  26374. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26375. "algorithm=MD5");
  26376. });
  26377. origin.listen();
  26378. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26379. ASSERT_NE(0, proxy.port());
  26380. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26381. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26382. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26383. // and answer with its own status, making this test flaky.
  26384. SSLClient cli("127.0.0.1", origin.port());
  26385. cli.enable_server_certificate_verification(false);
  26386. cli.set_proxy("127.0.0.1", proxy.port());
  26387. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26388. auto res = cli.Get("/x");
  26389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26390. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26391. EXPECT_EQ(1, origin_hits.load());
  26392. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26393. EXPECT_EQ(1, proxy.connect_hits());
  26394. }
  26395. #endif
  26396. namespace proxy_tunnel_test {
  26397. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26398. // anything else gets a 407 with `challenge`.
  26399. ConnectReply require_proxy_auth(const std::string &expected,
  26400. const std::string &challenge) {
  26401. return [=](const std::string &head) -> std::string {
  26402. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26403. std::string::npos) {
  26404. return kTunnelEstablished;
  26405. }
  26406. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26407. "Proxy-Authenticate: " +
  26408. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26409. };
  26410. }
  26411. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26412. // request, then echoes.
  26413. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26414. ws.send(
  26415. "authorization:" + req.get_header_value("Authorization") +
  26416. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26417. std::string msg;
  26418. while (ws.read(msg)) {
  26419. ws.send(msg);
  26420. }
  26421. }
  26422. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26423. class ScopedWebSocketOrigin {
  26424. public:
  26425. ScopedWebSocketOrigin() {
  26426. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26427. server_.listen();
  26428. }
  26429. int port() const { return server_.port(); }
  26430. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26431. std::string url() const {
  26432. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26433. }
  26434. private:
  26435. no_proxy_test::ScopedServer server_;
  26436. };
  26437. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26438. // passed as a constructor header, and checks that each reaches only its hop.
  26439. void WebSocketCredentialsStayWithTheirHop(
  26440. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26441. const std::string &proxy_authz, const std::string &origin_authz) {
  26442. ScopedWebSocketOrigin origin;
  26443. ScopedConnectProxy proxy(
  26444. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26445. ASSERT_NE(0, proxy.port());
  26446. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26447. client.set_proxy("127.0.0.1", proxy.port());
  26448. set_proxy_credentials(client);
  26449. auto res = client.connect();
  26450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26451. std::string msg;
  26452. ASSERT_TRUE(client.read(msg));
  26453. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26454. client.close();
  26455. EXPECT_EQ(1, proxy.connect_hits());
  26456. EXPECT_EQ(std::string::npos,
  26457. proxy.connect_request().find("\r\nAuthorization: "))
  26458. << "origin credentials must not be sent to the proxy";
  26459. }
  26460. } // namespace proxy_tunnel_test
  26461. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26462. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26463. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26464. ASSERT_NE(0, proxy.port());
  26465. ws::WebSocketClient client(origin.url());
  26466. client.set_proxy("127.0.0.1", proxy.port());
  26467. auto res = client.connect();
  26468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26469. std::string msg;
  26470. ASSERT_TRUE(client.read(msg));
  26471. ASSERT_TRUE(client.send("hello"));
  26472. ASSERT_TRUE(client.read(msg));
  26473. EXPECT_EQ("hello", msg);
  26474. client.close();
  26475. EXPECT_EQ(1, proxy.connect_hits());
  26476. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26477. auto connect_req = proxy.connect_request();
  26478. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26479. EXPECT_NE(std::string::npos,
  26480. connect_req.find("\r\nHost: " + target + "\r\n"));
  26481. }
  26482. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26483. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26484. [](ws::WebSocketClient &cli) {
  26485. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26486. },
  26487. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26488. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26489. }
  26490. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26491. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26492. [](ws::WebSocketClient &cli) {
  26493. cli.set_proxy_bearer_token_auth("proxy-token");
  26494. },
  26495. "Bearer proxy-token", "Bearer origin-token");
  26496. }
  26497. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26498. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26499. proxy_tunnel_test::ScopedConnectProxy proxy(
  26500. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26501. "Basic " + detail::base64_encode("proxy-user:"),
  26502. "Basic realm=\"proxy\""));
  26503. ASSERT_NE(0, proxy.port());
  26504. ws::WebSocketClient client(origin.url());
  26505. client.set_proxy("127.0.0.1", proxy.port());
  26506. client.set_proxy_basic_auth("proxy-user", "");
  26507. auto res = client.connect();
  26508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26509. client.close();
  26510. EXPECT_EQ(1, proxy.connect_hits());
  26511. }
  26512. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26513. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26514. proxy_tunnel_test::ScopedConnectProxy proxy(
  26515. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26516. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26517. ASSERT_NE(0, proxy.port());
  26518. ws::WebSocketClient client(origin.url());
  26519. client.set_proxy("127.0.0.1", proxy.port());
  26520. auto res = client.connect();
  26521. EXPECT_FALSE(res);
  26522. EXPECT_EQ(Error::ProxyConnection, res.error());
  26523. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26524. EXPECT_EQ("Basic realm=\"proxy\"",
  26525. res.get_header_value("Proxy-Authenticate"));
  26526. EXPECT_FALSE(client.is_open());
  26527. }
  26528. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26529. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26530. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26531. ASSERT_NE(0, proxy.port());
  26532. ws::WebSocketClient client(origin.url());
  26533. client.set_proxy("127.0.0.1", proxy.port());
  26534. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26535. client.set_no_proxy({"127.0.0.1"});
  26536. auto res = client.connect();
  26537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26538. std::string msg;
  26539. ASSERT_TRUE(client.read(msg));
  26540. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26541. << "proxy credentials must not reach a bypassed origin";
  26542. client.close();
  26543. EXPECT_EQ(0, proxy.connect_hits());
  26544. }
  26545. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26546. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26547. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26548. ASSERT_NE(0, proxy.port());
  26549. ws::WebSocketClient client(origin.url());
  26550. client.set_proxy("127.0.0.1", proxy.port());
  26551. ASSERT_TRUE(client.connect());
  26552. ASSERT_TRUE(client.connect());
  26553. client.close();
  26554. EXPECT_EQ(2, proxy.connect_hits());
  26555. }
  26556. #ifdef CPPHTTPLIB_SSL_ENABLED
  26557. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26558. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26559. proxy_tunnel_test::ScopedConnectProxy proxy(
  26560. origin.port(), [](const std::string &head) -> std::string {
  26561. if (head.find(
  26562. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26563. std::string::npos) {
  26564. return proxy_tunnel_test::kTunnelEstablished;
  26565. }
  26566. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26567. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26568. "nonce=\"abc\", algorithm=MD5\r\n"
  26569. "Content-Length: 0\r\n\r\n";
  26570. });
  26571. ASSERT_NE(0, proxy.port());
  26572. ws::WebSocketClient client(origin.url());
  26573. client.set_proxy("127.0.0.1", proxy.port());
  26574. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26575. auto res = client.connect();
  26576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26577. std::string msg;
  26578. ASSERT_TRUE(client.read(msg));
  26579. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26580. client.close();
  26581. EXPECT_EQ(2, proxy.connect_hits());
  26582. }
  26583. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26584. proxy_tunnel_test::ScopedSSLServer origin;
  26585. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26586. origin.listen();
  26587. proxy_tunnel_test::ScopedConnectProxy proxy(
  26588. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26589. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26590. ASSERT_NE(0, proxy.port());
  26591. ws::WebSocketClient client(
  26592. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26593. client.enable_server_certificate_verification(false);
  26594. client.set_proxy("127.0.0.1", proxy.port());
  26595. client.set_proxy_bearer_token_auth("proxy-token");
  26596. auto res = client.connect();
  26597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26598. std::string msg;
  26599. ASSERT_TRUE(client.read(msg));
  26600. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26601. << "Proxy-Authorization must not be sent inside the tunnel";
  26602. client.close();
  26603. EXPECT_EQ(1, proxy.connect_hits());
  26604. }
  26605. #endif