test.cc 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657
  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. bool is_valid_path(const std::string &path);
  492. #ifdef CPPHTTPLIB_SSL_ENABLED
  493. bool match_hostname(const std::string &pattern, const std::string &hostname);
  494. #endif
  495. } // namespace detail
  496. } // namespace httplib
  497. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  498. struct {
  499. const char *line;
  500. const char *version;
  501. int status;
  502. const char *reason;
  503. } cases[] = {
  504. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  505. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  506. // The reason phrase may be empty, or left out along with its space.
  507. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  508. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  509. };
  510. for (const auto &c : cases) {
  511. std::string version;
  512. int status = 0;
  513. std::string reason = "unset";
  514. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  515. << c.line;
  516. EXPECT_EQ(c.version, version);
  517. EXPECT_EQ(c.status, status);
  518. EXPECT_EQ(c.reason, reason);
  519. }
  520. }
  521. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  522. const char *lines[] = {
  523. "HTTP/2 200 OK\r\n",
  524. "HTTP/1.2 200 OK\r\n",
  525. "HTTP/1.1 20 OK\r\n",
  526. "HTTP/1.1 2000 OK\r\n",
  527. "HTTP/1.1 2x0 OK\r\n",
  528. "HTTP/1.1 200 OK\r\n",
  529. "HTTP/1.1 200OK\r\n",
  530. "HTTP/1.1 200 O\rK\r\n",
  531. "HTTP/1.1 200 OK",
  532. "HTTP/1.1 200 OK\r\nX",
  533. "",
  534. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  535. "HTTP/1.1 200 OK\n",
  536. #endif
  537. };
  538. for (auto line : lines) {
  539. std::string version;
  540. int status = 0;
  541. std::string reason;
  542. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  543. << line;
  544. }
  545. }
  546. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  547. // Long enough to overflow the stack when matched with std::regex.
  548. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  549. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  550. std::string version;
  551. int status = 0;
  552. std::string reason;
  553. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  554. EXPECT_EQ(200, status);
  555. EXPECT_EQ(long_reason, reason);
  556. }
  557. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  558. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  559. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  560. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  561. EXPECT_EQ("", detail::file_extension("noext"));
  562. EXPECT_EQ("", detail::file_extension("a."));
  563. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  564. EXPECT_EQ("", detail::file_extension("a.b-c"));
  565. // Long enough to overflow the stack when matched with std::regex.
  566. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  567. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  568. }
  569. #ifdef CPPHTTPLIB_SSL_ENABLED
  570. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  571. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  573. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  574. // A wildcard needs two labels after it, in the leftmost label only
  575. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  576. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  577. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  578. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  579. EXPECT_FALSE(
  580. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  581. // No name may have an empty label
  582. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  583. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  584. }
  585. #endif
  586. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  587. detail::case_ignore::hash hash;
  588. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  589. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  590. // Long enough to overflow the stack if hashed one call per character.
  591. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  592. }
  593. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  594. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  595. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  596. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  597. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  598. // Same 26-bit hash as html, svg and js.
  599. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  601. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  602. }
  603. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  604. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  605. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  606. }
  607. }
  608. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  609. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  610. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  611. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  612. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  613. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  614. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  615. // Same 26-bit hash as application/json.
  616. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  617. }
  618. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  619. Request req;
  620. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  621. EXPECT_TRUE(req.is_multipart_form_data());
  622. std::string boundary;
  623. EXPECT_TRUE(detail::parse_multipart_boundary(
  624. req.get_header_value("Content-Type"), boundary));
  625. EXPECT_EQ("x", boundary);
  626. }
  627. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  628. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  629. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  630. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  631. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  632. // Same 26-bit hash as REMOTE_ADDR.
  633. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  634. }
  635. // Forward declaration: in split builds split.py strips `inline` and moves the
  636. // definition into httplib.cc, so detail::base64_encode is not visible from the
  637. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  638. // in both header-only and split builds.
  639. namespace httplib {
  640. namespace detail {
  641. std::string base64_encode(const std::string &in);
  642. } // namespace detail
  643. } // namespace httplib
  644. TEST(Base64EncodeTest, KnownAnswers) {
  645. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  646. // where the accumulator's top bit is already set before the next shift.
  647. EXPECT_EQ("", detail::base64_encode(""));
  648. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  649. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  650. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  651. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  652. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  653. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  654. // High bytes keep the top bit set across several rounds.
  655. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  656. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  657. }
  658. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  659. string unescapedCharacters = "-_.!~*'()";
  660. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  661. }
  662. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  663. string reservedCharacters = ";,/?:@&=+$";
  664. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  665. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  666. }
  667. TEST(ClientQueryOrder, PreserveOrder) {
  668. // This test reproduces Issue #2259: client may reorder query parameters
  669. // when sending a GET request. The expected behavior is that the client
  670. // preserves the original query string order when the caller supplied it
  671. // as part of the path.
  672. Server svr;
  673. svr.Get("/", [&](const Request &req, Response &res) {
  674. // Echo back the raw target so the test can assert ordering
  675. res.set_content(req.target, "text/plain");
  676. });
  677. std::thread t{[&] { svr.listen(HOST, PORT); }};
  678. auto se = detail::scope_exit([&] {
  679. svr.stop();
  680. t.join();
  681. ASSERT_FALSE(svr.is_running());
  682. });
  683. svr.wait_until_ready();
  684. Client cli(HOST, PORT);
  685. ASSERT_TRUE(cli.is_valid());
  686. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  687. auto res = cli.Get(original);
  688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  689. // Expect the echoed target to exactly match the original path (order
  690. // preserved)
  691. EXPECT_EQ(res->body, original);
  692. }
  693. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  694. string chineseCharacters = U8("中国語");
  695. string russianCharacters = U8("дом");
  696. string brazilianCharacters = U8("óculos");
  697. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  698. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  699. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  700. "%D0%B4%D0%BE%D0%BC");
  701. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  702. }
  703. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  704. string unescapedCharacters = "-_.!~*'()";
  705. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  706. }
  707. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  708. string reservedCharacters = ";,/?:@&=+$";
  709. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  710. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  711. }
  712. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  713. string chineseCharacters = U8("中国語");
  714. string russianCharacters = U8("дом");
  715. string brazilianCharacters = U8("óculos");
  716. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  717. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  718. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  719. "%D0%B4%D0%BE%D0%BC");
  720. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  721. }
  722. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  723. // Issue #2082 use case: encoding path component with ampersand
  724. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  725. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  726. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  727. }
  728. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  729. string unescapedCharacters = "-_.!~*'()";
  730. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  731. }
  732. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  733. string reservedCharacters = ";,/?:@&=+$#";
  734. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  735. }
  736. TEST(EncodeUriTest, TestUTF8Characters) {
  737. string chineseCharacters = U8("中国語");
  738. string russianCharacters = U8("дом");
  739. string brazilianCharacters = U8("óculos");
  740. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  741. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  742. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  743. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  744. }
  745. TEST(EncodeUriTest, TestCompleteUri) {
  746. string uri =
  747. "https://example.com/path/to/resource?query=value&param=test#fragment";
  748. EXPECT_EQ(
  749. httplib::encode_uri(uri),
  750. "https://example.com/path/to/resource?query=value&param=test#fragment");
  751. }
  752. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  753. string uri =
  754. "https://example.com/path with spaces/file name.html?q=hello world";
  755. EXPECT_EQ(httplib::encode_uri(uri),
  756. "https://example.com/path%20with%20spaces/"
  757. "file%20name.html?q=hello%20world");
  758. }
  759. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  760. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  762. }
  763. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  764. string unescapedCharacters = "-_.!~*'()";
  765. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  766. }
  767. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  768. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  769. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  770. string encodedBrazilian = "%C3%B3culos";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  772. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  773. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  774. }
  775. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  776. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  777. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  778. "Piri Tommy Villiers - on & on");
  779. }
  780. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  781. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  782. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  783. }
  784. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  785. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  786. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  787. }
  788. TEST(DecodeUriTest, TestUTF8Characters) {
  789. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  790. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  791. string encodedBrazilian = "%C3%B3culos";
  792. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  793. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  794. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  795. }
  796. TEST(DecodeUriTest, TestCompleteUri) {
  797. string encodedUri = "https://example.com/path%20with%20spaces/"
  798. "file%20name.html?q=hello%20world";
  799. EXPECT_EQ(
  800. httplib::decode_uri(encodedUri),
  801. "https://example.com/path with spaces/file name.html?q=hello world");
  802. }
  803. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  804. string original =
  805. "https://example.com/path with spaces/file name.html?q=hello world";
  806. string encoded = httplib::encode_uri(original);
  807. string decoded = httplib::decode_uri(encoded);
  808. EXPECT_EQ(decoded, original);
  809. }
  810. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  811. // decode_uri is the inverse of encode_uri: an escaped reserved character
  812. // stays encoded so it is not promoted into a real delimiter, while
  813. // non-reserved escapes still decode (like JS decodeURI).
  814. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  815. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  816. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  817. "%3F%3A%40%26%3D%2B%24%2C%3B");
  818. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  819. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  820. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  821. "http://example.com/a%2Fb");
  822. // decode_uri_component still decodes the reserved character.
  823. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  824. }
  825. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  826. string original = "Piri Tommy Villiers - on & on";
  827. string encoded = httplib::encode_uri_component(original);
  828. string decoded = httplib::decode_uri_component(encoded);
  829. EXPECT_EQ(decoded, original);
  830. }
  831. TEST(TrimTests, TrimStringTests) {
  832. EXPECT_EQ("abc", detail::trim_copy("abc"));
  833. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  834. EXPECT_TRUE(detail::trim_copy("").empty());
  835. }
  836. TEST(AsciiTest, LocaleIndependentClassification) {
  837. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  838. // which consult the global C locale: std::isalnum(0xC5) can return true
  839. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  840. // helpers must classify every byte by the ASCII grammar alone.
  841. for (int i = 0; i < 256; i++) {
  842. auto c = static_cast<char>(i);
  843. auto is_digit = i >= '0' && i <= '9';
  844. auto is_upper = i >= 'A' && i <= 'Z';
  845. auto is_lower = i >= 'a' && i <= 'z';
  846. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  847. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  848. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  849. << "byte " << i;
  850. }
  851. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  852. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  853. // Non-ASCII bytes must be percent-encoded, never passed through as
  854. // alphanumeric.
  855. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  856. }
  857. TEST(FromCharsTest, Double) {
  858. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  859. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  860. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  861. auto parse = [](const std::string &s, double &v) {
  862. return detail::from_chars(s.data(), s.data() + s.size(), v);
  863. };
  864. double v = -1.0;
  865. // Representative quality values.
  866. EXPECT_EQ(parse("0", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.0);
  868. EXPECT_EQ(parse("1", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.8);
  872. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 0.001);
  874. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  875. EXPECT_DOUBLE_EQ(v, 1.0);
  876. // A missing integer or fractional part is tolerated.
  877. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.5);
  879. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  880. EXPECT_DOUBLE_EQ(v, 5.0);
  881. // Values outside [0, 1] still parse; the caller range-checks them.
  882. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  883. EXPECT_DOUBLE_EQ(v, 123.456);
  884. // Stops at the first byte that is not part of the number and reports where.
  885. std::string trailing = "0.9, text/html";
  886. auto r = parse(trailing, v);
  887. EXPECT_EQ(r.ec, std::errc{});
  888. EXPECT_DOUBLE_EQ(v, 0.9);
  889. EXPECT_EQ(*r.ptr, ',');
  890. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  891. // outright, and an 'e'/'E' simply ends the number.
  892. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  894. std::string exp_input = "1.5e3";
  895. r = parse(exp_input, v);
  896. EXPECT_EQ(r.ec, std::errc{});
  897. EXPECT_DOUBLE_EQ(v, 1.5);
  898. EXPECT_EQ(*r.ptr, 'e');
  899. // Invalid inputs.
  900. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  901. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  902. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  903. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  904. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  905. // Pathological but well-formed inputs must stay bounded (no overflow, no
  906. // out-of-bounds table access) and stay within [0, 1] for the caller.
  907. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  908. std::errc{});
  909. EXPECT_DOUBLE_EQ(v, 0.0);
  910. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  911. std::errc{});
  912. EXPECT_GE(v, 0.0);
  913. EXPECT_LE(v, 1.0);
  914. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  915. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  916. }
  917. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  918. // Simple case without quality values
  919. std::vector<std::string> result1;
  920. EXPECT_TRUE(detail::parse_accept_header(
  921. "text/html,application/json,text/plain", result1));
  922. EXPECT_EQ(result1.size(), 3U);
  923. EXPECT_EQ(result1[0], "text/html");
  924. EXPECT_EQ(result1[1], "application/json");
  925. EXPECT_EQ(result1[2], "text/plain");
  926. // With quality values
  927. std::vector<std::string> result2;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  930. EXPECT_EQ(result2.size(), 3U);
  931. EXPECT_EQ(result2[0], "application/json"); // highest q value
  932. EXPECT_EQ(result2[1], "text/html");
  933. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  934. }
  935. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  936. // Mixed with and without quality values
  937. std::vector<std::string> result;
  938. EXPECT_TRUE(detail::parse_accept_header(
  939. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  940. EXPECT_EQ(result.size(), 3U);
  941. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  942. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  943. EXPECT_EQ(result[2], "application/json"); // q=0.5
  944. }
  945. TEST(ParseAcceptHeaderTest, EdgeCases) {
  946. // Empty header
  947. std::vector<std::string> empty_result;
  948. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  949. EXPECT_TRUE(empty_result.empty());
  950. // Single type
  951. std::vector<std::string> single_result;
  952. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  953. EXPECT_EQ(single_result.size(), 1U);
  954. EXPECT_EQ(single_result[0], "application/json");
  955. // Wildcard types
  956. std::vector<std::string> wildcard_result;
  957. EXPECT_TRUE(detail::parse_accept_header(
  958. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  959. EXPECT_EQ(wildcard_result.size(), 3U);
  960. EXPECT_EQ(wildcard_result[0], "application/json");
  961. EXPECT_EQ(wildcard_result[1], "text/*");
  962. EXPECT_EQ(wildcard_result[2], "*/*");
  963. }
  964. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  965. // Common browser Accept header
  966. std::vector<std::string> browser_result;
  967. EXPECT_TRUE(
  968. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  969. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  970. browser_result));
  971. EXPECT_EQ(browser_result.size(), 6U);
  972. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  973. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  974. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  975. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  976. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  977. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  978. // API client header
  979. std::vector<std::string> api_result;
  980. EXPECT_TRUE(detail::parse_accept_header(
  981. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  982. api_result));
  983. EXPECT_EQ(api_result.size(), 3U);
  984. EXPECT_EQ(api_result[0], "application/json");
  985. EXPECT_EQ(api_result[1], "application/xml");
  986. EXPECT_EQ(api_result[2], "text/plain");
  987. }
  988. TEST(ParseAcceptHeaderTest, SpecialCases) {
  989. // Quality value with 3 decimal places
  990. std::vector<std::string> decimal_result;
  991. EXPECT_TRUE(detail::parse_accept_header(
  992. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  993. EXPECT_EQ(decimal_result.size(), 2U);
  994. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  995. EXPECT_EQ(decimal_result[1], "text/html");
  996. // Zero quality (should still be included but with lowest priority)
  997. std::vector<std::string> zero_q_result;
  998. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  999. zero_q_result));
  1000. EXPECT_EQ(zero_q_result.size(), 2U);
  1001. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1002. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1003. // No spaces around commas
  1004. std::vector<std::string> no_space_result;
  1005. EXPECT_TRUE(detail::parse_accept_header(
  1006. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1007. no_space_result));
  1008. EXPECT_EQ(no_space_result.size(), 3U);
  1009. EXPECT_EQ(no_space_result[0], "text/html");
  1010. EXPECT_EQ(no_space_result[1], "application/json");
  1011. EXPECT_EQ(no_space_result[2], "text/plain");
  1012. }
  1013. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1014. // Quality values always use '.' as the decimal separator, so parsing must
  1015. // not depend on the process locale. An embedding application may have
  1016. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1017. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1018. std::string saved = cur ? cur : "C";
  1019. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1020. "fr_FR.UTF-8"};
  1021. bool switched = false;
  1022. for (const auto loc : comma_locales) {
  1023. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1024. std::localeconv()->decimal_point[0] == ',') {
  1025. switched = true;
  1026. break;
  1027. }
  1028. }
  1029. if (!switched) {
  1030. std::setlocale(LC_NUMERIC, saved.c_str());
  1031. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1032. }
  1033. // The higher-weighted type appears later in the list, so a correct parse
  1034. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1035. // sensitive parse reads both weights as 0 and leaves the original order.
  1036. std::vector<std::string> result;
  1037. EXPECT_TRUE(detail::parse_accept_header(
  1038. "application/json;q=0.1,text/html;q=0.9", result));
  1039. ASSERT_EQ(result.size(), 2U);
  1040. EXPECT_EQ(result[0], "text/html");
  1041. EXPECT_EQ(result[1], "application/json");
  1042. std::setlocale(LC_NUMERIC, saved.c_str());
  1043. }
  1044. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1045. std::vector<std::string> result;
  1046. // Invalid quality value (> 1.0)
  1047. EXPECT_FALSE(
  1048. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1049. // Invalid quality value (< 0.0)
  1050. EXPECT_FALSE(
  1051. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1052. // Invalid quality value (not a number)
  1053. EXPECT_FALSE(detail::parse_accept_header(
  1054. "text/html;q=invalid,application/json", result));
  1055. // A valid numeric prefix does not make the entire quality value valid.
  1056. EXPECT_FALSE(detail::parse_accept_header(
  1057. "text/html;q=0.5junk,application/json", result));
  1058. // Empty quality value
  1059. EXPECT_FALSE(
  1060. detail::parse_accept_header("text/html;q=,application/json", result));
  1061. // Invalid media type format (no slash and not wildcard)
  1062. EXPECT_FALSE(
  1063. detail::parse_accept_header("invalidtype,application/json", result));
  1064. // Valid cases should still work
  1065. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "*/*");
  1068. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1069. EXPECT_EQ(result.size(), 1U);
  1070. EXPECT_EQ(result[0], "*");
  1071. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1072. EXPECT_EQ(result.size(), 1U);
  1073. EXPECT_EQ(result[0], "text/*");
  1074. }
  1075. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1076. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1077. // and must not be answered with 400 Bad Request.
  1078. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1079. struct {
  1080. const char *value;
  1081. std::vector<std::string> expected;
  1082. } cases[] = {
  1083. {",application/json", {"application/json"}},
  1084. {"text/html,", {"text/html"}},
  1085. {"text/html,,*/*", {"text/html", "*/*"}},
  1086. // An empty element may be spelled with whitespace in it
  1087. {"text/html, , application/json", {"text/html", "application/json"}},
  1088. // Nothing but empty elements is an empty list, which means the same
  1089. // thing as no Accept header at all
  1090. {",,,", {}},
  1091. // Quality values still apply across ignored empty elements
  1092. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1093. };
  1094. for (const auto &c : cases) {
  1095. std::vector<std::string> result;
  1096. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1097. << "value: " << c.value;
  1098. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1099. }
  1100. // An invalid entry is still rejected when empty elements surround it
  1101. std::vector<std::string> result;
  1102. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1103. }
  1104. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1105. // or ';' inside one does not end the list element or the parameter. Section
  1106. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1107. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1108. struct {
  1109. const char *value;
  1110. std::vector<std::string> expected;
  1111. } cases[] = {
  1112. {"text/html;profile=\"a,b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // A "q=" inside a quoted value is not the weight
  1115. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1116. {"text/html", "application/json"}},
  1117. // The weight after a quoted value still applies
  1118. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1119. {"application/json", "text/html"}},
  1120. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1121. {"application/json", "text/html"}},
  1122. {"text/html;profile=\"a\\\"b\",application/json",
  1123. {"text/html", "application/json"}},
  1124. // An escaped backslash does not escape the '"' after it
  1125. {"text/html;profile=\"a\\\\\",application/json",
  1126. {"text/html", "application/json"}},
  1127. };
  1128. for (const auto &c : cases) {
  1129. std::vector<std::string> result;
  1130. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1131. << "value: " << c.value;
  1132. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1133. }
  1134. }
  1135. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1136. Server svr;
  1137. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1138. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1139. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1140. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1141. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1142. res.set_content("ok", "text/plain");
  1143. });
  1144. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1145. EXPECT_TRUE(false);
  1146. res.set_content("bad request", "text/plain");
  1147. });
  1148. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1149. auto se = detail::scope_exit([&] {
  1150. svr.stop();
  1151. listen_thread.join();
  1152. ASSERT_FALSE(svr.is_running());
  1153. });
  1154. svr.wait_until_ready();
  1155. Client cli("localhost", PORT);
  1156. {
  1157. auto res = cli.Get(
  1158. "/accept_ok",
  1159. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::OK_200, res->status);
  1162. }
  1163. {
  1164. auto res = cli.Get("/accept_bad_request",
  1165. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1167. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1168. }
  1169. }
  1170. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1171. Server svr;
  1172. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1173. res.set_content("ok", "text/plain");
  1174. });
  1175. std::atomic<int> start_count{0};
  1176. std::atomic<bool> running_when_called{false};
  1177. svr.set_start_handler([&]() {
  1178. running_when_called = svr.is_running();
  1179. start_count++;
  1180. });
  1181. auto port = svr.bind_to_any_port(HOST);
  1182. std::thread t([&]() { svr.listen_after_bind(); });
  1183. auto se = detail::scope_exit([&] {
  1184. svr.stop();
  1185. t.join();
  1186. ASSERT_FALSE(svr.is_running());
  1187. });
  1188. svr.wait_until_ready();
  1189. // A successful request proves the accept loop is running, which the start
  1190. // handler precedes; so by now the handler must have run exactly once.
  1191. Client cli(HOST, port);
  1192. cli.set_connection_timeout(std::chrono::seconds(5));
  1193. auto res = cli.Get("/");
  1194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1195. EXPECT_EQ(StatusCode::OK_200, res->status);
  1196. EXPECT_EQ(1, start_count.load());
  1197. EXPECT_TRUE(running_when_called.load());
  1198. }
  1199. TEST(DivideTest, DivideStringTests) {
  1200. auto divide = [](const std::string &str, char d) {
  1201. std::string lhs;
  1202. std::string rhs;
  1203. detail::divide(str, d,
  1204. [&](const char *lhs_data, std::size_t lhs_size,
  1205. const char *rhs_data, std::size_t rhs_size) {
  1206. lhs.assign(lhs_data, lhs_size);
  1207. rhs.assign(rhs_data, rhs_size);
  1208. });
  1209. return std::make_pair(std::move(lhs), std::move(rhs));
  1210. };
  1211. {
  1212. const auto res = divide("", '=');
  1213. EXPECT_EQ(res.first, "");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("=", '=');
  1218. EXPECT_EQ(res.first, "");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide(" ", '=');
  1223. EXPECT_EQ(res.first, " ");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("a", '=');
  1228. EXPECT_EQ(res.first, "a");
  1229. EXPECT_EQ(res.second, "");
  1230. }
  1231. {
  1232. const auto res = divide("a=", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "");
  1235. }
  1236. {
  1237. const auto res = divide("=b", '=');
  1238. EXPECT_EQ(res.first, "");
  1239. EXPECT_EQ(res.second, "b");
  1240. }
  1241. {
  1242. const auto res = divide("a=b", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b");
  1245. }
  1246. {
  1247. const auto res = divide("a=b=", '=');
  1248. EXPECT_EQ(res.first, "a");
  1249. EXPECT_EQ(res.second, "b=");
  1250. }
  1251. {
  1252. const auto res = divide("a=b=c", '=');
  1253. EXPECT_EQ(res.first, "a");
  1254. EXPECT_EQ(res.second, "b=c");
  1255. }
  1256. }
  1257. TEST(SplitTest, ParseQueryString) {
  1258. string s = "key1=val1&key2=val2&key3=val3";
  1259. Params dic;
  1260. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1261. [&](const char *b, const char *e) {
  1262. string key, val;
  1263. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1264. if (key.empty()) {
  1265. key.assign(b2, e2);
  1266. } else {
  1267. val.assign(b2, e2);
  1268. }
  1269. });
  1270. dic.emplace(key, val);
  1271. });
  1272. EXPECT_EQ("val1", dic.find("key1")->second);
  1273. EXPECT_EQ("val2", dic.find("key2")->second);
  1274. EXPECT_EQ("val3", dic.find("key3")->second);
  1275. }
  1276. TEST(SplitTest, ParseInvalidQueryTests) {
  1277. {
  1278. string s = " ";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. {
  1284. string s = " = =";
  1285. Params dict;
  1286. detail::parse_query_text(s, dict);
  1287. EXPECT_TRUE(dict.empty());
  1288. }
  1289. }
  1290. TEST(ParseQueryTest, ParseQueryString) {
  1291. {
  1292. std::string s = "key1=val1&key2=val2&key3=val3";
  1293. Params dic;
  1294. detail::parse_query_text(s, dic);
  1295. EXPECT_EQ("val1", dic.find("key1")->second);
  1296. EXPECT_EQ("val2", dic.find("key2")->second);
  1297. EXPECT_EQ("val3", dic.find("key3")->second);
  1298. }
  1299. {
  1300. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1301. Params dic;
  1302. detail::parse_query_text(s, dic);
  1303. EXPECT_EQ("", dic.find("key1")->second);
  1304. EXPECT_EQ("val1", dic.find("key2")->second);
  1305. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1306. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1307. }
  1308. }
  1309. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1310. Params dic;
  1311. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1312. dic.emplace("key1", "val1");
  1313. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1314. dic.emplace("key2", "val2");
  1315. dic.emplace("key3", "val3");
  1316. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1317. }
  1318. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1319. Params params;
  1320. params.emplace("a", "1");
  1321. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1322. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1323. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1324. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1325. // Long enough to overflow the stack when matched with std::regex.
  1326. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1327. EXPECT_EQ("/p?" + long_query + "&a=1",
  1328. append_query_params("/p?" + long_query, params));
  1329. }
  1330. // Joins every entry of a Headers or Params into "key=value " so a whole
  1331. // traversal can be compared in one assertion. Both are instantiations of the
  1332. // same insertion-ordered container, so one helper serves both.
  1333. template <typename Map> static std::string entries_to_string(const Map &m) {
  1334. std::string s;
  1335. for (const auto &entry : m) {
  1336. s += entry.first + "=" + entry.second + " ";
  1337. }
  1338. return s;
  1339. }
  1340. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1341. // Params used to be a std::multimap, which sorted by name and handed the
  1342. // caller's query back alphabetised. A client signing its query string could
  1343. // not reproduce the order it asked for.
  1344. Params dic;
  1345. dic.emplace("zulu", "1");
  1346. dic.emplace("alpha", "2");
  1347. dic.emplace("mike", "3");
  1348. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1349. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1350. }
  1351. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1352. Params dic;
  1353. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1354. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1355. }
  1356. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1357. Request req;
  1358. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1359. req.params);
  1360. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1361. EXPECT_EQ("first", req.get_param_value("tag"));
  1362. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1363. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1364. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1365. EXPECT_EQ("", req.get_param_value("tag", 3));
  1366. }
  1367. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1368. // Params shares its container with Headers, which matches field names
  1369. // case-insensitively. Parameter names must not pick that up.
  1370. Params dic;
  1371. dic.emplace("Key", "upper");
  1372. dic.emplace("key", "lower");
  1373. EXPECT_EQ(2U, dic.size());
  1374. EXPECT_EQ(1U, dic.count("Key"));
  1375. EXPECT_EQ(1U, dic.count("key"));
  1376. EXPECT_EQ("upper", dic.find("Key")->second);
  1377. EXPECT_EQ("lower", dic.find("key")->second);
  1378. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1379. }
  1380. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1381. Server svr;
  1382. std::string order;
  1383. svr.Get("/order", [&](const Request &req, Response &res) {
  1384. order = entries_to_string(req.params);
  1385. res.set_content("ok", "text/plain");
  1386. });
  1387. auto port = svr.bind_to_any_port(HOST);
  1388. thread t = thread([&] { svr.listen_after_bind(); });
  1389. auto se = detail::scope_exit([&] {
  1390. svr.stop();
  1391. t.join();
  1392. ASSERT_FALSE(svr.is_running());
  1393. });
  1394. svr.wait_until_ready();
  1395. Client cli(HOST, port);
  1396. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1397. ASSERT_TRUE(res);
  1398. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1399. }
  1400. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1401. Server svr;
  1402. std::string field_order, file_order;
  1403. svr.Post("/order", [&](const Request &req, Response &res) {
  1404. for (const auto &field : req.form.fields) {
  1405. field_order += field.first + "=" + field.second.content + " ";
  1406. }
  1407. for (const auto &file : req.form.files) {
  1408. file_order += file.first + "=" + file.second.filename + " ";
  1409. }
  1410. res.set_content("ok", "text/plain");
  1411. });
  1412. auto port = svr.bind_to_any_port(HOST);
  1413. thread t = thread([&] { svr.listen_after_bind(); });
  1414. auto se = detail::scope_exit([&] {
  1415. svr.stop();
  1416. t.join();
  1417. ASSERT_FALSE(svr.is_running());
  1418. });
  1419. svr.wait_until_ready();
  1420. UploadFormDataItems items = {
  1421. {"zulu", "1", "", ""},
  1422. {"alpha", "2", "", ""},
  1423. {"mike", "3", "", ""},
  1424. {"zebra", "z", "z.txt", "text/plain"},
  1425. {"apple", "a", "a.txt", "text/plain"},
  1426. };
  1427. Client cli(HOST, port);
  1428. auto res = cli.Post("/order", items);
  1429. ASSERT_TRUE(res);
  1430. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1431. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1432. }
  1433. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1434. Server svr;
  1435. std::vector<std::string> values;
  1436. std::string first, second, out_of_range, order;
  1437. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1438. values = req.form.get_fields("tag");
  1439. first = req.form.get_field("tag", 0);
  1440. second = req.form.get_field("tag", 1);
  1441. out_of_range = req.form.get_field("tag", 2);
  1442. for (const auto &field : req.form.fields) {
  1443. order += field.first + "=" + field.second.content + " ";
  1444. }
  1445. res.set_content("ok", "text/plain");
  1446. });
  1447. auto port = svr.bind_to_any_port(HOST);
  1448. thread t = thread([&] { svr.listen_after_bind(); });
  1449. auto se = detail::scope_exit([&] {
  1450. svr.stop();
  1451. t.join();
  1452. ASSERT_FALSE(svr.is_running());
  1453. });
  1454. svr.wait_until_ready();
  1455. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1456. // not adjacent in the container.
  1457. UploadFormDataItems items = {
  1458. {"tag", "first", "", ""},
  1459. {"other", "x", "", ""},
  1460. {"tag", "second", "", ""},
  1461. };
  1462. Client cli(HOST, port);
  1463. auto res = cli.Post("/repeated", items);
  1464. ASSERT_TRUE(res);
  1465. ASSERT_EQ(2U, values.size());
  1466. EXPECT_EQ("first", values[0]);
  1467. EXPECT_EQ("second", values[1]);
  1468. EXPECT_EQ("first", first);
  1469. EXPECT_EQ("second", second);
  1470. // std::multimap already kept entries sharing a name in insertion order, so
  1471. // everything above passes without this change too. The whole traversal is
  1472. // what tells the two apart: sorting by name would hoist "other" to the front
  1473. // and the two "tag" parts would end up adjacent.
  1474. EXPECT_EQ("tag=first other=x tag=second ", order);
  1475. // Advancing past the last entry of a name used to run off the container;
  1476. // the container's saturating increment makes it return the default instead.
  1477. EXPECT_EQ("", out_of_range);
  1478. }
  1479. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1480. Server svr;
  1481. std::string file_names;
  1482. svr.Post("/upload", [&](const Request &req, Response &res) {
  1483. for (const auto &file : req.form.files) {
  1484. file_names += file.first + "|" + file.second.filename + " ";
  1485. }
  1486. res.set_content("ok", "text/plain");
  1487. });
  1488. auto port = svr.bind_to_any_port(HOST);
  1489. thread t = thread([&] { svr.listen_after_bind(); });
  1490. auto se = detail::scope_exit([&] {
  1491. svr.stop();
  1492. t.join();
  1493. ASSERT_FALSE(svr.is_running());
  1494. });
  1495. svr.wait_until_ready();
  1496. // A trailing backslash would otherwise escape the closing quote.
  1497. UploadFormDataItems items = {
  1498. {"dir\\", "x", "a.txt", "text/plain"},
  1499. {"b", "y", "a\\\\b.txt", "text/plain"},
  1500. };
  1501. Client cli(HOST, port);
  1502. auto res = cli.Post("/upload", items);
  1503. ASSERT_TRUE(res);
  1504. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1505. }
  1506. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1507. // Server::read_content() keeps a FormFields::iterator alive across the
  1508. // content callbacks that fill the part it points at. The container is
  1509. // vector-backed, so a later emplace can reallocate and invalidate an older
  1510. // iterator; 64 parts grow the vector through seven reallocations, which
  1511. // checks that every part's content still lands in its own entry.
  1512. const size_t part_count = 64;
  1513. // One formula for both the parts sent and the values expected back, so the
  1514. // two cannot drift apart.
  1515. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1516. auto content_of = [](size_t i) {
  1517. return std::string(64, static_cast<char>('a' + (i % 26)));
  1518. };
  1519. Server svr;
  1520. std::vector<std::pair<std::string, std::string>> received;
  1521. svr.Post("/many", [&](const Request &req, Response &res) {
  1522. for (const auto &field : req.form.fields) {
  1523. received.emplace_back(field.first, field.second.content);
  1524. }
  1525. res.set_content("ok", "text/plain");
  1526. });
  1527. auto port = svr.bind_to_any_port(HOST);
  1528. thread t = thread([&] { svr.listen_after_bind(); });
  1529. auto se = detail::scope_exit([&] {
  1530. svr.stop();
  1531. t.join();
  1532. ASSERT_FALSE(svr.is_running());
  1533. });
  1534. svr.wait_until_ready();
  1535. UploadFormDataItems items;
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. items.push_back({name_of(i), content_of(i), "", ""});
  1538. }
  1539. Client cli(HOST, port);
  1540. auto res = cli.Post("/many", items);
  1541. ASSERT_TRUE(res);
  1542. ASSERT_EQ(part_count, received.size());
  1543. for (size_t i = 0; i < part_count; i++) {
  1544. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1545. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1546. }
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1549. string content_type = "multipart/form-data; boundary=something";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "something");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1556. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1557. string boundary;
  1558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1559. EXPECT_TRUE(ret);
  1560. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1561. }
  1562. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1563. string content_type =
  1564. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1565. string boundary;
  1566. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1567. EXPECT_TRUE(ret);
  1568. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1569. }
  1570. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1571. string content_type =
  1572. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1573. string boundary;
  1574. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1575. EXPECT_TRUE(ret);
  1576. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1577. }
  1578. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1579. const string boundary(70, 'a');
  1580. string content_type = "multipart/form-data; boundary=" + boundary;
  1581. string parsed;
  1582. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1583. EXPECT_TRUE(ret);
  1584. EXPECT_EQ(parsed, boundary);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1587. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1588. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1589. string parsed;
  1590. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1591. EXPECT_FALSE(ret);
  1592. }
  1593. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1594. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1595. // is 72 characters on the wire and still valid.
  1596. const string boundary(70, 'a');
  1597. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1598. string parsed;
  1599. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1600. EXPECT_EQ(parsed, boundary);
  1601. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1602. parsed.clear();
  1603. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1604. }
  1605. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1606. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1607. // The parameter parser must not treat that '=' as the key/value separator.
  1608. string content_type =
  1609. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1610. "charset=UTF-8";
  1611. string parsed;
  1612. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1613. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1614. }
  1615. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1616. // A ';' inside the quoted-string is part of the value, not a parameter
  1617. // separator, so it must not truncate the boundary.
  1618. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1619. string parsed;
  1620. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1621. EXPECT_EQ(parsed, "a;b");
  1622. }
  1623. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1624. string parsed;
  1625. EXPECT_TRUE(detail::parse_multipart_boundary(
  1626. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1627. EXPECT_EQ("a\\b", parsed);
  1628. EXPECT_TRUE(detail::parse_multipart_boundary(
  1629. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1630. EXPECT_EQ("a\"b", parsed);
  1631. }
  1632. TEST(ParseDispositionParamsTest, QuotedValues) {
  1633. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1634. // ';' and '=' are ordinary characters inside one.
  1635. struct {
  1636. const char *value;
  1637. std::vector<std::pair<const char *, const char *>> expected;
  1638. } cases[] = {
  1639. {"name=\"file1\"; filename=\"a.txt\"",
  1640. {{"name", "file1"}, {"filename", "a.txt"}}},
  1641. // Whitespace around '=' and ';' is still trimmed
  1642. {"name=\"file2\" ;filename = \"a.html\"",
  1643. {{"name", "file2"}, {"filename", "a.html"}}},
  1644. // '=' inside the value used to leave only the text after the last one
  1645. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1646. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1647. {"name=\"x=y\"", {{"name", "x=y"}}},
  1648. // ';' inside the value used to truncate the pair and leave a bogus one
  1649. {"name=\"file3\"; filename=\"a;b.txt\"",
  1650. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1651. // An unquoted value keeps working, and so does filename*
  1652. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1653. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1654. // A parameter with no key is dropped rather than turned into one whose
  1655. // key is the value
  1656. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1657. // An escaped quote does not end the value
  1658. {"name=\"a\\\"; filename=evil.php\"",
  1659. {{"name", "a\"; filename=evil.php"}}},
  1660. // Other backslashes, as in a Windows path, are kept
  1661. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1662. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1663. };
  1664. for (const auto &c : cases) {
  1665. Params params;
  1666. detail::parse_disposition_params(c.value, params);
  1667. for (const auto &kv : c.expected) {
  1668. auto it = params.find(kv.first);
  1669. ASSERT_NE(it, params.end())
  1670. << "value: " << c.value << ", key: " << kv.first;
  1671. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1672. }
  1673. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1674. }
  1675. }
  1676. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1677. Server svr;
  1678. std::string filename;
  1679. std::string content;
  1680. svr.Post("/upload", [&](const Request &req, Response &) {
  1681. const auto &file = req.form.get_file("file");
  1682. filename = file.filename;
  1683. content = file.content;
  1684. });
  1685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1686. auto se = detail::scope_exit([&] {
  1687. svr.stop();
  1688. thread.join();
  1689. ASSERT_FALSE(svr.is_running());
  1690. });
  1691. svr.wait_until_ready();
  1692. std::string body = "--B\r\n"
  1693. "Content-Disposition: form-data; name=\"file\"; "
  1694. "filename=\"a.txt\"\r\n"
  1695. "Content-Type: text/plain\r\n"
  1696. "\r\n"
  1697. "hello\r\n"
  1698. "--B--\r\n";
  1699. Client cli(HOST, PORT);
  1700. auto res = cli.Post(
  1701. "/upload",
  1702. [&](size_t offset, DataSink &sink) {
  1703. if (offset < body.size()) {
  1704. sink.write(&body[offset], 1);
  1705. } else {
  1706. sink.done();
  1707. }
  1708. return true;
  1709. },
  1710. "multipart/form-data; boundary=B");
  1711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1712. EXPECT_EQ(StatusCode::OK_200, res->status);
  1713. EXPECT_EQ("a.txt", filename);
  1714. EXPECT_EQ("hello", content);
  1715. }
  1716. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1717. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1718. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1719. Server svr;
  1720. std::string field_value, file_name, file_filename;
  1721. bool has_field = false, has_file = false;
  1722. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1723. has_field = req.form.has_field("x=y");
  1724. field_value = req.form.get_field("x=y");
  1725. has_file = req.form.has_file("file1");
  1726. const auto &file = req.form.get_file("file1");
  1727. file_name = file.name;
  1728. file_filename = file.filename;
  1729. res.set_content("ok", "text/plain");
  1730. });
  1731. auto port = svr.bind_to_any_port(HOST);
  1732. thread t = thread([&] { svr.listen_after_bind(); });
  1733. auto se = detail::scope_exit([&] {
  1734. svr.stop();
  1735. t.join();
  1736. ASSERT_FALSE(svr.is_running());
  1737. });
  1738. svr.wait_until_ready();
  1739. UploadFormDataItems items = {
  1740. {"x=y", "field-value", "", ""},
  1741. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1742. };
  1743. Client cli(HOST, port);
  1744. auto res = cli.Post("/quoted", items);
  1745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1746. ASSERT_EQ(StatusCode::OK_200, res->status);
  1747. EXPECT_TRUE(has_field);
  1748. EXPECT_EQ("field-value", field_value);
  1749. EXPECT_TRUE(has_file);
  1750. EXPECT_EQ("file1", file_name);
  1751. EXPECT_EQ("a;b=report.pdf", file_filename);
  1752. }
  1753. TEST(GetHeaderValueTest, DefaultValue) {
  1754. Headers headers = {{"Dummy", "Dummy"}};
  1755. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1756. EXPECT_STREQ("text/plain", val);
  1757. }
  1758. TEST(GetHeaderValueTest, DefaultValueInt) {
  1759. Headers headers = {{"Dummy", "Dummy"}};
  1760. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1761. EXPECT_EQ(100ull, val);
  1762. }
  1763. TEST(GetHeaderValueTest, RegularValue) {
  1764. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1765. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1766. EXPECT_STREQ("text/html", val);
  1767. }
  1768. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1769. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1770. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1771. EXPECT_STREQ("text/html", val);
  1772. }
  1773. TEST(GetHeaderValueTest, SetContent) {
  1774. Response res;
  1775. res.set_content("html", "text/html");
  1776. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1777. res.set_content("text", "text/plain");
  1778. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1779. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1780. }
  1781. TEST(GetHeaderValueTest, RegularValueInt) {
  1782. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1784. EXPECT_EQ(100ull, val);
  1785. }
  1786. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1787. Headers headers = {{"Content-Length", "x"}};
  1788. auto is_invalid_value = false;
  1789. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1790. is_invalid_value);
  1791. EXPECT_EQ(0ull, val);
  1792. EXPECT_TRUE(is_invalid_value);
  1793. }
  1794. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1795. // An all-digit value that overflows size_t must be reported as invalid, not
  1796. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1797. // a large length to a small one on 32-bit builds, leaving the framing length
  1798. // wrong while is_invalid_value stayed false.
  1799. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1800. auto is_invalid_value = false;
  1801. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_TRUE(is_invalid_value);
  1804. // A well-formed length is unaffected.
  1805. Headers ok = {{"Content-Length", "1234"}};
  1806. is_invalid_value = false;
  1807. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1808. is_invalid_value);
  1809. EXPECT_EQ(1234ull, val);
  1810. EXPECT_FALSE(is_invalid_value);
  1811. }
  1812. TEST(GetHeaderValueTest, Range) {
  1813. {
  1814. Headers headers = {make_range_header({{1, -1}})};
  1815. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1816. EXPECT_STREQ("bytes=1-", val);
  1817. }
  1818. {
  1819. Headers headers = {make_range_header({{-1, 1}})};
  1820. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1821. EXPECT_STREQ("bytes=-1", val);
  1822. }
  1823. {
  1824. Headers headers = {make_range_header({{1, 10}})};
  1825. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1826. EXPECT_STREQ("bytes=1-10", val);
  1827. }
  1828. {
  1829. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1830. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1831. EXPECT_STREQ("bytes=1-10, 100-", val);
  1832. }
  1833. {
  1834. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1835. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1836. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1837. }
  1838. {
  1839. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1840. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1841. EXPECT_STREQ("bytes=0-0, -1", val);
  1842. }
  1843. }
  1844. TEST(BearerTokenAuthTest, SchemeValidation) {
  1845. // A value shorter than "Bearer " must not throw from the fixed-length
  1846. // substr, and a non-Bearer scheme must not be reported as a token.
  1847. struct {
  1848. const char *value;
  1849. const char *expected;
  1850. } cases[] = {
  1851. {"x", ""},
  1852. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1853. {"Bearer abc123", "abc123"},
  1854. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1855. };
  1856. for (const auto &c : cases) {
  1857. Request req;
  1858. req.set_header("Authorization", c.value);
  1859. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1860. }
  1861. }
  1862. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1863. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1864. // to depend on the standard library (libstdc++ handed back duplicates in
  1865. // reverse insertion order, libc++ in insertion order).
  1866. Request req;
  1867. req.set_header("Accept-Encoding", "gzip");
  1868. req.set_header("Accept-Encoding", "deflate");
  1869. req.set_header("Accept-Encoding", "br");
  1870. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1871. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1872. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1873. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1874. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1875. }
  1876. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1877. Request req;
  1878. req.set_header("X-Test", "only");
  1879. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1880. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1881. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1882. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1883. }
  1884. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1885. Request req;
  1886. req.set_header("X-First", "1");
  1887. req.set_header("X-Test", "2");
  1888. req.params.emplace("first", "1");
  1889. req.params.emplace("test", "2");
  1890. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1891. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1892. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1893. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1894. // The second one is negative when read as a signed value
  1895. const auto max_id = (std::numeric_limits<size_t>::max)();
  1896. for (auto id : {max_id / 2, max_id}) {
  1897. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1898. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1899. EXPECT_EQ("", req.get_param_value("test", id));
  1900. EXPECT_EQ("", req.form.get_field("test", id));
  1901. EXPECT_EQ("", req.form.get_file("test", id).content);
  1902. }
  1903. }
  1904. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1905. Headers headers;
  1906. headers.emplace("Host", "example.com");
  1907. headers.emplace("Accept-Encoding", "gzip");
  1908. headers.emplace("User-Agent", "test");
  1909. headers.emplace("Accept-Encoding", "deflate");
  1910. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1911. "Accept-Encoding=deflate ",
  1912. entries_to_string(headers));
  1913. }
  1914. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1915. Headers headers = {{"Content-Type", "text/html"},
  1916. {"CONTENT-TYPE", "text/xml"}};
  1917. EXPECT_EQ(2U, headers.count("content-type"));
  1918. auto it = headers.find("content-type");
  1919. ASSERT_TRUE(it != headers.end());
  1920. EXPECT_EQ("text/html", it->second);
  1921. }
  1922. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1923. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1924. // drop only those fields and leave everything positioned between them.
  1925. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1926. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1927. auto rng = headers.equal_range("a");
  1928. headers.erase(rng.first, rng.second);
  1929. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1932. Headers headers = {
  1933. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1934. EXPECT_EQ(3U, headers.erase("A"));
  1935. EXPECT_EQ(0U, headers.count("A"));
  1936. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1937. }
  1938. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1939. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1940. headers.emplace_front("Host", "example.com");
  1941. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1942. entries_to_string(headers));
  1943. }
  1944. TEST(ParseHeaderValueTest, Range) {
  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", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1960. EXPECT_TRUE(ret);
  1961. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1962. }
  1963. {
  1964. Ranges ranges;
  1965. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1966. EXPECT_FALSE(ret);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1971. EXPECT_TRUE(ret);
  1972. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. auto ret =
  1977. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1980. }
  1981. {
  1982. Ranges 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=0", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1990. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1996. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1997. EXPECT_FALSE(
  1998. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1999. EXPECT_TRUE(ranges.empty());
  2000. }
  2001. {
  2002. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2003. // remainder of the representation, so it stays accepted.
  2004. Ranges ranges;
  2005. auto ret =
  2006. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2007. EXPECT_TRUE(ret);
  2008. ASSERT_EQ(1u, ranges.size());
  2009. EXPECT_EQ(0, ranges[0].first);
  2010. EXPECT_EQ(-1, ranges[0].second);
  2011. }
  2012. // RFC 9110 14.1: range unit names are case-insensitive.
  2013. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2014. Ranges ranges;
  2015. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2016. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2017. }
  2018. }
  2019. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2020. Request req;
  2021. req.set_header("Accept-Encoding", "gzip");
  2022. Response res;
  2023. res.set_header("Content-Type", "text/plain");
  2024. auto ret = detail::encoding_type(req, res);
  2025. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2026. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2027. #else
  2028. EXPECT_TRUE(ret == detail::EncodingType::None);
  2029. #endif
  2030. }
  2031. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2032. Request req;
  2033. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2034. Response res;
  2035. res.set_header("Content-Type", "text/plain");
  2036. auto ret = detail::encoding_type(req, res);
  2037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2043. #else
  2044. EXPECT_TRUE(ret == detail::EncodingType::None);
  2045. #endif
  2046. }
  2047. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2048. Request req;
  2049. req.set_header("Accept-Encoding",
  2050. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2051. Response res;
  2052. res.set_header("Content-Type", "text/plain");
  2053. auto ret = detail::encoding_type(req, res);
  2054. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2055. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2056. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2060. #else
  2061. EXPECT_TRUE(ret == detail::EncodingType::None);
  2062. #endif
  2063. }
  2064. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2065. // All supported encodings rejected with q=0 should return None
  2066. Request req;
  2067. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2068. Response res;
  2069. res.set_header("Content-Type", "text/plain");
  2070. auto ret = detail::encoding_type(req, res);
  2071. EXPECT_TRUE(ret == detail::EncodingType::None);
  2072. }
  2073. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2074. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2075. Request req;
  2076. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2077. Response res;
  2078. res.set_header("Content-Type", "text/plain");
  2079. auto ret = detail::encoding_type(req, res);
  2080. EXPECT_TRUE(ret == detail::EncodingType::None);
  2081. }
  2082. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2083. Request req;
  2084. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2085. Response res;
  2086. res.set_header("Content-Type", "text/plain");
  2087. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2088. }
  2089. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2090. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2091. Request req;
  2092. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2093. Response res;
  2094. res.set_header("Content-Type", "text/plain");
  2095. auto ret = detail::encoding_type(req, res);
  2096. EXPECT_TRUE(ret == detail::EncodingType::None);
  2097. }
  2098. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2099. // RFC 7231: Accept-Encoding values are case-insensitive
  2100. Request req;
  2101. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2102. Response res;
  2103. res.set_header("Content-Type", "text/plain");
  2104. auto ret = detail::encoding_type(req, res);
  2105. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2106. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2107. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2108. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2109. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2110. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2111. #else
  2112. EXPECT_TRUE(ret == detail::EncodingType::None);
  2113. #endif
  2114. }
  2115. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2116. // q value should determine priority, not hardcoded order
  2117. Request req;
  2118. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2119. Response res;
  2120. res.set_header("Content-Type", "text/plain");
  2121. auto ret = detail::encoding_type(req, res);
  2122. // gzip has highest q=1.0, so it should be selected even though
  2123. // br and zstd are also supported
  2124. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2125. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2126. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2127. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2128. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2129. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2130. #else
  2131. EXPECT_TRUE(ret == detail::EncodingType::None);
  2132. #endif
  2133. }
  2134. TEST(BufferStreamTest, read) {
  2135. detail::BufferStream strm1;
  2136. Stream &strm = strm1;
  2137. EXPECT_EQ(5, strm.write("hello"));
  2138. char buf[512];
  2139. EXPECT_EQ(2, strm.read(buf, 2));
  2140. EXPECT_EQ('h', buf[0]);
  2141. EXPECT_EQ('e', buf[1]);
  2142. EXPECT_EQ(2, strm.read(buf, 2));
  2143. EXPECT_EQ('l', buf[0]);
  2144. EXPECT_EQ('l', buf[1]);
  2145. EXPECT_EQ(1, strm.read(buf, 1));
  2146. EXPECT_EQ('o', buf[0]);
  2147. EXPECT_EQ(0, strm.read(buf, 1));
  2148. }
  2149. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2150. auto host = "www.httpwatch.com";
  2151. auto ip = hosted_at(host);
  2152. EXPECT_EQ("23.96.13.243", ip);
  2153. std::vector<std::string> addrs;
  2154. hosted_at(host, addrs);
  2155. EXPECT_EQ(1u, addrs.size());
  2156. }
  2157. #if 0 // It depends on each test environment...
  2158. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2159. auto host = "www.youtube.com";
  2160. std::vector<std::string> addrs;
  2161. hosted_at(host, addrs);
  2162. EXPECT_EQ(20u, addrs.size());
  2163. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2164. EXPECT_TRUE(it != addrs.end());
  2165. }
  2166. #endif
  2167. class ChunkedEncodingTest : public ::testing::Test {
  2168. protected:
  2169. ChunkedEncodingTest()
  2170. : cli_(HOST, PORT)
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. ,
  2173. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2174. #endif
  2175. {
  2176. cli_.set_connection_timeout(2);
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. cli_.enable_server_certificate_verification(false);
  2179. #endif
  2180. }
  2181. virtual void SetUp() {
  2182. read_file("./image.jpg", image_data_);
  2183. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2184. res.set_content("Hello World!", "text/plain");
  2185. });
  2186. svr_.Get(
  2187. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2188. res.set_chunked_content_provider(
  2189. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2190. size_t remaining = image_data_.size() - offset;
  2191. if (remaining == 0) {
  2192. sink.done();
  2193. } else {
  2194. constexpr size_t CHUNK_SIZE = 1024;
  2195. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2196. sink.write(&image_data_[offset], send_size);
  2197. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2198. }
  2199. return true;
  2200. });
  2201. });
  2202. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2203. svr_.wait_until_ready();
  2204. }
  2205. virtual void TearDown() {
  2206. svr_.stop();
  2207. if (!request_threads_.empty()) {
  2208. std::this_thread::sleep_for(std::chrono::seconds(1));
  2209. for (auto &t : request_threads_) {
  2210. t.join();
  2211. }
  2212. }
  2213. t_.join();
  2214. }
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. SSLClient cli_;
  2217. SSLServer svr_;
  2218. #else
  2219. Client cli_;
  2220. Server svr_;
  2221. #endif
  2222. thread t_;
  2223. std::vector<thread> request_threads_;
  2224. std::string image_data_;
  2225. };
  2226. TEST_F(ChunkedEncodingTest, NormalGet) {
  2227. auto res = cli_.Get("/chunked");
  2228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2229. std::string out;
  2230. read_file("./image.jpg", out);
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. EXPECT_EQ(out, res->body);
  2233. }
  2234. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2235. std::string body;
  2236. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2237. body.append(data, data_length);
  2238. return true;
  2239. });
  2240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2241. std::string out;
  2242. read_file("./image.jpg", out);
  2243. EXPECT_EQ(StatusCode::OK_200, res->status);
  2244. EXPECT_EQ(out, body);
  2245. }
  2246. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2247. std::string body;
  2248. auto res = cli_.Get(
  2249. "/chunked",
  2250. [&](const Response &response) {
  2251. EXPECT_EQ(StatusCode::OK_200, response.status);
  2252. return true;
  2253. },
  2254. [&](const char *data, size_t data_length) {
  2255. body.append(data, data_length);
  2256. return true;
  2257. });
  2258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2259. std::string out;
  2260. read_file("./image.jpg", out);
  2261. EXPECT_EQ(StatusCode::OK_200, res->status);
  2262. EXPECT_EQ(out, body);
  2263. }
  2264. TEST(RangeTest, FromHTTPBin_Online) {
  2265. auto host = "httpbingo.org";
  2266. auto path = std::string{"/range/32"};
  2267. #ifdef CPPHTTPLIB_SSL_ENABLED
  2268. auto port = 443;
  2269. SSLClient cli(host, port);
  2270. #else
  2271. auto port = 80;
  2272. Client cli(host, port);
  2273. #endif
  2274. cli.set_connection_timeout(5);
  2275. {
  2276. auto res = cli.Get(path);
  2277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2278. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2279. EXPECT_EQ(StatusCode::OK_200, res->status);
  2280. }
  2281. {
  2282. Headers headers = {make_range_header({{1, -1}})};
  2283. auto res = cli.Get(path, headers);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2287. }
  2288. {
  2289. Headers headers = {make_range_header({{1, 10}})};
  2290. auto res = cli.Get(path, headers);
  2291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2292. EXPECT_EQ("bcdefghijk", res->body);
  2293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2294. }
  2295. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2296. // entire resource, while the original httpbin returned 200. Both are
  2297. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2298. {
  2299. Headers headers = {make_range_header({{0, 31}})};
  2300. auto res = cli.Get(path, headers);
  2301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2302. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2303. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2304. res->status == StatusCode::PartialContent_206);
  2305. }
  2306. {
  2307. Headers headers = {make_range_header({{0, -1}})};
  2308. auto res = cli.Get(path, headers);
  2309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2310. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2311. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2312. res->status == StatusCode::PartialContent_206);
  2313. }
  2314. // go-httpbin returns 206 with clamped range for over-range requests,
  2315. // while the original httpbin returned 416. Both behaviors are observed
  2316. // in real servers, so we only verify the request succeeds.
  2317. {
  2318. Headers headers = {make_range_header({{0, 32}})};
  2319. auto res = cli.Get(path, headers);
  2320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2321. }
  2322. }
  2323. TEST(RangeTest, IgnoredForPost) {
  2324. Server svr;
  2325. svr.Post("/", [](const Request &, Response &res) {
  2326. res.set_content("abcdefg", "text/plain");
  2327. });
  2328. auto port = svr.bind_to_any_port(HOST);
  2329. ASSERT_GT(port, 0);
  2330. thread t = thread([&] { svr.listen_after_bind(); });
  2331. auto se = detail::scope_exit([&] {
  2332. svr.stop();
  2333. t.join();
  2334. ASSERT_FALSE(svr.is_running());
  2335. });
  2336. svr.wait_until_ready();
  2337. Client cli(HOST, port);
  2338. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2339. auto res = cli.Post("/", Headers{{"Range", range}});
  2340. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2341. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2342. EXPECT_EQ("abcdefg", res->body) << range;
  2343. }
  2344. }
  2345. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2346. auto host = "unresolvableaddress.local";
  2347. auto path = std::string{"/"};
  2348. #ifdef CPPHTTPLIB_SSL_ENABLED
  2349. auto port = 443;
  2350. SSLClient cli(host, port);
  2351. #else
  2352. auto port = 80;
  2353. Client cli(host, port);
  2354. #endif
  2355. cli.set_connection_timeout(1);
  2356. {
  2357. auto res = cli.Get(path);
  2358. ASSERT_FALSE(res);
  2359. }
  2360. std::this_thread::sleep_for(std::chrono::seconds(8));
  2361. }
  2362. #if defined(__linux__) && defined(__GLIBC__) && \
  2363. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2364. // Forward declaration: in split builds split.py strips `inline` and moves the
  2365. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2366. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2367. // against the symbol in both header-only and split builds.
  2368. namespace httplib {
  2369. namespace detail {
  2370. int getaddrinfo_with_timeout(const char *node, const char *service,
  2371. const struct addrinfo *hints,
  2372. struct addrinfo **res, time_t timeout_sec);
  2373. } // namespace detail
  2374. } // namespace httplib
  2375. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2376. //
  2377. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2378. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2379. // gai_suspend() call hits the connection timeout the function calls
  2380. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2381. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2382. // still alive and still references the now-destroyed stack frame.
  2383. //
  2384. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2385. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2386. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2387. // and runs them in a container.
  2388. namespace {
  2389. bool should_run_issue_2431_tests() {
  2390. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2391. return v && *v && std::string(v) != "0";
  2392. }
  2393. std::string unique_unresolvable_host(int n) {
  2394. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2395. // glibc still asks the configured nameserver — which is exactly the path
  2396. // we want to exercise. A unique label per call avoids the resolver cache.
  2397. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2398. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2399. std::to_string(n) + ".invalid";
  2400. }
  2401. } // namespace
  2402. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2403. if (!should_run_issue_2431_tests()) {
  2404. GTEST_SKIP()
  2405. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2406. }
  2407. for (int i = 0; i < 8; ++i) {
  2408. struct addrinfo hints;
  2409. memset(&hints, 0, sizeof(hints));
  2410. hints.ai_family = AF_UNSPEC;
  2411. hints.ai_socktype = SOCK_STREAM;
  2412. auto host = unique_unresolvable_host(i);
  2413. struct addrinfo *result = nullptr;
  2414. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2415. &result, /*timeout_sec=*/1);
  2416. if (rc == 0 && result) { freeaddrinfo(result); }
  2417. }
  2418. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2419. // stack region they still believe holds their gaicb.
  2420. std::this_thread::sleep_for(std::chrono::seconds(3));
  2421. }
  2422. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2423. if (!should_run_issue_2431_tests()) {
  2424. GTEST_SKIP()
  2425. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2426. }
  2427. std::atomic<bool> stop{false};
  2428. std::vector<std::thread> threads;
  2429. for (int t = 0; t < 8; ++t) {
  2430. threads.emplace_back([t, &stop] {
  2431. int i = 0;
  2432. while (!stop.load(std::memory_order_relaxed)) {
  2433. struct addrinfo hints;
  2434. memset(&hints, 0, sizeof(hints));
  2435. hints.ai_family = AF_UNSPEC;
  2436. hints.ai_socktype = SOCK_STREAM;
  2437. auto host = unique_unresolvable_host(t * 100000 + i++);
  2438. struct addrinfo *result = nullptr;
  2439. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2440. &result, /*timeout_sec=*/1);
  2441. if (rc == 0 && result) { freeaddrinfo(result); }
  2442. }
  2443. });
  2444. }
  2445. std::this_thread::sleep_for(std::chrono::seconds(8));
  2446. stop.store(true, std::memory_order_relaxed);
  2447. for (auto &th : threads) {
  2448. th.join();
  2449. }
  2450. std::this_thread::sleep_for(std::chrono::seconds(3));
  2451. }
  2452. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2453. if (!should_run_issue_2431_tests()) {
  2454. GTEST_SKIP()
  2455. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2456. }
  2457. std::atomic<bool> stop{false};
  2458. std::vector<std::thread> threads;
  2459. for (int t = 0; t < 8; ++t) {
  2460. threads.emplace_back([t, &stop] {
  2461. int i = 0;
  2462. while (!stop.load(std::memory_order_relaxed)) {
  2463. auto host = unique_unresolvable_host(t * 100000 + i++);
  2464. Client cli(host, 80);
  2465. cli.set_connection_timeout(1, 0);
  2466. cli.set_read_timeout(1, 0);
  2467. cli.set_write_timeout(1, 0);
  2468. (void)cli.Get("/");
  2469. }
  2470. });
  2471. }
  2472. std::this_thread::sleep_for(std::chrono::seconds(8));
  2473. stop.store(true, std::memory_order_relaxed);
  2474. for (auto &th : threads) {
  2475. th.join();
  2476. }
  2477. std::this_thread::sleep_for(std::chrono::seconds(3));
  2478. }
  2479. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2480. TEST(ConnectionErrorTest, InvalidHost) {
  2481. auto host = "-abcde.com";
  2482. #ifdef CPPHTTPLIB_SSL_ENABLED
  2483. auto port = 443;
  2484. SSLClient cli(host, port);
  2485. #else
  2486. auto port = 80;
  2487. Client cli(host, port);
  2488. #endif
  2489. cli.set_connection_timeout(std::chrono::seconds(2));
  2490. auto res = cli.Get("/");
  2491. ASSERT_TRUE(!res);
  2492. EXPECT_EQ(Error::Connection, res.error());
  2493. }
  2494. TEST(ConnectionErrorTest, InvalidHost2) {
  2495. auto host = "httpcan.org/";
  2496. #ifdef CPPHTTPLIB_SSL_ENABLED
  2497. SSLClient cli(host);
  2498. #else
  2499. Client cli(host);
  2500. #endif
  2501. cli.set_connection_timeout(std::chrono::seconds(2));
  2502. auto res = cli.Get("/");
  2503. ASSERT_TRUE(!res);
  2504. EXPECT_EQ(Error::Connection, res.error());
  2505. }
  2506. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2507. auto host = "httpcan.org/";
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. SSLClient cli(host);
  2510. #else
  2511. Client cli(host);
  2512. #endif
  2513. cli.set_connection_timeout(std::chrono::seconds(2));
  2514. auto res = cli.Get("/");
  2515. ASSERT_TRUE(!res);
  2516. stringstream s;
  2517. s << "error code: " << res.error();
  2518. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2519. }
  2520. TEST(ConnectionErrorTest, InvalidPort) {
  2521. auto host = "localhost";
  2522. auto port = 44380;
  2523. #ifdef CPPHTTPLIB_SSL_ENABLED
  2524. SSLClient cli(host, port);
  2525. #else
  2526. Client cli(host, port);
  2527. #endif
  2528. cli.set_connection_timeout(std::chrono::seconds(2));
  2529. auto res = cli.Get("/");
  2530. ASSERT_TRUE(!res);
  2531. EXPECT_TRUE(Error::Connection == res.error() ||
  2532. Error::ConnectionTimeout == res.error());
  2533. }
  2534. TEST(ConnectionErrorTest, Timeout_Online) {
  2535. auto host = "google.com";
  2536. #ifdef CPPHTTPLIB_SSL_ENABLED
  2537. auto port = 44380;
  2538. SSLClient cli(host, port);
  2539. #else
  2540. auto port = 8080;
  2541. Client cli(host, port);
  2542. #endif
  2543. cli.set_connection_timeout(std::chrono::seconds(2));
  2544. // only probe one address type so that the error reason
  2545. // correlates to the timed-out IPv4, not the unsupported
  2546. // IPv6 connection attempt
  2547. cli.set_address_family(AF_INET);
  2548. auto res = cli.Get("/");
  2549. ASSERT_TRUE(!res);
  2550. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2551. }
  2552. TEST(CancelTest, NoCancel_Online) {
  2553. auto host = "httpbingo.org";
  2554. auto path = std::string{"/range/32"};
  2555. #ifdef CPPHTTPLIB_SSL_ENABLED
  2556. auto port = 443;
  2557. SSLClient cli(host, port);
  2558. #else
  2559. auto port = 80;
  2560. Client cli(host, port);
  2561. #endif
  2562. cli.set_connection_timeout(std::chrono::seconds(5));
  2563. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2565. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2566. EXPECT_EQ(StatusCode::OK_200, res->status);
  2567. }
  2568. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2569. // Use /bytes with a large payload so that the DownloadProgress callback
  2570. // (which only fires for Content-Length responses) is invoked before the
  2571. // entire body is received, giving cancellation a chance to fire.
  2572. auto host = "httpbingo.org";
  2573. auto path = std::string{"/bytes/524288"};
  2574. #ifdef CPPHTTPLIB_SSL_ENABLED
  2575. auto port = 443;
  2576. SSLClient cli(host, port);
  2577. #else
  2578. auto port = 80;
  2579. Client cli(host, port);
  2580. #endif
  2581. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2582. cli.set_connection_timeout(std::chrono::seconds(5));
  2583. ASSERT_TRUE(!res);
  2584. EXPECT_EQ(Error::Canceled, res.error());
  2585. }
  2586. TEST(CancelTest, WithCancelLargePayload_Online) {
  2587. auto host = "httpbingo.org";
  2588. auto path = std::string{"/bytes/524288"};
  2589. #ifdef CPPHTTPLIB_SSL_ENABLED
  2590. auto port = 443;
  2591. SSLClient cli(host, port);
  2592. #else
  2593. auto port = 80;
  2594. Client cli(host, port);
  2595. #endif
  2596. cli.set_connection_timeout(std::chrono::seconds(5));
  2597. uint32_t count = 0;
  2598. auto res =
  2599. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2600. ASSERT_TRUE(!res);
  2601. EXPECT_EQ(Error::Canceled, res.error());
  2602. }
  2603. TEST(CancelTest, NoCancelPost) {
  2604. Server svr;
  2605. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2606. res.set_content("Hello World!", "text/plain");
  2607. });
  2608. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2609. auto se = detail::scope_exit([&] {
  2610. svr.stop();
  2611. thread.join();
  2612. ASSERT_FALSE(svr.is_running());
  2613. });
  2614. svr.wait_until_ready();
  2615. Client cli(HOST, PORT);
  2616. cli.set_connection_timeout(std::chrono::seconds(5));
  2617. auto res =
  2618. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2619. "application/json", [](uint64_t, uint64_t) { return true; });
  2620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2621. EXPECT_EQ("Hello World!", res->body);
  2622. EXPECT_EQ(StatusCode::OK_200, res->status);
  2623. }
  2624. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2625. Server svr;
  2626. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2627. res.set_content("Hello World!", "text/plain");
  2628. });
  2629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2630. auto se = detail::scope_exit([&] {
  2631. svr.stop();
  2632. thread.join();
  2633. ASSERT_FALSE(svr.is_running());
  2634. });
  2635. svr.wait_until_ready();
  2636. Client cli(HOST, PORT);
  2637. cli.set_connection_timeout(std::chrono::seconds(5));
  2638. auto res =
  2639. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2640. "application/json", [](uint64_t, uint64_t) { return false; });
  2641. ASSERT_TRUE(!res);
  2642. EXPECT_EQ(Error::Canceled, res.error());
  2643. }
  2644. TEST(CancelTest, WithCancelLargePayloadPost) {
  2645. Server svr;
  2646. svr.set_payload_max_length(200 * 1024 * 1024);
  2647. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2648. res.set_content(LARGE_DATA, "text/plain");
  2649. });
  2650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2651. auto se = detail::scope_exit([&] {
  2652. svr.stop();
  2653. thread.join();
  2654. ASSERT_FALSE(svr.is_running());
  2655. });
  2656. svr.wait_until_ready();
  2657. Client cli(HOST, PORT);
  2658. cli.set_payload_max_length(200 * 1024 * 1024);
  2659. cli.set_connection_timeout(std::chrono::seconds(5));
  2660. auto res =
  2661. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2662. "application/json", [](uint64_t, uint64_t) { return false; });
  2663. ASSERT_TRUE(!res);
  2664. EXPECT_EQ(Error::Canceled, res.error());
  2665. }
  2666. TEST(CancelTest, NoCancelPut) {
  2667. Server svr;
  2668. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2669. res.set_content("Hello World!", "text/plain");
  2670. });
  2671. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2672. auto se = detail::scope_exit([&] {
  2673. svr.stop();
  2674. thread.join();
  2675. ASSERT_FALSE(svr.is_running());
  2676. });
  2677. svr.wait_until_ready();
  2678. Client cli(HOST, PORT);
  2679. cli.set_connection_timeout(std::chrono::seconds(5));
  2680. auto res =
  2681. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2682. "application/json", [](uint64_t, uint64_t) { return true; });
  2683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2684. EXPECT_EQ("Hello World!", res->body);
  2685. EXPECT_EQ(StatusCode::OK_200, res->status);
  2686. }
  2687. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2688. Server svr;
  2689. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2690. res.set_content("Hello World!", "text/plain");
  2691. });
  2692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. thread.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, PORT);
  2700. cli.set_connection_timeout(std::chrono::seconds(5));
  2701. auto res =
  2702. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2703. "application/json", [](uint64_t, uint64_t) { return false; });
  2704. ASSERT_TRUE(!res);
  2705. EXPECT_EQ(Error::Canceled, res.error());
  2706. }
  2707. TEST(CancelTest, WithCancelLargePayloadPut) {
  2708. Server svr;
  2709. svr.set_payload_max_length(200 * 1024 * 1024);
  2710. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2711. res.set_content(LARGE_DATA, "text/plain");
  2712. });
  2713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2714. auto se = detail::scope_exit([&] {
  2715. svr.stop();
  2716. thread.join();
  2717. ASSERT_FALSE(svr.is_running());
  2718. });
  2719. svr.wait_until_ready();
  2720. Client cli(HOST, PORT);
  2721. cli.set_payload_max_length(200 * 1024 * 1024);
  2722. cli.set_connection_timeout(std::chrono::seconds(5));
  2723. auto res =
  2724. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2725. "application/json", [](uint64_t, uint64_t) { return false; });
  2726. ASSERT_TRUE(!res);
  2727. EXPECT_EQ(Error::Canceled, res.error());
  2728. }
  2729. TEST(CancelTest, NoCancelPatch) {
  2730. Server svr;
  2731. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2732. res.set_content("Hello World!", "text/plain");
  2733. });
  2734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2735. auto se = detail::scope_exit([&] {
  2736. svr.stop();
  2737. thread.join();
  2738. ASSERT_FALSE(svr.is_running());
  2739. });
  2740. svr.wait_until_ready();
  2741. Client cli(HOST, PORT);
  2742. cli.set_connection_timeout(std::chrono::seconds(5));
  2743. auto res =
  2744. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2745. "application/json", [](uint64_t, uint64_t) { return true; });
  2746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2747. EXPECT_EQ("Hello World!", res->body);
  2748. EXPECT_EQ(StatusCode::OK_200, res->status);
  2749. }
  2750. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2751. Server svr;
  2752. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2753. res.set_content("Hello World!", "text/plain");
  2754. });
  2755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2756. auto se = detail::scope_exit([&] {
  2757. svr.stop();
  2758. thread.join();
  2759. ASSERT_FALSE(svr.is_running());
  2760. });
  2761. svr.wait_until_ready();
  2762. Client cli(HOST, PORT);
  2763. cli.set_connection_timeout(std::chrono::seconds(5));
  2764. auto res =
  2765. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2766. "application/json", [](uint64_t, uint64_t) { return false; });
  2767. ASSERT_TRUE(!res);
  2768. EXPECT_EQ(Error::Canceled, res.error());
  2769. }
  2770. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2771. Server svr;
  2772. svr.set_payload_max_length(200 * 1024 * 1024);
  2773. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2774. res.set_content(LARGE_DATA, "text/plain");
  2775. });
  2776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2777. auto se = detail::scope_exit([&] {
  2778. svr.stop();
  2779. thread.join();
  2780. ASSERT_FALSE(svr.is_running());
  2781. });
  2782. svr.wait_until_ready();
  2783. Client cli(HOST, PORT);
  2784. cli.set_payload_max_length(200 * 1024 * 1024);
  2785. cli.set_connection_timeout(std::chrono::seconds(5));
  2786. auto res =
  2787. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2788. "application/json", [](uint64_t, uint64_t) { return false; });
  2789. ASSERT_TRUE(!res);
  2790. EXPECT_EQ(Error::Canceled, res.error());
  2791. }
  2792. TEST(CancelTest, NoCancelDelete) {
  2793. Server svr;
  2794. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2795. res.set_content("Hello World!", "text/plain");
  2796. });
  2797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. thread.join();
  2801. ASSERT_FALSE(svr.is_running());
  2802. });
  2803. svr.wait_until_ready();
  2804. Client cli(HOST, PORT);
  2805. cli.set_connection_timeout(std::chrono::seconds(5));
  2806. auto res =
  2807. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2808. "application/json", [](uint64_t, uint64_t) { return true; });
  2809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2810. EXPECT_EQ("Hello World!", res->body);
  2811. EXPECT_EQ(StatusCode::OK_200, res->status);
  2812. }
  2813. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2814. Server svr;
  2815. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2816. res.set_content("Hello World!", "text/plain");
  2817. });
  2818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2819. auto se = detail::scope_exit([&] {
  2820. svr.stop();
  2821. thread.join();
  2822. ASSERT_FALSE(svr.is_running());
  2823. });
  2824. svr.wait_until_ready();
  2825. Client cli(HOST, PORT);
  2826. cli.set_connection_timeout(std::chrono::seconds(5));
  2827. auto res =
  2828. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2829. "application/json", [](uint64_t, uint64_t) { return false; });
  2830. ASSERT_TRUE(!res);
  2831. EXPECT_EQ(Error::Canceled, res.error());
  2832. }
  2833. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2834. Server svr;
  2835. svr.set_payload_max_length(200 * 1024 * 1024);
  2836. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2837. res.set_content(LARGE_DATA, "text/plain");
  2838. });
  2839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2840. auto se = detail::scope_exit([&] {
  2841. svr.stop();
  2842. thread.join();
  2843. ASSERT_FALSE(svr.is_running());
  2844. });
  2845. svr.wait_until_ready();
  2846. Client cli(HOST, PORT);
  2847. cli.set_payload_max_length(200 * 1024 * 1024);
  2848. cli.set_connection_timeout(std::chrono::seconds(5));
  2849. auto res =
  2850. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2851. "application/json", [](uint64_t, uint64_t) { return false; });
  2852. ASSERT_TRUE(!res);
  2853. EXPECT_EQ(Error::Canceled, res.error());
  2854. }
  2855. static std::string remove_whitespace(const std::string &input) {
  2856. std::string output;
  2857. output.reserve(input.size());
  2858. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2859. [](unsigned char c) { return !std::isspace(c); });
  2860. return output;
  2861. }
  2862. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2863. auto host = "httpbingo.org";
  2864. auto path = std::string{"/basic-auth/hello/world"};
  2865. #ifdef CPPHTTPLIB_SSL_ENABLED
  2866. auto port = 443;
  2867. SSLClient cli(host, port);
  2868. #else
  2869. auto port = 80;
  2870. Client cli(host, port);
  2871. #endif
  2872. {
  2873. auto res = cli.Get(path);
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2876. }
  2877. {
  2878. auto res = cli.Get(
  2879. path, Headers{make_basic_authentication_header("hello", "world")});
  2880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2881. auto body = remove_whitespace(res->body);
  2882. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2883. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2884. EXPECT_EQ(StatusCode::OK_200, res->status);
  2885. }
  2886. {
  2887. cli.set_basic_auth("hello", "world");
  2888. auto res = cli.Get(path);
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. auto body = remove_whitespace(res->body);
  2891. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2892. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2893. EXPECT_EQ(StatusCode::OK_200, res->status);
  2894. }
  2895. {
  2896. cli.set_basic_auth("hello", "bad");
  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. cli.set_basic_auth("bad", "world");
  2903. auto res = cli.Get(path);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2906. }
  2907. }
  2908. #ifdef CPPHTTPLIB_SSL_ENABLED
  2909. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2910. auto host = "httpbingo.org";
  2911. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2912. auto paths = std::vector<std::string>{
  2913. "/digest-auth/auth/hello/world/MD5",
  2914. "/digest-auth/auth/hello/world/SHA-256",
  2915. };
  2916. auto port = 443;
  2917. SSLClient cli(host, port);
  2918. {
  2919. auto res = cli.Get(unauth_path);
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2922. }
  2923. {
  2924. cli.set_digest_auth("hello", "world");
  2925. for (const auto &path : paths) {
  2926. auto res = cli.Get(path.c_str());
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. auto body = remove_whitespace(res->body);
  2929. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2930. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2931. EXPECT_EQ(StatusCode::OK_200, res->status);
  2932. }
  2933. cli.set_digest_auth("hello", "bad");
  2934. for (const auto &path : paths) {
  2935. auto res = cli.Get(path.c_str());
  2936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2937. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2938. }
  2939. }
  2940. }
  2941. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2942. // comma-separated list of challenges, and each challenge may itself carry a
  2943. // comma-separated auth-param list, so a server can legally offer Basic
  2944. // before Digest, either as two field lines or packed into one. Runs one 401
  2945. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2946. // value() joins them in receipt order) and checks that the retry carries a
  2947. // well-formed Digest Authorization header naming expected_realm.
  2948. static void
  2949. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2950. const std::string &expected_realm) {
  2951. std::atomic<int> hits{0};
  2952. Server svr;
  2953. svr.Get("/x", [&](const Request &req, Response &res) {
  2954. if (++hits == 1) {
  2955. res.status = StatusCode::Unauthorized_401;
  2956. for (const auto &challenge : challenges) {
  2957. res.set_header("WWW-Authenticate", challenge);
  2958. }
  2959. } else {
  2960. auto authorization = req.get_header_value("Authorization");
  2961. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2962. EXPECT_NE(std::string::npos,
  2963. authorization.find("realm=\"" + expected_realm + "\""));
  2964. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2965. res.set_content("ok", "text/plain");
  2966. }
  2967. });
  2968. auto port = svr.bind_to_any_port(HOST);
  2969. std::thread t([&]() { svr.listen_after_bind(); });
  2970. auto se = detail::scope_exit([&] {
  2971. svr.stop();
  2972. t.join();
  2973. });
  2974. svr.wait_until_ready();
  2975. Client cli(HOST, port);
  2976. cli.set_digest_auth("hello", "world");
  2977. auto res = cli.Get("/x");
  2978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2979. EXPECT_EQ(2, hits.load());
  2980. }
  2981. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2982. static const char *kDigestChallenge =
  2983. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2984. "algorithm=MD5";
  2985. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2986. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2987. "testrealm");
  2988. }
  2989. // Same challenge list with the schemes in the opposite order, to make sure
  2990. // the fix above didn't just special-case "Basic first".
  2991. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2992. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2993. "testrealm");
  2994. }
  2995. // A comma inside a quoted auth-param value must not be mistaken for the
  2996. // separator between two challenges (or two auth-params).
  2997. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2998. run_digest_challenge_list_test(
  2999. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3000. "algorithm=MD5"},
  3001. "test,realm");
  3002. }
  3003. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3004. // the params and leaves out the fragment.
  3005. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3006. Server svr;
  3007. std::string uri, target;
  3008. svr.Get("/a b", [&](const Request &req, Response &res) {
  3009. auto auth = req.get_header_value("Authorization");
  3010. if (auth.empty()) {
  3011. res.status = StatusCode::Unauthorized_401;
  3012. res.set_header("WWW-Authenticate",
  3013. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3014. return;
  3015. }
  3016. auto b = auth.find("uri=\"") + 5;
  3017. uri = auth.substr(b, auth.find('"', b) - b);
  3018. target = req.target;
  3019. });
  3020. auto port = svr.bind_to_any_port(HOST);
  3021. std::thread t([&]() { svr.listen_after_bind(); });
  3022. auto se = detail::scope_exit([&] {
  3023. svr.stop();
  3024. t.join();
  3025. });
  3026. svr.wait_until_ready();
  3027. Client cli(HOST, port);
  3028. cli.set_digest_auth("hello", "world");
  3029. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3031. EXPECT_EQ("/a%20b?x=1", target);
  3032. EXPECT_EQ(target, uri);
  3033. }
  3034. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3035. // make_digest_authentication_header() dereferences both unconditionally, so
  3036. // a server sending a challenge missing either one must not be treated as
  3037. // usable -- doing so used to crash the client with std::out_of_range.
  3038. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3039. Server svr;
  3040. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3041. res.status = StatusCode::Unauthorized_401;
  3042. res.set_header("WWW-Authenticate", challenge);
  3043. });
  3044. auto port = svr.bind_to_any_port(HOST);
  3045. std::thread t([&]() { svr.listen_after_bind(); });
  3046. auto se = detail::scope_exit([&] {
  3047. svr.stop();
  3048. t.join();
  3049. });
  3050. svr.wait_until_ready();
  3051. Client cli(HOST, port);
  3052. cli.set_digest_auth("hello", "world");
  3053. auto res = cli.Get("/x");
  3054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3055. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3056. }
  3057. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3058. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3059. }
  3060. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3061. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3062. }
  3063. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3064. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3065. }
  3066. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3067. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3068. // when storing the values, so the header builder has to re-escape them (and
  3069. // keep algorithm a bare token); otherwise the value breaks out of its
  3070. // quoted-string and injects extra auth-params into the client's Authorization.
  3071. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3072. std::atomic<int> hits{0};
  3073. std::string authorization;
  3074. Server svr;
  3075. svr.Get("/x", [&](const Request &req, Response &res) {
  3076. if (++hits == 1) {
  3077. res.status = StatusCode::Unauthorized_401;
  3078. // On the wire the quotes embedded in the values are backslash-escaped.
  3079. res.set_header("WWW-Authenticate",
  3080. "Digest realm=\"testrealm\", "
  3081. "nonce=\"n\\\"; injected=\\\"x\", "
  3082. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3083. } else {
  3084. authorization = req.get_header_value("Authorization");
  3085. res.set_content("ok", "text/plain");
  3086. }
  3087. });
  3088. auto port = svr.bind_to_any_port(HOST);
  3089. std::thread t([&]() { svr.listen_after_bind(); });
  3090. auto se = detail::scope_exit([&] {
  3091. svr.stop();
  3092. t.join();
  3093. });
  3094. svr.wait_until_ready();
  3095. Client cli(HOST, port);
  3096. cli.set_digest_auth("hello", "world");
  3097. auto res = cli.Get("/x");
  3098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3099. EXPECT_EQ(2, hits.load());
  3100. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3101. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3102. // inside its quoted-string rather than starting an "injected" auth-param.
  3103. EXPECT_NE(std::string::npos,
  3104. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3105. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3106. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3107. }
  3108. #endif
  3109. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3110. auto host = "google.com";
  3111. auto another_host = "example.com";
  3112. auto wrong_ip = "0.0.0.0";
  3113. #ifdef CPPHTTPLIB_SSL_ENABLED
  3114. SSLClient cli(host);
  3115. #else
  3116. Client cli(host);
  3117. #endif
  3118. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3119. auto res = cli.Get("/");
  3120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3121. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3122. }
  3123. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3124. auto host = "google.com";
  3125. auto wrong_ip = "0.0.0.0";
  3126. #ifdef CPPHTTPLIB_SSL_ENABLED
  3127. SSLClient cli(host);
  3128. #else
  3129. Client cli(host);
  3130. #endif
  3131. cli.set_hostname_addr_map({{host, wrong_ip}});
  3132. auto res = cli.Get("/");
  3133. ASSERT_TRUE(!res);
  3134. EXPECT_EQ(Error::Connection, res.error());
  3135. }
  3136. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3137. // A mapped value that is not an IP literal must be resolved. "localhost"
  3138. // resolves from the hosts file, so this test needs no external DNS.
  3139. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3140. auto host = "target.invalid";
  3141. Server svr;
  3142. std::string received_host;
  3143. svr.Get("/hi", [&](const Request &req, Response &res) {
  3144. received_host = req.get_header_value("Host");
  3145. res.set_content("Hello World!", "text/plain");
  3146. });
  3147. auto port = svr.bind_to_any_port(HOST);
  3148. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3149. auto se = detail::scope_exit([&] {
  3150. svr.stop();
  3151. thread.join();
  3152. ASSERT_FALSE(svr.is_running());
  3153. });
  3154. svr.wait_until_ready();
  3155. Client cli(host, port);
  3156. cli.set_hostname_addr_map({{host, HOST}});
  3157. auto res = cli.Get("/hi");
  3158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3159. EXPECT_EQ(StatusCode::OK_200, res->status);
  3160. // The mapping only redirects the connection; the identity stays host_.
  3161. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3162. }
  3163. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3164. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3165. auto host = "target.invalid";
  3166. Server svr;
  3167. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3168. res.set_content("Hello World!", "text/plain");
  3169. });
  3170. auto port = svr.bind_to_any_port("127.0.0.1");
  3171. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3172. auto se = detail::scope_exit([&] {
  3173. svr.stop();
  3174. thread.join();
  3175. ASSERT_FALSE(svr.is_running());
  3176. });
  3177. svr.wait_until_ready();
  3178. Client cli(host, port);
  3179. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3180. auto res = cli.Get("/hi");
  3181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3182. EXPECT_EQ(StatusCode::OK_200, res->status);
  3183. }
  3184. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3185. // An empty mapped value must leave host_ as the connection target. Without
  3186. // that guard the empty value would become the host argument, getaddrinfo
  3187. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3188. // loopback - silently connecting somewhere the caller never asked for.
  3189. // The server listens on loopback, so such a fallback would succeed and is
  3190. // therefore observable as a failure of this test.
  3191. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3192. Server svr;
  3193. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3194. res.set_content("Hello World!", "text/plain");
  3195. });
  3196. auto port = svr.bind_to_any_port(HOST);
  3197. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3198. auto se = detail::scope_exit([&] {
  3199. svr.stop();
  3200. thread.join();
  3201. ASSERT_FALSE(svr.is_running());
  3202. });
  3203. svr.wait_until_ready();
  3204. Client cli(blackhole, port);
  3205. cli.set_hostname_addr_map({{blackhole, ""}});
  3206. cli.set_connection_timeout(1);
  3207. auto res = cli.Get("/hi");
  3208. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3209. }
  3210. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3211. auto host = "httpbingo.org";
  3212. auto path = std::string{"/absolute-redirect/3"};
  3213. #ifdef CPPHTTPLIB_SSL_ENABLED
  3214. SSLClient cli(host);
  3215. #else
  3216. Client cli(host);
  3217. #endif
  3218. cli.set_follow_location(true);
  3219. auto res = cli.Get(path);
  3220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. }
  3223. TEST(RedirectTest, Redirect_Online) {
  3224. auto host = "httpbingo.org";
  3225. auto path = std::string{"/redirect/3"};
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. SSLClient cli(host);
  3228. #else
  3229. Client cli(host);
  3230. #endif
  3231. cli.set_follow_location(true);
  3232. auto res = cli.Get(path);
  3233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. }
  3236. TEST(RelativeRedirectTest, Redirect_Online) {
  3237. auto host = "httpbingo.org";
  3238. auto path = std::string{"/relative-redirect/3"};
  3239. #ifdef CPPHTTPLIB_SSL_ENABLED
  3240. SSLClient cli(host);
  3241. #else
  3242. Client cli(host);
  3243. #endif
  3244. cli.set_follow_location(true);
  3245. auto res = cli.Get(path);
  3246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3247. EXPECT_EQ(StatusCode::OK_200, res->status);
  3248. }
  3249. TEST(TooManyRedirectTest, Redirect_Online) {
  3250. auto host = "httpbingo.org";
  3251. auto path = std::string{"/redirect/21"};
  3252. #ifdef CPPHTTPLIB_SSL_ENABLED
  3253. SSLClient cli(host);
  3254. #else
  3255. Client cli(host);
  3256. #endif
  3257. cli.set_follow_location(true);
  3258. auto res = cli.Get(path);
  3259. ASSERT_TRUE(!res);
  3260. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3261. }
  3262. #ifdef CPPHTTPLIB_SSL_ENABLED
  3263. TEST(YahooRedirectTest, Redirect_Online) {
  3264. Client cli("yahoo.com");
  3265. auto res = cli.Get("/");
  3266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3267. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3268. cli.set_follow_location(true);
  3269. res = cli.Get("/");
  3270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3271. EXPECT_EQ(StatusCode::OK_200, res->status);
  3272. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3273. }
  3274. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3275. #define REDIR_HOST "httpbingo.org"
  3276. #define REDIR_PATH "/redirect-to"
  3277. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3278. SSLClient cli(REDIR_HOST);
  3279. cli.set_follow_location(true);
  3280. auto res =
  3281. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. }
  3285. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3286. SSLClient cli(REDIR_HOST);
  3287. cli.set_follow_location(true);
  3288. Params params;
  3289. params.emplace("url", "http://example.com");
  3290. params.emplace("status_code", "302");
  3291. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. }
  3295. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3296. SSLClient cli(REDIR_HOST);
  3297. cli.set_follow_location(true);
  3298. Params params;
  3299. params.emplace("url", "http://example.com");
  3300. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3302. EXPECT_EQ(StatusCode::OK_200, res->status);
  3303. }
  3304. TEST(UrlWithSpace, Redirect_Online) {
  3305. SSLClient cli("edge.forgecdn.net");
  3306. cli.set_follow_location(true);
  3307. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3309. EXPECT_EQ(StatusCode::OK_200, res->status);
  3310. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3311. }
  3312. #endif
  3313. #if !defined(_WIN32) && !defined(_WIN64)
  3314. TEST(ReceiveSignals, Signal) {
  3315. auto setupSignalHandlers = []() {
  3316. struct sigaction act;
  3317. sigemptyset(&act.sa_mask);
  3318. act.sa_flags = SA_SIGINFO;
  3319. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3320. switch (sig) {
  3321. case SIGINT:
  3322. default: break;
  3323. }
  3324. };
  3325. ::sigaction(SIGINT, &act, nullptr);
  3326. };
  3327. Server svr;
  3328. int port = 0;
  3329. auto thread = std::thread([&]() {
  3330. setupSignalHandlers();
  3331. port = svr.bind_to_any_port(HOST);
  3332. svr.listen_after_bind();
  3333. });
  3334. auto se = detail::scope_exit([&] {
  3335. svr.stop();
  3336. thread.join();
  3337. ASSERT_FALSE(svr.is_running());
  3338. });
  3339. svr.wait_until_ready();
  3340. ASSERT_TRUE(svr.is_running());
  3341. pthread_kill(thread.native_handle(), SIGINT);
  3342. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3343. ASSERT_TRUE(svr.is_running());
  3344. }
  3345. #endif
  3346. TEST(RedirectToDifferentPort, Redirect) {
  3347. Server svr1;
  3348. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3349. res.set_content("Hello World!", "text/plain");
  3350. });
  3351. int svr1_port = 0;
  3352. auto thread1 = std::thread([&]() {
  3353. svr1_port = svr1.bind_to_any_port(HOST);
  3354. svr1.listen_after_bind();
  3355. });
  3356. Server svr2;
  3357. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3358. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3359. });
  3360. int svr2_port = 0;
  3361. auto thread2 = std::thread([&]() {
  3362. svr2_port = svr2.bind_to_any_port(HOST);
  3363. svr2.listen_after_bind();
  3364. });
  3365. auto se = detail::scope_exit([&] {
  3366. svr2.stop();
  3367. thread2.join();
  3368. svr1.stop();
  3369. thread1.join();
  3370. ASSERT_FALSE(svr2.is_running());
  3371. ASSERT_FALSE(svr1.is_running());
  3372. });
  3373. svr1.wait_until_ready();
  3374. svr2.wait_until_ready();
  3375. Client cli("localhost", svr2_port);
  3376. cli.set_follow_location(true);
  3377. auto res = cli.Get("/2");
  3378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3379. EXPECT_EQ(StatusCode::OK_200, res->status);
  3380. EXPECT_EQ("Hello World!", res->body);
  3381. }
  3382. // GET /redir on one server redirects to /target on another port, so the
  3383. // client follows it with a new client.
  3384. static Result
  3385. GetThroughRedirectToDifferentPort(Server::Handler target,
  3386. const std::function<void(Client &)> &setup,
  3387. const Headers &headers = Headers()) {
  3388. Server target_svr;
  3389. target_svr.Get("/target", target);
  3390. int target_port = 0;
  3391. auto target_thread = std::thread([&]() {
  3392. target_port = target_svr.bind_to_any_port(HOST);
  3393. target_svr.listen_after_bind();
  3394. });
  3395. Server origin_svr;
  3396. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3397. res.set_redirect(
  3398. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3399. });
  3400. int origin_port = 0;
  3401. auto origin_thread = std::thread([&]() {
  3402. origin_port = origin_svr.bind_to_any_port(HOST);
  3403. origin_svr.listen_after_bind();
  3404. });
  3405. auto se = detail::scope_exit([&] {
  3406. origin_svr.stop();
  3407. origin_thread.join();
  3408. target_svr.stop();
  3409. target_thread.join();
  3410. });
  3411. target_svr.wait_until_ready();
  3412. origin_svr.wait_until_ready();
  3413. Client cli("localhost", origin_port);
  3414. cli.set_follow_location(true);
  3415. setup(cli);
  3416. return cli.Get("/redir", headers);
  3417. }
  3418. static void
  3419. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3420. std::string captured_authorization;
  3421. auto result = GetThroughRedirectToDifferentPort(
  3422. [&](const Request &req, Response &res) {
  3423. captured_authorization = req.get_header_value("Authorization");
  3424. res.set_content("OK", "text/plain");
  3425. },
  3426. set_auth);
  3427. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3428. EXPECT_EQ(StatusCode::OK_200, result->status);
  3429. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3430. EXPECT_TRUE(captured_authorization.empty());
  3431. }
  3432. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3433. TestDoNotForwardCredentialsOnRedirect(
  3434. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3435. }
  3436. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3437. TestDoNotForwardCredentialsOnRedirect(
  3438. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3439. }
  3440. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3441. std::string captured_cookie;
  3442. auto result = GetThroughRedirectToDifferentPort(
  3443. [&](const Request &req, Response &res) {
  3444. captured_cookie = req.get_header_value("Cookie");
  3445. res.set_content("OK", "text/plain");
  3446. },
  3447. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3448. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3449. EXPECT_EQ(StatusCode::OK_200, result->status);
  3450. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3451. EXPECT_TRUE(captured_cookie.empty());
  3452. }
  3453. TEST(RedirectToSamePort, ForwardCookie) {
  3454. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3455. // header so that ordinary session flows keep working.
  3456. Server svr;
  3457. std::string captured_cookie;
  3458. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3459. res.set_redirect("/target", 302);
  3460. });
  3461. svr.Get("/target", [&](const Request &req, Response &res) {
  3462. captured_cookie = req.get_header_value("Cookie");
  3463. res.set_content("OK", "text/plain");
  3464. });
  3465. auto port = svr.bind_to_any_port(HOST);
  3466. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3467. auto se = detail::scope_exit([&] {
  3468. svr.stop();
  3469. thread.join();
  3470. ASSERT_FALSE(svr.is_running());
  3471. });
  3472. svr.wait_until_ready();
  3473. Client cli(HOST, port);
  3474. cli.set_follow_location(true);
  3475. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3476. auto res = cli.Get("/redir", headers);
  3477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3478. EXPECT_EQ(StatusCode::OK_200, res->status);
  3479. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3480. }
  3481. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3482. std::string authorization;
  3483. std::string trace_id;
  3484. auto result = GetThroughRedirectToDifferentPort(
  3485. [&](const Request &req, Response &res) {
  3486. authorization = req.get_header_value("Authorization");
  3487. trace_id = req.get_header_value("X-Trace-Id");
  3488. res.set_content("OK", "text/plain");
  3489. },
  3490. [](Client &cli) {
  3491. cli.set_default_headers(
  3492. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3493. });
  3494. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3495. EXPECT_EQ(StatusCode::OK_200, result->status);
  3496. // Like a header given with the request, a default one goes along unless it
  3497. // carries credentials (RFC 9110 15.4).
  3498. EXPECT_TRUE(authorization.empty());
  3499. EXPECT_EQ("42", trace_id);
  3500. }
  3501. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3502. auto result = GetThroughRedirectToDifferentPort(
  3503. [](const Request &, Response &res) {
  3504. res.set_content(std::string(2048, 'x'), "text/plain");
  3505. },
  3506. [](Client &cli) { cli.set_payload_max_length(1024); });
  3507. EXPECT_FALSE(result);
  3508. }
  3509. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3510. auto result = GetThroughRedirectToDifferentPort(
  3511. [](const Request &req, Response &res) {
  3512. // Answer after a second, or once the client gives up.
  3513. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3514. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3515. }
  3516. res.set_content("late", "text/plain");
  3517. },
  3518. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3519. ASSERT_FALSE(result);
  3520. EXPECT_EQ(Error::Read, result.error());
  3521. }
  3522. #ifdef CPPHTTPLIB_SSL_ENABLED
  3523. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3524. auto result = GetThroughRedirectToDifferentPort(
  3525. [](const Request &, Response &res) {
  3526. res.status = StatusCode::Unauthorized_401;
  3527. res.set_header("WWW-Authenticate",
  3528. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3529. },
  3530. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3531. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3532. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3533. }
  3534. #endif
  3535. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3536. Server svr;
  3537. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3538. // Port number that overflows int — should not crash
  3539. res.set_redirect("http://localhost:99999999999999999999/target");
  3540. });
  3541. auto port = svr.bind_to_any_port(HOST);
  3542. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3543. auto se = detail::scope_exit([&] {
  3544. svr.stop();
  3545. thread.join();
  3546. ASSERT_FALSE(svr.is_running());
  3547. });
  3548. svr.wait_until_ready();
  3549. Client cli(HOST, port);
  3550. cli.set_follow_location(true);
  3551. auto res = cli.Get("/redir");
  3552. // Should fail gracefully, not crash (no valid response due to bad port)
  3553. EXPECT_FALSE(res);
  3554. }
  3555. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3556. Server svr;
  3557. auto port = svr.bind_to_any_port(HOST);
  3558. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3559. // The server's own port followed by junk must not be followed
  3560. res.set_redirect("http://" + std::string(HOST) + ":" +
  3561. std::to_string(port) + "junk/target");
  3562. });
  3563. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3564. res.set_content("target", "text/plain");
  3565. });
  3566. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3567. auto se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. Client cli(HOST, port);
  3574. cli.set_follow_location(true);
  3575. auto res = cli.Get("/redir");
  3576. EXPECT_FALSE(res);
  3577. }
  3578. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3579. Server svr;
  3580. std::atomic<bool> followed{false};
  3581. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3582. res.status = StatusCode::NotModified_304;
  3583. res.set_header("Location", "/target");
  3584. });
  3585. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3586. res.status = StatusCode::UseProxy_305;
  3587. res.set_header("Location", "/target");
  3588. });
  3589. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3590. followed = true;
  3591. res.set_content("target", "text/plain");
  3592. });
  3593. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3594. auto se = detail::scope_exit([&] {
  3595. svr.stop();
  3596. th.join();
  3597. ASSERT_FALSE(svr.is_running());
  3598. });
  3599. svr.wait_until_ready();
  3600. Client cli("localhost", PORT);
  3601. cli.set_follow_location(true);
  3602. auto res = cli.Get("/304");
  3603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3604. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3605. res = cli.Get("/305");
  3606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3607. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3608. EXPECT_FALSE(followed);
  3609. }
  3610. TEST(RedirectFromPageWithContent, Redirect) {
  3611. Server svr;
  3612. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3613. res.set_content("___", "text/plain");
  3614. res.set_redirect("/2");
  3615. });
  3616. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3617. res.set_content("Hello World!", "text/plain");
  3618. });
  3619. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3620. auto se = detail::scope_exit([&] {
  3621. svr.stop();
  3622. th.join();
  3623. ASSERT_FALSE(svr.is_running());
  3624. });
  3625. svr.wait_until_ready();
  3626. {
  3627. Client cli("localhost", PORT);
  3628. cli.set_follow_location(true);
  3629. std::string body;
  3630. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3631. body.append(data, data_length);
  3632. return true;
  3633. });
  3634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3635. EXPECT_EQ(StatusCode::OK_200, res->status);
  3636. EXPECT_EQ("Hello World!", body);
  3637. }
  3638. {
  3639. Client cli("localhost", PORT);
  3640. std::string body;
  3641. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3642. body.append(data, data_length);
  3643. return true;
  3644. });
  3645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3646. EXPECT_EQ(StatusCode::Found_302, res->status);
  3647. EXPECT_EQ("___", body);
  3648. }
  3649. }
  3650. // A server can close the connection after a request with "Connection: close"
  3651. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3652. // redirected request must go out on a new connection.
  3653. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3654. #ifndef _WIN32
  3655. signal(SIGPIPE, SIG_IGN);
  3656. #endif
  3657. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3658. default_socket_options(srv);
  3659. sockaddr_in addr{};
  3660. addr.sin_family = AF_INET;
  3661. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3662. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3663. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3664. ASSERT_EQ(0, ::listen(srv, 2));
  3665. auto send_text = [](socket_t sock, const std::string &text) {
  3666. ::send(sock,
  3667. #ifdef _WIN32
  3668. static_cast<const char *>(text.c_str()),
  3669. static_cast<int>(text.size()),
  3670. #else
  3671. text.c_str(), text.size(),
  3672. #endif
  3673. 0);
  3674. };
  3675. auto reused = false;
  3676. auto server_thread = std::thread([&] {
  3677. char buf[4096];
  3678. auto first = ::accept(srv, nullptr, nullptr);
  3679. if (first == INVALID_SOCKET) { return; }
  3680. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3681. ::recv(first, buf, sizeof(buf), 0);
  3682. send_text(
  3683. first,
  3684. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3685. auto next = first;
  3686. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3687. reused = true;
  3688. } else {
  3689. detail::close_socket(first);
  3690. next = ::accept(srv, nullptr, nullptr);
  3691. if (next == INVALID_SOCKET) { return; }
  3692. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3693. ::recv(next, buf, sizeof(buf), 0);
  3694. }
  3695. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3696. "Connection: close\r\n\r\nok");
  3697. detail::close_socket(next);
  3698. });
  3699. Client cli("127.0.0.1", PORT + 2);
  3700. cli.set_follow_location(true);
  3701. cli.set_read_timeout(5, 0);
  3702. auto res = cli.Get("/1");
  3703. server_thread.join();
  3704. detail::close_socket(srv);
  3705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3706. EXPECT_EQ(StatusCode::OK_200, res->status);
  3707. EXPECT_EQ("ok", res->body);
  3708. EXPECT_FALSE(reused);
  3709. }
  3710. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3711. Server svr;
  3712. auto port_str = std::to_string(PORT);
  3713. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3714. auto expected_host = "[::1]:" + port_str;
  3715. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3716. res.set_content("___", "text/plain");
  3717. // res.set_redirect("/2");
  3718. res.set_redirect(redirect_url);
  3719. });
  3720. svr.Get("/2", [&](const Request &req, Response &res) {
  3721. auto host_header = req.headers.find("Host");
  3722. ASSERT_TRUE(host_header != req.headers.end());
  3723. EXPECT_EQ(expected_host, host_header->second);
  3724. res.set_content("Hello World!", "text/plain");
  3725. });
  3726. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3727. auto se = detail::scope_exit([&] {
  3728. svr.stop();
  3729. th.join();
  3730. ASSERT_FALSE(svr.is_running());
  3731. });
  3732. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3733. // actually starts anything, so the condition !svr.is_running() will
  3734. // always remain true, and the loop never stops.
  3735. // This basically counts how many milliseconds have passed since the
  3736. // call to svr.listen(), and if after 5 seconds nothing started yet
  3737. // aborts the test.
  3738. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3739. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3740. ASSERT_LT(milliseconds, 5000U);
  3741. }
  3742. {
  3743. Client cli("::1", PORT);
  3744. cli.set_follow_location(true);
  3745. std::string body;
  3746. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3747. body.append(data, data_length);
  3748. return true;
  3749. });
  3750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3751. EXPECT_EQ(StatusCode::OK_200, res->status);
  3752. EXPECT_EQ("Hello World!", body);
  3753. }
  3754. {
  3755. Client cli("::1", PORT);
  3756. std::string body;
  3757. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3758. body.append(data, data_length);
  3759. return true;
  3760. });
  3761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3762. EXPECT_EQ(StatusCode::Found_302, res->status);
  3763. EXPECT_EQ("___", body);
  3764. }
  3765. }
  3766. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3767. Server svr;
  3768. svr.Get("/foo", [](const Request &req, Response &res) {
  3769. auto a = req.params.find("a");
  3770. if (a != req.params.end()) {
  3771. res.set_content((*a).second, "text/plain");
  3772. res.status = StatusCode::OK_200;
  3773. } else {
  3774. res.status = StatusCode::BadRequest_400;
  3775. }
  3776. });
  3777. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3778. auto se = detail::scope_exit([&] {
  3779. svr.stop();
  3780. thread.join();
  3781. ASSERT_FALSE(svr.is_running());
  3782. });
  3783. svr.wait_until_ready();
  3784. {
  3785. Client cli(HOST, PORT);
  3786. cli.set_path_encode(false);
  3787. auto res = cli.Get("/foo?a=explicitly+encoded");
  3788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3789. EXPECT_EQ(StatusCode::OK_200, res->status);
  3790. // This expects it back with a space, as the `+` won't have been
  3791. // url-encoded, and server-side the params get decoded turning `+`
  3792. // into spaces.
  3793. EXPECT_EQ("explicitly encoded", res->body);
  3794. }
  3795. }
  3796. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3797. // When path encoding is disabled the client must transmit the supplied
  3798. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3799. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3800. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3801. // than a space (0x20). Assert on the raw wire target to catch this.
  3802. Server svr;
  3803. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3804. svr.Get("/foo", [&](const Request &req, Response &res) {
  3805. EXPECT_EQ(expected_target, req.target);
  3806. res.status = StatusCode::OK_200;
  3807. });
  3808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3809. auto se = detail::scope_exit([&] {
  3810. svr.stop();
  3811. thread.join();
  3812. ASSERT_FALSE(svr.is_running());
  3813. });
  3814. svr.wait_until_ready();
  3815. {
  3816. Client cli(HOST, PORT);
  3817. cli.set_path_encode(false);
  3818. auto res = cli.Get(expected_target.c_str());
  3819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3820. EXPECT_EQ(StatusCode::OK_200, res->status);
  3821. }
  3822. }
  3823. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3824. // `open_stream()` used to skip the path encoding that the buffered send
  3825. // path applies, so the same `path` produced different bytes in the request
  3826. // line depending on which API was used. Assert the two agree.
  3827. Server svr;
  3828. std::string target;
  3829. svr.Get(".*", [&](const Request &req, Response &res) {
  3830. target = req.target;
  3831. res.status = StatusCode::OK_200;
  3832. });
  3833. auto port = svr.bind_to_any_port(HOST);
  3834. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3835. auto se = detail::scope_exit([&] {
  3836. svr.stop();
  3837. thread.join();
  3838. ASSERT_FALSE(svr.is_running());
  3839. });
  3840. svr.wait_until_ready();
  3841. struct {
  3842. const char *path;
  3843. const char *expected;
  3844. } cases[] = {
  3845. {"/a b?x=1", "/a%20b?x=1"},
  3846. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3847. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3848. };
  3849. for (const auto &c : cases) {
  3850. Client cli(HOST, port);
  3851. target.clear();
  3852. auto res = cli.Get(c.path);
  3853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3854. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3855. auto buffered_target = target;
  3856. target.clear();
  3857. auto handle = cli.open_stream("GET", c.path);
  3858. EXPECT_TRUE(handle.is_valid())
  3859. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3860. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3861. }
  3862. }
  3863. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3864. // The `set_path_encode(false)` contract — transmit the supplied target
  3865. // verbatim — must hold for the streaming API too.
  3866. Server svr;
  3867. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3868. std::string target;
  3869. svr.Get("/foo", [&](const Request &req, Response &res) {
  3870. target = req.target;
  3871. res.status = StatusCode::OK_200;
  3872. });
  3873. auto port = svr.bind_to_any_port(HOST);
  3874. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3875. auto se = detail::scope_exit([&] {
  3876. svr.stop();
  3877. thread.join();
  3878. ASSERT_FALSE(svr.is_running());
  3879. });
  3880. svr.wait_until_ready();
  3881. {
  3882. Client cli(HOST, port);
  3883. cli.set_path_encode(false);
  3884. auto handle = cli.open_stream("GET", expected_target);
  3885. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3886. EXPECT_EQ(expected_target, target);
  3887. }
  3888. }
  3889. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3890. // With path encoding enabled a CR/LF in the target is percent-encoded
  3891. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3892. // write_request_line still backstops `set_path_encode(false)`, which is
  3893. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3894. Server svr;
  3895. // Captured before routing: the decoded path contains a newline, which a
  3896. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3897. std::string target;
  3898. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3899. target = req.target;
  3900. res.status = StatusCode::OK_200;
  3901. return Server::HandlerResponse::Handled;
  3902. });
  3903. auto port = svr.bind_to_any_port(HOST);
  3904. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3905. auto se = detail::scope_exit([&] {
  3906. svr.stop();
  3907. thread.join();
  3908. ASSERT_FALSE(svr.is_running());
  3909. });
  3910. svr.wait_until_ready();
  3911. {
  3912. Client cli(HOST, port);
  3913. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3914. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3915. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3916. }
  3917. }
  3918. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3919. // Every control character is percent-encoded, not just CR/LF, so the target
  3920. // passes the request-target check in write_request_line.
  3921. Server svr;
  3922. std::string target;
  3923. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3924. target = req.target;
  3925. res.status = StatusCode::OK_200;
  3926. return Server::HandlerResponse::Handled;
  3927. });
  3928. auto port = svr.bind_to_any_port(HOST);
  3929. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3930. auto se = detail::scope_exit([&] {
  3931. svr.stop();
  3932. thread.join();
  3933. ASSERT_FALSE(svr.is_running());
  3934. });
  3935. svr.wait_until_ready();
  3936. {
  3937. Client cli(HOST, port);
  3938. auto res = cli.Get("/a\tb\x1b\x7f");
  3939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3940. EXPECT_EQ("/a%09b%1B%7F", target);
  3941. }
  3942. }
  3943. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3944. // Nothing may reach the wire: a raw CR/LF target would split the request
  3945. // line and inject headers.
  3946. Server svr;
  3947. // Pre-routing so that "not called" means nothing reached the server at all,
  3948. // rather than merely failing to match a handler pattern.
  3949. auto handler_called = false;
  3950. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3951. handler_called = true;
  3952. res.status = StatusCode::OK_200;
  3953. return Server::HandlerResponse::Handled;
  3954. });
  3955. auto port = svr.bind_to_any_port(HOST);
  3956. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3957. auto se = detail::scope_exit([&] {
  3958. svr.stop();
  3959. thread.join();
  3960. ASSERT_FALSE(svr.is_running());
  3961. });
  3962. svr.wait_until_ready();
  3963. {
  3964. Client cli(HOST, port);
  3965. cli.set_path_encode(false);
  3966. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3967. EXPECT_FALSE(handle.is_valid());
  3968. EXPECT_EQ(Error::Write, handle.error);
  3969. EXPECT_FALSE(handler_called);
  3970. }
  3971. }
  3972. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3973. // Which of the two branches runs is decided by whether the query component
  3974. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3975. // an empty query and must still fall back to building one from
  3976. // `req.params`, while a non-empty query must win over `req.params`.
  3977. Server svr;
  3978. std::string target;
  3979. svr.Get("/foo", [&](const Request &req, Response &res) {
  3980. target = req.target;
  3981. res.status = StatusCode::OK_200;
  3982. });
  3983. auto port = svr.bind_to_any_port(HOST);
  3984. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3985. auto se = detail::scope_exit([&] {
  3986. svr.stop();
  3987. thread.join();
  3988. ASSERT_FALSE(svr.is_running());
  3989. });
  3990. svr.wait_until_ready();
  3991. {
  3992. // Trailing `?` -> empty query component -> `req.params` is used.
  3993. Client cli(HOST, port);
  3994. Request req;
  3995. req.method = "GET";
  3996. req.path = "/foo?";
  3997. req.params.emplace("a", "1");
  3998. target.clear();
  3999. auto res = cli.send(req);
  4000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4001. EXPECT_EQ("/foo?a=1", target);
  4002. }
  4003. {
  4004. // Non-empty query in `req.path` -> `req.params` is not appended.
  4005. Client cli(HOST, port);
  4006. Request req;
  4007. req.method = "GET";
  4008. req.path = "/foo?b=2";
  4009. req.params.emplace("a", "1");
  4010. target.clear();
  4011. auto res = cli.send(req);
  4012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4013. EXPECT_EQ("/foo?b=2", target);
  4014. }
  4015. }
  4016. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4017. Server svr;
  4018. svr.Get("/", [](const Request &req, Response &) {
  4019. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4020. });
  4021. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4022. auto se = detail::scope_exit([&] {
  4023. svr.stop();
  4024. thread.join();
  4025. ASSERT_FALSE(svr.is_running());
  4026. });
  4027. svr.wait_until_ready();
  4028. {
  4029. Client cli(HOST, PORT);
  4030. cli.set_path_encode(false);
  4031. auto res = cli.Get("/?something=%0A");
  4032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4033. EXPECT_EQ(StatusCode::OK_200, res->status);
  4034. }
  4035. }
  4036. TEST(BindServerTest, BindDualStack) {
  4037. Server svr;
  4038. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4039. res.set_content("Hello World!", "text/plain");
  4040. });
  4041. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4042. auto se = detail::scope_exit([&] {
  4043. svr.stop();
  4044. thread.join();
  4045. ASSERT_FALSE(svr.is_running());
  4046. });
  4047. svr.wait_until_ready();
  4048. {
  4049. Client cli("127.0.0.1", PORT);
  4050. auto res = cli.Get("/1");
  4051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4052. EXPECT_EQ(StatusCode::OK_200, res->status);
  4053. EXPECT_EQ("Hello World!", res->body);
  4054. }
  4055. {
  4056. Client cli("::1", PORT);
  4057. auto res = cli.Get("/1");
  4058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4059. EXPECT_EQ(StatusCode::OK_200, res->status);
  4060. EXPECT_EQ("Hello World!", res->body);
  4061. }
  4062. }
  4063. TEST(BindServerTest, BindAndListenSeparately) {
  4064. Server svr;
  4065. int port = svr.bind_to_any_port("0.0.0.0");
  4066. ASSERT_TRUE(svr.is_valid());
  4067. ASSERT_TRUE(port > 0);
  4068. svr.stop();
  4069. }
  4070. // Reports whether anything is still listening on a loopback port. A plain
  4071. // connect() is used instead of a Client request because a socket left bound by
  4072. // mistake accepts the connection into its backlog and never answers, which
  4073. // would hang the test instead of failing it.
  4074. static bool is_loopback_port_accepting(int port) {
  4075. sockaddr_in addr{};
  4076. addr.sin_family = AF_INET;
  4077. addr.sin_port = htons(static_cast<uint16_t>(port));
  4078. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4079. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4080. EXPECT_NE(sock, INVALID_SOCKET);
  4081. if (sock == INVALID_SOCKET) { return false; }
  4082. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4083. static_cast<socklen_t>(sizeof(addr)));
  4084. detail::close_socket(sock);
  4085. return ret == 0;
  4086. }
  4087. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4088. Server svr;
  4089. auto port = svr.bind_to_any_port("127.0.0.1");
  4090. ASSERT_TRUE(port > 0);
  4091. svr.stop();
  4092. // bind_to_any_port() already called listen(2), so until stop() closed the
  4093. // descriptor the port kept accepting connections into the backlog. ASSERT
  4094. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4095. // below blocks forever in the accept loop.
  4096. ASSERT_FALSE(is_loopback_port_accepting(port));
  4097. // Nothing is left to accept on, so listen_after_bind() must report failure
  4098. // instead of returning success without ever serving.
  4099. EXPECT_FALSE(svr.listen_after_bind());
  4100. // The failed listen marks the server decommissioned, so a waiter returns
  4101. // instead of spinning forever.
  4102. svr.wait_until_ready();
  4103. }
  4104. #ifdef CPPHTTPLIB_SSL_ENABLED
  4105. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4107. CLIENT_CA_CERT_DIR);
  4108. int port = svr.bind_to_any_port("0.0.0.0");
  4109. ASSERT_TRUE(svr.is_valid());
  4110. ASSERT_TRUE(port > 0);
  4111. svr.stop();
  4112. }
  4113. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4114. // or a rejected CustomRoute() registration would not stop the server binding.
  4115. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4116. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4117. CLIENT_CA_CERT_DIR);
  4118. ASSERT_TRUE(svr.is_valid());
  4119. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4120. EXPECT_FALSE(svr.is_valid());
  4121. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4122. }
  4123. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4124. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4125. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4126. int port = svr.bind_to_any_port("0.0.0.0");
  4127. ASSERT_TRUE(svr.is_valid());
  4128. ASSERT_TRUE(port > 0);
  4129. svr.stop();
  4130. }
  4131. TEST(BindServerTest, UpdateCertsPem) {
  4132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4133. int port = svr.bind_to_any_port("0.0.0.0");
  4134. ASSERT_TRUE(svr.is_valid());
  4135. ASSERT_TRUE(port > 0);
  4136. // Read PEM files
  4137. std::string cert_pem, key_pem, ca_pem;
  4138. read_file(SERVER_CERT_FILE, cert_pem);
  4139. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4140. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4141. // Update server certificates using PEM API
  4142. ASSERT_TRUE(
  4143. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4144. ASSERT_TRUE(svr.is_valid());
  4145. svr.stop();
  4146. }
  4147. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4148. // Start server with client CA (enables client auth)
  4149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4150. ASSERT_TRUE(svr.is_valid());
  4151. bool handler_called = false;
  4152. svr.Get("/test", [&](const Request &req, Response &res) {
  4153. handler_called = true;
  4154. // Verify client certificate is present
  4155. auto cert = req.peer_cert();
  4156. EXPECT_TRUE(static_cast<bool>(cert));
  4157. res.set_content("ok", "text/plain");
  4158. });
  4159. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4160. auto se = detail::scope_exit([&] {
  4161. svr.stop();
  4162. t.join();
  4163. ASSERT_FALSE(svr.is_running());
  4164. });
  4165. svr.wait_until_ready();
  4166. // Read PEM files
  4167. std::string cert_pem, key_pem, ca_pem;
  4168. read_file(SERVER_CERT_FILE, cert_pem);
  4169. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4170. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4171. // Update server certificates and client CA using PEM API while server running
  4172. ASSERT_TRUE(
  4173. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4174. // Connect with client certificate
  4175. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4176. cli.enable_server_certificate_verification(false);
  4177. cli.set_connection_timeout(30);
  4178. auto res = cli.Get("/test");
  4179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4180. ASSERT_EQ(StatusCode::OK_200, res->status);
  4181. ASSERT_TRUE(handler_called);
  4182. EXPECT_EQ("ok", res->body);
  4183. }
  4184. // Puts a CA that did not sign the client's certificate in the old one's place.
  4185. static bool replace_client_ca(SSLServer &svr) {
  4186. std::string cert_pem, key_pem, ca_pem;
  4187. read_file(SERVER_CERT_FILE, cert_pem);
  4188. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4189. read_file(SERVER_CERT2_FILE, ca_pem);
  4190. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4191. ca_pem.c_str());
  4192. }
  4193. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4194. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4195. ASSERT_TRUE(svr.is_valid());
  4196. svr.Get("/test", [](const Request &, Response &res) {
  4197. res.set_content("ok", "text/plain");
  4198. });
  4199. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4200. auto se = detail::scope_exit([&] {
  4201. svr.stop();
  4202. t.join();
  4203. ASSERT_FALSE(svr.is_running());
  4204. });
  4205. svr.wait_until_ready();
  4206. auto get = [] {
  4207. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4208. cli.enable_server_certificate_verification(false);
  4209. return cli.Get("/test");
  4210. };
  4211. ASSERT_TRUE(get());
  4212. ASSERT_TRUE(replace_client_ca(svr));
  4213. EXPECT_FALSE(get());
  4214. }
  4215. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4216. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4217. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4218. ASSERT_TRUE(svr.is_valid());
  4219. tls::set_verify_callback(svr.tls_context(),
  4220. [](const tls::VerifyContext &) -> bool {
  4221. throw std::runtime_error("verify");
  4222. });
  4223. svr.Get("/test", [](const Request &, Response &res) {
  4224. res.set_content("ok", "text/plain");
  4225. });
  4226. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4227. auto se = detail::scope_exit([&] {
  4228. svr.stop();
  4229. t.join();
  4230. ASSERT_FALSE(svr.is_running());
  4231. });
  4232. svr.wait_until_ready();
  4233. auto get = [] {
  4234. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4235. cli.enable_server_certificate_verification(false);
  4236. return cli.Get("/test");
  4237. };
  4238. EXPECT_FALSE(get());
  4239. // The handshake is over, so an update does not wait for it.
  4240. std::string cert_pem, key_pem;
  4241. read_file(SERVER_CERT_FILE, cert_pem);
  4242. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4243. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4244. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4245. return v.preverify_ok;
  4246. });
  4247. auto res = get();
  4248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4249. EXPECT_EQ("ok", res->body);
  4250. }
  4251. #endif
  4252. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4253. // Sends each request over a new connection with a client certificate,
  4254. // resuming the session of the one before when there is one.
  4255. class ResumingClient {
  4256. public:
  4257. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4258. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4259. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4260. SSL_FILETYPE_PEM);
  4261. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4262. // callback, not through SSL_get1_session().
  4263. SSL_CTX_set_app_data(ctx_, this);
  4264. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4265. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4266. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4267. auto self = static_cast<ResumingClient *>(
  4268. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4269. SSL_SESSION_free(self->session_);
  4270. self->session_ = session;
  4271. return 1; // Keeps the reference
  4272. });
  4273. }
  4274. ~ResumingClient() {
  4275. SSL_SESSION_free(session_);
  4276. SSL_CTX_free(ctx_);
  4277. }
  4278. // Tells whether the request was answered.
  4279. bool get() {
  4280. auto error = Error::Success;
  4281. auto sock = detail::create_client_socket(
  4282. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4283. /*connection_timeout_sec=*/5, 0,
  4284. /*read_timeout_sec=*/5, 0,
  4285. /*write_timeout_sec=*/5, 0, std::string(), error);
  4286. if (sock == INVALID_SOCKET) { return false; }
  4287. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4288. auto ssl = SSL_new(ctx_);
  4289. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4290. SSL_set_fd(ssl, static_cast<int>(sock));
  4291. if (session_) { SSL_set_session(ssl, session_); }
  4292. if (SSL_connect(ssl) != 1) { return false; }
  4293. reused_ = SSL_session_reused(ssl) == 1;
  4294. // Reading the response also takes in a TLS 1.3 session ticket.
  4295. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4296. "Connection: close\r\n\r\n";
  4297. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4298. std::string res;
  4299. char buf[256];
  4300. int n;
  4301. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4302. res.append(buf, static_cast<size_t>(n));
  4303. }
  4304. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4305. SSL_shutdown(ssl);
  4306. return res.find("200 OK") != std::string::npos;
  4307. }
  4308. // Whether the last connection resumed a session
  4309. bool reused() const { return reused_; }
  4310. private:
  4311. SSL_CTX *ctx_;
  4312. SSL_SESSION *session_ = nullptr;
  4313. bool reused_ = false;
  4314. };
  4315. // A client that resumes its session gets through, but not once the client CA
  4316. // has changed, as a resumed session does not show the certificate again.
  4317. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4319. ASSERT_TRUE(svr.is_valid());
  4320. svr.Get("/test", [](const Request &, Response &res) {
  4321. res.set_content("ok", "text/plain");
  4322. });
  4323. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4324. auto se = detail::scope_exit([&] {
  4325. svr.stop();
  4326. t.join();
  4327. ASSERT_FALSE(svr.is_running());
  4328. });
  4329. svr.wait_until_ready();
  4330. ResumingClient cli;
  4331. ASSERT_TRUE(cli.get());
  4332. ASSERT_TRUE(cli.get());
  4333. EXPECT_TRUE(cli.reused());
  4334. ASSERT_TRUE(replace_client_ca(svr));
  4335. EXPECT_FALSE(cli.get());
  4336. }
  4337. // A resumed session does not show the certificate again, so the server does
  4338. // not resume one with a verify callback to run on it.
  4339. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4341. ASSERT_TRUE(svr.is_valid());
  4342. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4343. return v.preverify_ok;
  4344. });
  4345. svr.Get("/test", [](const Request &, Response &res) {
  4346. res.set_content("ok", "text/plain");
  4347. });
  4348. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4349. auto se = detail::scope_exit([&] {
  4350. svr.stop();
  4351. t.join();
  4352. ASSERT_FALSE(svr.is_running());
  4353. });
  4354. svr.wait_until_ready();
  4355. ResumingClient cli;
  4356. ASSERT_TRUE(cli.get());
  4357. ASSERT_TRUE(cli.get());
  4358. EXPECT_FALSE(cli.reused());
  4359. }
  4360. #endif
  4361. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4362. // wolfSSL shares its session cache between contexts, so a resumed session
  4363. // could carry a client certificate checked against another server's CA, or
  4364. // against a client CA since replaced.
  4365. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4366. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4367. ASSERT_TRUE(svr.is_valid());
  4368. // Trusts a CA that did not sign the client's certificate.
  4369. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4370. ASSERT_TRUE(other.is_valid());
  4371. for (auto s : {&svr, &other}) {
  4372. s->Get("/test", [](const Request &, Response &res) {
  4373. res.set_content("ok", "text/plain");
  4374. });
  4375. }
  4376. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4377. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4378. auto se = detail::scope_exit([&] {
  4379. other.stop();
  4380. svr.stop();
  4381. t2.join();
  4382. t.join();
  4383. });
  4384. svr.wait_until_ready();
  4385. other.wait_until_ready();
  4386. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4387. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4388. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4389. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4390. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4391. ASSERT_EQ(WOLFSSL_SUCCESS,
  4392. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4393. WOLFSSL_FILETYPE_PEM));
  4394. WOLFSSL_SESSION *session = nullptr;
  4395. auto session_se = detail::scope_exit([&] {
  4396. if (session) { wolfSSL_SESSION_free(session); }
  4397. });
  4398. // A request over a new connection, resuming `session` when there is one and
  4399. // keeping the connection's own in its place. Tells whether it was answered.
  4400. auto get = [&](int port) {
  4401. auto error = Error::Success;
  4402. auto sock = detail::create_client_socket(
  4403. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4404. /*connection_timeout_sec=*/5, 0,
  4405. /*read_timeout_sec=*/5, 0,
  4406. /*write_timeout_sec=*/5, 0, std::string(), error);
  4407. if (sock == INVALID_SOCKET) { return false; }
  4408. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4409. auto ssl = wolfSSL_new(ctx);
  4410. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4411. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4412. if (session) { wolfSSL_set_session(ssl, session); }
  4413. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4414. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4415. "Connection: close\r\n\r\n";
  4416. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4417. std::string res;
  4418. char buf[256];
  4419. int n;
  4420. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4421. res.append(buf, static_cast<size_t>(n));
  4422. }
  4423. wolfSSL_shutdown(ssl);
  4424. if (session) { wolfSSL_SESSION_free(session); }
  4425. session = wolfSSL_get1_session(ssl);
  4426. return res.find("200 OK") != std::string::npos;
  4427. };
  4428. ASSERT_TRUE(get(PORT));
  4429. EXPECT_FALSE(get(PORT + 1));
  4430. ASSERT_TRUE(get(PORT));
  4431. ASSERT_TRUE(replace_client_ca(svr));
  4432. EXPECT_FALSE(get(PORT));
  4433. }
  4434. #endif
  4435. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4437. ASSERT_TRUE(svr.is_valid());
  4438. svr.Get("/test", [](const Request &, Response &res) {
  4439. res.set_content("ok", "text/plain");
  4440. });
  4441. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4442. auto se = detail::scope_exit([&] {
  4443. svr.stop();
  4444. t.join();
  4445. ASSERT_FALSE(svr.is_running());
  4446. });
  4447. svr.wait_until_ready();
  4448. // A connection that sends no ClientHello keeps its handshake in progress,
  4449. // once the server has had a moment to start it.
  4450. auto error = Error::Success;
  4451. auto sock = detail::create_client_socket(
  4452. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4453. /*connection_timeout_sec=*/5, 0,
  4454. /*read_timeout_sec=*/5, 0,
  4455. /*write_timeout_sec=*/5, 0, std::string(), error);
  4456. ASSERT_NE(INVALID_SOCKET, sock);
  4457. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4458. std::string cert_pem, key_pem;
  4459. read_file(SERVER_CERT_FILE, cert_pem);
  4460. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4461. auto update = std::async(std::launch::async, [&]() {
  4462. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4463. });
  4464. EXPECT_EQ(std::future_status::timeout,
  4465. update.wait_for(std::chrono::milliseconds(200)));
  4466. detail::close_socket(sock);
  4467. EXPECT_TRUE(update.get());
  4468. SSLClient cli(HOST, PORT);
  4469. cli.enable_server_certificate_verification(false);
  4470. auto res = cli.Get("/test");
  4471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. }
  4474. #endif
  4475. TEST(ErrorHandlerTest, ContentLength) {
  4476. Server svr;
  4477. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4478. res.status = StatusCode::OK_200;
  4479. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4480. "text/html"); // <= Content-Length still 13
  4481. });
  4482. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4483. res.set_content("Hello World!\n", "text/plain");
  4484. res.status = 524;
  4485. });
  4486. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4487. auto se = detail::scope_exit([&] {
  4488. svr.stop();
  4489. thread.join();
  4490. ASSERT_FALSE(svr.is_running());
  4491. });
  4492. svr.wait_until_ready();
  4493. {
  4494. Client cli(HOST, PORT);
  4495. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4497. EXPECT_EQ(StatusCode::OK_200, res->status);
  4498. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4499. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4500. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4501. }
  4502. }
  4503. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4504. TEST(ExceptionTest, WithoutExceptionHandler) {
  4505. Server svr;
  4506. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4507. throw std::runtime_error("exception...");
  4508. });
  4509. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4510. throw std::runtime_error("exception\r\n...");
  4511. });
  4512. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4513. auto se = detail::scope_exit([&] {
  4514. svr.stop();
  4515. listen_thread.join();
  4516. ASSERT_FALSE(svr.is_running());
  4517. });
  4518. svr.wait_until_ready();
  4519. Client cli("localhost", PORT);
  4520. {
  4521. auto res = cli.Get("/exception");
  4522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4523. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4524. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4525. }
  4526. {
  4527. auto res = cli.Get("/unknown");
  4528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4529. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4530. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4531. }
  4532. }
  4533. TEST(ExceptionTest, WithExceptionHandler) {
  4534. Server svr;
  4535. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4536. std::exception_ptr ep) {
  4537. EXPECT_FALSE(ep == nullptr);
  4538. try {
  4539. std::rethrow_exception(ep);
  4540. } catch (std::exception &e) {
  4541. EXPECT_EQ("abc", std::string(e.what()));
  4542. } catch (...) {}
  4543. res.status = StatusCode::InternalServerError_500;
  4544. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4545. "text/html"); // <= Content-Length still 13 at this point
  4546. });
  4547. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4548. res.set_content("Hello World!\n", "text/plain");
  4549. throw std::runtime_error("abc");
  4550. });
  4551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4552. auto se = detail::scope_exit([&] {
  4553. svr.stop();
  4554. thread.join();
  4555. ASSERT_FALSE(svr.is_running());
  4556. });
  4557. svr.wait_until_ready();
  4558. for (size_t i = 0; i < 10; i++) {
  4559. Client cli(HOST, PORT);
  4560. for (size_t j = 0; j < 100; j++) {
  4561. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4563. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4564. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4565. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4566. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4567. }
  4568. cli.set_keep_alive(true);
  4569. for (size_t j = 0; j < 100; j++) {
  4570. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4572. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4573. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4574. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4575. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4576. }
  4577. }
  4578. }
  4579. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4580. Server svr;
  4581. svr.set_exception_handler(
  4582. [](const Request &, Response &res, std::exception_ptr) {
  4583. res.set_content("oops", "text/plain");
  4584. });
  4585. svr.Get("/throw", [](const Request &, Response &) {
  4586. throw std::runtime_error("throw");
  4587. });
  4588. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4589. res.status = StatusCode::Created_201;
  4590. throw std::runtime_error("created-then-throw");
  4591. });
  4592. auto port = svr.bind_to_any_port(HOST);
  4593. ASSERT_GT(port, 0);
  4594. thread t = thread([&] { svr.listen_after_bind(); });
  4595. auto se = detail::scope_exit([&] {
  4596. svr.stop();
  4597. t.join();
  4598. ASSERT_FALSE(svr.is_running());
  4599. });
  4600. svr.wait_until_ready();
  4601. Client cli(HOST, port);
  4602. for (auto path : {"/throw", "/created-then-throw"}) {
  4603. auto res = cli.Get(path);
  4604. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4605. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4606. }
  4607. }
  4608. TEST(ExceptionTest, AndErrorHandler) {
  4609. Server svr;
  4610. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4611. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4612. });
  4613. svr.set_exception_handler(
  4614. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4615. EXPECT_FALSE(ep == nullptr);
  4616. try {
  4617. std::rethrow_exception(ep);
  4618. } catch (std::exception &e) {
  4619. res.set_content(e.what(), "text/html");
  4620. } catch (...) {}
  4621. res.status = StatusCode::InternalServerError_500;
  4622. });
  4623. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4624. throw std::runtime_error("EXCEPTION");
  4625. });
  4626. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4627. res.set_content("ERROR", "text/html");
  4628. res.status = StatusCode::InternalServerError_500;
  4629. });
  4630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4631. auto se = detail::scope_exit([&] {
  4632. svr.stop();
  4633. thread.join();
  4634. ASSERT_FALSE(svr.is_running());
  4635. });
  4636. svr.wait_until_ready();
  4637. Client cli(HOST, PORT);
  4638. {
  4639. auto res = cli.Get("/exception");
  4640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4641. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4642. EXPECT_EQ("EXCEPTION", res->body);
  4643. }
  4644. {
  4645. auto res = cli.Get("/error");
  4646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4647. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4648. EXPECT_EQ("ERROR", res->body);
  4649. }
  4650. {
  4651. auto res = cli.Get("/invalid");
  4652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4653. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4654. EXPECT_EQ("NOT_FOUND", res->body);
  4655. }
  4656. }
  4657. #endif
  4658. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4659. // An exception from a user callback outside process_request()'s try/catch
  4660. // used to unwind into the task queue - which does not catch - and terminate
  4661. // the process. Each test below runs the server on a single worker thread: a
  4662. // guard that catches the exception but still loses the thread would otherwise
  4663. // be hidden by a spare worker serving the follow-up request. Note that a
  4664. // regression here aborts the whole test binary rather than failing one test.
  4665. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4666. Server svr;
  4667. svr.new_task_queue = [] { return new ThreadPool(1); };
  4668. std::atomic<int> reported{0};
  4669. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4670. if (err == Error::UserCallbackException) { reported++; }
  4671. });
  4672. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4673. res.set_content_provider(
  4674. 1024, "text/plain",
  4675. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4676. sink.write("hello", 5);
  4677. throw std::runtime_error("from the content provider");
  4678. });
  4679. });
  4680. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4681. res.set_content("ok", "text/plain");
  4682. });
  4683. auto port = svr.bind_to_any_port(HOST);
  4684. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4685. auto se = detail::scope_exit([&] {
  4686. svr.stop();
  4687. listen_thread.join();
  4688. ASSERT_FALSE(svr.is_running());
  4689. });
  4690. svr.wait_until_ready();
  4691. {
  4692. Client cli(HOST, port);
  4693. cli.set_read_timeout(5, 0);
  4694. EXPECT_FALSE(cli.Get("/throw"));
  4695. }
  4696. EXPECT_TRUE(svr.is_running());
  4697. EXPECT_EQ(1, reported.load());
  4698. // A request on a fresh connection is still served.
  4699. {
  4700. Client cli(HOST, port);
  4701. auto res = cli.Get("/ok");
  4702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("ok", res->body);
  4705. }
  4706. }
  4707. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4708. Server svr;
  4709. svr.new_task_queue = [] { return new ThreadPool(1); };
  4710. std::atomic<bool> should_throw{true};
  4711. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4712. res.set_content("hi", "text/plain");
  4713. });
  4714. svr.set_post_routing_handler(
  4715. [&](const Request & /*req*/, Response & /*res*/) {
  4716. if (should_throw) {
  4717. throw std::runtime_error("from the post-routing handler");
  4718. }
  4719. });
  4720. auto port = svr.bind_to_any_port(HOST);
  4721. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4722. auto se = detail::scope_exit([&] {
  4723. svr.stop();
  4724. listen_thread.join();
  4725. ASSERT_FALSE(svr.is_running());
  4726. });
  4727. svr.wait_until_ready();
  4728. {
  4729. Client cli(HOST, port);
  4730. cli.set_read_timeout(5, 0);
  4731. EXPECT_FALSE(cli.Get("/hi"));
  4732. }
  4733. EXPECT_TRUE(svr.is_running());
  4734. should_throw = false;
  4735. {
  4736. Client cli(HOST, port);
  4737. auto res = cli.Get("/hi");
  4738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4739. EXPECT_EQ(StatusCode::OK_200, res->status);
  4740. EXPECT_EQ("hi", res->body);
  4741. }
  4742. }
  4743. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4744. // The guard reports the caught exception through the error logger, which is
  4745. // a user callback too. A logger that throws has to be contained as well, or
  4746. // the process would terminate from inside the catch.
  4747. Server svr;
  4748. svr.new_task_queue = [] { return new ThreadPool(1); };
  4749. std::atomic<int> reported{0};
  4750. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4751. if (err == Error::UserCallbackException) {
  4752. reported++;
  4753. throw std::runtime_error("from the error logger");
  4754. }
  4755. });
  4756. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4757. res.set_content_provider(
  4758. 1024, "text/plain",
  4759. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4760. sink.write("hello", 5);
  4761. throw std::runtime_error("from the content provider");
  4762. });
  4763. });
  4764. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4765. res.set_content("ok", "text/plain");
  4766. });
  4767. auto port = svr.bind_to_any_port(HOST);
  4768. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4769. auto se = detail::scope_exit([&] {
  4770. svr.stop();
  4771. listen_thread.join();
  4772. ASSERT_FALSE(svr.is_running());
  4773. });
  4774. svr.wait_until_ready();
  4775. {
  4776. Client cli(HOST, port);
  4777. cli.set_read_timeout(5, 0);
  4778. EXPECT_FALSE(cli.Get("/throw"));
  4779. }
  4780. EXPECT_TRUE(svr.is_running());
  4781. EXPECT_EQ(1, reported.load());
  4782. {
  4783. Client cli(HOST, port);
  4784. auto res = cli.Get("/ok");
  4785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4786. EXPECT_EQ(StatusCode::OK_200, res->status);
  4787. EXPECT_EQ("ok", res->body);
  4788. }
  4789. }
  4790. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4791. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4792. // so the exception unwinds through the ws::WebSocket object on its way to
  4793. // the guard. None of the HTTP cases above cross that.
  4794. Server svr;
  4795. svr.new_task_queue = [] { return new ThreadPool(1); };
  4796. std::atomic<int> reported{0};
  4797. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4798. if (err == Error::UserCallbackException) { reported++; }
  4799. });
  4800. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4801. throw std::runtime_error("from the WebSocket handler");
  4802. });
  4803. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4804. res.set_content("ok", "text/plain");
  4805. });
  4806. auto port = svr.bind_to_any_port(HOST);
  4807. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4808. auto se = detail::scope_exit([&] {
  4809. svr.stop();
  4810. listen_thread.join();
  4811. ASSERT_FALSE(svr.is_running());
  4812. });
  4813. svr.wait_until_ready();
  4814. {
  4815. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4816. "/ws");
  4817. auto res = client.connect();
  4818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4819. // The server dropped the connection instead of dying.
  4820. std::string msg;
  4821. EXPECT_FALSE(client.read(msg));
  4822. client.close();
  4823. }
  4824. EXPECT_TRUE(svr.is_running());
  4825. EXPECT_EQ(1, reported.load());
  4826. {
  4827. Client cli(HOST, port);
  4828. auto res = cli.Get("/ok");
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. EXPECT_EQ(StatusCode::OK_200, res->status);
  4831. EXPECT_EQ("ok", res->body);
  4832. }
  4833. }
  4834. #ifdef CPPHTTPLIB_SSL_ENABLED
  4835. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4836. // SSLServer::process_and_close_socket() is a separate overload with its own
  4837. // guard, so it is exercised on its own.
  4838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4839. ASSERT_TRUE(svr.is_valid());
  4840. svr.new_task_queue = [] { return new ThreadPool(1); };
  4841. std::atomic<int> reported{0};
  4842. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4843. if (err == Error::UserCallbackException) { reported++; }
  4844. });
  4845. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4846. res.set_content_provider(
  4847. 1024, "text/plain",
  4848. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4849. sink.write("hello", 5);
  4850. throw std::runtime_error("from the content provider");
  4851. });
  4852. });
  4853. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4854. res.set_content("ok", "text/plain");
  4855. });
  4856. auto port = svr.bind_to_any_port(HOST);
  4857. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4858. auto se = detail::scope_exit([&] {
  4859. svr.stop();
  4860. listen_thread.join();
  4861. ASSERT_FALSE(svr.is_running());
  4862. });
  4863. svr.wait_until_ready();
  4864. {
  4865. SSLClient cli(HOST, port);
  4866. cli.enable_server_certificate_verification(false);
  4867. cli.set_read_timeout(5, 0);
  4868. EXPECT_FALSE(cli.Get("/throw"));
  4869. }
  4870. EXPECT_TRUE(svr.is_running());
  4871. EXPECT_EQ(1, reported.load());
  4872. {
  4873. SSLClient cli(HOST, port);
  4874. cli.enable_server_certificate_verification(false);
  4875. auto res = cli.Get("/ok");
  4876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4877. EXPECT_EQ(StatusCode::OK_200, res->status);
  4878. EXPECT_EQ("ok", res->body);
  4879. }
  4880. }
  4881. #endif
  4882. #endif
  4883. TEST(NoContentTest, ContentLength) {
  4884. Server svr;
  4885. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4886. res.status = StatusCode::NoContent_204;
  4887. });
  4888. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4889. auto se = detail::scope_exit([&] {
  4890. svr.stop();
  4891. thread.join();
  4892. ASSERT_FALSE(svr.is_running());
  4893. });
  4894. svr.wait_until_ready();
  4895. {
  4896. Client cli(HOST, PORT);
  4897. auto res = cli.Get("/hi");
  4898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4899. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4900. // RFC 9110 8.6: none in a 204 response
  4901. EXPECT_FALSE(res->has_header("Content-Length"));
  4902. }
  4903. }
  4904. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4905. Server svr;
  4906. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4907. res.set_header("Content-Length", "5");
  4908. res.set_content("hello world", "text/plain");
  4909. });
  4910. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4911. // A body that reads as the last chunk, were it taken as chunked
  4912. res.set_header("Transfer-Encoding", "chunked");
  4913. res.set_content("0\r\n\r\n", "text/plain");
  4914. });
  4915. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4916. res.set_header("Content-Length", "2");
  4917. res.set_content_provider(5, "text/plain",
  4918. [](size_t offset, size_t length, DataSink &sink) {
  4919. sink.write(&"hello"[offset], length);
  4920. return true;
  4921. });
  4922. });
  4923. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4924. res.set_header("Content-Length", "1234");
  4925. });
  4926. thread t = thread([&] { svr.listen(HOST, PORT); });
  4927. auto se = detail::scope_exit([&] {
  4928. svr.stop();
  4929. t.join();
  4930. ASSERT_FALSE(svr.is_running());
  4931. });
  4932. svr.wait_until_ready();
  4933. Client cli(HOST, PORT);
  4934. cli.set_read_timeout(1, 0);
  4935. auto expect_body = [&](const Result &res, const std::string &body) {
  4936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4937. EXPECT_EQ(body, res->body);
  4938. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4939. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4940. };
  4941. Headers identity{{"Accept-Encoding", ""}};
  4942. expect_body(cli.Get("/body", identity), "hello world");
  4943. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4944. expect_body(cli.Get("/body",
  4945. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4946. "he");
  4947. expect_body(cli.Get("/provider", identity), "hello");
  4948. expect_body(cli.Get("/empty", identity), "");
  4949. // A HEAD response may give the length of the body a GET would get.
  4950. auto res = cli.Head("/empty");
  4951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4952. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4953. }
  4954. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4955. Server svr;
  4956. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4957. res.set_content("short", "text/plain");
  4958. });
  4959. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4960. res.body += " with a footer";
  4961. res.set_header("Transfer-Encoding", "chunked");
  4962. });
  4963. thread t = thread([&] { svr.listen(HOST, PORT); });
  4964. auto se = detail::scope_exit([&] {
  4965. svr.stop();
  4966. t.join();
  4967. ASSERT_FALSE(svr.is_running());
  4968. });
  4969. svr.wait_until_ready();
  4970. Client cli(HOST, PORT);
  4971. cli.set_read_timeout(1, 0);
  4972. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4974. EXPECT_EQ("short with a footer", res->body);
  4975. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4976. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4977. }
  4978. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4979. Server svr;
  4980. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4981. res.set_header("Content-Length", "3");
  4982. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4983. sink.write("abc", 3);
  4984. sink.done();
  4985. return true;
  4986. });
  4987. });
  4988. thread t = thread([&] { svr.listen(HOST, PORT); });
  4989. auto se = detail::scope_exit([&] {
  4990. svr.stop();
  4991. t.join();
  4992. ASSERT_FALSE(svr.is_running());
  4993. });
  4994. svr.wait_until_ready();
  4995. Client cli(HOST, PORT);
  4996. cli.set_keep_alive(true);
  4997. auto res = cli.Get("/");
  4998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4999. EXPECT_EQ("abc", res->body);
  5000. EXPECT_FALSE(res->has_header("Content-Length"));
  5001. EXPECT_EQ("close", res->get_header_value("Connection"));
  5002. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5003. // No body to delimit
  5004. auto head = cli.Head("/");
  5005. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5006. EXPECT_FALSE(head->has_header("Connection"));
  5007. }
  5008. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5009. #ifdef CPPHTTPLIB_SSL_ENABLED
  5010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5011. ASSERT_TRUE(svr.is_valid());
  5012. #else
  5013. Server svr;
  5014. #endif
  5015. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5016. if (req.path == "/routing_handler") {
  5017. res.set_header("PRE_ROUTING", "on");
  5018. res.set_content("Routing Handler", "text/plain");
  5019. return httplib::Server::HandlerResponse::Handled;
  5020. }
  5021. return httplib::Server::HandlerResponse::Unhandled;
  5022. });
  5023. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5024. res.set_content("Error", "text/html");
  5025. });
  5026. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5027. if (req.path == "/routing_handler") {
  5028. res.set_header("POST_ROUTING", "on");
  5029. }
  5030. });
  5031. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5032. res.set_content("Hello World!\n", "text/plain");
  5033. });
  5034. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5035. auto se = detail::scope_exit([&] {
  5036. svr.stop();
  5037. thread.join();
  5038. ASSERT_FALSE(svr.is_running());
  5039. });
  5040. svr.wait_until_ready();
  5041. {
  5042. #ifdef CPPHTTPLIB_SSL_ENABLED
  5043. SSLClient cli(HOST, PORT);
  5044. cli.enable_server_certificate_verification(false);
  5045. #else
  5046. Client cli(HOST, PORT);
  5047. #endif
  5048. auto res = cli.Get("/routing_handler");
  5049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5050. EXPECT_EQ(StatusCode::OK_200, res->status);
  5051. EXPECT_EQ("Routing Handler", res->body);
  5052. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5053. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5054. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5055. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5056. }
  5057. {
  5058. #ifdef CPPHTTPLIB_SSL_ENABLED
  5059. SSLClient cli(HOST, PORT);
  5060. cli.enable_server_certificate_verification(false);
  5061. #else
  5062. Client cli(HOST, PORT);
  5063. #endif
  5064. auto res = cli.Get("/hi");
  5065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5066. EXPECT_EQ(StatusCode::OK_200, res->status);
  5067. EXPECT_EQ("Hello World!\n", res->body);
  5068. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5069. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5070. }
  5071. {
  5072. #ifdef CPPHTTPLIB_SSL_ENABLED
  5073. SSLClient cli(HOST, PORT);
  5074. cli.enable_server_certificate_verification(false);
  5075. #else
  5076. Client cli(HOST, PORT);
  5077. #endif
  5078. auto res = cli.Get("/aaa");
  5079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5081. EXPECT_EQ("Error", res->body);
  5082. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5083. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5084. }
  5085. }
  5086. TEST(RequestHandlerTest, PreRequestHandler) {
  5087. auto route_path = "/user/:user";
  5088. Server svr;
  5089. svr.Get("/hi", [](const Request &, Response &res) {
  5090. res.set_content("hi", "text/plain");
  5091. });
  5092. svr.Get(route_path, [](const Request &req, Response &res) {
  5093. res.set_content(req.path_params.at("user"), "text/plain");
  5094. });
  5095. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5096. if (req.matched_route == route_path) {
  5097. auto user = req.path_params.at("user");
  5098. if (user != "john") {
  5099. res.status = StatusCode::Forbidden_403;
  5100. res.set_content("error", "text/html");
  5101. return Server::HandlerResponse::Handled;
  5102. }
  5103. }
  5104. return Server::HandlerResponse::Unhandled;
  5105. });
  5106. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5107. auto se = detail::scope_exit([&] {
  5108. svr.stop();
  5109. thread.join();
  5110. ASSERT_FALSE(svr.is_running());
  5111. });
  5112. svr.wait_until_ready();
  5113. Client cli(HOST, PORT);
  5114. {
  5115. auto res = cli.Get("/hi");
  5116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. EXPECT_EQ("hi", res->body);
  5119. }
  5120. {
  5121. auto res = cli.Get("/user/john");
  5122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5123. EXPECT_EQ(StatusCode::OK_200, res->status);
  5124. EXPECT_EQ("john", res->body);
  5125. }
  5126. {
  5127. auto res = cli.Get("/user/invalid-user");
  5128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5129. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5130. EXPECT_EQ("error", res->body);
  5131. }
  5132. }
  5133. // The pre-request handler must run before the request body is read, so a
  5134. // rejected request never forces the server to buffer a (potentially large)
  5135. // body. Here the posted body is larger than the payload limit: if the body
  5136. // were read first the server would answer 413, but because the pre-request
  5137. // handler runs first it answers 403 and the body is never read.
  5138. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5139. Server svr;
  5140. svr.set_payload_max_length(8);
  5141. auto handler_ran = false;
  5142. svr.Post("/reject", [&](const Request &req, Response &res) {
  5143. handler_ran = true;
  5144. res.set_content(req.body, "text/plain");
  5145. });
  5146. svr.Post("/accept", [](const Request &req, Response &res) {
  5147. res.set_content(req.body, "text/plain");
  5148. });
  5149. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5150. if (req.matched_route == "/reject") {
  5151. res.status = StatusCode::Forbidden_403;
  5152. res.set_content("denied", "text/plain");
  5153. return Server::HandlerResponse::Handled;
  5154. }
  5155. return Server::HandlerResponse::Unhandled;
  5156. });
  5157. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5158. auto se = detail::scope_exit([&] {
  5159. svr.stop();
  5160. thread.join();
  5161. ASSERT_FALSE(svr.is_running());
  5162. });
  5163. svr.wait_until_ready();
  5164. Client cli(HOST, PORT);
  5165. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5166. // rejects with 403 before the body is read, so 413 is never reached.
  5167. {
  5168. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5170. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5171. EXPECT_EQ("denied", res->body);
  5172. EXPECT_FALSE(handler_ran);
  5173. }
  5174. // An approved route still reads the body and enforces the payload limit.
  5175. {
  5176. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5179. }
  5180. }
  5181. TEST(UserDataTest, BasicOperations) {
  5182. httplib::UserData ud;
  5183. // Initially empty
  5184. EXPECT_FALSE(ud.has("key"));
  5185. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5186. // set and get
  5187. ud.set("key", 42);
  5188. EXPECT_TRUE(ud.has("key"));
  5189. auto *p = ud.get<int>("key");
  5190. ASSERT_NE(nullptr, p);
  5191. EXPECT_EQ(42, *p);
  5192. // Type mismatch → nullptr
  5193. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5194. // Overwrite with different type
  5195. ud.set("key", std::string("hello"));
  5196. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5197. auto *s = ud.get<std::string>("key");
  5198. ASSERT_NE(nullptr, s);
  5199. EXPECT_EQ("hello", *s);
  5200. // erase
  5201. ud.erase("key");
  5202. EXPECT_FALSE(ud.has("key"));
  5203. // clear
  5204. ud.set("a", 1);
  5205. ud.set("b", 2);
  5206. ud.clear();
  5207. EXPECT_FALSE(ud.has("a"));
  5208. EXPECT_FALSE(ud.has("b"));
  5209. }
  5210. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5211. struct AuthCtx {
  5212. std::string user_id;
  5213. };
  5214. Server svr;
  5215. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5216. res.user_data.set("auth", AuthCtx{"alice"});
  5217. return Server::HandlerResponse::Unhandled;
  5218. });
  5219. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5220. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5221. ASSERT_NE(nullptr, ctx);
  5222. res.set_content("Hello " + ctx->user_id, "text/plain");
  5223. });
  5224. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5225. auto se = detail::scope_exit([&] {
  5226. svr.stop();
  5227. thread.join();
  5228. ASSERT_FALSE(svr.is_running());
  5229. });
  5230. svr.wait_until_ready();
  5231. Client cli(HOST, PORT);
  5232. auto res = cli.Get("/me");
  5233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. EXPECT_EQ("Hello alice", res->body);
  5236. }
  5237. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5238. struct RoleCtx {
  5239. std::string role;
  5240. };
  5241. Server svr;
  5242. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5243. res.user_data.set("role", RoleCtx{"admin"});
  5244. return Server::HandlerResponse::Unhandled;
  5245. });
  5246. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5247. auto *ctx = res.user_data.get<RoleCtx>("role");
  5248. ASSERT_NE(nullptr, ctx);
  5249. res.set_content(ctx->role, "text/plain");
  5250. });
  5251. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5252. auto se = detail::scope_exit([&] {
  5253. svr.stop();
  5254. thread.join();
  5255. ASSERT_FALSE(svr.is_running());
  5256. });
  5257. svr.wait_until_ready();
  5258. Client cli(HOST, PORT);
  5259. auto res = cli.Get("/role");
  5260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5261. EXPECT_EQ(StatusCode::OK_200, res->status);
  5262. EXPECT_EQ("admin", res->body);
  5263. }
  5264. TEST(InvalidFormatTest, StatusCode) {
  5265. Server svr;
  5266. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5267. res.set_content("Hello World!\n", "text/plain");
  5268. res.status = 9999; // Status should be a three-digit code...
  5269. });
  5270. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5271. auto se = detail::scope_exit([&] {
  5272. svr.stop();
  5273. thread.join();
  5274. ASSERT_FALSE(svr.is_running());
  5275. });
  5276. svr.wait_until_ready();
  5277. {
  5278. Client cli(HOST, PORT);
  5279. auto res = cli.Get("/hi");
  5280. ASSERT_FALSE(res);
  5281. }
  5282. }
  5283. TEST(URLFragmentTest, WithFragment) {
  5284. Server svr;
  5285. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5286. EXPECT_TRUE(req.target == "/hi");
  5287. });
  5288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5289. auto se = detail::scope_exit([&] {
  5290. svr.stop();
  5291. thread.join();
  5292. ASSERT_FALSE(svr.is_running());
  5293. });
  5294. svr.wait_until_ready();
  5295. {
  5296. Client cli(HOST, PORT);
  5297. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5298. EXPECT_TRUE(res);
  5299. EXPECT_EQ(StatusCode::OK_200, res->status);
  5300. res = cli.Get("/hi%23key1=val1=key2=val2");
  5301. EXPECT_TRUE(res);
  5302. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5303. }
  5304. }
  5305. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5306. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5307. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5308. Server svr;
  5309. std::vector<std::string> targets;
  5310. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5311. targets.push_back(req.target);
  5312. });
  5313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5314. auto se = detail::scope_exit([&] {
  5315. svr.stop();
  5316. thread.join();
  5317. ASSERT_FALSE(svr.is_running());
  5318. });
  5319. svr.wait_until_ready();
  5320. Client cli(HOST, PORT);
  5321. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5322. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5323. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5324. // A '?' after the '#' belongs to the fragment, not to the query.
  5325. Request req;
  5326. req.method = "GET";
  5327. req.path = "/hi#f?x=1";
  5328. req.params.emplace("a", "1");
  5329. Response res;
  5330. auto error = Error::Success;
  5331. EXPECT_TRUE(cli.send(req, res, error));
  5332. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5333. "/hi?a=1"}),
  5334. targets);
  5335. }
  5336. TEST(HeaderWriter, SetHeaderWriter) {
  5337. Server svr;
  5338. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5339. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5340. return detail::write_headers(strm, hdrs);
  5341. });
  5342. svr.Get("/hi", [](const Request &req, Response &res) {
  5343. auto it = req.headers.find("CustomClientHeader");
  5344. EXPECT_TRUE(it != req.headers.end());
  5345. EXPECT_EQ(it->second, "CustomClientValue");
  5346. res.set_content("Hello World!\n", "text/plain");
  5347. });
  5348. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5349. auto se = detail::scope_exit([&] {
  5350. svr.stop();
  5351. thread.join();
  5352. ASSERT_FALSE(svr.is_running());
  5353. });
  5354. svr.wait_until_ready();
  5355. {
  5356. Client cli(HOST, PORT);
  5357. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5358. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5359. return detail::write_headers(strm, hdrs);
  5360. });
  5361. auto res = cli.Get("/hi");
  5362. EXPECT_TRUE(res);
  5363. EXPECT_EQ(StatusCode::OK_200, res->status);
  5364. auto it = res->headers.find("CustomServerHeader");
  5365. EXPECT_TRUE(it != res->headers.end());
  5366. EXPECT_EQ(it->second, "CustomServerValue");
  5367. }
  5368. }
  5369. class ServerTest : public ::testing::Test {
  5370. protected:
  5371. ServerTest()
  5372. : cli_(HOST, PORT)
  5373. #ifdef CPPHTTPLIB_SSL_ENABLED
  5374. ,
  5375. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5376. #endif
  5377. {
  5378. #ifdef CPPHTTPLIB_SSL_ENABLED
  5379. cli_.enable_server_certificate_verification(false);
  5380. #endif
  5381. // Allow LARGE_DATA (100MB) responses
  5382. cli_.set_payload_max_length(200 * 1024 * 1024);
  5383. }
  5384. virtual void SetUp() {
  5385. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5386. svr_.set_payload_max_length(200 * 1024 * 1024);
  5387. svr_.set_mount_point("/", "./www");
  5388. svr_.set_mount_point("/mount", "./www2");
  5389. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5390. svr_.Get("/hi",
  5391. [&](const Request & /*req*/, Response &res) {
  5392. res.set_content("Hello World!", "text/plain");
  5393. })
  5394. .Get("/file_content",
  5395. [&](const Request & /*req*/, Response &res) {
  5396. res.set_file_content("./www/dir/test.html");
  5397. })
  5398. .Get("/file_content_with_content_type",
  5399. [&](const Request & /*req*/, Response &res) {
  5400. res.set_file_content("./www/file", "text/plain");
  5401. })
  5402. .Get("/invalid_file_content",
  5403. [&](const Request & /*req*/, Response &res) {
  5404. res.set_file_content("./www/dir/invalid_file_path");
  5405. })
  5406. .Get("/http_response_splitting",
  5407. [&](const Request & /*req*/, Response &res) {
  5408. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5409. EXPECT_EQ(0U, res.headers.size());
  5410. EXPECT_FALSE(res.has_header("a"));
  5411. res.set_header("a", "1\nSet-Cookie: a=1");
  5412. EXPECT_EQ(0U, res.headers.size());
  5413. EXPECT_FALSE(res.has_header("a"));
  5414. res.set_header("a", "1\rSet-Cookie: a=1");
  5415. EXPECT_EQ(0U, res.headers.size());
  5416. EXPECT_FALSE(res.has_header("a"));
  5417. res.set_header("a\r\nb", "0");
  5418. EXPECT_EQ(0U, res.headers.size());
  5419. EXPECT_FALSE(res.has_header("a"));
  5420. res.set_header("a\rb", "0");
  5421. EXPECT_EQ(0U, res.headers.size());
  5422. EXPECT_FALSE(res.has_header("a"));
  5423. res.set_header("a\nb", "0");
  5424. EXPECT_EQ(0U, res.headers.size());
  5425. EXPECT_FALSE(res.has_header("a"));
  5426. res.set_redirect("1\r\nSet-Cookie: a=1");
  5427. EXPECT_EQ(0U, res.headers.size());
  5428. EXPECT_FALSE(res.has_header("Location"));
  5429. })
  5430. .Get("/slow",
  5431. [&](const Request & /*req*/, Response &res) {
  5432. std::this_thread::sleep_for(std::chrono::seconds(4));
  5433. res.set_content("slow", "text/plain");
  5434. })
  5435. #if 0
  5436. .Post("/slowpost",
  5437. [&](const Request & /*req*/, Response &res) {
  5438. std::this_thread::sleep_for(std::chrono::seconds(2));
  5439. res.set_content("slow", "text/plain");
  5440. })
  5441. #endif
  5442. .Get("/remote_addr",
  5443. [&](const Request &req, Response &res) {
  5444. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5445. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5446. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5447. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5448. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5449. #endif
  5450. res.set_content(req.remote_addr, "text/plain");
  5451. })
  5452. .Get("/local_addr",
  5453. [&](const Request &req, Response &res) {
  5454. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5455. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5456. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5457. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5458. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5459. #endif
  5460. auto local_addr = req.local_addr;
  5461. auto local_port = std::to_string(req.local_port);
  5462. res.set_content(local_addr.append(":").append(local_port),
  5463. "text/plain");
  5464. })
  5465. .Get("/endwith%",
  5466. [&](const Request & /*req*/, Response &res) {
  5467. res.set_content("Hello World!", "text/plain");
  5468. })
  5469. .Get("/a\\+\\+b",
  5470. [&](const Request &req, Response &res) {
  5471. ASSERT_TRUE(req.has_param("a +b"));
  5472. auto val = req.get_param_value("a +b");
  5473. res.set_content(val, "text/plain");
  5474. })
  5475. .Get("/", [&](const Request & /*req*/,
  5476. Response &res) { res.set_redirect("/hi"); })
  5477. .Post("/1",
  5478. [](const Request & /*req*/, Response &res) {
  5479. res.set_redirect("/2", StatusCode::SeeOther_303);
  5480. })
  5481. .Get("/2",
  5482. [](const Request & /*req*/, Response &res) {
  5483. res.set_content("redirected.", "text/plain");
  5484. res.status = StatusCode::OK_200;
  5485. })
  5486. .Post("/person",
  5487. [&](const Request &req, Response &res) {
  5488. if (req.has_param("name") && req.has_param("note")) {
  5489. persons_[req.get_param_value("name")] =
  5490. req.get_param_value("note");
  5491. } else {
  5492. res.status = StatusCode::BadRequest_400;
  5493. }
  5494. })
  5495. .Put("/person",
  5496. [&](const Request &req, Response &res) {
  5497. if (req.has_param("name") && req.has_param("note")) {
  5498. persons_[req.get_param_value("name")] =
  5499. req.get_param_value("note");
  5500. } else {
  5501. res.status = StatusCode::BadRequest_400;
  5502. }
  5503. })
  5504. .Get("/person/(.*)",
  5505. [&](const Request &req, Response &res) {
  5506. string name = req.matches[1];
  5507. if (persons_.find(name) != persons_.end()) {
  5508. auto note = persons_[name];
  5509. res.set_content(note, "text/plain");
  5510. } else {
  5511. res.status = StatusCode::NotFound_404;
  5512. }
  5513. })
  5514. .Delete("/person",
  5515. [&](const Request &req, Response &res) {
  5516. if (req.has_param("name")) {
  5517. string name = req.get_param_value("name");
  5518. if (persons_.find(name) != persons_.end()) {
  5519. persons_.erase(name);
  5520. res.set_content("DELETED", "text/plain");
  5521. } else {
  5522. res.status = StatusCode::NotFound_404;
  5523. }
  5524. } else {
  5525. res.status = StatusCode::BadRequest_400;
  5526. }
  5527. })
  5528. .Post("/x-www-form-urlencoded-json",
  5529. [&](const Request &req, Response &res) {
  5530. auto json = req.get_param_value("json");
  5531. ASSERT_EQ(JSON_DATA, json);
  5532. res.set_content(json, "appliation/json");
  5533. res.status = StatusCode::OK_200;
  5534. })
  5535. .Get("/streamed-chunked",
  5536. [&](const Request & /*req*/, Response &res) {
  5537. res.set_chunked_content_provider(
  5538. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5539. sink.os << "123";
  5540. sink.os << "456";
  5541. sink.os << "789";
  5542. sink.done();
  5543. return true;
  5544. });
  5545. })
  5546. .Get("/streamed-chunked-with-prohibited-trailer",
  5547. [&](const Request & /*req*/, Response &res) {
  5548. auto i = new int(0);
  5549. // Declare both a prohibited trailer (Content-Length) and an
  5550. // allowed one
  5551. res.set_header("Trailer", "Content-Length, X-Allowed");
  5552. res.set_chunked_content_provider(
  5553. "text/plain",
  5554. [i](size_t /*offset*/, DataSink &sink) {
  5555. switch (*i) {
  5556. case 0: sink.os << "123"; break;
  5557. case 1: sink.os << "456"; break;
  5558. case 2: sink.os << "789"; break;
  5559. case 3: {
  5560. sink.done_with_trailer(
  5561. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5562. } break;
  5563. }
  5564. (*i)++;
  5565. return true;
  5566. },
  5567. [i](bool success) {
  5568. EXPECT_TRUE(success);
  5569. delete i;
  5570. });
  5571. })
  5572. .Get("/streamed-chunked2",
  5573. [&](const Request & /*req*/, Response &res) {
  5574. auto i = new int(0);
  5575. res.set_chunked_content_provider(
  5576. "text/plain",
  5577. [i](size_t /*offset*/, DataSink &sink) {
  5578. switch (*i) {
  5579. case 0: sink.os << "123"; break;
  5580. case 1: sink.os << "456"; break;
  5581. case 2: sink.os << "789"; break;
  5582. case 3: sink.done(); break;
  5583. }
  5584. (*i)++;
  5585. return true;
  5586. },
  5587. [i](bool success) {
  5588. EXPECT_TRUE(success);
  5589. delete i;
  5590. });
  5591. })
  5592. .Get("/streamed-chunked-with-trailer",
  5593. [&](const Request & /*req*/, Response &res) {
  5594. auto i = new int(0);
  5595. res.set_header("Trailer", "Dummy1, Dummy2");
  5596. res.set_chunked_content_provider(
  5597. "text/plain",
  5598. [i](size_t /*offset*/, DataSink &sink) {
  5599. switch (*i) {
  5600. case 0: sink.os << "123"; break;
  5601. case 1: sink.os << "456"; break;
  5602. case 2: sink.os << "789"; break;
  5603. case 3: {
  5604. sink.done_with_trailer(
  5605. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5606. } break;
  5607. }
  5608. (*i)++;
  5609. return true;
  5610. },
  5611. [i](bool success) {
  5612. EXPECT_TRUE(success);
  5613. delete i;
  5614. });
  5615. })
  5616. .Get("/streamed",
  5617. [&](const Request & /*req*/, Response &res) {
  5618. res.set_content_provider(
  5619. 6, "text/plain",
  5620. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5621. sink.os << (offset < 3 ? "a" : "b");
  5622. return true;
  5623. });
  5624. })
  5625. .Get("/streamed-without-length",
  5626. [&](const Request & /*req*/, Response &res) {
  5627. auto data = new std::string("abcdefg");
  5628. res.set_content_provider(
  5629. "text/plain",
  5630. [data](size_t offset, DataSink &sink) {
  5631. if (offset < data->size()) {
  5632. sink.os << data->substr(offset);
  5633. }
  5634. sink.done();
  5635. return true;
  5636. },
  5637. [data](bool success) {
  5638. EXPECT_TRUE(success);
  5639. delete data;
  5640. });
  5641. })
  5642. .Get("/streamed-with-range",
  5643. [&](const Request &req, Response &res) {
  5644. auto data = new std::string("abcdefg");
  5645. // An explicit status keeps the server from picking the 206 it
  5646. // would otherwise choose for a ranged request, so the response
  5647. // is not a partial representation.
  5648. auto status = req.get_param_value("status");
  5649. if (status == "200") {
  5650. res.status = StatusCode::OK_200;
  5651. } else if (status == "403") {
  5652. res.status = StatusCode::Forbidden_403;
  5653. }
  5654. res.set_content_provider(
  5655. data->size(), "text/plain",
  5656. [data](size_t offset, size_t length, DataSink &sink) {
  5657. size_t DATA_CHUNK_SIZE = 4;
  5658. const auto &d = *data;
  5659. auto out_len =
  5660. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5661. auto ret =
  5662. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5663. EXPECT_TRUE(ret);
  5664. return true;
  5665. },
  5666. [data, &req](bool success) {
  5667. EXPECT_EQ(success, !req.has_param("error"));
  5668. delete data;
  5669. });
  5670. })
  5671. .Get("/streamed-cancel",
  5672. [&](const Request & /*req*/, Response &res) {
  5673. res.set_content_provider(
  5674. size_t(-1), "text/plain",
  5675. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5676. sink.os << "data_chunk";
  5677. return true;
  5678. });
  5679. })
  5680. .Get("/regex-with-delimiter",
  5681. [&](const Request &req, Response & /*res*/) {
  5682. ASSERT_TRUE(req.has_param("key"));
  5683. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5684. })
  5685. .Get("/with-range",
  5686. [&](const Request & /*req*/, Response &res) {
  5687. res.set_content("abcdefg", "text/plain");
  5688. })
  5689. .Get("/test-start-time",
  5690. [&](const Request &req, Response & /*res*/) {
  5691. EXPECT_NE(req.start_time_,
  5692. std::chrono::steady_clock::time_point::min());
  5693. })
  5694. .Get("/with-range-customized-response",
  5695. [&](const Request & /*req*/, Response &res) {
  5696. res.status = StatusCode::BadRequest_400;
  5697. res.set_content(JSON_DATA, "application/json");
  5698. })
  5699. .Post("/chunked",
  5700. [&](const Request &req, Response & /*res*/) {
  5701. EXPECT_EQ(req.body, "dechunked post body");
  5702. })
  5703. .Post("/large-chunked",
  5704. [&](const Request &req, Response & /*res*/) {
  5705. std::string expected(6 * 30 * 1024u, 'a');
  5706. EXPECT_EQ(req.body, expected);
  5707. })
  5708. .Post("/multipart",
  5709. [&](const Request &req, Response & /*res*/) {
  5710. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5711. req.form.get_field_count("text2") +
  5712. req.form.get_field_count("file3") +
  5713. req.form.get_field_count("file4"));
  5714. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5715. req.form.get_file_count("file2"));
  5716. ASSERT_TRUE(!req.form.has_file("???"));
  5717. ASSERT_TRUE(!req.form.has_field("???"));
  5718. ASSERT_TRUE(req.body.empty());
  5719. {
  5720. const auto &text = req.form.get_field("text1");
  5721. EXPECT_EQ("text default", text);
  5722. }
  5723. {
  5724. const auto &text = req.form.get_field("text2");
  5725. EXPECT_EQ("aωb", text);
  5726. }
  5727. {
  5728. const auto &file = req.form.get_file("file1");
  5729. EXPECT_EQ("hello.txt", file.filename);
  5730. EXPECT_EQ("text/plain", file.content_type);
  5731. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5732. }
  5733. {
  5734. const auto &file = req.form.get_file("file2");
  5735. EXPECT_EQ("world.json", file.filename);
  5736. EXPECT_EQ("application/json", file.content_type);
  5737. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5738. }
  5739. {
  5740. const auto &text = req.form.get_field("file3");
  5741. EXPECT_EQ(0u, text.size());
  5742. }
  5743. {
  5744. const auto &text = req.form.get_field("file4");
  5745. EXPECT_EQ(0u, text.size());
  5746. }
  5747. })
  5748. .Post("/multipart/multi_file_values",
  5749. [&](const Request &req, Response & /*res*/) {
  5750. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5751. req.form.get_field_count("multi_text1"));
  5752. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5753. ASSERT_TRUE(!req.form.has_file("???"));
  5754. ASSERT_TRUE(!req.form.has_field("???"));
  5755. ASSERT_TRUE(req.body.empty());
  5756. {
  5757. const auto &text = req.form.get_field("text");
  5758. EXPECT_EQ("default text", text);
  5759. }
  5760. {
  5761. const auto &text1_values = req.form.get_fields("multi_text1");
  5762. EXPECT_EQ(2u, text1_values.size());
  5763. EXPECT_EQ("aaaaa", text1_values[0]);
  5764. EXPECT_EQ("bbbbb", text1_values[1]);
  5765. }
  5766. {
  5767. const auto &file1_values = req.form.get_files("multi_file1");
  5768. EXPECT_EQ(2u, file1_values.size());
  5769. auto file1 = file1_values[0];
  5770. EXPECT_EQ(file1.filename, "hello.txt");
  5771. EXPECT_EQ(file1.content_type, "text/plain");
  5772. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5773. auto file2 = file1_values[1];
  5774. EXPECT_EQ(file2.filename, "world.json");
  5775. EXPECT_EQ(file2.content_type, "application/json");
  5776. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5777. }
  5778. })
  5779. .Post("/empty",
  5780. [&](const Request &req, Response &res) {
  5781. EXPECT_EQ(req.body, "");
  5782. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5783. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5784. res.set_content("empty", "text/plain");
  5785. })
  5786. .Post("/empty-no-content-type",
  5787. [&](const Request &req, Response &res) {
  5788. EXPECT_EQ(req.body, "");
  5789. EXPECT_FALSE(req.has_header("Content-Type"));
  5790. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5791. res.set_content("empty-no-content-type", "text/plain");
  5792. })
  5793. .Post("/path-only",
  5794. [&](const Request &req, Response &res) {
  5795. EXPECT_EQ(req.body, "");
  5796. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5797. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5798. res.set_content("path-only", "text/plain");
  5799. })
  5800. .Post("/path-headers-only",
  5801. [&](const Request &req, Response &res) {
  5802. EXPECT_EQ(req.body, "");
  5803. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5804. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5805. EXPECT_EQ("world", req.get_header_value("hello"));
  5806. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5807. res.set_content("path-headers-only", "text/plain");
  5808. })
  5809. .Post("/post-large",
  5810. [&](const Request &req, Response &res) {
  5811. EXPECT_EQ(req.body, LARGE_DATA);
  5812. res.set_content(req.body, "text/plain");
  5813. })
  5814. .Post("/post-loopback",
  5815. [&](const Request &, Response &res,
  5816. ContentReader const &content_reader) {
  5817. std::string body;
  5818. content_reader([&](const char *data, size_t data_length) {
  5819. body.append(data, data_length);
  5820. return true;
  5821. });
  5822. res.set_content(body, "text/plain");
  5823. })
  5824. .Put("/put-loopback",
  5825. [&](const Request &, Response &res,
  5826. ContentReader const &content_reader) {
  5827. std::string body;
  5828. content_reader([&](const char *data, size_t data_length) {
  5829. body.append(data, data_length);
  5830. return true;
  5831. });
  5832. res.set_content(body, "text/plain");
  5833. })
  5834. .Patch("/patch-loopback",
  5835. [&](const Request &, Response &res,
  5836. ContentReader const &content_reader) {
  5837. std::string body;
  5838. content_reader([&](const char *data, size_t data_length) {
  5839. body.append(data, data_length);
  5840. return true;
  5841. });
  5842. res.set_content(body, "text/plain");
  5843. })
  5844. .Put("/empty-no-content-type",
  5845. [&](const Request &req, Response &res) {
  5846. EXPECT_EQ(req.body, "");
  5847. EXPECT_FALSE(req.has_header("Content-Type"));
  5848. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5849. res.set_content("empty-no-content-type", "text/plain");
  5850. })
  5851. .Put("/put",
  5852. [&](const Request &req, Response &res) {
  5853. EXPECT_EQ(req.body, "PUT");
  5854. res.set_content(req.body, "text/plain");
  5855. })
  5856. .Put("/put-large",
  5857. [&](const Request &req, Response &res) {
  5858. EXPECT_EQ(req.body, LARGE_DATA);
  5859. res.set_content(req.body, "text/plain");
  5860. })
  5861. .Patch("/patch",
  5862. [&](const Request &req, Response &res) {
  5863. EXPECT_EQ(req.body, "PATCH");
  5864. res.set_content(req.body, "text/plain");
  5865. })
  5866. .Delete("/delete",
  5867. [&](const Request & /*req*/, Response &res) {
  5868. res.set_content("DELETE", "text/plain");
  5869. })
  5870. .Delete("/delete-body",
  5871. [&](const Request &req, Response &res) {
  5872. EXPECT_EQ(req.body, "content");
  5873. res.set_content(req.body, "text/plain");
  5874. })
  5875. .Options(R"(\*)",
  5876. [&](const Request & /*req*/, Response &res) {
  5877. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5878. })
  5879. .CustomRoute("PROPFIND", "/dav/:id",
  5880. [&](const Request &req, Response &res) {
  5881. res.set_header("x-body-size",
  5882. std::to_string(req.body.size()));
  5883. res.set_header("x-matched-route", req.matched_route);
  5884. res.set_header("x-dav-id", req.path_params.at("id"));
  5885. res.status = StatusCode::MultiStatus_207;
  5886. res.set_content(req.body, "application/xml");
  5887. })
  5888. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5889. [&](const Request &req, Response &res) {
  5890. res.set_header("x-dav-match", req.matches[1]);
  5891. res.status = StatusCode::MultiStatus_207;
  5892. })
  5893. .CustomRoute("MKCOL", "/dav-mkcol",
  5894. [&](const Request &req, Response &res) {
  5895. EXPECT_TRUE(req.body.empty());
  5896. res.status = StatusCode::Created_201;
  5897. })
  5898. .CustomRoute(
  5899. "REPORT", "/dav-report",
  5900. [&](const Request & /*req*/, Response &res,
  5901. const ContentReader &content_reader) {
  5902. std::string body;
  5903. content_reader([&](const char *data, size_t data_length) {
  5904. body.append(data, data_length);
  5905. return true;
  5906. });
  5907. res.set_header("x-body-size", std::to_string(body.size()));
  5908. res.status = StatusCode::MultiStatus_207;
  5909. res.set_content(body, "application/xml");
  5910. })
  5911. .Get("/request-target",
  5912. [&](const Request &req, Response & /*res*/) {
  5913. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5914. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5915. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5916. })
  5917. .Get("/long-query-value",
  5918. [&](const Request &req, Response & /*res*/) {
  5919. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5920. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5921. })
  5922. .Get("/too-long-query-value",
  5923. [&](const Request &req, Response & /*res*/) {
  5924. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5925. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5926. })
  5927. .Get("/array-param",
  5928. [&](const Request &req, Response & /*res*/) {
  5929. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5930. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5931. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5932. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5933. })
  5934. .Get("/array-param-values",
  5935. [&](const Request &req, Response & /*res*/) {
  5936. auto values = req.get_param_values("array");
  5937. EXPECT_EQ(3u, values.size());
  5938. EXPECT_EQ("value1", values[0]);
  5939. EXPECT_EQ("value2", values[1]);
  5940. EXPECT_EQ("value3", values[2]);
  5941. auto empty = req.get_param_values("nonexistent");
  5942. EXPECT_TRUE(empty.empty());
  5943. })
  5944. .Post("/validate-no-multiple-headers",
  5945. [&](const Request &req, Response & /*res*/) {
  5946. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5947. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5948. })
  5949. .Post("/content_receiver",
  5950. [&](const Request &req, Response &res,
  5951. const ContentReader &content_reader) {
  5952. if (req.is_multipart_form_data()) {
  5953. std::vector<FormData> items;
  5954. content_reader(
  5955. [&](const FormData &file) {
  5956. items.push_back(file);
  5957. return true;
  5958. },
  5959. [&](const char *data, size_t data_length) {
  5960. items.back().content.append(data, data_length);
  5961. return true;
  5962. });
  5963. EXPECT_EQ(5u, items.size());
  5964. {
  5965. const auto &file = get_file_value(items, "text1");
  5966. EXPECT_TRUE(file.filename.empty());
  5967. EXPECT_EQ("text default", file.content);
  5968. }
  5969. {
  5970. const auto &file = get_file_value(items, "text2");
  5971. EXPECT_TRUE(file.filename.empty());
  5972. EXPECT_EQ("aωb", file.content);
  5973. }
  5974. {
  5975. const auto &file = get_file_value(items, "file1");
  5976. EXPECT_EQ("hello.txt", file.filename);
  5977. EXPECT_EQ("text/plain", file.content_type);
  5978. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5979. }
  5980. {
  5981. const auto &file = get_file_value(items, "file2");
  5982. EXPECT_EQ("world.json", file.filename);
  5983. EXPECT_EQ("application/json", file.content_type);
  5984. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5985. }
  5986. {
  5987. const auto &file = get_file_value(items, "file3");
  5988. EXPECT_TRUE(file.filename.empty());
  5989. EXPECT_EQ("application/octet-stream", file.content_type);
  5990. EXPECT_EQ(0u, file.content.size());
  5991. }
  5992. } else {
  5993. std::string body;
  5994. content_reader([&](const char *data, size_t data_length) {
  5995. EXPECT_EQ(7U, data_length);
  5996. body.append(data, data_length);
  5997. return true;
  5998. });
  5999. EXPECT_EQ(body, "content");
  6000. res.set_content(body, "text/plain");
  6001. }
  6002. })
  6003. .Put("/content_receiver",
  6004. [&](const Request & /*req*/, Response &res,
  6005. const ContentReader &content_reader) {
  6006. std::string body;
  6007. content_reader([&](const char *data, size_t data_length) {
  6008. body.append(data, data_length);
  6009. return true;
  6010. });
  6011. EXPECT_EQ(body, "content");
  6012. res.set_content(body, "text/plain");
  6013. })
  6014. .Patch("/content_receiver",
  6015. [&](const Request & /*req*/, Response &res,
  6016. const ContentReader &content_reader) {
  6017. std::string body;
  6018. content_reader([&](const char *data, size_t data_length) {
  6019. body.append(data, data_length);
  6020. return true;
  6021. });
  6022. EXPECT_EQ(body, "content");
  6023. res.set_content(body, "text/plain");
  6024. })
  6025. .Post("/query-string-and-body",
  6026. [&](const Request &req, Response & /*res*/) {
  6027. ASSERT_TRUE(req.has_param("key"));
  6028. EXPECT_EQ(req.get_param_value("key"), "value");
  6029. EXPECT_EQ(req.body, "content");
  6030. })
  6031. .Get("/last-request",
  6032. [&](const Request &req, Response & /*res*/) {
  6033. EXPECT_EQ("close", req.get_header_value("Connection"));
  6034. })
  6035. .Get(R"(/redirect/(\d+))",
  6036. [&](const Request &req, Response &res) {
  6037. auto num = std::stoi(req.matches[1]) + 1;
  6038. std::string url = "/redirect/" + std::to_string(num);
  6039. res.set_redirect(url);
  6040. })
  6041. .Post("/binary",
  6042. [&](const Request &req, Response &res) {
  6043. EXPECT_EQ(4U, req.body.size());
  6044. EXPECT_EQ("application/octet-stream",
  6045. req.get_header_value("Content-Type"));
  6046. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6047. res.set_content(req.body, "application/octet-stream");
  6048. })
  6049. .Put("/binary",
  6050. [&](const Request &req, Response &res) {
  6051. EXPECT_EQ(4U, req.body.size());
  6052. EXPECT_EQ("application/octet-stream",
  6053. req.get_header_value("Content-Type"));
  6054. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6055. res.set_content(req.body, "application/octet-stream");
  6056. })
  6057. .Patch("/binary",
  6058. [&](const Request &req, Response &res) {
  6059. EXPECT_EQ(4U, req.body.size());
  6060. EXPECT_EQ("application/octet-stream",
  6061. req.get_header_value("Content-Type"));
  6062. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6063. res.set_content(req.body, "application/octet-stream");
  6064. })
  6065. .Delete("/binary",
  6066. [&](const Request &req, Response &res) {
  6067. EXPECT_EQ(4U, req.body.size());
  6068. EXPECT_EQ("application/octet-stream",
  6069. req.get_header_value("Content-Type"));
  6070. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6071. res.set_content(req.body, "application/octet-stream");
  6072. })
  6073. .Get("/issue1772",
  6074. [&](const Request & /*req*/, Response &res) {
  6075. res.status = 401;
  6076. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6077. })
  6078. .Delete("/issue609",
  6079. [](const httplib::Request &, httplib::Response &res,
  6080. const httplib::ContentReader &) {
  6081. res.set_content("ok", "text/plain");
  6082. })
  6083. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6084. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6085. .Get("/compress",
  6086. [&](const Request & /*req*/, Response &res) {
  6087. res.set_content(
  6088. "12345678901234567890123456789012345678901234567890123456789"
  6089. "01234567890123456789012345678901234567890",
  6090. "text/plain");
  6091. })
  6092. .Get("/compress-with-charset",
  6093. [&](const Request & /*req*/, Response &res) {
  6094. res.set_content(
  6095. "12345678901234567890123456789012345678901234567890123456789"
  6096. "01234567890123456789012345678901234567890",
  6097. "application/json; charset=utf-8");
  6098. })
  6099. .Get("/nocompress",
  6100. [&](const Request & /*req*/, Response &res) {
  6101. res.set_content(
  6102. "12345678901234567890123456789012345678901234567890123456789"
  6103. "01234567890123456789012345678901234567890",
  6104. "application/octet-stream");
  6105. })
  6106. .Post("/compress-multipart",
  6107. [&](const Request &req, Response & /*res*/) {
  6108. EXPECT_EQ(2u, req.form.fields.size());
  6109. ASSERT_TRUE(!req.form.has_field("???"));
  6110. {
  6111. const auto &text = req.form.get_field("key1");
  6112. EXPECT_EQ("test", text);
  6113. }
  6114. {
  6115. const auto &text = req.form.get_field("key2");
  6116. EXPECT_EQ("--abcdefg123", text);
  6117. }
  6118. })
  6119. #endif
  6120. ;
  6121. persons_["john"] = "programmer";
  6122. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6123. svr_.wait_until_ready();
  6124. }
  6125. virtual void TearDown() {
  6126. svr_.stop();
  6127. if (!request_threads_.empty()) {
  6128. std::this_thread::sleep_for(std::chrono::seconds(1));
  6129. for (auto &t : request_threads_) {
  6130. t.join();
  6131. }
  6132. }
  6133. t_.join();
  6134. }
  6135. map<string, string> persons_;
  6136. #ifdef CPPHTTPLIB_SSL_ENABLED
  6137. SSLClient cli_;
  6138. SSLServer svr_;
  6139. #else
  6140. Client cli_;
  6141. Server svr_;
  6142. #endif
  6143. thread t_;
  6144. std::vector<thread> request_threads_;
  6145. };
  6146. TEST_F(ServerTest, GetMethod200) {
  6147. auto res = cli_.Get("/hi");
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. EXPECT_EQ("HTTP/1.1", res->version);
  6150. EXPECT_EQ(StatusCode::OK_200, res->status);
  6151. EXPECT_EQ("OK", res->reason);
  6152. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6153. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6154. EXPECT_EQ("Hello World!", res->body);
  6155. }
  6156. TEST_F(ServerTest, GetEmptyFile) {
  6157. auto res = cli_.Get("/empty_file");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. EXPECT_EQ(StatusCode::OK_200, res->status);
  6160. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6161. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6162. EXPECT_EQ("", res->body);
  6163. }
  6164. TEST_F(ServerTest, GetFileContent) {
  6165. auto res = cli_.Get("/file_content");
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. EXPECT_EQ(StatusCode::OK_200, res->status);
  6168. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6169. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6170. EXPECT_EQ("test.html", res->body);
  6171. }
  6172. TEST_F(ServerTest, GetFileContentWithRange) {
  6173. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6176. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6177. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6178. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6179. EXPECT_EQ("est", res->body);
  6180. }
  6181. TEST_F(ServerTest, GetFileContentWithContentType) {
  6182. auto res = cli_.Get("/file_content_with_content_type");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. EXPECT_EQ(StatusCode::OK_200, res->status);
  6185. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6186. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6187. EXPECT_EQ("file\n", res->body);
  6188. }
  6189. TEST_F(ServerTest, GetInvalidFileContent) {
  6190. auto res = cli_.Get("/invalid_file_content");
  6191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6192. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6193. }
  6194. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6195. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. EXPECT_EQ("HTTP/1.1", res->version);
  6198. EXPECT_EQ(StatusCode::OK_200, res->status);
  6199. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6200. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6201. EXPECT_EQ("Hello World!", res->body);
  6202. }
  6203. TEST_F(ServerTest, GetMethod302) {
  6204. auto res = cli_.Get("/");
  6205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6206. EXPECT_EQ(StatusCode::Found_302, res->status);
  6207. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6208. }
  6209. TEST_F(ServerTest, GetMethod302Redirect) {
  6210. cli_.set_follow_location(true);
  6211. auto res = cli_.Get("/");
  6212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6213. EXPECT_EQ(StatusCode::OK_200, res->status);
  6214. EXPECT_EQ("Hello World!", res->body);
  6215. EXPECT_EQ("/hi", res->location);
  6216. }
  6217. TEST_F(ServerTest, GetMethod404) {
  6218. auto res = cli_.Get("/invalid");
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6221. }
  6222. TEST_F(ServerTest, HeadMethod200) {
  6223. auto res = cli_.Head("/hi");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. EXPECT_EQ(StatusCode::OK_200, res->status);
  6226. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6227. EXPECT_TRUE(res->body.empty());
  6228. }
  6229. TEST_F(ServerTest, HeadMethod200Static) {
  6230. auto res = cli_.Head("/mount/dir/index.html");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::OK_200, res->status);
  6233. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6234. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6235. EXPECT_TRUE(res->body.empty());
  6236. }
  6237. TEST_F(ServerTest, HeadMethod404) {
  6238. auto res = cli_.Head("/invalid");
  6239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6240. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6241. EXPECT_TRUE(res->body.empty());
  6242. }
  6243. TEST_F(ServerTest, GetMethodPersonJohn) {
  6244. auto res = cli_.Get("/person/john");
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::OK_200, res->status);
  6247. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6248. EXPECT_EQ("programmer", res->body);
  6249. }
  6250. TEST_F(ServerTest, PostMethod1) {
  6251. auto res = cli_.Get("/person/john1");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6254. res = cli_.Post("/person", "name=john1&note=coder",
  6255. "application/x-www-form-urlencoded");
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. ASSERT_EQ(StatusCode::OK_200, res->status);
  6258. res = cli_.Get("/person/john1");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. ASSERT_EQ(StatusCode::OK_200, res->status);
  6261. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6262. ASSERT_EQ("coder", res->body);
  6263. }
  6264. TEST_F(ServerTest, PostMethod2) {
  6265. auto res = cli_.Get("/person/john2");
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6268. Params params;
  6269. params.emplace("name", "john2");
  6270. params.emplace("note", "coder");
  6271. res = cli_.Post("/person", params);
  6272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6273. ASSERT_EQ(StatusCode::OK_200, res->status);
  6274. res = cli_.Get("/person/john2");
  6275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6276. ASSERT_EQ(StatusCode::OK_200, res->status);
  6277. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6278. ASSERT_EQ("coder", res->body);
  6279. }
  6280. TEST_F(ServerTest, PutMethod3) {
  6281. auto res = cli_.Get("/person/john3");
  6282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6283. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6284. Params params;
  6285. params.emplace("name", "john3");
  6286. params.emplace("note", "coder");
  6287. res = cli_.Put("/person", params);
  6288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6289. ASSERT_EQ(StatusCode::OK_200, res->status);
  6290. res = cli_.Get("/person/john3");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. ASSERT_EQ(StatusCode::OK_200, res->status);
  6293. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6294. ASSERT_EQ("coder", res->body);
  6295. }
  6296. TEST_F(ServerTest, DeleteMethod1) {
  6297. auto res = cli_.Get("/person/john4");
  6298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6299. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6300. Params params;
  6301. params.emplace("name", "john4");
  6302. params.emplace("note", "coder");
  6303. res = cli_.Post("/person", params);
  6304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6305. ASSERT_EQ(StatusCode::OK_200, res->status);
  6306. res = cli_.Get("/person/john4");
  6307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6308. ASSERT_EQ(StatusCode::OK_200, res->status);
  6309. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6310. ASSERT_EQ("coder", res->body);
  6311. Params delete_params;
  6312. delete_params.emplace("name", "john4");
  6313. res = cli_.Delete("/person", delete_params);
  6314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6315. ASSERT_EQ(StatusCode::OK_200, res->status);
  6316. ASSERT_EQ("DELETED", res->body);
  6317. res = cli_.Get("/person/john4");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6320. }
  6321. TEST_F(ServerTest, DeleteMethod2) {
  6322. auto res = cli_.Get("/person/john5");
  6323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6324. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6325. Params params;
  6326. params.emplace("name", "john5");
  6327. params.emplace("note", "developer");
  6328. res = cli_.Post("/person", params);
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. ASSERT_EQ(StatusCode::OK_200, res->status);
  6331. res = cli_.Get("/person/john5");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. ASSERT_EQ(StatusCode::OK_200, res->status);
  6334. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6335. ASSERT_EQ("developer", res->body);
  6336. Params delete_params;
  6337. delete_params.emplace("name", "john5");
  6338. Headers headers;
  6339. headers.emplace("Custom-Header", "test-value");
  6340. res = cli_.Delete("/person", headers, delete_params);
  6341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6342. ASSERT_EQ(StatusCode::OK_200, res->status);
  6343. ASSERT_EQ("DELETED", res->body);
  6344. res = cli_.Get("/person/john5");
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6347. }
  6348. TEST_F(ServerTest, DeleteMethod3) {
  6349. auto res = cli_.Get("/person/john6");
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6352. Params params;
  6353. params.emplace("name", "john6");
  6354. params.emplace("note", "tester");
  6355. res = cli_.Post("/person", params);
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. ASSERT_EQ(StatusCode::OK_200, res->status);
  6358. res = cli_.Get("/person/john6");
  6359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6360. ASSERT_EQ(StatusCode::OK_200, res->status);
  6361. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6362. ASSERT_EQ("tester", res->body);
  6363. Params delete_params;
  6364. delete_params.emplace("name", "john6");
  6365. Headers headers;
  6366. headers.emplace("Custom-Header", "test-value");
  6367. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. ASSERT_EQ(StatusCode::OK_200, res->status);
  6370. ASSERT_EQ("DELETED", res->body);
  6371. res = cli_.Get("/person/john6");
  6372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6373. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6374. }
  6375. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6376. Params params;
  6377. params.emplace("json", JSON_DATA);
  6378. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. ASSERT_EQ(StatusCode::OK_200, res->status);
  6381. ASSERT_EQ(JSON_DATA, res->body);
  6382. }
  6383. TEST_F(ServerTest, PostEmptyContent) {
  6384. auto res = cli_.Post("/empty", "", "text/plain");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. ASSERT_EQ(StatusCode::OK_200, res->status);
  6387. ASSERT_EQ("empty", res->body);
  6388. }
  6389. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6390. auto res = cli_.Post("/empty-no-content-type");
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. ASSERT_EQ(StatusCode::OK_200, res->status);
  6393. ASSERT_EQ("empty-no-content-type", res->body);
  6394. }
  6395. TEST_F(ServerTest, PostPathOnly) {
  6396. auto res = cli_.Post("/path-only");
  6397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6398. ASSERT_EQ(StatusCode::OK_200, res->status);
  6399. ASSERT_EQ("path-only", res->body);
  6400. }
  6401. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6402. auto res = cli_.Post("/path-headers-only",
  6403. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. ASSERT_EQ(StatusCode::OK_200, res->status);
  6406. ASSERT_EQ("path-headers-only", res->body);
  6407. }
  6408. TEST_F(ServerTest, PostLarge) {
  6409. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. ASSERT_EQ(StatusCode::OK_200, res->status);
  6412. EXPECT_EQ(LARGE_DATA, res->body);
  6413. }
  6414. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6415. auto res = cli_.Put("/empty-no-content-type");
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. ASSERT_EQ(StatusCode::OK_200, res->status);
  6418. ASSERT_EQ("empty-no-content-type", res->body);
  6419. }
  6420. TEST_F(ServerTest, GetMethodDir) {
  6421. auto res = cli_.Get("/dir/");
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ(StatusCode::OK_200, res->status);
  6424. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6425. auto body = R"(<html>
  6426. <head>
  6427. </head>
  6428. <body>
  6429. <a href="/dir/test.html">Test</a>
  6430. <a href="/hi">hi</a>
  6431. </body>
  6432. </html>
  6433. )";
  6434. EXPECT_EQ(body, res->body);
  6435. }
  6436. TEST_F(ServerTest, GetMethodDirTest) {
  6437. auto res = cli_.Get("/dir/test.html");
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::OK_200, res->status);
  6440. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6441. EXPECT_EQ("test.html", res->body);
  6442. }
  6443. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6444. auto res = cli_.Get("/dir/../dir/test.html");
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6447. }
  6448. TEST_F(ServerTest, GetMethodInvalidPath) {
  6449. auto res = cli_.Get("/dir/../test.html");
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6452. }
  6453. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6454. auto res = cli_.Get("/../www/dir/test.html");
  6455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6456. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6457. }
  6458. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6459. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6462. }
  6463. TEST_F(ServerTest, GetMethodDirMountTest) {
  6464. auto res = cli_.Get("/mount/dir/test.html");
  6465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6466. EXPECT_EQ(StatusCode::OK_200, res->status);
  6467. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6468. EXPECT_EQ("test.html", res->body);
  6469. }
  6470. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6471. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6474. }
  6475. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6476. auto res = cli_.Get("/mount/dir/../test.html");
  6477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6478. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6479. }
  6480. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6481. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6484. }
  6485. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6486. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6489. }
  6490. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6491. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6493. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6494. }
  6495. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6496. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6499. }
  6500. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6501. auto res = cli_.Get("/mount/dir");
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6504. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6505. }
  6506. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6507. auto res = cli_.Get("//dir");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6510. EXPECT_FALSE(res->has_header("Location"));
  6511. }
  6512. TEST_F(ServerTest, PostMethod303) {
  6513. auto res = cli_.Post("/1", "body", "text/plain");
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6516. EXPECT_EQ("/2", res->get_header_value("Location"));
  6517. }
  6518. TEST_F(ServerTest, PostMethod303Redirect) {
  6519. cli_.set_follow_location(true);
  6520. auto res = cli_.Post("/1", "body", "text/plain");
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::OK_200, res->status);
  6523. EXPECT_EQ("redirected.", res->body);
  6524. EXPECT_EQ("/2", res->location);
  6525. }
  6526. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6527. auto res = cli_.Get("/dir/test.abcde");
  6528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6529. EXPECT_EQ(StatusCode::OK_200, res->status);
  6530. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6531. EXPECT_EQ("abcde", res->body);
  6532. }
  6533. TEST_F(ServerTest, StaticFileRange) {
  6534. auto res =
  6535. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6537. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6538. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6539. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6540. EXPECT_EQ(true, res->has_header("Content-Range"));
  6541. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6542. EXPECT_EQ(std::string("cd"), res->body);
  6543. }
  6544. TEST_F(ServerTest, StaticFileRanges) {
  6545. auto res = cli_.Get("/dir/test.abcde",
  6546. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6548. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6549. EXPECT_TRUE(
  6550. res->get_header_value("Content-Type")
  6551. .find(
  6552. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6553. 0);
  6554. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6555. }
  6556. TEST_F(ServerTest, StaticFileRangeHead) {
  6557. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6559. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6560. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6561. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6562. EXPECT_EQ(true, res->has_header("Content-Range"));
  6563. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6564. }
  6565. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6566. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6568. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6569. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6570. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6571. EXPECT_EQ(true, res->has_header("Content-Range"));
  6572. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6573. res->get_header_value("Content-Range"));
  6574. EXPECT_EQ("LAST\n", res->body);
  6575. }
  6576. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6577. auto res =
  6578. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6582. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6583. EXPECT_EQ(true, res->has_header("Content-Range"));
  6584. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6585. }
  6586. TEST_F(ServerTest, StaticFileBigFile) {
  6587. auto res = cli_.Get("/dir/1MB.txt");
  6588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6589. EXPECT_EQ(StatusCode::OK_200, res->status);
  6590. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6591. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6592. }
  6593. TEST_F(ServerTest, InvalidBaseDirMount) {
  6594. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6595. }
  6596. TEST_F(ServerTest, Binary) {
  6597. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6598. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6599. "application/octet-stream");
  6600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6601. ASSERT_EQ(StatusCode::OK_200, res->status);
  6602. ASSERT_EQ(4U, res->body.size());
  6603. res = cli_.Put("/binary", binary.data(), binary.size(),
  6604. "application/octet-stream");
  6605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6606. ASSERT_EQ(StatusCode::OK_200, res->status);
  6607. ASSERT_EQ(4U, res->body.size());
  6608. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6609. "application/octet-stream");
  6610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6611. ASSERT_EQ(StatusCode::OK_200, res->status);
  6612. ASSERT_EQ(4U, res->body.size());
  6613. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6614. "application/octet-stream");
  6615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6616. ASSERT_EQ(StatusCode::OK_200, res->status);
  6617. ASSERT_EQ(4U, res->body.size());
  6618. }
  6619. TEST_F(ServerTest, BinaryString) {
  6620. auto binary = std::string("\x00\x01\x02\x03", 4);
  6621. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. ASSERT_EQ(StatusCode::OK_200, res->status);
  6624. ASSERT_EQ(4U, res->body.size());
  6625. res = cli_.Put("/binary", binary, "application/octet-stream");
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. ASSERT_EQ(StatusCode::OK_200, res->status);
  6628. ASSERT_EQ(4U, res->body.size());
  6629. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6631. ASSERT_EQ(StatusCode::OK_200, res->status);
  6632. ASSERT_EQ(4U, res->body.size());
  6633. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. ASSERT_EQ(StatusCode::OK_200, res->status);
  6636. ASSERT_EQ(4U, res->body.size());
  6637. }
  6638. TEST_F(ServerTest, EmptyRequest) {
  6639. auto res = cli_.Get("");
  6640. ASSERT_TRUE(!res);
  6641. EXPECT_EQ(Error::Connection, res.error());
  6642. }
  6643. TEST_F(ServerTest, LongRequest) {
  6644. std::string request;
  6645. for (size_t i = 0; i < 545; i++) {
  6646. request += "/TooLongRequest";
  6647. }
  6648. request += "OK";
  6649. auto res = cli_.Get(request.c_str());
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6652. }
  6653. TEST_F(ServerTest, TooLongRequest) {
  6654. std::string request;
  6655. for (size_t i = 0; i < 546; i++) {
  6656. request += "/TooLongRequest";
  6657. }
  6658. request += "_NG";
  6659. auto start = std::chrono::high_resolution_clock::now();
  6660. cli_.set_keep_alive(true);
  6661. auto res = cli_.Get(request.c_str());
  6662. auto end = std::chrono::high_resolution_clock::now();
  6663. auto elapsed =
  6664. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6665. .count();
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6668. EXPECT_LE(elapsed, 1000);
  6669. EXPECT_EQ("close", res->get_header_value("Connection"));
  6670. EXPECT_FALSE(cli_.is_socket_open());
  6671. }
  6672. TEST_F(ServerTest, AlmostTooLongRequest) {
  6673. // test for #2046 - URI length check shouldn't include other content on req
  6674. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6675. // leading /, space, HTTP/1.1)
  6676. std::string request =
  6677. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6678. auto res = cli_.Get(request.c_str());
  6679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6681. }
  6682. TEST_F(ServerTest, LongHeader) {
  6683. Request req;
  6684. req.method = "GET";
  6685. req.path = "/hi";
  6686. std::string host_and_port;
  6687. host_and_port += HOST;
  6688. host_and_port += ":";
  6689. host_and_port += std::to_string(PORT);
  6690. req.headers.emplace("Host", host_and_port.c_str());
  6691. req.headers.emplace("Accept", "*/*");
  6692. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6693. req.headers.emplace(
  6694. "Header-Name",
  6695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6723. "@@@@@@@@@@@@@@@@");
  6724. auto res = std::make_shared<Response>();
  6725. auto error = Error::Success;
  6726. auto ret = cli_.send(req, *res, error);
  6727. ASSERT_TRUE(ret);
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. }
  6730. TEST_F(ServerTest, LongQueryValue) {
  6731. auto start = std::chrono::high_resolution_clock::now();
  6732. cli_.set_keep_alive(true);
  6733. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6734. auto end = std::chrono::high_resolution_clock::now();
  6735. auto elapsed =
  6736. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6737. .count();
  6738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6739. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6740. EXPECT_LE(elapsed, 1000);
  6741. EXPECT_EQ("close", res->get_header_value("Connection"));
  6742. EXPECT_FALSE(cli_.is_socket_open());
  6743. }
  6744. TEST_F(ServerTest, TooLongQueryValue) {
  6745. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6746. ASSERT_FALSE(res);
  6747. EXPECT_EQ(Error::Read, res.error());
  6748. }
  6749. TEST_F(ServerTest, TooLongHeader) {
  6750. Request req;
  6751. req.method = "GET";
  6752. req.path = "/hi";
  6753. std::string host_and_port;
  6754. host_and_port += HOST;
  6755. host_and_port += ":";
  6756. host_and_port += std::to_string(PORT);
  6757. req.headers.emplace("Host", host_and_port.c_str());
  6758. req.headers.emplace("Accept", "*/*");
  6759. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6760. req.headers.emplace(
  6761. "Header-Name",
  6762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6790. "@@@@@@@@@@@@@@@@@");
  6791. auto res = std::make_shared<Response>();
  6792. auto error = Error::Success;
  6793. auto ret = cli_.send(req, *res, error);
  6794. ASSERT_TRUE(ret);
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. }
  6797. TEST_F(ServerTest, HeaderCountAtLimit) {
  6798. // Test with headers just under the 100 limit
  6799. httplib::Headers headers;
  6800. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6801. // This should keep us just under the 100 header limit
  6802. for (int i = 0; i < 95; i++) {
  6803. std::string name = "X-Test-Header-" + std::to_string(i);
  6804. std::string value = "value" + std::to_string(i);
  6805. headers.emplace(name, value);
  6806. }
  6807. // This should work fine as we're under the limit
  6808. auto res = cli_.Get("/hi", headers);
  6809. EXPECT_TRUE(res);
  6810. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6811. }
  6812. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6813. // Test with many headers to exceed the 100 limit
  6814. httplib::Headers headers;
  6815. // Add 150 headers to definitely exceed the 100 limit
  6816. for (int i = 0; i < 150; i++) {
  6817. std::string name = "X-Test-Header-" + std::to_string(i);
  6818. std::string value = "value" + std::to_string(i);
  6819. headers.emplace(name, value);
  6820. }
  6821. // This should fail due to exceeding header count limit
  6822. cli_.set_keep_alive(true);
  6823. auto res = cli_.Get("/hi", headers);
  6824. // The server should respond with 400 Bad Request
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6827. EXPECT_EQ("close", res->get_header_value("Connection"));
  6828. EXPECT_FALSE(cli_.is_socket_open());
  6829. }
  6830. TEST_F(ServerTest, PercentEncoding) {
  6831. auto res = cli_.Get("/e%6edwith%");
  6832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. }
  6835. TEST_F(ServerTest, PercentEncodingUnicode) {
  6836. auto res = cli_.Get("/e%u006edwith%");
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. EXPECT_EQ(StatusCode::OK_200, res->status);
  6839. }
  6840. TEST_F(ServerTest, InvalidPercentEncoding) {
  6841. auto res = cli_.Get("/%endwith%");
  6842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6843. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6844. }
  6845. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6846. auto res = cli_.Get("/%uendwith%");
  6847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6848. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6849. }
  6850. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6851. auto res = cli_.Get("/hello?aaa=bbb%");
  6852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6853. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6854. }
  6855. TEST_F(ServerTest, PlusSignEncoding) {
  6856. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_EQ(StatusCode::OK_200, res->status);
  6859. EXPECT_EQ("a +b", res->body);
  6860. }
  6861. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6862. // This test simulates a potential DoS attack using many headers
  6863. // to verify our security fix prevents memory exhaustion
  6864. httplib::Headers attack_headers;
  6865. // Attempt to add many headers like an attacker would (200 headers to far
  6866. // exceed limit)
  6867. for (int i = 0; i < 200; i++) {
  6868. std::string name = "X-Attack-Header-" + std::to_string(i);
  6869. std::string value = "attack_payload_" + std::to_string(i);
  6870. attack_headers.emplace(name, value);
  6871. }
  6872. // Try to POST with excessive headers
  6873. cli_.set_keep_alive(true);
  6874. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6875. // Should either fail or return 400 Bad Request due to security limit
  6876. if (res) {
  6877. // If we get a response, it should be 400 Bad Request
  6878. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6879. EXPECT_EQ("close", res->get_header_value("Connection"));
  6880. }
  6881. EXPECT_FALSE(cli_.is_socket_open());
  6882. }
  6883. TEST_F(ServerTest, MultipartFormData) {
  6884. UploadFormDataItems items = {
  6885. {"text1", "text default", "", ""},
  6886. {"text2", "aωb", "", ""},
  6887. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6888. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6889. {"file3", "", "", "application/octet-stream"},
  6890. {"file4", "", "", " application/json tmp-string "}};
  6891. auto res = cli_.Post("/multipart", items);
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. }
  6895. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6896. UploadFormDataItems items = {
  6897. {"text", "default text", "", ""},
  6898. {"multi_text1", "aaaaa", "", ""},
  6899. {"multi_text1", "bbbbb", "", ""},
  6900. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6901. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6902. "application/json"},
  6903. };
  6904. auto res = cli_.Post("/multipart/multi_file_values", items);
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. }
  6908. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6909. auto res = cli_.Get("/hi");
  6910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6911. EXPECT_EQ(StatusCode::OK_200, res->status);
  6912. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6913. EXPECT_EQ("Hello World!", res->body);
  6914. }
  6915. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6916. Request req;
  6917. req.method = "POST";
  6918. req.path = "/chunked";
  6919. std::string host_and_port;
  6920. host_and_port += HOST;
  6921. host_and_port += ":";
  6922. host_and_port += std::to_string(PORT);
  6923. req.headers.emplace("Host", host_and_port.c_str());
  6924. req.headers.emplace("Accept", "*/*");
  6925. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6926. req.headers.emplace("Content-Type", "text/plain");
  6927. req.headers.emplace("Content-Length", "0");
  6928. req.headers.emplace(
  6929. "Transfer-Encoding",
  6930. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6931. // Client does not chunk, so make a chunked body manually.
  6932. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6933. auto res = std::make_shared<Response>();
  6934. auto error = Error::Success;
  6935. auto ret = cli_.send(req, *res, error);
  6936. ASSERT_TRUE(ret);
  6937. EXPECT_EQ(StatusCode::OK_200, res->status);
  6938. }
  6939. template <typename ClientT>
  6940. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6941. int expected_status) {
  6942. Request req;
  6943. req.method = "POST";
  6944. req.path = "/chunked";
  6945. std::string host_and_port;
  6946. host_and_port += HOST;
  6947. host_and_port += ":";
  6948. host_and_port += std::to_string(PORT);
  6949. req.headers.emplace("Host", host_and_port.c_str());
  6950. req.headers.emplace("Content-Length", "0");
  6951. req.headers.emplace("Transfer-Encoding", "chunked");
  6952. req.body = body;
  6953. auto res = std::make_shared<Response>();
  6954. auto error = Error::Success;
  6955. ASSERT_TRUE(cli.send(req, *res, error));
  6956. EXPECT_EQ(expected_status, res->status);
  6957. }
  6958. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6959. // rather than treat them as valid lengths.
  6960. template <typename ClientT>
  6961. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6962. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6963. }
  6964. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6965. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6966. }
  6967. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6968. expect_chunked_body_rejected(
  6969. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6970. }
  6971. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6972. // chunk-size line carries no CR, LF or other control character ahead of its
  6973. // terminator. Such a line must be refused rather than read as extension text.
  6974. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6975. expect_chunked_body_rejected(
  6976. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6977. }
  6978. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6979. expect_chunked_body_rejected(
  6980. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6981. }
  6982. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6983. expect_chunked_body_rejected(
  6984. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6985. }
  6986. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6987. // The literal stays split: a hex escape consumes every hex digit that
  6988. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6989. expect_chunked_body_rejected(
  6990. cli_, "4;a\x01"
  6991. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6992. }
  6993. // The bytes around chunk data are no payload, so they cannot ride on the
  6994. // payload limit
  6995. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6996. // Small enough that the whole request is sent before the server turns it
  6997. // down, yet past the limit by the last chunks
  6998. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  6999. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7000. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7001. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7002. SCOPED_TRACE(size_line.substr(0, 2));
  7003. std::string body;
  7004. for (auto c : std::string("dechunked post body")) {
  7005. body += size_line + "\r\n" + c + "\r\n";
  7006. }
  7007. body += "0\r\n\r\n";
  7008. expect_chunked_body_rejected(cli_, body.c_str());
  7009. }
  7010. }
  7011. TEST_F(ServerTest, AcceptsChunkExtension) {
  7012. expect_chunked_body_status(cli_,
  7013. "4;name=value\r\ndech\r\n"
  7014. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7015. "0;last\r\n\r\n",
  7016. StatusCode::OK_200);
  7017. }
  7018. TEST_F(ServerTest, GetStreamed2) {
  7019. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7022. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7023. EXPECT_EQ(true, res->has_header("Content-Range"));
  7024. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7025. EXPECT_EQ(std::string("ab"), res->body);
  7026. }
  7027. TEST_F(ServerTest, GetStreamed) {
  7028. auto res = cli_.Get("/streamed");
  7029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7030. EXPECT_EQ(StatusCode::OK_200, res->status);
  7031. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7032. EXPECT_EQ(std::string("aaabbb"), res->body);
  7033. }
  7034. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7035. auto res = cli_.Get("/streamed-without-length",
  7036. Headers{make_range_header({{0, -1}})});
  7037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7038. EXPECT_EQ(StatusCode::OK_200, res->status);
  7039. EXPECT_EQ(false, res->has_header("Content-Length"));
  7040. EXPECT_EQ(false, res->has_header("Content-Range"));
  7041. EXPECT_EQ(std::string("abcdefg"), res->body);
  7042. }
  7043. TEST_F(ServerTest, GetStreamedWithRange1) {
  7044. auto res =
  7045. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7047. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7048. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7049. EXPECT_EQ(true, res->has_header("Content-Range"));
  7050. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7051. EXPECT_EQ(std::string("def"), res->body);
  7052. }
  7053. TEST_F(ServerTest, GetStreamedWithRange2) {
  7054. auto res =
  7055. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7057. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7058. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7059. EXPECT_EQ(true, res->has_header("Content-Range"));
  7060. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7061. EXPECT_EQ(std::string("bcdefg"), res->body);
  7062. }
  7063. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7064. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7067. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7068. EXPECT_EQ(true, res->has_header("Content-Range"));
  7069. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7070. EXPECT_EQ(std::string("efg"), res->body);
  7071. }
  7072. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7073. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7074. // the entire representation.
  7075. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7076. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7078. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7079. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7080. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7081. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7082. }
  7083. }
  7084. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7085. auto res =
  7086. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7089. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7090. EXPECT_EQ(false, res->has_header("Content-Range"));
  7091. EXPECT_EQ(0U, res->body.size());
  7092. }
  7093. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7094. // Only a 206 is served as a partial representation. Under any other status
  7095. // `apply_ranges()` reported the full content length, so the body must match
  7096. // that header, and the content provider must never be asked for an offset
  7097. // outside the representation.
  7098. auto check = [&](int status, const char *range) {
  7099. auto path =
  7100. std::string("/streamed-with-range?status=") + std::to_string(status);
  7101. auto ctx = path + " Range: " + range;
  7102. auto res = cli_.Get(path, Headers{{"Range", range}});
  7103. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7104. EXPECT_EQ(status, res->status) << ctx;
  7105. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7106. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7107. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7108. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7109. };
  7110. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7111. check(403, "bytes=3-5");
  7112. // The offset is far past the representation.
  7113. check(403, "bytes=100000-100200");
  7114. // `first_pos` is still -1 here, and the bounds asserts in
  7115. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7116. check(403, "bytes=-3");
  7117. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7118. // multipart branch would have written one that is empty.
  7119. check(403, "bytes=1-2, 4-5");
  7120. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7121. // covers the whole representation.
  7122. check(200, "bytes=3-5");
  7123. check(200, "bytes=1-2, 4-5");
  7124. }
  7125. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7126. auto res =
  7127. cli_.Get("/streamed-with-range",
  7128. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7129. "92233720368547758079223372036854775807"}});
  7130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7131. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7132. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7133. EXPECT_EQ(false, res->has_header("Content-Range"));
  7134. EXPECT_EQ(0U, res->body.size());
  7135. }
  7136. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7137. auto res = cli_.Get(
  7138. "/with-range",
  7139. Headers{{"Range",
  7140. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7141. {"Accept-Encoding", ""}});
  7142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7143. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7144. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7145. EXPECT_EQ(true, res->has_header("Content-Range"));
  7146. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7147. EXPECT_EQ(std::string("abcdefg"), res->body);
  7148. }
  7149. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7150. auto res = cli_.Get("/with-range", Headers{
  7151. {"Range", "bytes=0-"},
  7152. {"Accept-Encoding", ""},
  7153. });
  7154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7156. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7157. EXPECT_EQ(true, res->has_header("Content-Range"));
  7158. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7159. EXPECT_EQ(std::string("abcdefg"), res->body);
  7160. }
  7161. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7162. auto res = cli_.Get("/streamed-with-range",
  7163. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7165. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7166. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7167. EXPECT_EQ(false, res->has_header("Content-Range"));
  7168. EXPECT_EQ(267U, res->body.size());
  7169. // Check that both range contents are present
  7170. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7171. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7172. // Check that Content-Range headers are present for both ranges
  7173. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7174. std::string::npos);
  7175. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7176. std::string::npos);
  7177. }
  7178. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7179. Ranges ranges;
  7180. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7181. ranges.emplace_back(0, -1);
  7182. }
  7183. auto res = cli_.Get("/streamed-with-range?error",
  7184. Headers{{make_range_header(ranges)}});
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7187. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(false, res->has_header("Content-Range"));
  7189. EXPECT_EQ(0U, res->body.size());
  7190. }
  7191. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7192. auto res = cli_.Get("/streamed-with-range",
  7193. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7195. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7196. EXPECT_EQ(5U, res->body.size());
  7197. // Check that overlapping ranges are coalesced into a single range
  7198. EXPECT_EQ("bcdef", res->body);
  7199. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7200. // Should be single range, not multipart
  7201. EXPECT_TRUE(res->has_header("Content-Range"));
  7202. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7203. }
  7204. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7205. auto res = cli_.Get("/streamed-with-range",
  7206. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7209. EXPECT_EQ(268U, res->body.size());
  7210. // Check that both range contents are present
  7211. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7212. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7213. // Check that Content-Range headers are present for both ranges
  7214. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7215. std::string::npos);
  7216. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7217. std::string::npos);
  7218. }
  7219. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7220. auto res = cli_.Get("/streamed-with-range",
  7221. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7224. EXPECT_EQ(269U, res->body.size());
  7225. // Check that both duplicate range contents are present
  7226. size_t first_abc = res->body.find("abc\r\n");
  7227. EXPECT_TRUE(first_abc != std::string::npos);
  7228. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7229. EXPECT_TRUE(second_abc != std::string::npos);
  7230. // Check that Content-Range headers are present for both ranges
  7231. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7232. EXPECT_TRUE(first_range != std::string::npos);
  7233. size_t second_range =
  7234. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7235. EXPECT_TRUE(second_range != std::string::npos);
  7236. }
  7237. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7238. auto res =
  7239. cli_.Get("/streamed-with-range?error",
  7240. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7243. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7244. EXPECT_EQ(false, res->has_header("Content-Range"));
  7245. EXPECT_EQ(0U, res->body.size());
  7246. }
  7247. TEST_F(ServerTest, GetStreamedEndless) {
  7248. uint64_t offset = 0;
  7249. auto res = cli_.Get("/streamed-cancel",
  7250. [&](const char * /*data*/, uint64_t data_length) {
  7251. if (offset < 100) {
  7252. offset += data_length;
  7253. return true;
  7254. }
  7255. return false;
  7256. });
  7257. ASSERT_TRUE(!res);
  7258. EXPECT_EQ(Error::Canceled, res.error());
  7259. }
  7260. TEST_F(ServerTest, ClientStop) {
  7261. std::atomic_size_t count{4};
  7262. std::vector<std::thread> threads;
  7263. for (auto i = count.load(); i != 0; --i) {
  7264. threads.emplace_back([&]() {
  7265. auto res = cli_.Get("/streamed-cancel",
  7266. [&](const char *, uint64_t) { return true; });
  7267. --count;
  7268. ASSERT_TRUE(!res);
  7269. EXPECT_TRUE(res.error() == Error::Canceled ||
  7270. res.error() == Error::Read || res.error() == Error::Write);
  7271. });
  7272. }
  7273. std::this_thread::sleep_for(std::chrono::seconds(2));
  7274. while (count != 0) {
  7275. cli_.stop();
  7276. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7277. }
  7278. for (auto &t : threads) {
  7279. t.join();
  7280. }
  7281. }
  7282. TEST_F(ServerTest, GetWithRange1) {
  7283. auto res = cli_.Get("/with-range", Headers{
  7284. make_range_header({{3, 5}}),
  7285. {"Accept-Encoding", ""},
  7286. });
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7289. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7290. EXPECT_EQ(true, res->has_header("Content-Range"));
  7291. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7292. EXPECT_EQ(std::string("def"), res->body);
  7293. }
  7294. TEST_F(ServerTest, GetWithRange2) {
  7295. auto res = cli_.Get("/with-range", Headers{
  7296. make_range_header({{1, -1}}),
  7297. {"Accept-Encoding", ""},
  7298. });
  7299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7300. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7301. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7302. EXPECT_EQ(true, res->has_header("Content-Range"));
  7303. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7304. EXPECT_EQ(std::string("bcdefg"), res->body);
  7305. }
  7306. TEST_F(ServerTest, GetWithRange3) {
  7307. auto res = cli_.Get("/with-range", Headers{
  7308. make_range_header({{0, 0}}),
  7309. {"Accept-Encoding", ""},
  7310. });
  7311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7313. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7314. EXPECT_EQ(true, res->has_header("Content-Range"));
  7315. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7316. EXPECT_EQ(std::string("a"), res->body);
  7317. }
  7318. TEST_F(ServerTest, GetWithRange4) {
  7319. auto res = cli_.Get("/with-range", Headers{
  7320. make_range_header({{-1, 2}}),
  7321. {"Accept-Encoding", ""},
  7322. });
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7325. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7326. EXPECT_EQ(true, res->has_header("Content-Range"));
  7327. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7328. EXPECT_EQ(std::string("fg"), res->body);
  7329. }
  7330. TEST_F(ServerTest, GetWithRange5) {
  7331. auto res = cli_.Get("/with-range", Headers{
  7332. make_range_header({{0, 5}}),
  7333. {"Accept-Encoding", ""},
  7334. });
  7335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7336. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7337. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7338. EXPECT_EQ(true, res->has_header("Content-Range"));
  7339. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7340. EXPECT_EQ(std::string("abcdef"), res->body);
  7341. }
  7342. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7343. auto res =
  7344. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7346. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7347. }
  7348. TEST_F(ServerTest, GetWithRangeMultipart) {
  7349. auto res =
  7350. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7353. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7354. EXPECT_EQ(false, res->has_header("Content-Range"));
  7355. EXPECT_EQ(267U, res->body.size());
  7356. }
  7357. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7358. auto res = cli_.Get("/with-range",
  7359. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7361. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7362. }
  7363. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7364. auto res = cli_.Get("/with-range-customized-response",
  7365. Headers{{make_range_header({{1, 2}})}});
  7366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7367. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7368. EXPECT_EQ(true, res->has_header("Content-Length"));
  7369. EXPECT_EQ(false, res->has_header("Content-Range"));
  7370. EXPECT_EQ(JSON_DATA, res->body);
  7371. }
  7372. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7373. auto res = cli_.Get("/with-range-customized-response",
  7374. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7376. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7377. EXPECT_EQ(true, res->has_header("Content-Length"));
  7378. EXPECT_EQ(false, res->has_header("Content-Range"));
  7379. EXPECT_EQ(JSON_DATA, res->body);
  7380. }
  7381. TEST_F(ServerTest, Issue1772) {
  7382. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7385. }
  7386. TEST_F(ServerTest, Issue609) {
  7387. auto res = cli_.Delete("/issue609");
  7388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7389. EXPECT_EQ(StatusCode::OK_200, res->status);
  7390. EXPECT_EQ(std::string("ok"), res->body);
  7391. }
  7392. TEST_F(ServerTest, GetStreamedChunked) {
  7393. auto res = cli_.Get("/streamed-chunked");
  7394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7395. EXPECT_EQ(StatusCode::OK_200, res->status);
  7396. EXPECT_EQ(std::string("123456789"), res->body);
  7397. }
  7398. TEST_F(ServerTest, GetStreamedChunked2) {
  7399. auto res = cli_.Get("/streamed-chunked2");
  7400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7401. EXPECT_EQ(StatusCode::OK_200, res->status);
  7402. EXPECT_EQ(std::string("123456789"), res->body);
  7403. }
  7404. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7405. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7407. EXPECT_EQ(StatusCode::OK_200, res->status);
  7408. EXPECT_EQ(std::string("123456789"), res->body);
  7409. EXPECT_TRUE(res->has_header("Trailer"));
  7410. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7411. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7412. // Trailers are now stored separately from headers (security fix)
  7413. EXPECT_EQ(2U, res->trailers.size());
  7414. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7415. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7416. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7417. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7418. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7419. // Verify trailers are NOT in headers (security verification)
  7420. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7421. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7422. }
  7423. TEST_F(ServerTest, LargeChunkedPost) {
  7424. Request req;
  7425. req.method = "POST";
  7426. req.path = "/large-chunked";
  7427. std::string host_and_port;
  7428. host_and_port += HOST;
  7429. host_and_port += ":";
  7430. host_and_port += std::to_string(PORT);
  7431. req.headers.emplace("Host", host_and_port.c_str());
  7432. req.headers.emplace("Accept", "*/*");
  7433. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7434. req.headers.emplace("Content-Type", "text/plain");
  7435. req.headers.emplace("Content-Length", "0");
  7436. req.headers.emplace("Transfer-Encoding", "chunked");
  7437. std::string long_string(30 * 1024u, 'a');
  7438. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7439. // Attempt to make a large enough post to exceed OS buffers, to test that
  7440. // the server handles short reads if the full chunk data isn't available.
  7441. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7442. auto res = std::make_shared<Response>();
  7443. auto error = Error::Success;
  7444. auto ret = cli_.send(req, *res, error);
  7445. ASSERT_TRUE(ret);
  7446. EXPECT_EQ(StatusCode::OK_200, res->status);
  7447. }
  7448. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7449. auto res = cli_.Get("/remote_addr");
  7450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7451. EXPECT_EQ(StatusCode::OK_200, res->status);
  7452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7453. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7454. }
  7455. TEST_F(ServerTest, GetMethodLocalAddr) {
  7456. auto res = cli_.Get("/local_addr");
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7460. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7461. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7462. }
  7463. TEST_F(ServerTest, HTTPResponseSplitting) {
  7464. auto res = cli_.Get("/http_response_splitting");
  7465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7466. EXPECT_EQ(StatusCode::OK_200, res->status);
  7467. }
  7468. TEST_F(ServerTest, SlowRequest) {
  7469. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7470. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7471. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7472. }
  7473. #if 0
  7474. TEST_F(ServerTest, SlowPost) {
  7475. char buffer[64 * 1024];
  7476. memset(buffer, 0x42, sizeof(buffer));
  7477. auto res = cli_.Post(
  7478. "/slowpost", 64 * 1024 * 1024,
  7479. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7480. auto ret = sink.write(buffer, sizeof(buffer));
  7481. EXPECT_TRUE(ret);
  7482. return true;
  7483. },
  7484. "text/plain");
  7485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7486. EXPECT_EQ(StatusCode::OK_200, res->status);
  7487. }
  7488. TEST_F(ServerTest, SlowPostFail) {
  7489. char buffer[64 * 1024];
  7490. memset(buffer, 0x42, sizeof(buffer));
  7491. cli_.set_write_timeout(std::chrono::seconds(0));
  7492. auto res = cli_.Post(
  7493. "/slowpost", 64 * 1024 * 1024,
  7494. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7495. sink.write(buffer, sizeof(buffer));
  7496. return true;
  7497. },
  7498. "text/plain");
  7499. ASSERT_TRUE(!res);
  7500. EXPECT_EQ(Error::Write, res.error());
  7501. }
  7502. #endif
  7503. TEST_F(ServerTest, Put) {
  7504. auto res = cli_.Put("/put", "PUT", "text/plain");
  7505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7506. EXPECT_EQ(StatusCode::OK_200, res->status);
  7507. EXPECT_EQ("PUT", res->body);
  7508. }
  7509. TEST_F(ServerTest, PutWithContentProvider) {
  7510. auto res = cli_.Put(
  7511. "/put", 3,
  7512. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7513. sink.os << "PUT";
  7514. return true;
  7515. },
  7516. "text/plain");
  7517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7518. EXPECT_EQ(StatusCode::OK_200, res->status);
  7519. EXPECT_EQ("PUT", res->body);
  7520. }
  7521. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7522. auto res = cli_.Post(
  7523. "/post", 42,
  7524. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7525. return false;
  7526. },
  7527. "text/plain");
  7528. ASSERT_TRUE(!res);
  7529. EXPECT_EQ(Error::Canceled, res.error());
  7530. }
  7531. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  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, PostWithContentProviderWithoutLengthAbort) {
  7545. auto res = cli_.Post(
  7546. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7547. "text/plain");
  7548. ASSERT_TRUE(!res);
  7549. EXPECT_EQ(Error::Canceled, res.error());
  7550. }
  7551. TEST_F(ServerTest, PostLoopBack) {
  7552. std::string body;
  7553. auto res = cli_.Post(
  7554. "/post-loopback", 9,
  7555. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7556. EXPECT_EQ(9u, length);
  7557. sink.write("123", 3);
  7558. sink.write("456", 3);
  7559. sink.write("789", 3);
  7560. return true;
  7561. },
  7562. "text/plain",
  7563. [&body](const char *data, size_t data_length) {
  7564. body.append(data, data_length);
  7565. return true;
  7566. });
  7567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7568. EXPECT_EQ(StatusCode::OK_200, res->status);
  7569. EXPECT_EQ("123456789", body);
  7570. }
  7571. TEST_F(ServerTest, PutLoopBack) {
  7572. std::string body;
  7573. auto res = cli_.Put(
  7574. "/put-loopback", 9,
  7575. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7576. EXPECT_EQ(9u, length);
  7577. sink.write("123", 3);
  7578. sink.write("456", 3);
  7579. sink.write("789", 3);
  7580. return true;
  7581. },
  7582. "text/plain",
  7583. [&body](const char *data, size_t data_length) {
  7584. body.append(data, data_length);
  7585. return true;
  7586. });
  7587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7588. EXPECT_EQ(StatusCode::OK_200, res->status);
  7589. EXPECT_EQ("123456789", body);
  7590. }
  7591. TEST_F(ServerTest, PatchLoopBack) {
  7592. std::string body;
  7593. auto res = cli_.Patch(
  7594. "/patch-loopback", 9,
  7595. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7596. EXPECT_EQ(9u, length);
  7597. sink.write("123", 3);
  7598. sink.write("456", 3);
  7599. sink.write("789", 3);
  7600. return true;
  7601. },
  7602. "text/plain",
  7603. [&body](const char *data, size_t data_length) {
  7604. body.append(data, data_length);
  7605. return true;
  7606. });
  7607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7608. EXPECT_EQ(StatusCode::OK_200, res->status);
  7609. EXPECT_EQ("123456789", body);
  7610. }
  7611. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7612. std::string body;
  7613. auto res = cli_.Post(
  7614. "/post-loopback",
  7615. [](size_t /*offset*/, DataSink &sink) {
  7616. sink.write("123", 3);
  7617. sink.write("456", 3);
  7618. sink.write("789", 3);
  7619. sink.done();
  7620. return true;
  7621. },
  7622. "text/plain",
  7623. [&body](const char *data, size_t data_length) {
  7624. body.append(data, data_length);
  7625. return true;
  7626. });
  7627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7628. EXPECT_EQ(StatusCode::OK_200, res->status);
  7629. EXPECT_EQ("123456789", body);
  7630. }
  7631. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7632. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7633. cli_.set_compress(true);
  7634. auto res = cli_.Put(
  7635. "/put", 3,
  7636. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7637. sink.os << "PUT";
  7638. return true;
  7639. },
  7640. "text/plain");
  7641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7642. EXPECT_EQ(StatusCode::OK_200, res->status);
  7643. EXPECT_EQ("PUT", res->body);
  7644. }
  7645. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7646. cli_.set_compress(true);
  7647. auto res = cli_.Post(
  7648. "/post", 42,
  7649. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7650. return false;
  7651. },
  7652. "text/plain");
  7653. ASSERT_TRUE(!res);
  7654. EXPECT_EQ(Error::Canceled, res.error());
  7655. }
  7656. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7657. cli_.set_compress(true);
  7658. auto res = cli_.Put(
  7659. "/put",
  7660. [](size_t /*offset*/, DataSink &sink) {
  7661. sink.os << "PUT";
  7662. sink.done();
  7663. return true;
  7664. },
  7665. "text/plain");
  7666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7667. EXPECT_EQ(StatusCode::OK_200, res->status);
  7668. EXPECT_EQ("PUT", res->body);
  7669. }
  7670. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7671. cli_.set_compress(true);
  7672. auto res = cli_.Post(
  7673. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7674. "text/plain");
  7675. ASSERT_TRUE(!res);
  7676. EXPECT_EQ(Error::Canceled, res.error());
  7677. }
  7678. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7679. cli_.set_compress(true);
  7680. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7682. EXPECT_EQ(StatusCode::OK_200, res->status);
  7683. EXPECT_EQ(LARGE_DATA, res->body);
  7684. }
  7685. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7686. #ifdef CPPHTTPLIB_SSL_ENABLED
  7687. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7688. Client cli(s.c_str());
  7689. cli.enable_server_certificate_verification(false);
  7690. #else
  7691. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7692. Client cli(s.c_str());
  7693. #endif
  7694. cli.set_compress(true);
  7695. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ(LARGE_DATA, res->body);
  7699. // The compressed size should be less than a 10th of the original. May vary
  7700. // depending on the zlib library.
  7701. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7702. static_cast<uint64_t>(10 * 1024 * 1024));
  7703. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7704. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7705. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7706. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7707. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7708. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7709. #endif
  7710. }
  7711. TEST_F(ServerTest, PutContentWithDeflate) {
  7712. cli_.set_compress(false);
  7713. Headers headers;
  7714. headers.emplace("Content-Encoding", "deflate");
  7715. // PUT in deflate format:
  7716. auto res = cli_.Put("/put", headers,
  7717. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7719. EXPECT_EQ(StatusCode::OK_200, res->status);
  7720. EXPECT_EQ("PUT", res->body);
  7721. }
  7722. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7723. Headers headers;
  7724. headers.emplace("Accept-Encoding", "gzip, deflate");
  7725. auto res = cli_.Get("/streamed-chunked", headers);
  7726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7727. EXPECT_EQ(StatusCode::OK_200, res->status);
  7728. EXPECT_EQ(std::string("123456789"), res->body);
  7729. }
  7730. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7731. Headers headers;
  7732. headers.emplace("Accept-Encoding", "gzip, deflate");
  7733. auto res = cli_.Get("/streamed-chunked2", headers);
  7734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7735. EXPECT_EQ(StatusCode::OK_200, res->status);
  7736. EXPECT_EQ(std::string("123456789"), res->body);
  7737. }
  7738. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7739. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. EXPECT_EQ(StatusCode::OK_200, res->status);
  7742. }
  7743. TEST(GzipDecompressor, ChunkedDecompression) {
  7744. std::string data;
  7745. for (size_t i = 0; i < 32 * 1024; ++i) {
  7746. data.push_back(static_cast<char>('a' + i % 26));
  7747. }
  7748. std::string compressed_data;
  7749. {
  7750. httplib::detail::gzip_compressor compressor;
  7751. bool result = compressor.compress(
  7752. data.data(), data.size(),
  7753. /*last=*/true,
  7754. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7755. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7756. compressed_data_size);
  7757. return true;
  7758. });
  7759. ASSERT_TRUE(result);
  7760. }
  7761. std::string decompressed_data;
  7762. {
  7763. httplib::detail::gzip_decompressor decompressor;
  7764. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7765. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7766. size_t chunk_size = 130;
  7767. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7768. chunk_begin += chunk_size) {
  7769. size_t current_chunk_size =
  7770. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7771. bool result = decompressor.decompress(
  7772. compressed_data.data() + chunk_begin, current_chunk_size,
  7773. [&](const char *decompressed_data_chunk,
  7774. size_t decompressed_data_chunk_size) {
  7775. decompressed_data.insert(decompressed_data.size(),
  7776. decompressed_data_chunk,
  7777. decompressed_data_chunk_size);
  7778. return true;
  7779. });
  7780. ASSERT_TRUE(result);
  7781. }
  7782. }
  7783. ASSERT_EQ(data, decompressed_data);
  7784. }
  7785. TEST(GzipDecompressor, DeflateDecompression) {
  7786. std::string original_text = "Raw deflate without gzip";
  7787. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7788. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7789. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7790. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7791. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7792. std::string decompressed_data;
  7793. {
  7794. httplib::detail::gzip_decompressor decompressor;
  7795. bool result = decompressor.decompress(
  7796. compressed_data.data(), compressed_data.size(),
  7797. [&](const char *decompressed_data_chunk,
  7798. size_t decompressed_data_chunk_size) {
  7799. decompressed_data.insert(decompressed_data.size(),
  7800. decompressed_data_chunk,
  7801. decompressed_data_chunk_size);
  7802. return true;
  7803. });
  7804. ASSERT_TRUE(result);
  7805. }
  7806. ASSERT_EQ(original_text, decompressed_data);
  7807. }
  7808. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7809. std::string original_text = "Raw deflate without gzip";
  7810. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7811. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7812. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7813. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7814. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7815. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7816. std::string decompressed_data;
  7817. {
  7818. httplib::detail::gzip_decompressor decompressor;
  7819. bool result = decompressor.decompress(
  7820. compressed_data.data(), compressed_data.size(),
  7821. [&](const char *decompressed_data_chunk,
  7822. size_t decompressed_data_chunk_size) {
  7823. decompressed_data.insert(decompressed_data.size(),
  7824. decompressed_data_chunk,
  7825. decompressed_data_chunk_size);
  7826. return true;
  7827. });
  7828. ASSERT_TRUE(result);
  7829. }
  7830. ASSERT_EQ(original_text, decompressed_data);
  7831. }
  7832. #endif
  7833. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7834. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7835. Headers headers;
  7836. headers.emplace("Accept-Encoding", "br");
  7837. auto res = cli_.Get("/streamed-chunked", headers);
  7838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7839. EXPECT_EQ(StatusCode::OK_200, res->status);
  7840. EXPECT_EQ(std::string("123456789"), res->body);
  7841. }
  7842. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7843. Headers headers;
  7844. headers.emplace("Accept-Encoding", "br");
  7845. auto res = cli_.Get("/streamed-chunked2", headers);
  7846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7847. EXPECT_EQ(StatusCode::OK_200, res->status);
  7848. EXPECT_EQ(std::string("123456789"), res->body);
  7849. }
  7850. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7851. cli_.set_compress(true);
  7852. auto res = cli_.Put(
  7853. "/put", 3,
  7854. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7855. sink.os << "PUT";
  7856. return true;
  7857. },
  7858. "text/plain");
  7859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7860. EXPECT_EQ(StatusCode::OK_200, res->status);
  7861. EXPECT_EQ("PUT", res->body);
  7862. }
  7863. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7864. cli_.set_compress(true);
  7865. auto res = cli_.Put(
  7866. "/put",
  7867. [](size_t /*offset*/, DataSink &sink) {
  7868. sink.os << "PUT";
  7869. sink.done();
  7870. return true;
  7871. },
  7872. "text/plain");
  7873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7874. EXPECT_EQ(StatusCode::OK_200, res->status);
  7875. EXPECT_EQ("PUT", res->body);
  7876. }
  7877. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7878. cli_.set_compress(true);
  7879. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. EXPECT_EQ(LARGE_DATA, res->body);
  7883. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7884. }
  7885. #endif
  7886. TEST_F(ServerTest, Patch) {
  7887. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. EXPECT_EQ("PATCH", res->body);
  7891. }
  7892. TEST_F(ServerTest, Delete) {
  7893. auto res = cli_.Delete("/delete");
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ(StatusCode::OK_200, res->status);
  7896. EXPECT_EQ("DELETE", res->body);
  7897. }
  7898. TEST_F(ServerTest, DeleteContentReceiver) {
  7899. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7901. EXPECT_EQ(StatusCode::OK_200, res->status);
  7902. EXPECT_EQ("content", res->body);
  7903. }
  7904. TEST_F(ServerTest, Options) {
  7905. auto res = cli_.Options("*");
  7906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7907. EXPECT_EQ(StatusCode::OK_200, res->status);
  7908. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7909. EXPECT_TRUE(res->body.empty());
  7910. }
  7911. TEST_F(ServerTest, URL) {
  7912. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7914. EXPECT_EQ(StatusCode::OK_200, res->status);
  7915. }
  7916. TEST_F(ServerTest, ArrayParam) {
  7917. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7919. EXPECT_EQ(StatusCode::OK_200, res->status);
  7920. }
  7921. TEST_F(ServerTest, ArrayParamValues) {
  7922. auto res =
  7923. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7925. EXPECT_EQ(StatusCode::OK_200, res->status);
  7926. }
  7927. TEST_F(ServerTest, NoMultipleHeaders) {
  7928. Headers headers = {{"Content-Length", "5"}};
  7929. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7930. "text/plain");
  7931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7932. EXPECT_EQ(StatusCode::OK_200, res->status);
  7933. }
  7934. TEST_F(ServerTest, PostContentReceiver) {
  7935. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7937. ASSERT_EQ(StatusCode::OK_200, res->status);
  7938. ASSERT_EQ("content", res->body);
  7939. }
  7940. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7941. UploadFormDataItems items = {
  7942. {"text1", "text default", "", ""},
  7943. {"text2", "aωb", "", ""},
  7944. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7945. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7946. {"file3", "", "", "application/octet-stream"},
  7947. };
  7948. auto res = cli_.Post("/content_receiver", items);
  7949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7950. EXPECT_EQ(StatusCode::OK_200, res->status);
  7951. }
  7952. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7953. UploadFormDataItems items = {
  7954. {"text1", "text default", "", ""},
  7955. {"text2", "aωb", "", ""},
  7956. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7957. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7958. {"file3", "", "", "application/octet-stream"},
  7959. };
  7960. auto boundary = std::string("+++++");
  7961. std::string body;
  7962. for (const auto &item : items) {
  7963. body += "--" + boundary + "\r\n";
  7964. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7965. if (!item.filename.empty()) {
  7966. body += "; filename=\"" + item.filename + "\"";
  7967. }
  7968. body += "\r\n";
  7969. if (!item.content_type.empty()) {
  7970. body += "Content-Type: " + item.content_type + "\r\n";
  7971. }
  7972. body += "\r\n";
  7973. body += item.content + "\r\n";
  7974. }
  7975. body += "--" + boundary + "--\r\n";
  7976. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7977. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. EXPECT_EQ(StatusCode::OK_200, res->status);
  7980. }
  7981. TEST(MultipartFormDataTest, FieldEscaping) {
  7982. Server svr;
  7983. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7984. const ContentReader &content_reader) {
  7985. ASSERT_TRUE(req.is_multipart_form_data());
  7986. std::vector<FormData> received;
  7987. content_reader(
  7988. [&](const FormData &file) {
  7989. received.push_back(file);
  7990. return true;
  7991. },
  7992. [&](const char *data, size_t data_length) {
  7993. received.back().content.append(data, data_length);
  7994. return true;
  7995. });
  7996. // '"', CR and LF in names and filenames are escaped following the
  7997. // WHATWG HTML standard, so each part still parses as a single part
  7998. // with no injected headers. Content types get CR/LF escaped too,
  7999. // while '"' (legal there, e.g. quoted charset) is preserved.
  8000. ASSERT_EQ(4U, received.size());
  8001. EXPECT_EQ("na%22me", received[0].name);
  8002. EXPECT_EQ("quoted name", received[0].content);
  8003. EXPECT_EQ("file", received[1].name);
  8004. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8005. received[1].filename);
  8006. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8007. EXPECT_EQ("injected", received[1].content);
  8008. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8009. EXPECT_EQ("my%22file.txt", received[2].filename);
  8010. EXPECT_EQ("cr lf name", received[2].content);
  8011. EXPECT_EQ("typed", received[3].name);
  8012. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8013. received[3].content_type);
  8014. EXPECT_EQ("typed content", received[3].content);
  8015. });
  8016. auto port = svr.bind_to_any_port("localhost");
  8017. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8018. auto se = detail::scope_exit([&] {
  8019. svr.stop();
  8020. t.join();
  8021. ASSERT_FALSE(svr.is_running());
  8022. });
  8023. svr.wait_until_ready();
  8024. Client cli("localhost", port);
  8025. UploadFormDataItems items = {
  8026. {"na\"me", "quoted name", "", ""},
  8027. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8028. "application/octet-stream"},
  8029. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8030. {"typed", "typed content", "",
  8031. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8032. };
  8033. auto res = cli.Post("/post", items);
  8034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8035. EXPECT_EQ(StatusCode::OK_200, res->status);
  8036. }
  8037. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8038. const UploadFormDataItems items = {
  8039. {"name1", "Content 1", "", ""},
  8040. {"name2", "Content 2", "file2.txt", "text/plain"},
  8041. };
  8042. Server svr;
  8043. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8044. const ContentReader &content_reader) {
  8045. ASSERT_TRUE(req.is_multipart_form_data());
  8046. std::vector<FormData> received;
  8047. content_reader(
  8048. [&](const FormData &file) {
  8049. received.push_back(file);
  8050. return true;
  8051. },
  8052. [&](const char *data, size_t data_length) {
  8053. received.back().content.append(data, data_length);
  8054. return true;
  8055. });
  8056. ASSERT_EQ(2U, received.size());
  8057. EXPECT_EQ("name1", received[0].name);
  8058. EXPECT_EQ("Content 1", received[0].content);
  8059. EXPECT_EQ("name2", received[1].name);
  8060. EXPECT_EQ("Content 2", received[1].content);
  8061. EXPECT_EQ("file2.txt", received[1].filename);
  8062. EXPECT_EQ("text/plain", received[1].content_type);
  8063. });
  8064. auto port = svr.bind_to_any_port("localhost");
  8065. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8066. auto se = detail::scope_exit([&] {
  8067. svr.stop();
  8068. t.join();
  8069. ASSERT_FALSE(svr.is_running());
  8070. });
  8071. svr.wait_until_ready();
  8072. Client cli("localhost", port);
  8073. // Whole-body serialization with a generated boundary
  8074. {
  8075. MultipartFormDataWriter writer;
  8076. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8077. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8078. writer.content_type());
  8079. auto body = writer.serialize(items);
  8080. EXPECT_EQ(body.size(), writer.content_length(items));
  8081. auto res = cli.Post("/post", body, writer.content_type());
  8082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8083. EXPECT_EQ(StatusCode::OK_200, res->status);
  8084. }
  8085. // Per-part framing with a custom boundary via a content provider
  8086. {
  8087. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8088. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8089. MultipartFormDataWriter writer("custom-boundary_123");
  8090. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8091. std::string body;
  8092. for (const auto &item : items) {
  8093. body += writer.item_begin(item);
  8094. body += item.content;
  8095. body += MultipartFormDataWriter::item_end();
  8096. }
  8097. body += writer.finish();
  8098. EXPECT_EQ(body.size(), writer.content_length(items));
  8099. auto res = cli.Post(
  8100. "/post", body.size(),
  8101. [&](size_t offset, size_t length, DataSink &sink) {
  8102. sink.write(body.data() + offset, length);
  8103. return true;
  8104. },
  8105. writer.content_type());
  8106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8107. EXPECT_EQ(StatusCode::OK_200, res->status);
  8108. }
  8109. }
  8110. TEST_F(ServerTest, PostContentReceiverGzip) {
  8111. cli_.set_compress(true);
  8112. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8114. ASSERT_EQ(StatusCode::OK_200, res->status);
  8115. ASSERT_EQ("content", res->body);
  8116. }
  8117. TEST_F(ServerTest, PutContentReceiver) {
  8118. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8120. ASSERT_EQ(StatusCode::OK_200, res->status);
  8121. ASSERT_EQ("content", res->body);
  8122. }
  8123. TEST_F(ServerTest, PatchContentReceiver) {
  8124. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8126. ASSERT_EQ(StatusCode::OK_200, res->status);
  8127. ASSERT_EQ("content", res->body);
  8128. }
  8129. template <typename ClientType>
  8130. void TestWithHeadersAndContentReceiver(
  8131. ClientType &cli,
  8132. std::function<Result(ClientType &, const std::string &, const Headers &,
  8133. const std::string &, const std::string &,
  8134. ContentReceiver, DownloadProgress)>
  8135. request_func) {
  8136. Headers headers;
  8137. headers.emplace("X-Custom-Header", "test-value");
  8138. std::string received_body;
  8139. auto res = request_func(
  8140. cli, "/content_receiver", headers, "content", "application/json",
  8141. [&](const char *data, size_t data_length) {
  8142. received_body.append(data, data_length);
  8143. return true;
  8144. },
  8145. nullptr);
  8146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8147. EXPECT_EQ(StatusCode::OK_200, res->status);
  8148. EXPECT_EQ("content", received_body);
  8149. }
  8150. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8151. #ifdef CPPHTTPLIB_SSL_ENABLED
  8152. using ClientT = SSLClient;
  8153. #else
  8154. using ClientT = Client;
  8155. #endif
  8156. TestWithHeadersAndContentReceiver<ClientT>(
  8157. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8158. const std::string &body, const std::string &content_type,
  8159. ContentReceiver receiver, DownloadProgress progress) {
  8160. return cli.Post(path, headers, body, content_type, receiver, progress);
  8161. });
  8162. }
  8163. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8164. #ifdef CPPHTTPLIB_SSL_ENABLED
  8165. using ClientT = SSLClient;
  8166. #else
  8167. using ClientT = Client;
  8168. #endif
  8169. TestWithHeadersAndContentReceiver<ClientT>(
  8170. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8171. const std::string &body, const std::string &content_type,
  8172. ContentReceiver receiver, DownloadProgress progress) {
  8173. return cli.Put(path, headers, body, content_type, receiver, progress);
  8174. });
  8175. }
  8176. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8177. #ifdef CPPHTTPLIB_SSL_ENABLED
  8178. using ClientT = SSLClient;
  8179. #else
  8180. using ClientT = Client;
  8181. #endif
  8182. TestWithHeadersAndContentReceiver<ClientT>(
  8183. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8184. const std::string &body, const std::string &content_type,
  8185. ContentReceiver receiver, DownloadProgress progress) {
  8186. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8187. });
  8188. }
  8189. template <typename ClientType>
  8190. void TestWithHeadersAndContentReceiverWithProgress(
  8191. ClientType &cli,
  8192. std::function<Result(ClientType &, const std::string &, const Headers &,
  8193. const std::string &, const std::string &,
  8194. ContentReceiver, DownloadProgress)>
  8195. request_func) {
  8196. Headers headers;
  8197. headers.emplace("X-Test-Header", "progress-test");
  8198. std::string received_body;
  8199. auto progress_called = false;
  8200. auto res = request_func(
  8201. cli, "/content_receiver", headers, "content", "text/plain",
  8202. [&](const char *data, size_t data_length) {
  8203. received_body.append(data, data_length);
  8204. return true;
  8205. },
  8206. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8207. progress_called = true;
  8208. return true;
  8209. });
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::OK_200, res->status);
  8212. EXPECT_EQ("content", received_body);
  8213. EXPECT_TRUE(progress_called);
  8214. }
  8215. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8216. #ifdef CPPHTTPLIB_SSL_ENABLED
  8217. using ClientT = SSLClient;
  8218. #else
  8219. using ClientT = Client;
  8220. #endif
  8221. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8222. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8223. const std::string &body, const std::string &content_type,
  8224. ContentReceiver receiver, DownloadProgress progress) {
  8225. return cli.Post(path, headers, body, content_type, receiver, progress);
  8226. });
  8227. }
  8228. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8229. #ifdef CPPHTTPLIB_SSL_ENABLED
  8230. using ClientT = SSLClient;
  8231. #else
  8232. using ClientT = Client;
  8233. #endif
  8234. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8235. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8236. const std::string &body, const std::string &content_type,
  8237. ContentReceiver receiver, DownloadProgress progress) {
  8238. return cli.Put(path, headers, body, content_type, receiver, progress);
  8239. });
  8240. }
  8241. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8242. #ifdef CPPHTTPLIB_SSL_ENABLED
  8243. using ClientT = SSLClient;
  8244. #else
  8245. using ClientT = Client;
  8246. #endif
  8247. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8248. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8249. const std::string &body, const std::string &content_type,
  8250. ContentReceiver receiver, DownloadProgress progress) {
  8251. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8252. });
  8253. }
  8254. template <typename ClientType>
  8255. void TestWithHeadersAndContentReceiverError(
  8256. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8257. const Headers &, const std::string &,
  8258. const std::string &, ContentReceiver)>
  8259. request_func) {
  8260. Headers headers;
  8261. headers.emplace("X-Error-Test", "true");
  8262. std::string received_body;
  8263. auto receiver_failed = false;
  8264. auto res =
  8265. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8266. [&](const char *data, size_t data_length) {
  8267. received_body.append(data, data_length);
  8268. receiver_failed = true;
  8269. return false;
  8270. });
  8271. ASSERT_FALSE(res);
  8272. EXPECT_TRUE(receiver_failed);
  8273. }
  8274. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8275. #ifdef CPPHTTPLIB_SSL_ENABLED
  8276. using ClientT = SSLClient;
  8277. #else
  8278. using ClientT = Client;
  8279. #endif
  8280. TestWithHeadersAndContentReceiverError<ClientT>(
  8281. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8282. const std::string &body, const std::string &content_type,
  8283. ContentReceiver receiver) {
  8284. return cli.Post(path, headers, body, content_type, receiver);
  8285. });
  8286. }
  8287. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8288. #ifdef CPPHTTPLIB_SSL_ENABLED
  8289. using ClientT = SSLClient;
  8290. #else
  8291. using ClientT = Client;
  8292. #endif
  8293. TestWithHeadersAndContentReceiverError<ClientT>(
  8294. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8295. const std::string &body, const std::string &content_type,
  8296. ContentReceiver receiver) {
  8297. return cli.Put(path, headers, body, content_type, receiver);
  8298. });
  8299. }
  8300. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8301. #ifdef CPPHTTPLIB_SSL_ENABLED
  8302. using ClientT = SSLClient;
  8303. #else
  8304. using ClientT = Client;
  8305. #endif
  8306. TestWithHeadersAndContentReceiverError<ClientT>(
  8307. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8308. const std::string &body, const std::string &content_type,
  8309. ContentReceiver receiver) {
  8310. return cli.Patch(path, headers, body, content_type, receiver);
  8311. });
  8312. }
  8313. TEST_F(ServerTest, PostQueryStringAndBody) {
  8314. auto res =
  8315. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. ASSERT_EQ(StatusCode::OK_200, res->status);
  8318. }
  8319. TEST_F(ServerTest, HTTP2Magic) {
  8320. Request req;
  8321. req.method = "PRI";
  8322. req.path = "*";
  8323. req.body = "SM";
  8324. auto res = std::make_shared<Response>();
  8325. auto error = Error::Success;
  8326. auto ret = cli_.send(req, *res, error);
  8327. ASSERT_TRUE(ret);
  8328. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8329. }
  8330. TEST_F(ServerTest, KeepAlive) {
  8331. auto res = cli_.Get("/hi");
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8335. EXPECT_EQ("Hello World!", res->body);
  8336. res = cli_.Get("/hi");
  8337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8338. EXPECT_EQ(StatusCode::OK_200, res->status);
  8339. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8340. EXPECT_EQ("Hello World!", res->body);
  8341. res = cli_.Get("/hi");
  8342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8343. EXPECT_EQ(StatusCode::OK_200, res->status);
  8344. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8345. EXPECT_EQ("Hello World!", res->body);
  8346. res = cli_.Get("/not-exist");
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8349. res = cli_.Post("/empty", "", "text/plain");
  8350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8351. EXPECT_EQ(StatusCode::OK_200, res->status);
  8352. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8353. EXPECT_EQ("empty", res->body);
  8354. EXPECT_EQ("close", res->get_header_value("Connection"));
  8355. res = cli_.Post(
  8356. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8357. "text/plain");
  8358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8359. EXPECT_EQ(StatusCode::OK_200, res->status);
  8360. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8361. EXPECT_EQ("empty", res->body);
  8362. cli_.set_keep_alive(false);
  8363. res = cli_.Get("/last-request");
  8364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8365. EXPECT_EQ(StatusCode::OK_200, res->status);
  8366. EXPECT_EQ("close", res->get_header_value("Connection"));
  8367. }
  8368. TEST_F(ServerTest, TooManyRedirect) {
  8369. cli_.set_follow_location(true);
  8370. auto res = cli_.Get("/redirect/0");
  8371. ASSERT_TRUE(!res);
  8372. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8373. }
  8374. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8375. Request req;
  8376. req.method = "FOOBAR";
  8377. req.path = "/hi";
  8378. cli_.set_keep_alive(true);
  8379. auto res = cli_.send(req);
  8380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8381. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8382. EXPECT_EQ("close", res->get_header_value("Connection"));
  8383. EXPECT_FALSE(cli_.is_socket_open());
  8384. }
  8385. TEST_F(ServerTest, CustomRouteReadsBody) {
  8386. const std::string xml =
  8387. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8388. Request req;
  8389. req.method = "PROPFIND";
  8390. req.path = "/dav/dir";
  8391. req.set_header("Depth", "1");
  8392. req.body = xml;
  8393. auto res = cli_.send(req);
  8394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8395. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8396. EXPECT_EQ(xml, res->body);
  8397. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8398. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8399. }
  8400. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8401. Request req;
  8402. req.method = "PROPFIND";
  8403. req.path = "/dav/42";
  8404. auto res = cli_.send(req);
  8405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8406. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8407. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8408. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8409. }
  8410. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8411. Request req;
  8412. req.method = "PROPFIND";
  8413. req.path = "/dav-re/123";
  8414. auto res = cli_.send(req);
  8415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8416. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8417. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8418. }
  8419. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8420. Request req;
  8421. req.method = "MKCOL";
  8422. req.path = "/dav-mkcol";
  8423. auto res = cli_.send(req);
  8424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8425. EXPECT_EQ(StatusCode::Created_201, res->status);
  8426. }
  8427. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8428. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8429. Request req;
  8430. req.method = "REPORT";
  8431. req.path = "/dav-report";
  8432. req.body = xml;
  8433. auto res = cli_.send(req);
  8434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8435. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8436. EXPECT_EQ(xml, res->body);
  8437. }
  8438. // A content reader route must fire even when the request carries no body,
  8439. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8440. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8441. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8442. Request req;
  8443. req.method = "REPORT";
  8444. req.path = "/dav-report";
  8445. auto res = cli_.send(req);
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8448. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8449. }
  8450. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8451. Request req;
  8452. req.method = "PROPFIND";
  8453. req.path = "/not-dav";
  8454. auto res = cli_.send(req);
  8455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8456. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8457. }
  8458. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8459. Request req;
  8460. req.method = "UNLOCK";
  8461. req.path = "/dav/dir";
  8462. cli_.set_keep_alive(true);
  8463. auto res = cli_.send(req);
  8464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8465. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8466. EXPECT_EQ("close", res->get_header_value("Connection"));
  8467. EXPECT_FALSE(cli_.is_socket_open());
  8468. }
  8469. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8470. // The mount point serves this path, but only for GET and HEAD.
  8471. auto get_res = cli_.Get("/dir/index.html");
  8472. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8473. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8474. Request req;
  8475. req.method = "PROPFIND";
  8476. req.path = "/dir/index.html";
  8477. auto res = cli_.send(req);
  8478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8480. }
  8481. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8482. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8483. cli_.set_keep_alive(true);
  8484. for (auto i = 0; i < 2; i++) {
  8485. Request req;
  8486. req.method = "PROPFIND";
  8487. req.path = "/dav/dir";
  8488. req.body = xml;
  8489. auto res = cli_.send(req);
  8490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8491. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8492. EXPECT_EQ(xml, res->body);
  8493. EXPECT_TRUE(cli_.is_socket_open());
  8494. }
  8495. // A built-in method must still be served on the same connection.
  8496. cli_.set_keep_alive(false);
  8497. auto res = cli_.Get("/hi");
  8498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8499. EXPECT_EQ(StatusCode::OK_200, res->status);
  8500. EXPECT_EQ("close", res->get_header_value("Connection"));
  8501. }
  8502. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8503. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8504. Request req;
  8505. req.method = "PROPFIND";
  8506. req.path = "/dav/dir";
  8507. req.set_header("Expect", "100-continue");
  8508. req.body = xml;
  8509. auto res = cli_.send(req);
  8510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8511. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8512. EXPECT_EQ(xml, res->body);
  8513. }
  8514. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8515. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8516. TEST_F(ServerTest, Gzip) {
  8517. Headers headers;
  8518. headers.emplace("Accept-Encoding", "gzip, deflate");
  8519. auto res = cli_.Get("/compress", headers);
  8520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8521. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8522. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8523. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8524. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8525. "7890123456789012345678901234567890",
  8526. res->body);
  8527. EXPECT_EQ(StatusCode::OK_200, res->status);
  8528. }
  8529. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8530. Headers headers;
  8531. headers.emplace("Accept-Encoding", "gzip, deflate");
  8532. auto res = cli_.Get("/compress-with-charset", headers);
  8533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8534. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8535. EXPECT_EQ("application/json; charset=utf-8",
  8536. res->get_header_value("Content-Type"));
  8537. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8538. "7890123456789012345678901234567890",
  8539. res->body);
  8540. EXPECT_EQ(StatusCode::OK_200, res->status);
  8541. }
  8542. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8543. Headers headers;
  8544. headers.emplace("Accept-Encoding", "");
  8545. auto res = cli_.Get("/compress", headers);
  8546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8547. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8548. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8549. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8550. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8551. "7890123456789012345678901234567890",
  8552. res->body);
  8553. EXPECT_EQ(StatusCode::OK_200, res->status);
  8554. }
  8555. TEST_F(ServerTest, GzipWithContentReceiver) {
  8556. Headers headers;
  8557. headers.emplace("Accept-Encoding", "gzip, deflate");
  8558. std::string body;
  8559. auto res =
  8560. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8561. EXPECT_EQ(100U, data_length);
  8562. body.append(data, data_length);
  8563. return true;
  8564. });
  8565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8566. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8568. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8569. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8570. "7890123456789012345678901234567890",
  8571. body);
  8572. EXPECT_EQ(StatusCode::OK_200, res->status);
  8573. }
  8574. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8575. Headers headers;
  8576. headers.emplace("Accept-Encoding", "gzip, deflate");
  8577. cli_.set_decompress(false);
  8578. auto res = cli_.Get("/compress", headers);
  8579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8580. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8582. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8583. EXPECT_EQ(33U, res->body.size());
  8584. EXPECT_EQ(StatusCode::OK_200, res->status);
  8585. }
  8586. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8587. Headers headers;
  8588. headers.emplace("Accept-Encoding", "");
  8589. std::string body;
  8590. auto res =
  8591. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8592. EXPECT_EQ(100U, data_length);
  8593. body.append(data, data_length);
  8594. return true;
  8595. });
  8596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8597. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8598. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8599. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8600. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8601. "7890123456789012345678901234567890",
  8602. body);
  8603. EXPECT_EQ(StatusCode::OK_200, res->status);
  8604. }
  8605. TEST_F(ServerTest, NoGzip) {
  8606. Headers headers;
  8607. headers.emplace("Accept-Encoding", "gzip, deflate");
  8608. auto res = cli_.Get("/nocompress", headers);
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8611. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8612. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8613. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8614. "7890123456789012345678901234567890",
  8615. res->body);
  8616. EXPECT_EQ(StatusCode::OK_200, res->status);
  8617. }
  8618. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8619. Headers headers;
  8620. headers.emplace("Accept-Encoding", "gzip, deflate");
  8621. std::string body;
  8622. auto res = cli_.Get("/nocompress", headers,
  8623. [&](const char *data, size_t data_length) {
  8624. EXPECT_EQ(100U, data_length);
  8625. body.append(data, data_length);
  8626. return true;
  8627. });
  8628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8629. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8630. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8631. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8632. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8633. "7890123456789012345678901234567890",
  8634. body);
  8635. EXPECT_EQ(StatusCode::OK_200, res->status);
  8636. }
  8637. TEST_F(ServerTest, MultipartFormDataGzip) {
  8638. UploadFormDataItems items = {
  8639. {"key1", "test", "", ""},
  8640. {"key2", "--abcdefg123", "", ""},
  8641. };
  8642. cli_.set_compress(true);
  8643. auto res = cli_.Post("/compress-multipart", items);
  8644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8645. EXPECT_EQ(StatusCode::OK_200, res->status);
  8646. }
  8647. #endif
  8648. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8649. // Static file compression is opt-in, so these run their own server rather than
  8650. // flipping it on for the shared ServerTest fixture, which would silently
  8651. // rewrite what every other static file test is asserting.
  8652. class StaticFileCompressionTest : public ::testing::Test {
  8653. protected:
  8654. void TearDown() override {
  8655. if (t_.joinable()) {
  8656. svr_.stop();
  8657. t_.join();
  8658. }
  8659. }
  8660. int start(const std::function<void(Server &)> &configure = nullptr) {
  8661. // Serves the same tree as a directory of build-time compressed assets
  8662. // would be served: the mount point names the coding the files are already
  8663. // stored in. Registered before "/" so it is the one that matches.
  8664. svr_.set_mount_point("/pre-encoded", "./www",
  8665. {{"Content-Encoding", "gzip"}});
  8666. svr_.set_mount_point("/", "./www");
  8667. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8668. res.set_file_content("./www/dir/index.html", "text/html");
  8669. });
  8670. svr_.Get("/pre-encoded-file-content",
  8671. [](const Request & /*req*/, Response &res) {
  8672. res.set_header("Content-Encoding", "gzip");
  8673. res.set_file_content("./www/dir/index.html", "text/html");
  8674. });
  8675. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8676. res.set_content_provider(
  8677. 6, "text/plain",
  8678. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8679. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8680. return true;
  8681. });
  8682. });
  8683. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8684. res.set_content_provider(
  8685. 1000, "text/plain",
  8686. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8687. if (offset < 100) {
  8688. std::string data(100, 'A');
  8689. sink.write(data.data(), data.size());
  8690. return true;
  8691. }
  8692. std::this_thread::sleep_for(std::chrono::seconds(2));
  8693. std::string data(900, 'B');
  8694. sink.write(data.data(), data.size());
  8695. return true;
  8696. });
  8697. });
  8698. if (configure) { configure(svr_); }
  8699. auto port = svr_.bind_to_any_port(HOST);
  8700. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8701. svr_.wait_until_ready();
  8702. return port;
  8703. }
  8704. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8705. // Every file under ./www except 1MB.txt is smaller than the default
  8706. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8707. // it out of the way.
  8708. static void enable_without_floor(Server &svr) {
  8709. svr.set_static_file_compression(true);
  8710. svr.set_static_file_compression_min_length(0);
  8711. }
  8712. Server svr_;
  8713. std::thread t_;
  8714. };
  8715. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8716. auto port = start();
  8717. Client cli(HOST, port);
  8718. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8720. EXPECT_EQ(StatusCode::OK_200, res->status);
  8721. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8722. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8723. EXPECT_EQ(1048576U, res->body.size());
  8724. }
  8725. TEST_F(StaticFileCompressionTest, MountPoint) {
  8726. auto port = start(enable);
  8727. Client cli(HOST, port);
  8728. cli.set_decompress(false);
  8729. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8731. EXPECT_EQ(StatusCode::OK_200, res->status);
  8732. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8733. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8734. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8735. // The response stays self-delimiting: a length, not a chunked body.
  8736. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8737. EXPECT_EQ(std::to_string(res->body.size()),
  8738. res->get_header_value("Content-Length"));
  8739. EXPECT_LT(res->body.size(), 1048576U);
  8740. EXPECT_FALSE(res->body.empty());
  8741. }
  8742. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8743. auto port = start(enable);
  8744. Client cli(HOST, port);
  8745. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8747. EXPECT_EQ(StatusCode::OK_200, res->status);
  8748. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8749. EXPECT_EQ(1048576U, res->body.size());
  8750. }
  8751. TEST_F(StaticFileCompressionTest, FileContent) {
  8752. auto port = start(enable_without_floor);
  8753. Client cli(HOST, port);
  8754. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8756. EXPECT_EQ(StatusCode::OK_200, res->status);
  8757. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8758. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8759. EXPECT_EQ(104U, res->body.size());
  8760. }
  8761. // A handler that serves an already-encoded file names the coding itself. The
  8762. // file-backed path decided its coding from Accept-Encoding and the content
  8763. // type alone, so it compressed the stored bytes a second time and appended a
  8764. // second Content-Encoding field line.
  8765. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8766. auto port = start(enable_without_floor);
  8767. Client cli(HOST, port);
  8768. cli.set_decompress(false);
  8769. auto res = cli.Get("/pre-encoded-file-content",
  8770. Headers{{"Accept-Encoding", "gzip"}});
  8771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8772. EXPECT_EQ(StatusCode::OK_200, res->status);
  8773. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8774. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8775. // Vary belongs to a coding the server chose, and it chose none here.
  8776. EXPECT_FALSE(res->has_header("Vary"));
  8777. // The file travels exactly as it is stored on disk.
  8778. EXPECT_EQ(104U, res->body.size());
  8779. }
  8780. // The 1MB file clears the default floor, so this one runs the configuration a
  8781. // deployment would actually have.
  8782. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8783. auto port = start(enable);
  8784. Client cli(HOST, port);
  8785. cli.set_decompress(false);
  8786. auto res =
  8787. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8789. EXPECT_EQ(StatusCode::OK_200, res->status);
  8790. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8791. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8792. EXPECT_FALSE(res->has_header("Vary"));
  8793. EXPECT_EQ(1048576U, res->body.size());
  8794. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8795. }
  8796. TEST_F(StaticFileCompressionTest, Head) {
  8797. auto port = start(enable);
  8798. Client cli(HOST, port);
  8799. cli.set_decompress(false);
  8800. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8801. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8802. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8804. EXPECT_EQ(StatusCode::OK_200, res->status);
  8805. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8806. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8807. // HEAD still reports the size a GET would return.
  8808. EXPECT_EQ(get->get_header_value("Content-Length"),
  8809. res->get_header_value("Content-Length"));
  8810. EXPECT_TRUE(res->body.empty());
  8811. }
  8812. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8813. auto port = start(enable);
  8814. Client cli(HOST, port);
  8815. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8816. {"Accept-Encoding", "gzip"}});
  8817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8818. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8819. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8820. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8821. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8822. EXPECT_EQ("cd", res->body);
  8823. }
  8824. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8825. auto port = start(enable);
  8826. Client cli(HOST, port);
  8827. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8829. EXPECT_EQ(StatusCode::OK_200, res->status);
  8830. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8831. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8832. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8833. }
  8834. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8835. auto port = start(enable);
  8836. Client cli(HOST, port);
  8837. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8839. EXPECT_EQ(StatusCode::OK_200, res->status);
  8840. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8841. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8842. EXPECT_TRUE(res->body.empty());
  8843. }
  8844. TEST_F(StaticFileCompressionTest, MinLength) {
  8845. auto port = start(enable);
  8846. Client cli(HOST, port);
  8847. // 104 bytes, well under the default floor. Compressing it would add the
  8848. // gzip header and trailer to a body that already fits in one packet.
  8849. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8851. EXPECT_EQ(StatusCode::OK_200, res->status);
  8852. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8853. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8854. }
  8855. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8856. auto port = start([](Server &svr) {
  8857. svr.set_static_file_compression(true);
  8858. svr.set_static_file_compression_min_length(1);
  8859. });
  8860. Client cli(HOST, port);
  8861. cli.set_decompress(false);
  8862. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8864. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8865. // A 9-byte file comes back larger than it went in, because gzip's header and
  8866. // trailer outweigh anything deflate can save. That is the end of the range
  8867. // the floor exists to keep out.
  8868. EXPECT_GT(res->body.size(), 9U);
  8869. }
  8870. TEST_F(StaticFileCompressionTest, MaxLength) {
  8871. auto port = start([](Server &svr) {
  8872. svr.set_static_file_compression(true);
  8873. svr.set_static_file_compression_min_length(0);
  8874. svr.set_static_file_compression_max_length(1024);
  8875. });
  8876. Client cli(HOST, port);
  8877. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8878. // defines `small` as a macro on Windows.
  8879. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8880. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8881. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8882. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8883. // Under it: compressed.
  8884. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8885. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8886. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8887. }
  8888. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8889. auto port = start(enable_without_floor);
  8890. Client cli(HOST, port);
  8891. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8892. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8893. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8894. auto identity_etag = identity->get_header_value("ETag");
  8895. ASSERT_FALSE(identity_etag.empty());
  8896. auto gzipped =
  8897. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8898. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8899. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8900. auto gzip_etag = gzipped->get_header_value("ETag");
  8901. ASSERT_FALSE(gzip_etag.empty());
  8902. // Two representations, two validators.
  8903. EXPECT_NE(identity_etag, gzip_etag);
  8904. // Each one revalidates against the request that would produce it...
  8905. auto fresh =
  8906. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8907. {"If-None-Match", gzip_etag}});
  8908. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8909. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8910. auto fresh_identity =
  8911. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8912. {"If-None-Match", identity_etag}});
  8913. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8914. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8915. // ...and not against the other representation.
  8916. auto crossed =
  8917. cli.Get("/dir/index.html",
  8918. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8919. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8920. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8921. }
  8922. // The opt-in covers responses the server reads off disk itself. A caller's own
  8923. // known-length provider keeps its Content-Length and, more importantly, keeps
  8924. // delivering incrementally: routing it through a compressor would hold every
  8925. // write back until zlib's window filled.
  8926. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8927. auto port = start(enable);
  8928. Client cli(HOST, port);
  8929. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8931. EXPECT_EQ(StatusCode::OK_200, res->status);
  8932. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8933. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8934. EXPECT_EQ("aaabbb", res->body);
  8935. }
  8936. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8937. auto port = start(enable);
  8938. Client cli(HOST, port);
  8939. cli.set_read_timeout(1, 0);
  8940. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8941. Headers{{"Accept-Encoding", "gzip"}});
  8942. ASSERT_TRUE(handle.is_valid());
  8943. // The provider writes 100 bytes and then stalls for longer than the read
  8944. // timeout. Those first bytes have to arrive anyway: run the response through
  8945. // a compressor and zlib holds them until its window fills, so the read would
  8946. // come back empty instead.
  8947. char buf[256];
  8948. auto n = handle.read(buf, sizeof(buf));
  8949. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8950. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8951. }
  8952. #endif
  8953. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8954. TEST_F(ServerTest, Brotli) {
  8955. Headers headers;
  8956. headers.emplace("Accept-Encoding", "br");
  8957. auto res = cli_.Get("/compress", headers);
  8958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8959. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8960. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8961. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8962. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8963. "7890123456789012345678901234567890",
  8964. res->body);
  8965. EXPECT_EQ(StatusCode::OK_200, res->status);
  8966. }
  8967. #endif
  8968. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8969. TEST_F(ServerTest, Zstd) {
  8970. Headers headers;
  8971. headers.emplace("Accept-Encoding", "zstd");
  8972. auto res = cli_.Get("/compress", headers);
  8973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8974. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8975. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8976. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8977. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8978. "7890123456789012345678901234567890",
  8979. res->body);
  8980. EXPECT_EQ(StatusCode::OK_200, res->status);
  8981. }
  8982. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8983. Headers headers;
  8984. headers.emplace("Accept-Encoding", "");
  8985. auto res = cli_.Get("/compress", headers);
  8986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8987. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8988. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8989. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8990. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8991. "7890123456789012345678901234567890",
  8992. res->body);
  8993. EXPECT_EQ(StatusCode::OK_200, res->status);
  8994. }
  8995. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8996. Headers headers;
  8997. headers.emplace("Accept-Encoding", "zstd");
  8998. std::string body;
  8999. auto res =
  9000. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9001. EXPECT_EQ(100U, data_length);
  9002. body.append(data, data_length);
  9003. return true;
  9004. });
  9005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9006. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9007. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9008. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9009. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9010. "7890123456789012345678901234567890",
  9011. body);
  9012. EXPECT_EQ(StatusCode::OK_200, res->status);
  9013. }
  9014. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9015. Headers headers;
  9016. headers.emplace("Accept-Encoding", "zstd");
  9017. cli_.set_decompress(false);
  9018. auto res = cli_.Get("/compress", headers);
  9019. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9020. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9021. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9022. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9024. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9025. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9026. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9027. EXPECT_EQ(StatusCode::OK_200, res->status);
  9028. ASSERT_EQ(26U, res->body.size());
  9029. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9030. 0);
  9031. }
  9032. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9033. Headers headers;
  9034. headers.emplace("Accept-Encoding", "");
  9035. std::string body;
  9036. auto res =
  9037. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9038. EXPECT_EQ(100U, data_length);
  9039. body.append(data, data_length);
  9040. return true;
  9041. });
  9042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9043. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9044. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9045. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9046. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9047. "7890123456789012345678901234567890",
  9048. body);
  9049. EXPECT_EQ(StatusCode::OK_200, res->status);
  9050. }
  9051. TEST_F(ServerTest, NoZstd) {
  9052. Headers headers;
  9053. headers.emplace("Accept-Encoding", "zstd");
  9054. auto res = cli_.Get("/nocompress", headers);
  9055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9056. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9057. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9058. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9059. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9060. "7890123456789012345678901234567890",
  9061. res->body);
  9062. EXPECT_EQ(StatusCode::OK_200, res->status);
  9063. }
  9064. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9065. Headers headers;
  9066. headers.emplace("Accept-Encoding", "zstd");
  9067. std::string body;
  9068. auto res = cli_.Get("/nocompress", headers,
  9069. [&](const char *data, size_t data_length) {
  9070. EXPECT_EQ(100U, data_length);
  9071. body.append(data, data_length);
  9072. return true;
  9073. });
  9074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9075. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9076. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9077. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9078. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9079. "7890123456789012345678901234567890",
  9080. body);
  9081. EXPECT_EQ(StatusCode::OK_200, res->status);
  9082. }
  9083. // TODO: How to enable zstd ??
  9084. TEST_F(ServerTest, MultipartFormDataZstd) {
  9085. UploadFormDataItems items = {
  9086. {"key1", "test", "", ""},
  9087. {"key2", "--abcdefg123", "", ""},
  9088. };
  9089. Headers headers;
  9090. headers.emplace("Accept-Encoding", "zstd");
  9091. cli_.set_compress(true);
  9092. auto res = cli_.Post("/compress-multipart", headers, items);
  9093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9094. EXPECT_EQ(StatusCode::OK_200, res->status);
  9095. }
  9096. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9097. Headers headers;
  9098. headers.emplace("Accept-Encoding", "zstd");
  9099. cli_.set_compress(true);
  9100. auto res = cli_.Put(
  9101. "/put", headers, 3,
  9102. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9103. sink.os << "PUT";
  9104. return true;
  9105. },
  9106. "text/plain");
  9107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9108. EXPECT_EQ(StatusCode::OK_200, res->status);
  9109. EXPECT_EQ("PUT", res->body);
  9110. }
  9111. // Pre-compression logging tests
  9112. TEST_F(ServerTest, PreCompressionLogging) {
  9113. // Test data for compression (matches the actual /compress endpoint content)
  9114. const std::string test_content =
  9115. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9116. "3456789012345678901234567890";
  9117. // Variables to capture logging data
  9118. std::string pre_compression_body;
  9119. std::string pre_compression_content_type;
  9120. std::string pre_compression_content_encoding;
  9121. std::string post_compression_body;
  9122. std::string post_compression_content_type;
  9123. std::string post_compression_content_encoding;
  9124. // Set up pre-compression logger
  9125. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9126. const Response &res) {
  9127. pre_compression_body = res.body;
  9128. pre_compression_content_type = res.get_header_value("Content-Type");
  9129. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9130. });
  9131. // Set up post-compression logger
  9132. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9133. post_compression_body = res.body;
  9134. post_compression_content_type = res.get_header_value("Content-Type");
  9135. post_compression_content_encoding =
  9136. res.get_header_value("Content-Encoding");
  9137. });
  9138. // Test with gzip compression
  9139. Headers headers;
  9140. headers.emplace("Accept-Encoding", "gzip");
  9141. auto res = cli_.Get("/compress", headers);
  9142. // Verify response was compressed
  9143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9144. EXPECT_EQ(StatusCode::OK_200, res->status);
  9145. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9146. // Verify pre-compression logger captured uncompressed content
  9147. EXPECT_EQ(test_content, pre_compression_body);
  9148. EXPECT_EQ("text/plain", pre_compression_content_type);
  9149. EXPECT_TRUE(pre_compression_content_encoding
  9150. .empty()); // No encoding header before compression
  9151. // Verify post-compression logger captured compressed content
  9152. EXPECT_NE(test_content,
  9153. post_compression_body); // Should be different after compression
  9154. EXPECT_EQ("text/plain", post_compression_content_type);
  9155. EXPECT_EQ("gzip", post_compression_content_encoding);
  9156. // Verify compressed content is smaller
  9157. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9158. }
  9159. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9160. const std::string test_content =
  9161. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9162. "3456789012345678901234567890";
  9163. std::string pre_compression_body;
  9164. std::string post_compression_body;
  9165. svr_.set_pre_compression_logger(
  9166. [&](const Request & /*req*/, const Response &res) {
  9167. pre_compression_body = res.body;
  9168. });
  9169. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9170. post_compression_body = res.body;
  9171. });
  9172. Headers headers;
  9173. headers.emplace("Accept-Encoding", "br");
  9174. auto res = cli_.Get("/compress", headers);
  9175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9176. EXPECT_EQ(StatusCode::OK_200, res->status);
  9177. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9178. // Verify pre-compression content is uncompressed
  9179. EXPECT_EQ(test_content, pre_compression_body);
  9180. // Verify post-compression content is compressed
  9181. EXPECT_NE(test_content, post_compression_body);
  9182. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9183. }
  9184. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9185. const std::string test_content =
  9186. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9187. "3456789012345678901234567890";
  9188. std::string pre_compression_body;
  9189. std::string post_compression_body;
  9190. svr_.set_pre_compression_logger(
  9191. [&](const Request & /*req*/, const Response &res) {
  9192. pre_compression_body = res.body;
  9193. });
  9194. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9195. post_compression_body = res.body;
  9196. });
  9197. // Request without compression (use /nocompress endpoint)
  9198. Headers headers;
  9199. auto res = cli_.Get("/nocompress", headers);
  9200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9201. EXPECT_EQ(StatusCode::OK_200, res->status);
  9202. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9203. // Pre-compression logger should not be called when no compression is applied
  9204. EXPECT_TRUE(
  9205. pre_compression_body.empty()); // Pre-compression logger not called
  9206. EXPECT_EQ(
  9207. test_content,
  9208. post_compression_body); // Post-compression logger captures final content
  9209. }
  9210. TEST_F(ServerTest, LoggerSeesContentLength) {
  9211. size_t logged_content_length = 0;
  9212. std::string logged_content_length_header;
  9213. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9214. logged_content_length = res.content_length_;
  9215. logged_content_length_header = res.get_header_value("Content-Length");
  9216. });
  9217. auto res = cli_.Get("/nocompress");
  9218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9219. EXPECT_EQ(StatusCode::OK_200, res->status);
  9220. EXPECT_EQ(res->body.size(), logged_content_length);
  9221. EXPECT_EQ(std::to_string(logged_content_length),
  9222. logged_content_length_header);
  9223. }
  9224. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9225. const std::string test_content =
  9226. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9227. "3456789012345678901234567890";
  9228. std::string pre_compression_body;
  9229. bool pre_logger_called = false;
  9230. // Set only pre-compression logger
  9231. svr_.set_pre_compression_logger(
  9232. [&](const Request & /*req*/, const Response &res) {
  9233. pre_compression_body = res.body;
  9234. pre_logger_called = true;
  9235. });
  9236. Headers headers;
  9237. headers.emplace("Accept-Encoding", "gzip");
  9238. auto res = cli_.Get("/compress", headers);
  9239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9240. EXPECT_EQ(StatusCode::OK_200, res->status);
  9241. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9242. // Verify pre-compression logger was called
  9243. EXPECT_TRUE(pre_logger_called);
  9244. EXPECT_EQ(test_content, pre_compression_body);
  9245. }
  9246. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9247. {
  9248. // Test with Expect: 100-continue header - success case
  9249. // Server returns 100 Continue, client sends body, server returns 200 OK
  9250. Request req;
  9251. req.method = "POST";
  9252. req.path = "/post-large";
  9253. req.set_header("Expect", "100-continue");
  9254. req.body = LARGE_DATA;
  9255. Response res;
  9256. auto error = Error::Success;
  9257. cli_.set_keep_alive(true);
  9258. auto ret = cli_.send(req, res, error);
  9259. EXPECT_TRUE(ret);
  9260. EXPECT_EQ(StatusCode::OK_200, res.status);
  9261. EXPECT_EQ(LARGE_DATA, res.body);
  9262. }
  9263. {
  9264. // Test with Expect: 100-continue header - error case
  9265. // Client should not send the body when server returns an error
  9266. Request req;
  9267. req.method = "POST";
  9268. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9269. req.set_header("Expect", "100-continue");
  9270. req.body = LARGE_DATA;
  9271. Response res;
  9272. auto error = Error::Success;
  9273. auto start = std::chrono::high_resolution_clock::now();
  9274. cli_.set_keep_alive(true);
  9275. auto ret = cli_.send(req, res, error);
  9276. auto end = std::chrono::high_resolution_clock::now();
  9277. auto elapsed =
  9278. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9279. .count();
  9280. // With Expect: 100-continue, request completes successfully but with error
  9281. EXPECT_TRUE(ret);
  9282. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9283. EXPECT_EQ("close", res.get_header_value("Connection"));
  9284. EXPECT_FALSE(cli_.is_socket_open());
  9285. EXPECT_LE(elapsed, 2000);
  9286. }
  9287. {
  9288. // Send an extra GET request to ensure error recovery without hanging
  9289. Request req;
  9290. req.method = "GET";
  9291. req.path = "/hi";
  9292. auto start = std::chrono::high_resolution_clock::now();
  9293. auto res = cli_.send(req);
  9294. auto end = std::chrono::high_resolution_clock::now();
  9295. auto elapsed =
  9296. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9297. .count();
  9298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9299. EXPECT_EQ(StatusCode::OK_200, res->status);
  9300. EXPECT_EQ("Hello World!", res->body);
  9301. EXPECT_LE(elapsed, 500);
  9302. }
  9303. }
  9304. TEST(ZstdDecompressor, ChunkedDecompression) {
  9305. std::string data;
  9306. for (size_t i = 0; i < 32 * 1024; ++i) {
  9307. data.push_back(static_cast<char>('a' + i % 26));
  9308. }
  9309. std::string compressed_data;
  9310. {
  9311. httplib::detail::zstd_compressor compressor;
  9312. bool result = compressor.compress(
  9313. data.data(), data.size(),
  9314. /*last=*/true,
  9315. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9316. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9317. compressed_data_size);
  9318. return true;
  9319. });
  9320. ASSERT_TRUE(result);
  9321. }
  9322. std::string decompressed_data;
  9323. {
  9324. httplib::detail::zstd_decompressor decompressor;
  9325. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9326. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9327. size_t chunk_size = 130;
  9328. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9329. chunk_begin += chunk_size) {
  9330. size_t current_chunk_size =
  9331. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9332. bool result = decompressor.decompress(
  9333. compressed_data.data() + chunk_begin, current_chunk_size,
  9334. [&](const char *decompressed_data_chunk,
  9335. size_t decompressed_data_chunk_size) {
  9336. decompressed_data.insert(decompressed_data.size(),
  9337. decompressed_data_chunk,
  9338. decompressed_data_chunk_size);
  9339. return true;
  9340. });
  9341. ASSERT_TRUE(result);
  9342. }
  9343. }
  9344. ASSERT_EQ(data, decompressed_data);
  9345. }
  9346. TEST(ZstdDecompressor, Decompress) {
  9347. std::string original_text = "Compressed with ZSTD";
  9348. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9349. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9350. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9351. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9352. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9353. std::string decompressed_data;
  9354. {
  9355. httplib::detail::zstd_decompressor decompressor;
  9356. bool result = decompressor.decompress(
  9357. compressed_data.data(), compressed_data.size(),
  9358. [&](const char *decompressed_data_chunk,
  9359. size_t decompressed_data_chunk_size) {
  9360. decompressed_data.insert(decompressed_data.size(),
  9361. decompressed_data_chunk,
  9362. decompressed_data_chunk_size);
  9363. return true;
  9364. });
  9365. ASSERT_TRUE(result);
  9366. }
  9367. ASSERT_EQ(original_text, decompressed_data);
  9368. }
  9369. #endif
  9370. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9371. // separate chunks so that the server sees each part in its own read(). Used to
  9372. // place a read boundary at a specific offset of a request body.
  9373. static bool send_request_in_parts(time_t read_timeout_sec,
  9374. const std::vector<std::string> &parts,
  9375. std::string *resp = nullptr,
  9376. int port = PORT) {
  9377. auto error = Error::Success;
  9378. auto client_sock = detail::create_client_socket(
  9379. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9380. /*connection_timeout_sec=*/5, 0,
  9381. /*read_timeout_sec=*/5, 0,
  9382. /*write_timeout_sec=*/5, 0, std::string(), error);
  9383. if (client_sock == INVALID_SOCKET) { return false; }
  9384. auto ret = detail::process_client_socket(
  9385. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9386. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9387. for (size_t i = 0; i < parts.size(); i++) {
  9388. const auto &part = parts[i];
  9389. if (part.size() !=
  9390. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9391. return false;
  9392. }
  9393. if (i + 1 < parts.size()) {
  9394. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9395. }
  9396. }
  9397. char buf[512];
  9398. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9399. while (line_reader.getline()) {
  9400. if (resp) { *resp += line_reader.ptr(); }
  9401. }
  9402. return true;
  9403. });
  9404. detail::close_socket(client_sock);
  9405. return ret;
  9406. }
  9407. // Sends a raw request to a server listening at HOST:PORT.
  9408. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9409. std::string *resp = nullptr, int port = PORT) {
  9410. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9411. }
  9412. #ifdef CPPHTTPLIB_SSL_ENABLED
  9413. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9415. ASSERT_TRUE(svr.is_valid());
  9416. svr.set_read_timeout(1, 0);
  9417. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9418. auto se = detail::scope_exit([&] {
  9419. svr.stop();
  9420. t.join();
  9421. ASSERT_FALSE(svr.is_running());
  9422. });
  9423. svr.wait_until_ready();
  9424. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9425. // keeps each wait well within the read timeout. The server gives up a
  9426. // second in, so the bytes sent after that fail.
  9427. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9428. parts.resize(26, std::string(1, '\0'));
  9429. EXPECT_FALSE(send_request_in_parts(5, parts));
  9430. }
  9431. #endif
  9432. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9433. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9434. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9435. const std::vector<std::string> &parts,
  9436. std::string *resp = nullptr,
  9437. int port = PORT) {
  9438. auto error = Error::Success;
  9439. auto sock = detail::create_client_socket(
  9440. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9441. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9442. /*write_timeout_sec=*/5, 0, std::string(), error);
  9443. if (sock == INVALID_SOCKET) { return false; }
  9444. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9445. auto ctx = SSL_CTX_new(TLS_client_method());
  9446. auto ssl = SSL_new(ctx);
  9447. auto ssl_se = detail::scope_exit([&] {
  9448. SSL_free(ssl);
  9449. SSL_CTX_free(ctx);
  9450. });
  9451. SSL_set_fd(ssl, static_cast<int>(sock));
  9452. if (SSL_connect(ssl) != 1) { return false; }
  9453. for (size_t i = 0; i < parts.size(); i++) {
  9454. const auto &part = parts[i];
  9455. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9456. static_cast<int>(part.size())) {
  9457. return false;
  9458. }
  9459. if (i + 1 < parts.size()) {
  9460. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9461. }
  9462. }
  9463. char buf[512];
  9464. int n;
  9465. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9466. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9467. }
  9468. return true;
  9469. }
  9470. #endif
  9471. // The request line, then a header value a byte at a time.
  9472. static std::vector<std::string> slow_request_head_parts() {
  9473. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9474. parts.resize(26, "a");
  9475. parts.emplace_back("\r\n\r\n");
  9476. return parts;
  9477. }
  9478. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9479. // within the one-second read timeout. The server gives up a second in, before
  9480. // the head is complete.
  9481. static void
  9482. expect_slow_request_head_dropped(Server &svr,
  9483. const std::function<std::string()> &send) {
  9484. std::atomic<bool> handled(false);
  9485. svr.Get("/", [&](const Request &, Response &res) {
  9486. handled = true;
  9487. res.set_content("ok", "text/plain");
  9488. });
  9489. svr.set_read_timeout(1, 0);
  9490. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9491. auto se = detail::scope_exit([&] {
  9492. svr.stop();
  9493. t.join();
  9494. ASSERT_FALSE(svr.is_running());
  9495. });
  9496. svr.wait_until_ready();
  9497. auto resp = send();
  9498. EXPECT_FALSE(handled);
  9499. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9500. }
  9501. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9502. Server svr;
  9503. expect_slow_request_head_dropped(svr, [] {
  9504. std::string resp;
  9505. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9506. return resp;
  9507. });
  9508. }
  9509. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9510. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9511. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9512. ASSERT_TRUE(svr.is_valid());
  9513. expect_slow_request_head_dropped(svr, [] {
  9514. std::string resp;
  9515. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9516. return resp;
  9517. });
  9518. }
  9519. #endif
  9520. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9521. Server svr;
  9522. std::string header_value;
  9523. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9524. header_value = req.get_header_value("foo");
  9525. res.set_content("ok", "text/plain");
  9526. });
  9527. thread t = thread([&] { svr.listen(HOST, PORT); });
  9528. auto se = detail::scope_exit([&] {
  9529. svr.stop();
  9530. t.join();
  9531. ASSERT_FALSE(svr.is_running());
  9532. });
  9533. svr.wait_until_ready();
  9534. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9535. // like characters are not treated the same - use vertical tab and escape.
  9536. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9537. "foo: \t \v bar \x1B\t \r\n"
  9538. "Connection: close\r\n"
  9539. "\r\n";
  9540. std::string res;
  9541. ASSERT_TRUE(send_request(5, req, &res));
  9542. EXPECT_EQ(header_value, "");
  9543. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9544. }
  9545. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9546. Server svr;
  9547. std::string received;
  9548. svr.Get("/order", [&](const Request &req, Response &res) {
  9549. received = entries_to_string(req.headers);
  9550. res.set_content("ok", "text/plain");
  9551. });
  9552. auto port = svr.bind_to_any_port(HOST);
  9553. thread t = thread([&] { svr.listen_after_bind(); });
  9554. auto se = detail::scope_exit([&] {
  9555. svr.stop();
  9556. t.join();
  9557. ASSERT_FALSE(svr.is_running());
  9558. });
  9559. svr.wait_until_ready();
  9560. const std::string req = "GET /order HTTP/1.1\r\n"
  9561. "Host: localhost\r\n"
  9562. "X-First: 1\r\n"
  9563. "X-Dup: a\r\n"
  9564. "X-Second: 2\r\n"
  9565. "X-Dup: b\r\n"
  9566. "Connection: close\r\n"
  9567. "\r\n";
  9568. std::string res;
  9569. ASSERT_TRUE(send_request(5, req, &res, port));
  9570. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9571. EXPECT_EQ(
  9572. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9573. received);
  9574. }
  9575. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9576. Server svr;
  9577. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9578. res.set_header("Set-Cookie", "first=1");
  9579. res.set_header("X-Between", "y");
  9580. res.set_header("Set-Cookie", "second=2");
  9581. res.set_content("ok", "text/plain");
  9582. });
  9583. auto port = svr.bind_to_any_port(HOST);
  9584. thread t = thread([&] { svr.listen_after_bind(); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. t.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.wait_until_ready();
  9591. Client cli(HOST, port);
  9592. auto res = cli.Get("/cookies");
  9593. ASSERT_TRUE(res);
  9594. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9595. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9596. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9597. }
  9598. // A stream may send a byte at a time with a small extension on each chunk,
  9599. // however long it runs
  9600. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9601. Server svr;
  9602. svr.Post("/count", [](const Request &req, Response &res) {
  9603. res.set_content(std::to_string(req.body.size()), "text/plain");
  9604. });
  9605. auto port = svr.bind_to_any_port(HOST);
  9606. ASSERT_LT(0, port);
  9607. thread t = thread([&] { svr.listen_after_bind(); });
  9608. auto se = detail::scope_exit([&] {
  9609. svr.stop();
  9610. t.join();
  9611. ASSERT_FALSE(svr.is_running());
  9612. });
  9613. svr.wait_until_ready();
  9614. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9615. "\r\nTransfer-Encoding: chunked\r\n"
  9616. "Connection: close\r\n\r\n";
  9617. for (auto i = 0; i < 4096; i++) {
  9618. req += "1;a=b\r\nx\r\n";
  9619. }
  9620. req += "0\r\n\r\n";
  9621. std::string res;
  9622. ASSERT_TRUE(send_request(5, req, &res, port));
  9623. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9624. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9625. }
  9626. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9627. Server svr;
  9628. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9629. auto i = new int(0);
  9630. res.set_header("Trailer", "X-Safe, X-Reflected");
  9631. res.set_chunked_content_provider(
  9632. "text/plain",
  9633. [i](size_t /*offset*/, DataSink &sink) {
  9634. if (*i == 0) {
  9635. sink.os << "body";
  9636. } else {
  9637. Headers trailer;
  9638. // A valid trailer that must survive.
  9639. trailer.emplace("X-Safe", "safe");
  9640. // Attacker-controlled value carrying CR/LF (response splitting).
  9641. trailer.emplace("X-Reflected",
  9642. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9643. // Attacker-controlled name carrying CR/LF.
  9644. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9645. sink.done_with_trailer(trailer);
  9646. }
  9647. (*i)++;
  9648. return true;
  9649. },
  9650. [i](bool /*success*/) { delete i; });
  9651. });
  9652. thread t = thread([&] { svr.listen(HOST, PORT); });
  9653. auto se = detail::scope_exit([&] {
  9654. svr.stop();
  9655. t.join();
  9656. ASSERT_FALSE(svr.is_running());
  9657. });
  9658. svr.wait_until_ready();
  9659. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9660. "Host: " + HOST +
  9661. "\r\n"
  9662. "Connection: close\r\n"
  9663. "\r\n";
  9664. std::string res;
  9665. ASSERT_TRUE(send_request(5, req, &res));
  9666. // The injected fields must not appear anywhere in the raw response.
  9667. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9668. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9669. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9670. // Invalid trailers are dropped entirely, matching set_header().
  9671. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9672. // The valid trailer still passes through.
  9673. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9674. }
  9675. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9676. // A custom header writer gets only the fields the default one writes
  9677. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9678. std::string s;
  9679. for (const auto &h : hdrs) {
  9680. s += h.first + ": " + h.second + "\r\n";
  9681. }
  9682. s += "\r\n";
  9683. return strm.write(s.data(), s.size());
  9684. };
  9685. for (auto custom_writer : {false, true}) {
  9686. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9687. Server svr;
  9688. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9689. svr.set_post_routing_handler([](const Request &, Response &res) {
  9690. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9691. });
  9692. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9693. // res.headers is a public field an application can populate directly,
  9694. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9695. // A valid header that must survive.
  9696. res.headers.emplace("X-Safe", "safe");
  9697. // Attacker-controlled value carrying CR/LF (response splitting).
  9698. res.headers.emplace("X-Reflected",
  9699. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9700. // Attacker-controlled name carrying CR/LF.
  9701. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9702. res.set_content("body", "text/plain");
  9703. });
  9704. thread t = thread([&] { svr.listen(HOST, PORT); });
  9705. auto se = detail::scope_exit([&] {
  9706. svr.stop();
  9707. t.join();
  9708. ASSERT_FALSE(svr.is_running());
  9709. });
  9710. svr.wait_until_ready();
  9711. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9712. "Host: " + HOST +
  9713. "\r\n"
  9714. "Connection: close\r\n"
  9715. "\r\n";
  9716. std::string res;
  9717. ASSERT_TRUE(send_request(5, req, &res));
  9718. // The injected fields must not appear anywhere in the raw response.
  9719. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9720. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9721. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9722. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9723. // Invalid headers are dropped entirely, matching set_header().
  9724. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9725. // The valid header still passes through.
  9726. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9727. }
  9728. }
  9729. // Forward declaration: in split builds split.py strips `inline` and moves the
  9730. // definition into httplib.cc, so detail::write_request_line is not visible from
  9731. // the public httplib.h. Re-declaring it here lets the tests link against the
  9732. // symbol in both header-only and split builds.
  9733. namespace httplib {
  9734. namespace detail {
  9735. ssize_t write_request_line(Stream &strm, const std::string &method,
  9736. const std::string &path);
  9737. } // namespace detail
  9738. } // namespace httplib
  9739. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9740. // A well-formed target is written verbatim.
  9741. {
  9742. detail::BufferStream strm;
  9743. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9744. EXPECT_GT(n, 0);
  9745. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9746. }
  9747. // A target carrying CR/LF, SP or other control octets must be rejected
  9748. // before anything reaches the wire, otherwise it splits the request line and
  9749. // injects a header or a whole request.
  9750. const std::string evil_targets[] = {
  9751. "/a\r\nInjected: pwned",
  9752. "/a\rInjected",
  9753. "/a\nInjected",
  9754. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9755. "/a b",
  9756. "/a\tb",
  9757. "/a\x7f",
  9758. };
  9759. for (const auto &evil : evil_targets) {
  9760. detail::BufferStream strm;
  9761. auto n = detail::write_request_line(strm, "GET", evil);
  9762. EXPECT_LT(n, 0);
  9763. EXPECT_TRUE(strm.get_buffer().empty());
  9764. }
  9765. }
  9766. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9767. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9768. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9769. // target reaches write_request. The client must fail cleanly with
  9770. // Error::Write instead of putting a request-line-less, header-injecting
  9771. // request on the wire.
  9772. Server svr;
  9773. svr.Get("/a", [](const Request &, Response &res) {
  9774. res.set_content("ok", "text/plain");
  9775. });
  9776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9777. auto se = detail::scope_exit([&] {
  9778. svr.stop();
  9779. thread.join();
  9780. ASSERT_FALSE(svr.is_running());
  9781. });
  9782. svr.wait_until_ready();
  9783. {
  9784. Client cli(HOST, PORT);
  9785. cli.set_path_encode(false);
  9786. // The request is rejected before anything is written, so the connection
  9787. // stays silent and the subsequent response read would otherwise block for
  9788. // the full default read timeout. Shorten it -- the assertion is on the
  9789. // error, not the timeout.
  9790. cli.set_read_timeout(1, 0);
  9791. auto res = cli.Get("/a\r\nInjected: pwned");
  9792. EXPECT_FALSE(res);
  9793. EXPECT_EQ(Error::Write, res.error());
  9794. }
  9795. }
  9796. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9797. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9798. // including extension methods.
  9799. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9800. for (const auto &method : good_methods) {
  9801. detail::BufferStream strm;
  9802. auto n = detail::write_request_line(strm, method, "/");
  9803. EXPECT_GT(n, 0);
  9804. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9805. }
  9806. // A method carrying CR/LF would split the request line and smuggle a whole
  9807. // request ahead of the real one. A space or an empty method corrupts the
  9808. // request line. All must be rejected before anything reaches the wire.
  9809. const std::string evil_methods[] = {
  9810. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9811. "GET\r\nInjected: pwned",
  9812. "GET\r",
  9813. "GET\n",
  9814. "GE T",
  9815. "",
  9816. };
  9817. for (const auto &evil : evil_methods) {
  9818. detail::BufferStream strm;
  9819. auto n = detail::write_request_line(strm, evil, "/");
  9820. EXPECT_LT(n, 0);
  9821. EXPECT_TRUE(strm.get_buffer().empty());
  9822. }
  9823. }
  9824. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9825. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9826. // through Client::send must fail with Error::Write and no request, neither
  9827. // the smuggled one nor the real one, may reach the server.
  9828. Server svr;
  9829. std::atomic<int> request_count(0);
  9830. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9831. request_count++;
  9832. res.status = StatusCode::OK_200;
  9833. return Server::HandlerResponse::Handled;
  9834. });
  9835. auto port = svr.bind_to_any_port(HOST);
  9836. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9837. auto se = detail::scope_exit([&] {
  9838. svr.stop();
  9839. thread.join();
  9840. ASSERT_FALSE(svr.is_running());
  9841. });
  9842. svr.wait_until_ready();
  9843. {
  9844. Client cli(HOST, port);
  9845. const std::string evil_methods[] = {
  9846. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9847. "GE T",
  9848. "",
  9849. };
  9850. for (const auto &evil : evil_methods) {
  9851. Request req;
  9852. req.method = evil;
  9853. req.path = "/";
  9854. auto res = cli.send(req);
  9855. EXPECT_FALSE(res);
  9856. EXPECT_EQ(Error::Write, res.error());
  9857. }
  9858. auto handle =
  9859. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9860. EXPECT_FALSE(handle.is_valid());
  9861. EXPECT_EQ(Error::Write, handle.error);
  9862. // A valid request on the same client still goes through.
  9863. auto res = cli.Get("/");
  9864. ASSERT_TRUE(res);
  9865. EXPECT_EQ(StatusCode::OK_200, res->status);
  9866. }
  9867. EXPECT_EQ(1, request_count.load());
  9868. }
  9869. // Sends a raw request and verifies that there isn't a crash or exception.
  9870. static void test_raw_request(const std::string &req,
  9871. std::string *out = nullptr) {
  9872. Server svr;
  9873. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9874. res.set_content("ok", "text/plain");
  9875. });
  9876. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9877. res.set_content("ok", "text/plain");
  9878. });
  9879. svr.Get("/header_field_value_check",
  9880. [&](const Request & /*req*/, Response &res) {
  9881. res.set_content("ok", "text/plain");
  9882. });
  9883. svr.CustomRoute("PROPFIND", "/dav",
  9884. [&](const Request & /*req*/, Response &res) {
  9885. res.status = StatusCode::MultiStatus_207;
  9886. });
  9887. // Server read timeout must be longer than the client read timeout for the
  9888. // bug to reproduce, probably to force the server to process a request
  9889. // without a trailing blank line.
  9890. const time_t client_read_timeout_sec = 1;
  9891. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9892. bool listen_thread_ok = false;
  9893. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9894. auto se = detail::scope_exit([&] {
  9895. svr.stop();
  9896. t.join();
  9897. ASSERT_FALSE(svr.is_running());
  9898. EXPECT_TRUE(listen_thread_ok);
  9899. });
  9900. svr.wait_until_ready();
  9901. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9902. }
  9903. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9904. // A certain header line causes an exception if the header property is parsed
  9905. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9906. test_raw_request(
  9907. "GET /hi HTTP/1.1\r\n"
  9908. " : "
  9909. " "
  9910. " ");
  9911. }
  9912. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9913. // A certain header line causes an exception if the header property *name* is
  9914. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9915. // greedy matcher and requires backtracking when there are a lot of ":"
  9916. // characters.
  9917. // This occurs with libc++ but not libstdc++.
  9918. test_raw_request(
  9919. "GET /hi HTTP/1.1\r\n"
  9920. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9921. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9922. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9923. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9924. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9925. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9926. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9927. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9928. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9929. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9930. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9931. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9932. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9933. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9934. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9935. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9936. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9937. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9938. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9939. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9940. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9941. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9942. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9943. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9944. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9945. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9946. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9947. "&&&%%%");
  9948. }
  9949. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9950. // Make sure this doesn't crash the server.
  9951. // In a previous version of the header line regex, the "\r" rendered the line
  9952. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9953. // a new position where the leading white space ended and the field value
  9954. // began.
  9955. // The crash occurs with libc++ but not libstdc++.
  9956. test_raw_request("GET /hi HTTP/1.1\r\n"
  9957. "a:" +
  9958. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9959. "\r\n"
  9960. "\r\n");
  9961. }
  9962. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9963. const char *rejected[] = {
  9964. // RFC 9112 §3: one SP between the parts, and nothing else
  9965. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9966. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9967. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9968. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9969. // A request-target has no fragment
  9970. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9971. // An HTTP/1.1 request needs a Host
  9972. "GET /hi HTTP/1.1\r\n\r\n",
  9973. };
  9974. for (auto request : rejected) {
  9975. std::string out;
  9976. test_raw_request(request, &out);
  9977. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9978. }
  9979. std::string out;
  9980. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9981. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9982. }
  9983. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9984. // RFC 9112 §6.1
  9985. const char *requests[] = {
  9986. "PUT /put_hi HTTP/1.1\r\n"
  9987. "Host: localhost\r\n"
  9988. "Content-Length: 0\r\n"
  9989. "Transfer-Encoding: chunked\r\n"
  9990. "\r\n"
  9991. "0\r\n\r\n",
  9992. "PUT /put_hi HTTP/1.0\r\n"
  9993. "Connection: keep-alive\r\n"
  9994. "Transfer-Encoding: chunked\r\n"
  9995. "\r\n"
  9996. "0\r\n\r\n",
  9997. };
  9998. for (auto request : requests) {
  9999. std::string out;
  10000. test_raw_request(request, &out);
  10001. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10002. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10003. }
  10004. }
  10005. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10006. std::string out;
  10007. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10008. "Content-Type: text/plain\r\n"
  10009. "Transfer-Encoding: chunked\r\n"
  10010. "\r\n"
  10011. "nothex\r\n",
  10012. &out);
  10013. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10014. }
  10015. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10016. std::string out;
  10017. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10018. "Content-Type: text/plain\r\n"
  10019. "Transfer-Encoding: chunked\r\n"
  10020. "\r\n"
  10021. "3\r\n"
  10022. "xyz\r\n"
  10023. "NaN\r\n",
  10024. &out);
  10025. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10026. }
  10027. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10028. std::string out;
  10029. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10030. "Content-Type: text/plain\r\n"
  10031. "Transfer-Encoding: chunked\r\n"
  10032. "\r\n"
  10033. // Length is too large for 64 bits.
  10034. "1ffffffffffffffff\r\n"
  10035. "xyz\r\n",
  10036. &out);
  10037. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10038. }
  10039. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10040. test_raw_request("GET /hi HTTP/1.1\r\n"
  10041. "Content-Type: text/plain\r\n\r");
  10042. }
  10043. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10044. std::string out;
  10045. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10046. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10047. }
  10048. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10049. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10050. std::string out;
  10051. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10052. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10053. }
  10054. }
  10055. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10056. std::string out;
  10057. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10058. "Host: localhost\r\n"
  10059. "Connection: close\r\n\r\n",
  10060. &out);
  10061. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10062. }
  10063. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10064. Server svr;
  10065. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10066. EXPECT_TRUE(!req.remote_addr.empty());
  10067. });
  10068. thread t = thread([&] { svr.listen(HOST, PORT); });
  10069. auto se = detail::scope_exit([&] {
  10070. svr.stop();
  10071. t.join();
  10072. ASSERT_FALSE(svr.is_running());
  10073. });
  10074. svr.wait_until_ready();
  10075. // Send an invalid request line to trigger Bad Request
  10076. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10077. std::string out;
  10078. ASSERT_TRUE(send_request(5, bad_req, &out));
  10079. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10080. }
  10081. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10082. // answered right away rather than blocking on a read that waits for EOF.
  10083. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10084. std::string out;
  10085. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10086. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10087. }
  10088. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10089. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10090. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10091. for (const auto *method : methods) {
  10092. Server svr;
  10093. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10094. EXPECT_FALSE(svr.is_valid()) << method;
  10095. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10096. }
  10097. }
  10098. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10099. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10100. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10101. for (const auto *method : methods) {
  10102. Server svr;
  10103. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10104. EXPECT_FALSE(svr.is_valid()) << method;
  10105. }
  10106. }
  10107. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10108. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10109. "COPY", "MOVE", "LOCK",
  10110. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10111. Server svr;
  10112. for (const auto *method : methods) {
  10113. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10114. }
  10115. EXPECT_TRUE(svr.is_valid());
  10116. }
  10117. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10118. Server svr;
  10119. svr.CustomRoute("POST", "/x",
  10120. [](const Request &, Response &, const ContentReader &) {});
  10121. EXPECT_FALSE(svr.is_valid());
  10122. }
  10123. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10124. Server svr;
  10125. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10126. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10127. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10128. EXPECT_FALSE(svr.is_valid());
  10129. }
  10130. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10131. Server svr;
  10132. auto captured = Error::Success;
  10133. svr.set_error_logger(
  10134. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10135. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10136. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10137. }
  10138. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10139. std::string out;
  10140. std::string request(
  10141. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10142. test_raw_request(request, &out);
  10143. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10144. }
  10145. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10146. std::string out;
  10147. std::string request(
  10148. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10149. test_raw_request(request, &out);
  10150. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10151. }
  10152. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10153. std::string out;
  10154. std::string request(
  10155. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10156. test_raw_request(request, &out);
  10157. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10158. }
  10159. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10160. std::string out;
  10161. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10162. "Host: localhost\r\n"
  10163. "Test: \r\n\r\n",
  10164. &out);
  10165. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10166. }
  10167. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10168. Server svr;
  10169. std::string x_custom;
  10170. std::string cookie;
  10171. std::string xff;
  10172. std::string x_unicode;
  10173. std::string x_iis;
  10174. svr.Get("/check", [&](const Request &req, Response &res) {
  10175. x_custom = req.get_header_value("X-Custom");
  10176. cookie = req.get_header_value("Cookie");
  10177. xff = req.get_header_value("X-Forwarded-For");
  10178. x_unicode = req.get_header_value("X-Unicode");
  10179. x_iis = req.get_header_value("X-IIS");
  10180. res.set_content("ok", "text/plain");
  10181. });
  10182. thread t = thread([&] { svr.listen(HOST, PORT); });
  10183. auto se = detail::scope_exit([&] {
  10184. svr.stop();
  10185. t.join();
  10186. ASSERT_FALSE(svr.is_running());
  10187. });
  10188. svr.wait_until_ready();
  10189. const std::string req = "GET /check HTTP/1.1\r\n"
  10190. "Host: localhost\r\n"
  10191. "X-Custom: a%0D%0AInjected: b\r\n"
  10192. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10193. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10194. "X-Unicode: %E3%81%82\r\n"
  10195. "X-IIS: %u00E9\r\n"
  10196. "Connection: close\r\n"
  10197. "\r\n";
  10198. std::string res;
  10199. ASSERT_TRUE(send_request(5, req, &res));
  10200. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10201. // Every value must be returned verbatim (wire form), with no decoding.
  10202. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10203. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10204. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10205. EXPECT_EQ("%E3%81%82", x_unicode);
  10206. EXPECT_EQ("%u00E9", x_iis);
  10207. }
  10208. // Applications that previously relied on automatic percent-decoding can
  10209. // reproduce the old behavior by explicitly calling decode_path_component()
  10210. // or, for RFC 3986 conformance, decode_uri_component().
  10211. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10212. Server svr;
  10213. std::string decoded;
  10214. svr.Get("/check", [&](const Request &req, Response &res) {
  10215. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10216. res.set_content("ok", "text/plain");
  10217. });
  10218. thread t = thread([&] { svr.listen(HOST, PORT); });
  10219. auto se = detail::scope_exit([&] {
  10220. svr.stop();
  10221. t.join();
  10222. ASSERT_FALSE(svr.is_running());
  10223. });
  10224. svr.wait_until_ready();
  10225. const std::string req = "GET /check HTTP/1.1\r\n"
  10226. "Host: localhost\r\n"
  10227. "X-Custom: hello%20world\r\n"
  10228. "Connection: close\r\n"
  10229. "\r\n";
  10230. std::string res;
  10231. ASSERT_TRUE(send_request(5, req, &res));
  10232. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10233. EXPECT_EQ("hello world", decoded);
  10234. }
  10235. // Regression test for #2033. Browsers send Referer values that include
  10236. // percent-encoded characters such as %0A inside the URL. Decoding the
  10237. // header value would either trip the post-decode CR/LF/NUL guard (the
  10238. // original bug, returning 400) or, after that guard was relaxed, silently
  10239. // store a literal LF — both unacceptable. The wire form must round-trip.
  10240. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10241. Server svr;
  10242. std::string referer;
  10243. svr.Get("/check", [&](const Request &req, Response &res) {
  10244. referer = req.get_header_value("Referer");
  10245. res.set_content("ok", "text/plain");
  10246. });
  10247. thread t = thread([&] { svr.listen(HOST, PORT); });
  10248. auto se = detail::scope_exit([&] {
  10249. svr.stop();
  10250. t.join();
  10251. ASSERT_FALSE(svr.is_running());
  10252. });
  10253. svr.wait_until_ready();
  10254. const std::string req = "GET /check HTTP/1.1\r\n"
  10255. "Host: localhost\r\n"
  10256. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10257. "Connection: close\r\n"
  10258. "\r\n";
  10259. std::string res;
  10260. ASSERT_TRUE(send_request(5, req, &res));
  10261. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10262. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10263. }
  10264. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10265. Server svr;
  10266. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10267. res.set_header("Cache-Control", "no-cache");
  10268. res.set_chunked_content_provider(
  10269. "text/event-stream", [](size_t offset, DataSink &sink) {
  10270. std::string s = "data:";
  10271. s += std::to_string(offset);
  10272. s += "\n\n";
  10273. auto ret = sink.write(s.data(), s.size());
  10274. EXPECT_TRUE(ret);
  10275. std::this_thread::sleep_for(std::chrono::seconds(1));
  10276. return true;
  10277. });
  10278. });
  10279. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10280. svr.wait_until_ready();
  10281. Client client(HOST, PORT);
  10282. const Headers headers = {{"Accept", "text/event-stream"}};
  10283. auto get_thread = std::thread([&client, &headers]() {
  10284. auto res = client.Get(
  10285. "/events", headers,
  10286. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10287. });
  10288. auto se = detail::scope_exit([&] {
  10289. svr.stop();
  10290. get_thread.join();
  10291. listen_thread.join();
  10292. ASSERT_FALSE(svr.is_running());
  10293. });
  10294. // Give GET time to get a few messages.
  10295. std::this_thread::sleep_for(std::chrono::seconds(2));
  10296. }
  10297. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10298. httplib::Server svr;
  10299. svr.Post("/hi",
  10300. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10301. res.status = StatusCode::OK_200;
  10302. });
  10303. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10304. svr.wait_until_ready();
  10305. Client cli(HOST, PORT);
  10306. auto res = cli.Post("/hi", "data", "text/plain");
  10307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10308. EXPECT_EQ(StatusCode::OK_200, res->status);
  10309. svr.stop();
  10310. thread.join();
  10311. ASSERT_FALSE(svr.is_running());
  10312. res = cli.Post("/hi", "data", "text/plain");
  10313. ASSERT_FALSE(res);
  10314. }
  10315. TEST(ServerStopTest, ListenFailure) {
  10316. Server svr;
  10317. auto t = thread([&]() {
  10318. auto ret = svr.listen("????", PORT);
  10319. EXPECT_FALSE(ret);
  10320. });
  10321. svr.wait_until_ready();
  10322. svr.stop();
  10323. t.join();
  10324. }
  10325. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10326. TEST(ServerStopTest, Decommision) {
  10327. Server svr;
  10328. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10329. for (int i = 0; i < 4; i++) {
  10330. auto is_even = !(i % 2);
  10331. std::thread t{[&] {
  10332. try {
  10333. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10334. if (is_even) {
  10335. throw std::runtime_error("Some thing that happens to go wrong.");
  10336. }
  10337. svr.listen(HOST, PORT);
  10338. } catch (...) { svr.decommission(); }
  10339. }};
  10340. svr.wait_until_ready();
  10341. // Server is up
  10342. {
  10343. Client cli(HOST, PORT);
  10344. auto res = cli.Get("/hi");
  10345. if (is_even) {
  10346. EXPECT_FALSE(res);
  10347. } else {
  10348. EXPECT_TRUE(res);
  10349. EXPECT_EQ("hi...", res->body);
  10350. }
  10351. }
  10352. svr.stop();
  10353. t.join();
  10354. // Server is down...
  10355. {
  10356. Client cli(HOST, PORT);
  10357. auto res = cli.Get("/hi");
  10358. EXPECT_FALSE(res);
  10359. }
  10360. }
  10361. }
  10362. #endif
  10363. // Helper function for string body upload progress tests
  10364. template <typename SetupHandler, typename ClientCall>
  10365. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10366. ClientCall &&client_call,
  10367. const string &body) {
  10368. Server svr;
  10369. setup_handler(svr);
  10370. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10371. auto se = detail::scope_exit([&] {
  10372. svr.stop();
  10373. t.join();
  10374. });
  10375. svr.wait_until_ready();
  10376. Client cli(HOST, PORT);
  10377. vector<uint64_t> progress_values;
  10378. bool progress_called = false;
  10379. auto res =
  10380. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10381. progress_values.push_back(current);
  10382. progress_called = true;
  10383. return true;
  10384. });
  10385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10386. EXPECT_EQ(200, res->status);
  10387. EXPECT_TRUE(progress_called);
  10388. }
  10389. TEST(UploadProgressTest, PostStringBodyBasic) {
  10390. TestStringBodyUploadProgress(
  10391. [](Server &svr) {
  10392. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10393. res.set_content("received", "text/plain");
  10394. });
  10395. },
  10396. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10397. return cli.Post("/test", body, "text/plain", progress_callback);
  10398. },
  10399. "test data for upload progress");
  10400. }
  10401. TEST(UploadProgressTest, PutStringBodyBasic) {
  10402. TestStringBodyUploadProgress(
  10403. [](Server &svr) {
  10404. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10405. res.set_content("put received", "text/plain");
  10406. });
  10407. },
  10408. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10409. return cli.Put("/test", body, "text/plain", progress_callback);
  10410. },
  10411. "put test data for upload progress");
  10412. }
  10413. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10414. TestStringBodyUploadProgress(
  10415. [](Server &svr) {
  10416. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10417. res.set_content("patch received", "text/plain");
  10418. });
  10419. },
  10420. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10421. return cli.Patch("/test", body, "text/plain", progress_callback);
  10422. },
  10423. "patch test data for upload progress");
  10424. }
  10425. // Helper function for content provider upload progress tests
  10426. template <typename SetupHandler, typename ClientCall>
  10427. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10428. ClientCall &&client_call) {
  10429. Server svr;
  10430. setup_handler(svr);
  10431. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10432. auto se = detail::scope_exit([&] {
  10433. svr.stop();
  10434. t.join();
  10435. });
  10436. svr.wait_until_ready();
  10437. Client cli(HOST, PORT);
  10438. vector<uint64_t> progress_values;
  10439. auto res =
  10440. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10441. progress_values.push_back(current);
  10442. return true;
  10443. });
  10444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10445. EXPECT_EQ(200, res->status);
  10446. EXPECT_FALSE(progress_values.empty());
  10447. }
  10448. TEST(UploadProgressTest, PostContentProviderProgress) {
  10449. TestContentProviderUploadProgress(
  10450. [](Server &svr) {
  10451. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10452. res.set_content("provider received", "text/plain");
  10453. });
  10454. },
  10455. [](Client &cli, UploadProgress progress_callback) {
  10456. return cli.Post(
  10457. "/test", 9,
  10458. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10459. sink.os << "test data";
  10460. return true;
  10461. },
  10462. "text/plain", progress_callback);
  10463. });
  10464. }
  10465. // Helper function for multipart upload progress tests
  10466. template <typename SetupHandler, typename ClientCall>
  10467. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10468. ClientCall &&client_call,
  10469. const string &endpoint) {
  10470. Server svr;
  10471. setup_handler(svr);
  10472. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10473. auto se = detail::scope_exit([&] {
  10474. svr.stop();
  10475. t.join();
  10476. });
  10477. svr.wait_until_ready();
  10478. Client cli(HOST, PORT);
  10479. vector<uint64_t> progress_values;
  10480. UploadFormDataItems items = {
  10481. {"field1", "value1", "", ""},
  10482. {"field2", "longer value for progress tracking test", "", ""},
  10483. {"file1", "file content data for upload progress", "test.txt",
  10484. "text/plain"}};
  10485. auto res = client_call(cli, endpoint, items,
  10486. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10487. progress_values.push_back(current);
  10488. return true;
  10489. });
  10490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10491. EXPECT_EQ(200, res->status);
  10492. EXPECT_FALSE(progress_values.empty());
  10493. }
  10494. TEST(UploadProgressTest, PostMultipartProgress) {
  10495. TestMultipartUploadProgress(
  10496. [](Server &svr) {
  10497. svr.Post("/multipart", [](const Request &req, Response &res) {
  10498. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10499. res.set_content("multipart received", "text/plain");
  10500. });
  10501. },
  10502. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10503. UploadProgress progress_callback) {
  10504. return cli.Post(endpoint, items, progress_callback);
  10505. },
  10506. "/multipart");
  10507. }
  10508. // Helper function for basic download progress tests
  10509. template <typename SetupHandler, typename ClientCall>
  10510. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10511. ClientCall &&client_call, const string &endpoint,
  10512. size_t expected_content_size) {
  10513. Server svr;
  10514. setup_handler(svr);
  10515. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10516. auto se = detail::scope_exit([&] {
  10517. svr.stop();
  10518. t.join();
  10519. });
  10520. svr.wait_until_ready();
  10521. Client cli(HOST, PORT);
  10522. vector<uint64_t> progress_values;
  10523. auto res = client_call(cli, endpoint,
  10524. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10525. progress_values.push_back(current);
  10526. return true;
  10527. });
  10528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10529. EXPECT_EQ(200, res->status);
  10530. EXPECT_FALSE(progress_values.empty());
  10531. EXPECT_EQ(expected_content_size, res->body.size());
  10532. }
  10533. TEST(DownloadProgressTest, GetBasic) {
  10534. TestBasicDownloadProgress(
  10535. [](Server &svr) {
  10536. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10537. string content(1000, 'D');
  10538. res.set_content(content, "text/plain");
  10539. });
  10540. },
  10541. [](Client &cli, const string &endpoint,
  10542. DownloadProgress progress_callback) {
  10543. return cli.Get(endpoint, progress_callback);
  10544. },
  10545. "/download", 1000u);
  10546. }
  10547. // Helper function for content receiver download progress tests
  10548. template <typename SetupHandler, typename ClientCall>
  10549. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10550. ClientCall &&client_call,
  10551. const string &endpoint,
  10552. size_t expected_content_size) {
  10553. Server svr;
  10554. setup_handler(svr);
  10555. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10556. auto se = detail::scope_exit([&] {
  10557. svr.stop();
  10558. t.join();
  10559. });
  10560. svr.wait_until_ready();
  10561. Client cli(HOST, PORT);
  10562. vector<uint64_t> progress_values;
  10563. string received_body;
  10564. auto res = client_call(
  10565. cli, endpoint,
  10566. [&](const char *data, size_t data_length) -> bool {
  10567. received_body.append(data, data_length);
  10568. return true;
  10569. },
  10570. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10571. progress_values.push_back(current);
  10572. return true;
  10573. });
  10574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10575. EXPECT_EQ(200, res->status);
  10576. EXPECT_FALSE(progress_values.empty());
  10577. EXPECT_EQ(expected_content_size, received_body.size());
  10578. EXPECT_TRUE(res->body.empty());
  10579. }
  10580. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10581. TestContentReceiverDownloadProgress(
  10582. [](Server &svr) {
  10583. svr.Get("/download-receiver",
  10584. [](const Request & /*req*/, Response &res) {
  10585. string content(2000, 'R');
  10586. res.set_content(content, "text/plain");
  10587. });
  10588. },
  10589. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10590. DownloadProgress progress_callback) {
  10591. return cli.Get(endpoint, content_receiver, progress_callback);
  10592. },
  10593. "/download-receiver", 2000u);
  10594. }
  10595. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10596. // A provider reaching a pass with nothing to hand over - an empty buffer
  10597. // popped off a queue, say - must not be taken to mean the body is finished.
  10598. // It used to end the loop with the terminating chunk unwritten while the
  10599. // server still considered the response complete, so the peer waited for an
  10600. // end that never arrived.
  10601. Server svr;
  10602. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10603. auto step = std::make_shared<int>(0);
  10604. res.set_chunked_content_provider("text/plain",
  10605. [step](size_t /*offset*/, DataSink &sink) {
  10606. switch ((*step)++) {
  10607. case 0: sink.write("", 0); break;
  10608. case 1: sink.write("hello", 5); break;
  10609. default: sink.done(); break;
  10610. }
  10611. return true;
  10612. });
  10613. });
  10614. auto port = svr.bind_to_any_port(HOST);
  10615. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10616. auto listen_se = detail::scope_exit([&] {
  10617. svr.stop();
  10618. listen_thread.join();
  10619. ASSERT_FALSE(svr.is_running());
  10620. });
  10621. svr.wait_until_ready();
  10622. Client cli(HOST, port);
  10623. // Without the fix the body is never terminated, so bound the wait rather
  10624. // than letting the test hang on the default read timeout.
  10625. cli.set_read_timeout(5, 0);
  10626. auto res = cli.Get("/stream");
  10627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10628. EXPECT_EQ(StatusCode::OK_200, res->status);
  10629. EXPECT_EQ("hello", res->body);
  10630. }
  10631. TEST(StreamingTest, NoContentLengthStreaming) {
  10632. Server svr;
  10633. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10634. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10635. if (offset < 6) {
  10636. sink.os << (offset < 3 ? "a" : "b");
  10637. } else {
  10638. sink.done();
  10639. }
  10640. return true;
  10641. });
  10642. });
  10643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10644. auto listen_se = detail::scope_exit([&] {
  10645. svr.stop();
  10646. listen_thread.join();
  10647. ASSERT_FALSE(svr.is_running());
  10648. });
  10649. svr.wait_until_ready();
  10650. Client client(HOST, PORT);
  10651. auto get_thread = std::thread([&client]() {
  10652. std::string s;
  10653. auto res =
  10654. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10655. s += std::string(data, len);
  10656. return true;
  10657. });
  10658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10659. EXPECT_EQ(StatusCode::OK_200, res->status);
  10660. EXPECT_EQ("aaabbb", s);
  10661. });
  10662. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10663. // Give GET time to get a few messages.
  10664. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10665. }
  10666. TEST(MountTest, Unmount) {
  10667. Server svr;
  10668. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10669. auto se = detail::scope_exit([&] {
  10670. svr.stop();
  10671. listen_thread.join();
  10672. ASSERT_FALSE(svr.is_running());
  10673. });
  10674. svr.wait_until_ready();
  10675. Client cli("localhost", PORT);
  10676. svr.set_mount_point("/mount2", "./www2");
  10677. auto res = cli.Get("/");
  10678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10679. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10680. res = cli.Get("/mount2/dir/test.html");
  10681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10682. EXPECT_EQ(StatusCode::OK_200, res->status);
  10683. svr.set_mount_point("/", "./www");
  10684. res = cli.Get("/dir/");
  10685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10686. EXPECT_EQ(StatusCode::OK_200, res->status);
  10687. svr.remove_mount_point("/");
  10688. res = cli.Get("/dir/");
  10689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10690. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10691. svr.remove_mount_point("/mount2");
  10692. res = cli.Get("/mount2/dir/test.html");
  10693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10694. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10695. }
  10696. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10697. Server svr;
  10698. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10699. svr.Get("/api/hello", [](const Request &, Response &res) {
  10700. res.set_content("api", "text/plain");
  10701. });
  10702. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10703. auto se = detail::scope_exit([&] {
  10704. svr.stop();
  10705. listen_thread.join();
  10706. ASSERT_FALSE(svr.is_running());
  10707. });
  10708. svr.wait_until_ready();
  10709. Client cli(HOST, PORT);
  10710. auto res = cli.Get("/dir/test.html");
  10711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10712. EXPECT_EQ(StatusCode::OK_200, res->status);
  10713. res = cli.Get("/api/hello");
  10714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10715. EXPECT_EQ(StatusCode::OK_200, res->status);
  10716. EXPECT_EQ("api", res->body);
  10717. }
  10718. TEST(MountTest, PathSegmentBoundary) {
  10719. Server svr;
  10720. svr.set_mount_point("/mount2", "./www2");
  10721. svr.set_mount_point("/", "./www");
  10722. auto port = svr.bind_to_any_port(HOST);
  10723. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10724. auto se = detail::scope_exit([&] {
  10725. svr.stop();
  10726. listen_thread.join();
  10727. ASSERT_FALSE(svr.is_running());
  10728. });
  10729. svr.wait_until_ready();
  10730. Client cli(HOST, port);
  10731. auto res = cli.Get("/mount2/dir/test.html");
  10732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10733. EXPECT_EQ(StatusCode::OK_200, res->status);
  10734. // "/mount2" must not match part-way through a path segment.
  10735. res = cli.Get("/mount2dir/test.html");
  10736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10737. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10738. // A mount point ending in '/' keeps matching every path below it.
  10739. res = cli.Get("/dir/test.html");
  10740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10741. EXPECT_EQ(StatusCode::OK_200, res->status);
  10742. }
  10743. TEST(MountTest, Redicect) {
  10744. Server svr;
  10745. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10746. auto se = detail::scope_exit([&] {
  10747. svr.stop();
  10748. listen_thread.join();
  10749. ASSERT_FALSE(svr.is_running());
  10750. });
  10751. svr.set_mount_point("/", "./www");
  10752. svr.wait_until_ready();
  10753. Client cli("localhost", PORT);
  10754. auto res = cli.Get("/dir/");
  10755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10756. EXPECT_EQ(StatusCode::OK_200, res->status);
  10757. res = cli.Get("/dir");
  10758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10759. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10760. res = cli.Get("/file");
  10761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10762. EXPECT_EQ(StatusCode::OK_200, res->status);
  10763. res = cli.Get("/file/");
  10764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10765. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10766. cli.set_follow_location(true);
  10767. res = cli.Get("/dir");
  10768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10769. EXPECT_EQ(StatusCode::OK_200, res->status);
  10770. }
  10771. TEST(MountTest, MultibytesPathName) {
  10772. Server svr;
  10773. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10774. auto se = detail::scope_exit([&] {
  10775. svr.stop();
  10776. listen_thread.join();
  10777. ASSERT_FALSE(svr.is_running());
  10778. });
  10779. svr.set_mount_point("/", "./www");
  10780. svr.wait_until_ready();
  10781. Client cli("localhost", PORT);
  10782. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10784. EXPECT_EQ(StatusCode::OK_200, res->status);
  10785. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10786. }
  10787. // A mount point serves no path with an empty segment or one ending in '.' or
  10788. // a space, so a guard in the pre-routing handler sees the path of every file
  10789. // that is served
  10790. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10791. Server svr;
  10792. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10793. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10794. if (req.path == "/dir/test.html") {
  10795. res.status = StatusCode::Unauthorized_401;
  10796. return Server::HandlerResponse::Handled;
  10797. }
  10798. return Server::HandlerResponse::Unhandled;
  10799. });
  10800. auto port = svr.bind_to_any_port(HOST);
  10801. ASSERT_LT(0, port);
  10802. thread t = thread([&] { svr.listen_after_bind(); });
  10803. auto se = detail::scope_exit([&] {
  10804. svr.stop();
  10805. t.join();
  10806. ASSERT_FALSE(svr.is_running());
  10807. });
  10808. svr.wait_until_ready();
  10809. Client cli(HOST, port);
  10810. for (auto path :
  10811. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10812. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10813. "/dir/test.html.", "/dir/test.html%20"}) {
  10814. SCOPED_TRACE(path);
  10815. auto res = cli.Get(path);
  10816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10817. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10818. }
  10819. }
  10820. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10821. Server svr;
  10822. svr.set_mount_point("/", "./www");
  10823. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10824. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10825. auto port = svr.bind_to_any_port(HOST);
  10826. ASSERT_GT(port, 0);
  10827. thread t = thread([&] { svr.listen_after_bind(); });
  10828. auto se = detail::scope_exit([&] {
  10829. svr.stop();
  10830. t.join();
  10831. ASSERT_FALSE(svr.is_running());
  10832. });
  10833. svr.wait_until_ready();
  10834. Client cli(HOST, port);
  10835. auto res = cli.Get("/dir/test.abcde");
  10836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10837. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10838. res = cli.Get("/dir/test.html");
  10839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10840. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10841. }
  10842. #ifdef _WIN32
  10843. // Issue #2435: mmap::open() must succeed even when another handle holds
  10844. // the file open for writing (e.g. an active log file).
  10845. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10846. const char *path = "mmap_concurrent_writer_test.txt";
  10847. const char *content = "hello";
  10848. {
  10849. std::ofstream f(path, std::ios::binary);
  10850. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10851. }
  10852. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10853. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10854. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10855. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10856. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10857. detail::mmap m(path);
  10858. ASSERT_TRUE(m.is_open());
  10859. EXPECT_EQ(strlen(content), m.size());
  10860. char buf[8];
  10861. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10862. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10863. }
  10864. #endif
  10865. #ifndef _WIN32
  10866. // A directory or a device has no size to serve.
  10867. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10868. const char *path = "./mmap_not_regular_test_dir";
  10869. ASSERT_EQ(0, ::mkdir(path, 0755));
  10870. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10871. for (auto p : {path, "/dev/null"}) {
  10872. detail::mmap m(p);
  10873. EXPECT_FALSE(m.is_open()) << p;
  10874. EXPECT_EQ(0U, m.size()) << p;
  10875. }
  10876. Server svr;
  10877. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10878. res.set_file_content("/dev/null");
  10879. });
  10880. auto port = svr.bind_to_any_port(HOST);
  10881. thread t = thread([&] { svr.listen_after_bind(); });
  10882. auto se = detail::scope_exit([&] {
  10883. svr.stop();
  10884. t.join();
  10885. });
  10886. svr.wait_until_ready();
  10887. auto res = Client(HOST, port).Get("/null");
  10888. ASSERT_TRUE(res);
  10889. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10890. }
  10891. #endif
  10892. #ifdef __linux__
  10893. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10894. TEST(MmapTest, FileIsNotMapped) {
  10895. const char *path = "mmap_not_mapped_test.txt";
  10896. {
  10897. std::ofstream f(path, std::ios::binary);
  10898. f << "hello";
  10899. }
  10900. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10901. detail::mmap m(path);
  10902. ASSERT_TRUE(m.is_open());
  10903. std::ifstream maps("/proc/self/maps");
  10904. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10905. std::istreambuf_iterator<char>());
  10906. EXPECT_EQ(std::string::npos, mappings.find(path));
  10907. }
  10908. #endif
  10909. TEST(KeepAliveTest, ReadTimeout) {
  10910. Server svr;
  10911. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10912. std::this_thread::sleep_for(std::chrono::seconds(2));
  10913. res.set_content("a", "text/plain");
  10914. });
  10915. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10916. res.set_content("b", "text/plain");
  10917. });
  10918. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10919. auto se = detail::scope_exit([&] {
  10920. svr.stop();
  10921. listen_thread.join();
  10922. ASSERT_FALSE(svr.is_running());
  10923. });
  10924. svr.wait_until_ready();
  10925. Client cli("localhost", PORT);
  10926. cli.set_keep_alive(true);
  10927. cli.set_read_timeout(std::chrono::seconds(1));
  10928. auto resa = cli.Get("/a");
  10929. ASSERT_FALSE(resa);
  10930. EXPECT_EQ(Error::Read, resa.error());
  10931. auto resb = cli.Get("/b");
  10932. ASSERT_TRUE(resb);
  10933. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10934. EXPECT_EQ("b", resb->body);
  10935. }
  10936. TEST(KeepAliveTest, MaxCount) {
  10937. size_t keep_alive_max_count = 3;
  10938. Server svr;
  10939. svr.set_keep_alive_max_count(keep_alive_max_count);
  10940. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10941. res.set_content("Hello World!", "text/plain");
  10942. });
  10943. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10944. auto se = detail::scope_exit([&] {
  10945. svr.stop();
  10946. listen_thread.join();
  10947. ASSERT_FALSE(svr.is_running());
  10948. });
  10949. svr.wait_until_ready();
  10950. Client cli(HOST, PORT);
  10951. cli.set_keep_alive(true);
  10952. for (size_t i = 0; i < 5; i++) {
  10953. auto result = cli.Get("/hi");
  10954. ASSERT_TRUE(result);
  10955. EXPECT_EQ(StatusCode::OK_200, result->status);
  10956. if (i == keep_alive_max_count - 1) {
  10957. EXPECT_EQ("close", result->get_header_value("Connection"));
  10958. } else {
  10959. EXPECT_FALSE(result->has_header("Connection"));
  10960. }
  10961. }
  10962. }
  10963. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10964. // can pull the next one into the server's buffer. The server must serve it
  10965. // without waiting for the socket to become readable again. The keep-alive
  10966. // timeout outlasts the client's read timeout, so a request left waiting for it
  10967. // shows up as a missing response.
  10968. static void serve_pipelining_routes(Server &svr,
  10969. const std::function<void(int)> &client) {
  10970. svr.set_keep_alive_timeout(5);
  10971. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10972. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10973. });
  10974. svr.Post("/echo", [](const Request &req, Response &res) {
  10975. res.set_content("echo " + req.body, "text/plain");
  10976. });
  10977. auto port = svr.bind_to_any_port(HOST);
  10978. thread t = thread([&] { svr.listen_after_bind(); });
  10979. auto se = detail::scope_exit([&] {
  10980. svr.stop();
  10981. t.join();
  10982. });
  10983. svr.wait_until_ready();
  10984. client(port);
  10985. }
  10986. static std::string
  10987. send_pipelined_requests(const std::vector<std::string> &parts) {
  10988. Server svr;
  10989. std::string res;
  10990. serve_pipelining_routes(svr, [&](int port) {
  10991. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10992. });
  10993. return res;
  10994. }
  10995. static void expect_in_order(const std::string &res,
  10996. const std::vector<std::string> &bodies) {
  10997. size_t pos = 0;
  10998. for (const auto &body : bodies) {
  10999. pos = res.find(body, pos);
  11000. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11001. pos += body.size();
  11002. }
  11003. }
  11004. TEST(KeepAliveTest, PipelinedRequests) {
  11005. auto res = send_pipelined_requests(
  11006. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11007. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11008. "Content-Length: 4\r\n\r\nbody"
  11009. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11010. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11011. }
  11012. // The second request starts in the server's buffer and ends on the socket.
  11013. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11014. auto res =
  11015. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11016. "GET /hi/2 HTTP/1.1\r\nHo",
  11017. "st: localhost\r\nConnection: close\r\n\r\n"});
  11018. expect_in_order(res, {"hi 1", "hi 2"});
  11019. }
  11020. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11021. // CRLF after a body does not turn into a 400 for the next request.
  11022. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11023. auto res = send_pipelined_requests(
  11024. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11025. "Content-Length: 4\r\n\r\nbody\r\n"
  11026. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11027. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11028. expect_in_order(res, {"echo body", "hi 2"});
  11029. }
  11030. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11031. // must not be served as the next request.
  11032. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11033. auto res = send_pipelined_requests(
  11034. {"INVALID REQUEST LINE\r\n\r\n"
  11035. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11036. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11037. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11038. }
  11039. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11040. // Over TLS, the next request is held by the TLS library as already decrypted
  11041. // data rather than on the socket.
  11042. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11044. std::string res;
  11045. serve_pipelining_routes(svr, [&](int port) {
  11046. // One part, so all three requests arrive in one TLS record
  11047. EXPECT_TRUE(send_ssl_request_in_parts(
  11048. 2,
  11049. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11050. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11051. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11052. &res, port));
  11053. });
  11054. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11055. }
  11056. #endif
  11057. TEST(KeepAliveTest, Issue1041) {
  11058. Server svr;
  11059. svr.set_keep_alive_timeout(3);
  11060. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11061. res.set_content("Hello World!", "text/plain");
  11062. });
  11063. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11064. auto se = detail::scope_exit([&] {
  11065. svr.stop();
  11066. listen_thread.join();
  11067. ASSERT_FALSE(svr.is_running());
  11068. });
  11069. svr.wait_until_ready();
  11070. Client cli(HOST, PORT);
  11071. cli.set_keep_alive(true);
  11072. auto result = cli.Get("/hi");
  11073. ASSERT_TRUE(result);
  11074. EXPECT_EQ(StatusCode::OK_200, result->status);
  11075. std::this_thread::sleep_for(std::chrono::seconds(5));
  11076. result = cli.Get("/hi");
  11077. ASSERT_TRUE(result);
  11078. EXPECT_EQ(StatusCode::OK_200, result->status);
  11079. }
  11080. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11081. Server svr;
  11082. svr.set_keep_alive_max_count(0);
  11083. std::set<int> remote_ports;
  11084. svr.Get("/hi", [&](const Request &req, Response &res) {
  11085. remote_ports.insert(req.remote_port);
  11086. res.set_content("hi", "text/plain");
  11087. });
  11088. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11089. auto se = detail::scope_exit([&] {
  11090. svr.stop();
  11091. listen_thread.join();
  11092. ASSERT_FALSE(svr.is_running());
  11093. });
  11094. svr.wait_until_ready();
  11095. Client cli(HOST, PORT);
  11096. cli.set_keep_alive(true);
  11097. for (int i = 0; i < 3; i++) {
  11098. auto res = cli.Get("/hi");
  11099. ASSERT_TRUE(res);
  11100. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11101. }
  11102. // All three over one connection
  11103. EXPECT_EQ(1u, remote_ports.size());
  11104. }
  11105. TEST(KeepAliveTest, Issue1959) {
  11106. Server svr;
  11107. svr.set_keep_alive_timeout(5);
  11108. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11109. res.set_content("a", "text/plain");
  11110. });
  11111. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11112. auto se = detail::scope_exit([&] {
  11113. if (!svr.is_running()) return;
  11114. svr.stop();
  11115. listen_thread.join();
  11116. ASSERT_FALSE(svr.is_running());
  11117. });
  11118. svr.wait_until_ready();
  11119. Client cli("localhost", PORT);
  11120. cli.set_keep_alive(true);
  11121. using namespace std::chrono;
  11122. auto start = steady_clock::now();
  11123. cli.Get("/a");
  11124. svr.stop();
  11125. listen_thread.join();
  11126. auto end = steady_clock::now();
  11127. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11128. EXPECT_LT(elapsed, 5000);
  11129. }
  11130. #ifdef CPPHTTPLIB_SSL_ENABLED
  11131. TEST(KeepAliveTest, SSLClientReconnection) {
  11132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11133. ASSERT_TRUE(svr.is_valid());
  11134. svr.set_keep_alive_timeout(1);
  11135. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11136. res.set_content("Hello World!", "text/plain");
  11137. });
  11138. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11139. auto se = detail::scope_exit([&] {
  11140. svr.stop();
  11141. listen_thread.join();
  11142. ASSERT_FALSE(svr.is_running());
  11143. });
  11144. svr.wait_until_ready();
  11145. SSLClient cli(HOST, PORT);
  11146. cli.enable_server_certificate_verification(false);
  11147. cli.set_keep_alive(true);
  11148. auto result = cli.Get("/hi");
  11149. ASSERT_TRUE(result);
  11150. EXPECT_EQ(StatusCode::OK_200, result->status);
  11151. result = cli.Get("/hi");
  11152. ASSERT_TRUE(result);
  11153. EXPECT_EQ(StatusCode::OK_200, result->status);
  11154. std::this_thread::sleep_for(std::chrono::seconds(2));
  11155. // Recoonect
  11156. result = cli.Get("/hi");
  11157. ASSERT_TRUE(result);
  11158. EXPECT_EQ(StatusCode::OK_200, result->status);
  11159. result = cli.Get("/hi");
  11160. ASSERT_TRUE(result);
  11161. EXPECT_EQ(StatusCode::OK_200, result->status);
  11162. }
  11163. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11164. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11165. ASSERT_TRUE(svr.is_valid());
  11166. svr.set_keep_alive_timeout(1);
  11167. std::string content = "reconnect";
  11168. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11169. res.set_content("Hello World!", "text/plain");
  11170. });
  11171. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11172. auto se = detail::scope_exit([&] {
  11173. svr.stop();
  11174. listen_thread.join();
  11175. ASSERT_FALSE(svr.is_running());
  11176. });
  11177. svr.wait_until_ready();
  11178. SSLClient cli(HOST, PORT);
  11179. cli.enable_server_certificate_verification(false);
  11180. cli.set_keep_alive(true);
  11181. auto result = cli.Post(
  11182. "/hi", content.size(),
  11183. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11184. sink.write(content.c_str(), content.size());
  11185. return true;
  11186. },
  11187. "text/plain");
  11188. ASSERT_TRUE(result);
  11189. EXPECT_EQ(200, result->status);
  11190. std::this_thread::sleep_for(std::chrono::seconds(2));
  11191. // Recoonect
  11192. result = cli.Post(
  11193. "/hi", content.size(),
  11194. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11195. sink.write(content.c_str(), content.size());
  11196. return true;
  11197. },
  11198. "text/plain");
  11199. ASSERT_TRUE(result);
  11200. EXPECT_EQ(200, result->status);
  11201. result = cli.Post(
  11202. "/hi", content.size(),
  11203. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11204. sink.write(content.c_str(), content.size());
  11205. return true;
  11206. },
  11207. "text/plain");
  11208. ASSERT_TRUE(result);
  11209. EXPECT_EQ(200, result->status);
  11210. }
  11211. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11212. using namespace httplib::tls;
  11213. {
  11214. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11215. ASSERT_TRUE(svr.is_valid());
  11216. svr.Get("/sni", [&](const Request &req, Response &res) {
  11217. std::string expected = req.sni();
  11218. EXPECT_EQ(expected, req.get_param_value("expected"));
  11219. res.set_content("ok", "text/plain");
  11220. });
  11221. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11222. auto se = detail::scope_exit([&] {
  11223. svr.stop();
  11224. listen_thread.join();
  11225. ASSERT_FALSE(svr.is_running());
  11226. });
  11227. svr.wait_until_ready();
  11228. {
  11229. SSLClient cli("localhost", PORT);
  11230. cli.enable_server_certificate_verification(false);
  11231. auto res = cli.Get("/sni?expected=localhost");
  11232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11233. }
  11234. {
  11235. SSLClient cli("::1", PORT);
  11236. cli.enable_server_certificate_verification(false);
  11237. auto res = cli.Get("/sni?expected=");
  11238. // NOTE: This may fail if the server is listening on IPv4 only
  11239. // (e.g., when localhost resolves to 127.0.0.1 only)
  11240. if (res) {
  11241. EXPECT_EQ(StatusCode::OK_200, res->status);
  11242. } else {
  11243. EXPECT_EQ(Error::Connection, res.error());
  11244. }
  11245. }
  11246. }
  11247. }
  11248. // The SNI of a failed handshake does not reach the next connection that the
  11249. // same worker thread serves
  11250. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11251. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11252. ASSERT_TRUE(svr.is_valid());
  11253. svr.new_task_queue = [] { return new ThreadPool(1); };
  11254. svr.Get("/sni", [](const Request &req, Response &res) {
  11255. res.set_content(req.sni(), "text/plain");
  11256. });
  11257. auto port = svr.bind_to_any_port("127.0.0.1");
  11258. ASSERT_LT(0, port);
  11259. thread t = thread([&] { svr.listen_after_bind(); });
  11260. auto se = detail::scope_exit([&] {
  11261. svr.stop();
  11262. t.join();
  11263. ASSERT_FALSE(svr.is_running());
  11264. });
  11265. svr.wait_until_ready();
  11266. {
  11267. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11268. SSLClient cli("localhost", port);
  11269. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11270. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11271. auto res = cli.Get("/sni");
  11272. ASSERT_FALSE(res);
  11273. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11274. }
  11275. // An IP host sends no SNI (RFC 6066)
  11276. SSLClient cli("127.0.0.1", port);
  11277. cli.enable_server_certificate_verification(false);
  11278. auto res = cli.Get("/sni");
  11279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11280. EXPECT_EQ("", res->body);
  11281. }
  11282. #endif
  11283. TEST(ClientProblemDetectionTest, ContentProvider) {
  11284. Server svr;
  11285. size_t content_length = 1024 * 1024;
  11286. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11287. res.set_content_provider(
  11288. content_length, "text/plain",
  11289. [&](size_t offset, size_t length, DataSink &sink) {
  11290. auto out_len = std::min(length, static_cast<size_t>(1024));
  11291. std::string out(out_len, '@');
  11292. sink.write(out.data(), out_len);
  11293. return offset < 4096;
  11294. },
  11295. [](bool success) { ASSERT_FALSE(success); });
  11296. });
  11297. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11298. res.set_content_provider(
  11299. 0, "text/plain",
  11300. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11301. EXPECT_TRUE(false);
  11302. return true;
  11303. },
  11304. [](bool success) { ASSERT_FALSE(success); });
  11305. });
  11306. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11307. auto se = detail::scope_exit([&] {
  11308. svr.stop();
  11309. listen_thread.join();
  11310. ASSERT_FALSE(svr.is_running());
  11311. });
  11312. svr.wait_until_ready();
  11313. Client cli("localhost", PORT);
  11314. {
  11315. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11316. size_t /*data_length*/) { return false; });
  11317. ASSERT_FALSE(res);
  11318. }
  11319. {
  11320. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11321. size_t /*data_length*/) { return false; });
  11322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11323. }
  11324. }
  11325. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11326. // A provider that reports success without writing anything and without
  11327. // calling done() used to be handed the same offset and length again on every
  11328. // pass, so it spun for as long as the peer stayed connected.
  11329. Server svr;
  11330. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11331. res.set_content("ok", "text/plain");
  11332. });
  11333. auto port = svr.bind_to_any_port(HOST);
  11334. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11335. auto se = detail::scope_exit([&] {
  11336. svr.stop();
  11337. listen_thread.join();
  11338. ASSERT_FALSE(svr.is_running());
  11339. });
  11340. svr.wait_until_ready();
  11341. std::atomic<int> call_count{0};
  11342. Client cli(HOST, port);
  11343. auto res = cli.Post(
  11344. "/", 1024,
  11345. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11346. // Give up after enough passes to show the spin, so that losing the
  11347. // check below fails this test instead of hanging it.
  11348. return ++call_count < 100;
  11349. },
  11350. "text/plain");
  11351. ASSERT_FALSE(res);
  11352. EXPECT_EQ(Error::Write, res.error());
  11353. EXPECT_EQ(1, call_count.load());
  11354. }
  11355. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11356. // A writer only has to assign `write`. The other three used to be left as
  11357. // empty std::functions, so a provider calling one threw
  11358. // std::bad_function_call out of the thread running it and took the whole
  11359. // process down.
  11360. DataSink sink;
  11361. std::string written;
  11362. sink.write = [&](const char *data, size_t data_len) {
  11363. written.append(data, data_len);
  11364. return true;
  11365. };
  11366. EXPECT_TRUE(sink.is_writable());
  11367. sink.done();
  11368. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11369. EXPECT_TRUE(written.empty());
  11370. }
  11371. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11372. // A sink that cannot carry trailers still has to finish.
  11373. DataSink sink;
  11374. auto done_count = 0;
  11375. sink.done = [&]() { done_count++; };
  11376. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11377. EXPECT_EQ(1, done_count);
  11378. }
  11379. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11380. Server svr;
  11381. const std::string body(4096, 'x');
  11382. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11383. res.set_content_provider(body.size(), "text/plain",
  11384. [&](size_t offset, size_t length, DataSink &sink) {
  11385. sink.write(body.data() + offset, length);
  11386. sink.done();
  11387. return true;
  11388. });
  11389. });
  11390. auto port = svr.bind_to_any_port(HOST);
  11391. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11392. auto se = detail::scope_exit([&] {
  11393. svr.stop();
  11394. listen_thread.join();
  11395. ASSERT_FALSE(svr.is_running());
  11396. });
  11397. svr.wait_until_ready();
  11398. Client cli(HOST, port);
  11399. auto res = cli.Get("/");
  11400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11401. EXPECT_EQ(StatusCode::OK_200, res->status);
  11402. EXPECT_EQ(body, res->body);
  11403. }
  11404. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11405. Server svr;
  11406. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11407. res.set_content_provider(
  11408. 1024, "text/plain",
  11409. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11410. sink.write("hello", 5);
  11411. sink.done(); // short of the 1024 bytes the response promised
  11412. return true;
  11413. });
  11414. });
  11415. auto port = svr.bind_to_any_port(HOST);
  11416. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11417. auto se = detail::scope_exit([&] {
  11418. svr.stop();
  11419. listen_thread.join();
  11420. ASSERT_FALSE(svr.is_running());
  11421. });
  11422. svr.wait_until_ready();
  11423. Client cli(HOST, port);
  11424. cli.set_read_timeout(5, 0);
  11425. // The response is short of its Content-Length, so the client cannot read a
  11426. // complete body. What matters is that this returns at all: a no-op done()
  11427. // would leave the writer looping over a provider that never makes progress.
  11428. auto res = cli.Get("/");
  11429. EXPECT_FALSE(res);
  11430. }
  11431. // Read as the next response by a peer that sees it after a framed body.
  11432. static const std::string smuggled_response =
  11433. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11434. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11435. Server svr;
  11436. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11437. res.set_content_provider(
  11438. 5, "text/plain",
  11439. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11440. auto data = "AAAAA" + smuggled_response;
  11441. sink.write(data.data(), data.size());
  11442. return true;
  11443. });
  11444. });
  11445. thread t = thread([&] { svr.listen(HOST, PORT); });
  11446. auto se = detail::scope_exit([&] {
  11447. svr.stop();
  11448. t.join();
  11449. ASSERT_FALSE(svr.is_running());
  11450. });
  11451. svr.wait_until_ready();
  11452. std::string resp;
  11453. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11454. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11455. resp.clear();
  11456. ASSERT_TRUE(send_request(
  11457. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11458. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11459. }
  11460. TEST(NoContentTest, BodyIsNotSent) {
  11461. Server svr;
  11462. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11463. res.status = StatusCode::NoContent_204;
  11464. res.set_content(smuggled_response, "text/plain");
  11465. });
  11466. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11467. res.status = StatusCode::NotModified_304;
  11468. res.set_chunked_content_provider(
  11469. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11470. sink.write(smuggled_response.data(), smuggled_response.size());
  11471. sink.done();
  11472. return true;
  11473. });
  11474. });
  11475. thread t = thread([&] { svr.listen(HOST, PORT); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. t.join();
  11479. ASSERT_FALSE(svr.is_running());
  11480. });
  11481. svr.wait_until_ready();
  11482. for (auto path : {"/204", "/304"}) {
  11483. std::string resp;
  11484. ASSERT_TRUE(send_request(
  11485. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11486. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11487. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11488. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11489. }
  11490. }
  11491. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11492. Server svr;
  11493. std::atomic<bool> smuggled(false);
  11494. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11495. res.set_content("ok", "text/plain");
  11496. });
  11497. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11498. smuggled = true;
  11499. });
  11500. auto port = svr.bind_to_any_port(HOST);
  11501. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11502. auto se = detail::scope_exit([&] {
  11503. svr.stop();
  11504. listen_thread.join();
  11505. ASSERT_FALSE(svr.is_running());
  11506. });
  11507. svr.wait_until_ready();
  11508. // What follows the body would be read as the next request.
  11509. Client cli(HOST, port);
  11510. auto res = cli.Post(
  11511. "/", 5,
  11512. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11513. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11514. sink.write(data.data(), data.size());
  11515. return true;
  11516. },
  11517. "text/plain");
  11518. ASSERT_FALSE(res);
  11519. EXPECT_EQ(Error::Write, res.error());
  11520. EXPECT_FALSE(smuggled);
  11521. }
  11522. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11523. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11524. // The compressed path builds the whole body before connecting, so this
  11525. // fails client-side and never reaches a server.
  11526. Client cli(HOST, PORT);
  11527. cli.set_compress(true);
  11528. auto res = cli.Post(
  11529. "/", 1024,
  11530. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11531. sink.write("hello", 5);
  11532. sink.done(); // short of the 1024 bytes the request announced
  11533. return true;
  11534. },
  11535. "text/plain");
  11536. ASSERT_FALSE(res);
  11537. EXPECT_EQ(Error::Write, res.error());
  11538. }
  11539. #endif
  11540. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11541. Server svr;
  11542. svr.set_error_handler([](Request const &, Response &res) -> void {
  11543. res.set_chunked_content_provider(
  11544. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11545. sink.os << "hello";
  11546. sink.os << "world";
  11547. sink.done();
  11548. return true;
  11549. });
  11550. });
  11551. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11552. auto se = detail::scope_exit([&] {
  11553. svr.stop();
  11554. listen_thread.join();
  11555. ASSERT_FALSE(svr.is_running());
  11556. });
  11557. svr.wait_until_ready();
  11558. Client cli("localhost", PORT);
  11559. auto res = cli.Get("/");
  11560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11561. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11562. EXPECT_EQ("helloworld", res->body);
  11563. }
  11564. // A body set after a content provider must replace it, not be sent through it.
  11565. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11566. Server svr;
  11567. svr.set_mount_point("/", "./www");
  11568. svr.set_file_request_handler([](const Request &req, Response &res) {
  11569. if (req.path == "/dir/test.html") {
  11570. res.status = StatusCode::Forbidden_403;
  11571. res.set_content(std::string(5000, 'D'), "text/plain");
  11572. } else if (req.path == "/file") {
  11573. res.status = StatusCode::Forbidden_403;
  11574. res.body = "Denied";
  11575. }
  11576. });
  11577. auto port = svr.bind_to_any_port(HOST);
  11578. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11579. auto se = detail::scope_exit([&] {
  11580. svr.stop();
  11581. t.join();
  11582. ASSERT_FALSE(svr.is_running());
  11583. });
  11584. svr.wait_until_ready();
  11585. Client cli(HOST, port);
  11586. {
  11587. auto res = cli.Get("/dir/test.html");
  11588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11589. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11590. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11591. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11592. }
  11593. {
  11594. auto res = cli.Get("/file");
  11595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11596. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11597. EXPECT_EQ("Denied", res->body);
  11598. }
  11599. {
  11600. auto res = cli.Get("/dir/index.html");
  11601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11602. EXPECT_EQ(StatusCode::OK_200, res->status);
  11603. EXPECT_EQ(0U, res->body.find("<html>"));
  11604. }
  11605. }
  11606. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11607. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11608. Server svr;
  11609. std::vector<bool> released;
  11610. std::mutex released_mutex;
  11611. auto releaser = [&](bool success) {
  11612. std::lock_guard<std::mutex> guard(released_mutex);
  11613. released.push_back(success);
  11614. };
  11615. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11616. return sink.write(&"hello"[offset], length);
  11617. };
  11618. svr.Get("/sized", [&](const Request &, Response &res) {
  11619. res.status = StatusCode::NotFound_404;
  11620. res.set_content_provider(5, "text/plain", provider, releaser);
  11621. });
  11622. svr.Get("/chunked", [&](const Request &, Response &res) {
  11623. res.status = StatusCode::ServiceUnavailable_503;
  11624. res.set_chunked_content_provider(
  11625. "text/plain",
  11626. [](size_t, DataSink &sink) {
  11627. sink.os << "chunk";
  11628. sink.done();
  11629. return true;
  11630. },
  11631. releaser);
  11632. });
  11633. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11634. res.set_content_provider(5, "text/plain", provider, releaser);
  11635. throw std::runtime_error("after the provider");
  11636. });
  11637. svr.set_error_handler([](const Request &req, Response &res) {
  11638. // Leave the exception handler's content to it.
  11639. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11640. res.set_content(std::string(1000, 'E'), "text/html");
  11641. return Server::HandlerResponse::Handled;
  11642. });
  11643. svr.set_exception_handler(
  11644. [](const Request &, Response &res, std::exception_ptr) {
  11645. res.status = StatusCode::InternalServerError_500;
  11646. res.set_content(std::string(1000, 'X'), "text/html");
  11647. });
  11648. auto port = svr.bind_to_any_port(HOST);
  11649. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11650. auto se = detail::scope_exit([&] {
  11651. svr.stop();
  11652. t.join();
  11653. ASSERT_FALSE(svr.is_running());
  11654. });
  11655. svr.wait_until_ready();
  11656. Client cli(HOST, port);
  11657. {
  11658. auto res = cli.Get("/sized");
  11659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11660. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11661. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11662. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11663. }
  11664. {
  11665. auto res = cli.Get("/chunked");
  11666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11667. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11668. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11669. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11670. }
  11671. {
  11672. auto res = cli.Get("/throw");
  11673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11674. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11675. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11676. }
  11677. std::lock_guard<std::mutex> guard(released_mutex);
  11678. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11679. }
  11680. #endif
  11681. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11682. Server svr;
  11683. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11684. return sink.write(&"abc"[offset], length);
  11685. };
  11686. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11687. res.set_file_content("./www/dir/test.html");
  11688. res.set_content("body", "text/plain");
  11689. });
  11690. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11691. res.set_content(std::string(100, 'B'), "text/plain");
  11692. res.set_file_content("./www/dir/test.html");
  11693. });
  11694. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11695. res.set_content(std::string(100, 'B'), "text/plain");
  11696. res.set_content_provider(3, "text/x-provider", abc);
  11697. });
  11698. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11699. res.set_content_provider(3, "text/x-provider", abc);
  11700. res.set_content(std::string(100, 'B'), "text/plain");
  11701. });
  11702. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11703. res.set_content_provider(3, "text/x-provider", abc);
  11704. res.set_file_content("./www/dir/test.html", "text/x-file");
  11705. });
  11706. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11707. res.set_file_content("./www/dir/test.html");
  11708. res.set_header("Content-Type", "text/x-handler");
  11709. });
  11710. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11711. res.set_content_provider(3, "text/plain", abc);
  11712. res.body = "direct";
  11713. });
  11714. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11715. res.set_file_content("./www/dir/test.html");
  11716. res.body = "direct";
  11717. });
  11718. auto port = svr.bind_to_any_port(HOST);
  11719. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11720. auto se = detail::scope_exit([&] {
  11721. svr.stop();
  11722. t.join();
  11723. ASSERT_FALSE(svr.is_running());
  11724. });
  11725. svr.wait_until_ready();
  11726. Client cli(HOST, port);
  11727. auto expect_body = [&](const char *path, const std::string &body,
  11728. const std::string &type) {
  11729. // Uncompressed, so Content-Length can be compared with the body.
  11730. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11731. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11732. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11733. EXPECT_EQ(body, res->body) << path;
  11734. EXPECT_EQ(std::to_string(body.size()),
  11735. res->get_header_value("Content-Length"))
  11736. << path;
  11737. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11738. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11739. };
  11740. expect_body("/file-then-body", "body", "text/plain");
  11741. expect_body("/body-then-file", "test.html", "text/html");
  11742. expect_body("/body-then-provider", "abc", "text/x-provider");
  11743. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11744. expect_body("/provider-then-file", "test.html", "text/x-file");
  11745. expect_body("/file-then-header", "test.html", "text/x-handler");
  11746. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11747. expect_body("/file-then-direct-body", "direct", "text/plain");
  11748. // Ranges are checked against the body, not the dropped provider.
  11749. {
  11750. auto res = cli.Get("/provider-then-direct-body",
  11751. Headers{{make_range_header({{1, 2}})}});
  11752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11753. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11754. EXPECT_EQ("ir", res->body);
  11755. }
  11756. {
  11757. auto res = cli.Get("/file-then-direct-body",
  11758. Headers{{make_range_header({{7, 8}})}});
  11759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11760. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11761. }
  11762. }
  11763. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11764. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11765. const char *path = "./truncated_while_served.txt";
  11766. const size_t size = 32 * 1024 * 1024;
  11767. {
  11768. std::ofstream f(path, std::ios::binary);
  11769. f << std::string(size, 'x');
  11770. }
  11771. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11772. // Over TLS, where the bytes are encrypted in this process rather than
  11773. // copied by send().
  11774. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11775. svr.Get("/file", [&](const Request &, Response &res) {
  11776. res.set_file_content(path, "text/plain");
  11777. });
  11778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11779. auto se = detail::scope_exit([&] {
  11780. svr.stop();
  11781. thread.join();
  11782. ASSERT_FALSE(svr.is_running());
  11783. });
  11784. svr.wait_until_ready();
  11785. // The file shrinks once the first bytes are in, as a rewrite in place
  11786. // would, and reading the mapping past its new end used to raise SIGBUS.
  11787. SSLClient cli(HOST, PORT);
  11788. cli.enable_server_certificate_verification(false);
  11789. size_t received = 0;
  11790. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11791. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11792. received += len;
  11793. return true;
  11794. });
  11795. EXPECT_FALSE(res);
  11796. EXPECT_LT(received, size);
  11797. }
  11798. #endif
  11799. // Forward declaration (see the base64_encode note).
  11800. namespace httplib {
  11801. namespace detail {
  11802. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11803. const std::string &content_type,
  11804. EncodingType encoding);
  11805. } // namespace detail
  11806. } // namespace httplib
  11807. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11808. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11809. ASSERT_TRUE(mm->is_open());
  11810. Response res;
  11811. detail::set_file_content_provider(res, mm, "text/html",
  11812. detail::EncodingType::None);
  11813. std::string out;
  11814. DataSink sink;
  11815. sink.write = [&](const char *d, size_t l) {
  11816. out.append(d, l);
  11817. return true;
  11818. };
  11819. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11820. EXPECT_EQ("test.html", out);
  11821. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11822. EXPECT_EQ("test.html", out);
  11823. }
  11824. TEST(LongPollingTest, ClientCloseDetection) {
  11825. Server svr;
  11826. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11827. res.set_chunked_content_provider(
  11828. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11829. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11830. sink.os << "hello";
  11831. auto count = 10;
  11832. while (count > 0 && sink.is_writable()) {
  11833. this_thread::sleep_for(chrono::milliseconds(10));
  11834. count--;
  11835. }
  11836. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11837. return true;
  11838. });
  11839. });
  11840. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11841. auto se = detail::scope_exit([&] {
  11842. svr.stop();
  11843. listen_thread.join();
  11844. ASSERT_FALSE(svr.is_running());
  11845. });
  11846. svr.wait_until_ready();
  11847. Client cli("localhost", PORT);
  11848. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11849. EXPECT_EQ("hello", string(data, data_length));
  11850. return false; // close the socket immediately.
  11851. });
  11852. ASSERT_FALSE(res);
  11853. }
  11854. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11855. Server svr;
  11856. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11857. res.set_chunked_content_provider(
  11858. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11859. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11860. sink.os << "hello";
  11861. EXPECT_TRUE(sink.os.good());
  11862. // Wait for the client to close the connection
  11863. auto count = 10;
  11864. while (count > 0 && sink.is_writable()) {
  11865. this_thread::sleep_for(chrono::milliseconds(10));
  11866. count--;
  11867. }
  11868. // After client disconnect, write repeatedly until the socket
  11869. // write actually fails (small writes may be absorbed by the
  11870. // kernel buffer)
  11871. std::string chunk(1024, 'x');
  11872. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11873. sink.os << chunk;
  11874. }
  11875. EXPECT_TRUE(sink.os.fail());
  11876. return true;
  11877. });
  11878. });
  11879. auto port = svr.bind_to_any_port("localhost");
  11880. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11881. auto se = detail::scope_exit([&] {
  11882. svr.stop();
  11883. listen_thread.join();
  11884. ASSERT_FALSE(svr.is_running());
  11885. });
  11886. svr.wait_until_ready();
  11887. Client cli("localhost", port);
  11888. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11889. EXPECT_EQ("hello", string(data, data_length));
  11890. return false; // close the socket immediately.
  11891. });
  11892. ASSERT_FALSE(res);
  11893. }
  11894. TEST(GetWithParametersTest, GetWithParameters) {
  11895. Server svr;
  11896. svr.Get("/", [&](const Request &req, Response &) {
  11897. EXPECT_EQ("world", req.get_param_value("hello"));
  11898. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11899. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11900. });
  11901. svr.Get("/params", [&](const Request &req, Response &) {
  11902. EXPECT_EQ("world", req.get_param_value("hello"));
  11903. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11904. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11905. });
  11906. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11907. EXPECT_EQ("resource-id", req.matches[1]);
  11908. EXPECT_EQ("foo", req.get_param_value("param1"));
  11909. EXPECT_EQ("bar", req.get_param_value("param2"));
  11910. });
  11911. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11912. EXPECT_EQ("user-id", req.path_params.at("id"));
  11913. EXPECT_EQ("foo", req.get_param_value("param1"));
  11914. EXPECT_EQ("bar", req.get_param_value("param2"));
  11915. });
  11916. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11917. auto se = detail::scope_exit([&] {
  11918. svr.stop();
  11919. listen_thread.join();
  11920. ASSERT_FALSE(svr.is_running());
  11921. });
  11922. svr.wait_until_ready();
  11923. {
  11924. Client cli(HOST, PORT);
  11925. Params params;
  11926. params.emplace("hello", "world");
  11927. params.emplace("hello2", "world2");
  11928. params.emplace("hello3", "world3");
  11929. auto res = cli.Get("/", params, Headers{});
  11930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11931. EXPECT_EQ(StatusCode::OK_200, res->status);
  11932. }
  11933. {
  11934. Client cli(HOST, PORT);
  11935. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11937. EXPECT_EQ(StatusCode::OK_200, res->status);
  11938. }
  11939. {
  11940. Client cli(HOST, PORT);
  11941. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11943. EXPECT_EQ(StatusCode::OK_200, res->status);
  11944. }
  11945. {
  11946. Client cli(HOST, PORT);
  11947. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11949. EXPECT_EQ(StatusCode::OK_200, res->status);
  11950. }
  11951. }
  11952. TEST(GetWithParametersTest, GetWithParameters2) {
  11953. Server svr;
  11954. svr.Get("/", [&](const Request &req, Response &res) {
  11955. auto text = req.get_param_value("hello");
  11956. res.set_content(text, "text/plain");
  11957. });
  11958. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11959. auto se = detail::scope_exit([&] {
  11960. svr.stop();
  11961. listen_thread.join();
  11962. ASSERT_FALSE(svr.is_running());
  11963. });
  11964. svr.wait_until_ready();
  11965. Client cli("localhost", PORT);
  11966. Params params;
  11967. params.emplace("hello", "world");
  11968. std::string body;
  11969. auto res = cli.Get("/", params, Headers{},
  11970. [&](const char *data, size_t data_length) {
  11971. body.append(data, data_length);
  11972. return true;
  11973. });
  11974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11975. EXPECT_EQ(StatusCode::OK_200, res->status);
  11976. EXPECT_EQ("world", body);
  11977. }
  11978. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11979. Server svr;
  11980. svr.Get("/search", [&](const Request &req, Response &res) {
  11981. auto q = req.get_param_value("q");
  11982. res.set_content(q, "text/plain");
  11983. });
  11984. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11985. auto se = detail::scope_exit([&] {
  11986. svr.stop();
  11987. listen_thread.join();
  11988. ASSERT_FALSE(svr.is_running());
  11989. });
  11990. svr.wait_until_ready();
  11991. Client cli("localhost", PORT);
  11992. // Verify that Get(path, params) works without requiring Headers argument
  11993. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11995. EXPECT_EQ(StatusCode::OK_200, res->status);
  11996. EXPECT_EQ("cpp-httplib", res->body);
  11997. }
  11998. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11999. auto host = "httpbingo.org";
  12000. auto path = std::string{"/range/32"};
  12001. #ifdef CPPHTTPLIB_SSL_ENABLED
  12002. SSLClient cli(host);
  12003. #else
  12004. Client cli(host);
  12005. #endif
  12006. cli.set_default_headers({make_range_header({{1, 10}})});
  12007. cli.set_connection_timeout(5);
  12008. {
  12009. auto res = cli.Get(path);
  12010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12011. EXPECT_EQ("bcdefghijk", res->body);
  12012. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12013. }
  12014. {
  12015. auto res = cli.Get(path);
  12016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12017. EXPECT_EQ("bcdefghijk", res->body);
  12018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12019. }
  12020. }
  12021. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12022. Server svr;
  12023. svr.set_default_headers({{"Hello", "World"}});
  12024. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12025. res.set_content("ok", "text/plain");
  12026. });
  12027. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12028. auto se = detail::scope_exit([&] {
  12029. svr.stop();
  12030. listen_thread.join();
  12031. ASSERT_FALSE(svr.is_running());
  12032. });
  12033. svr.wait_until_ready();
  12034. Client cli("localhost", PORT);
  12035. auto res = cli.Get("/");
  12036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12037. EXPECT_EQ(StatusCode::OK_200, res->status);
  12038. EXPECT_EQ("ok", res->body);
  12039. EXPECT_EQ("World", res->get_header_value("Hello"));
  12040. }
  12041. #ifdef CPPHTTPLIB_SSL_ENABLED
  12042. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12044. ASSERT_TRUE(svr.is_valid());
  12045. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12046. std::this_thread::sleep_for(std::chrono::seconds(2));
  12047. res.set_content("a", "text/plain");
  12048. });
  12049. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12050. res.set_content("b", "text/plain");
  12051. });
  12052. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12053. auto se = detail::scope_exit([&] {
  12054. svr.stop();
  12055. listen_thread.join();
  12056. ASSERT_FALSE(svr.is_running());
  12057. });
  12058. svr.wait_until_ready();
  12059. SSLClient cli("localhost", PORT);
  12060. cli.enable_server_certificate_verification(false);
  12061. cli.set_keep_alive(true);
  12062. cli.set_read_timeout(std::chrono::seconds(1));
  12063. auto resa = cli.Get("/a");
  12064. ASSERT_TRUE(!resa);
  12065. EXPECT_EQ(Error::Read, resa.error());
  12066. auto resb = cli.Get("/b");
  12067. ASSERT_TRUE(resb);
  12068. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12069. EXPECT_EQ("b", resb->body);
  12070. }
  12071. // Closing an idle keep-alive connection sends close_notify and returns. The
  12072. // server must not wait for the client's close_notify: an idle client never
  12073. // sends one, so the worker would be held until the read timeout expires, and
  12074. // stop() would wait for it.
  12075. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12076. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12077. ASSERT_TRUE(svr.is_valid());
  12078. svr.set_keep_alive_timeout(1);
  12079. svr.set_read_timeout(10, 0);
  12080. svr.Get("/", [](const Request &, Response &res) {
  12081. res.set_content("ok", "text/plain");
  12082. });
  12083. auto port = svr.bind_to_any_port(HOST);
  12084. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12085. auto se = detail::scope_exit([&] {
  12086. if (listen_thread.joinable()) {
  12087. svr.stop();
  12088. listen_thread.join();
  12089. }
  12090. });
  12091. svr.wait_until_ready();
  12092. SSLClient cli(HOST, port);
  12093. cli.enable_server_certificate_verification(false);
  12094. cli.set_keep_alive(true);
  12095. auto res = cli.Get("/");
  12096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12097. EXPECT_EQ(StatusCode::OK_200, res->status);
  12098. // Stay idle past the keep-alive timeout so the server closes the connection.
  12099. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12100. auto start = std::chrono::steady_clock::now();
  12101. svr.stop();
  12102. listen_thread.join();
  12103. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12104. std::chrono::steady_clock::now() - start)
  12105. .count();
  12106. EXPECT_LT(elapsed, 3000);
  12107. }
  12108. #endif
  12109. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12110. protected:
  12111. ServerTestWithAI_PASSIVE()
  12112. : cli_(HOST, PORT)
  12113. #ifdef CPPHTTPLIB_SSL_ENABLED
  12114. ,
  12115. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12116. #endif
  12117. {
  12118. #ifdef CPPHTTPLIB_SSL_ENABLED
  12119. cli_.enable_server_certificate_verification(false);
  12120. #endif
  12121. }
  12122. virtual void SetUp() {
  12123. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12124. res.set_content("Hello World!", "text/plain");
  12125. });
  12126. t_ = thread(
  12127. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12128. svr_.wait_until_ready();
  12129. }
  12130. virtual void TearDown() {
  12131. svr_.stop();
  12132. t_.join();
  12133. }
  12134. #ifdef CPPHTTPLIB_SSL_ENABLED
  12135. SSLClient cli_;
  12136. SSLServer svr_;
  12137. #else
  12138. Client cli_;
  12139. Server svr_;
  12140. #endif
  12141. thread t_;
  12142. };
  12143. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12144. auto res = cli_.Get("/hi");
  12145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12146. EXPECT_EQ(StatusCode::OK_200, res->status);
  12147. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12148. EXPECT_EQ("Hello World!", res->body);
  12149. }
  12150. class ServerUpDownTest : public ::testing::Test {
  12151. protected:
  12152. ServerUpDownTest() : cli_(HOST, PORT) {}
  12153. virtual void SetUp() {
  12154. t_ = thread([&]() {
  12155. svr_.bind_to_any_port(HOST);
  12156. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12157. ASSERT_TRUE(svr_.listen_after_bind());
  12158. });
  12159. svr_.wait_until_ready();
  12160. }
  12161. virtual void TearDown() {
  12162. svr_.stop();
  12163. t_.join();
  12164. }
  12165. Client cli_;
  12166. Server svr_;
  12167. thread t_;
  12168. };
  12169. TEST_F(ServerUpDownTest, QuickStartStop) {
  12170. // Should not crash, especially when run with
  12171. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12172. }
  12173. class PayloadMaxLengthTest : public ::testing::Test {
  12174. protected:
  12175. PayloadMaxLengthTest()
  12176. : cli_(HOST, PORT)
  12177. #ifdef CPPHTTPLIB_SSL_ENABLED
  12178. ,
  12179. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12180. #endif
  12181. {
  12182. #ifdef CPPHTTPLIB_SSL_ENABLED
  12183. cli_.enable_server_certificate_verification(false);
  12184. #endif
  12185. }
  12186. virtual void SetUp() {
  12187. svr_.set_payload_max_length(8);
  12188. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12189. res.set_content("test", "text/plain");
  12190. });
  12191. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12192. svr_.wait_until_ready();
  12193. }
  12194. virtual void TearDown() {
  12195. svr_.stop();
  12196. t_.join();
  12197. }
  12198. #ifdef CPPHTTPLIB_SSL_ENABLED
  12199. SSLClient cli_;
  12200. SSLServer svr_;
  12201. #else
  12202. Client cli_;
  12203. Server svr_;
  12204. #endif
  12205. thread t_;
  12206. };
  12207. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12208. auto res = cli_.Post("/test", "123456789", "text/plain");
  12209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12210. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12211. res = cli_.Post("/test", "12345678", "text/plain");
  12212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12213. EXPECT_EQ(StatusCode::OK_200, res->status);
  12214. }
  12215. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12216. // Test chunked encoding with payload exceeding the 8-byte limit
  12217. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12218. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12220. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12221. }
  12222. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12223. // Test chunked encoding with payload within the 8-byte limit
  12224. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12225. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12227. EXPECT_EQ(StatusCode::OK_200, res->status);
  12228. }
  12229. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12230. // Test using send_request to send chunked data exceeding payload limit
  12231. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12232. "Host: " +
  12233. std::string(HOST) + ":" + std::to_string(PORT) +
  12234. "\r\n"
  12235. "Transfer-Encoding: chunked\r\n"
  12236. "Connection: close\r\n"
  12237. "\r\n"
  12238. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12239. "0123456789\r\n"
  12240. "0\r\n" // End chunk
  12241. "\r\n";
  12242. std::string response;
  12243. bool result = send_request(1, chunked_request, &response);
  12244. if (!result) {
  12245. // If send_request fails, it might be because the server closed the
  12246. // connection due to payload limit enforcement, which is acceptable
  12247. SUCCEED()
  12248. << "Server rejected oversized chunked request (connection closed)";
  12249. } else {
  12250. // If we got a response, check if it's an error response or connection was
  12251. // closed early Short response length indicates connection was closed due to
  12252. // payload limit
  12253. if (response.length() <= 10) {
  12254. SUCCEED() << "Server closed connection for oversized chunked request";
  12255. } else {
  12256. // Check for error status codes
  12257. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12258. response.find("Payload Too Large") != std::string::npos ||
  12259. response.find("400") != std::string::npos);
  12260. }
  12261. }
  12262. }
  12263. class LargePayloadMaxLengthTest : public ::testing::Test {
  12264. protected:
  12265. LargePayloadMaxLengthTest()
  12266. : cli_(HOST, PORT)
  12267. #ifdef CPPHTTPLIB_SSL_ENABLED
  12268. ,
  12269. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12270. #endif
  12271. {
  12272. #ifdef CPPHTTPLIB_SSL_ENABLED
  12273. cli_.enable_server_certificate_verification(false);
  12274. #endif
  12275. }
  12276. virtual void SetUp() {
  12277. // Set 10MB payload limit
  12278. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12279. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12280. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12281. res.set_content("Large payload test", "text/plain");
  12282. });
  12283. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12284. svr_.wait_until_ready();
  12285. }
  12286. virtual void TearDown() {
  12287. svr_.stop();
  12288. t_.join();
  12289. }
  12290. #ifdef CPPHTTPLIB_SSL_ENABLED
  12291. SSLClient cli_;
  12292. SSLServer svr_;
  12293. #else
  12294. Client cli_;
  12295. Server svr_;
  12296. #endif
  12297. thread t_;
  12298. };
  12299. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12300. // Test chunked encoding with payload within 10MB limit
  12301. std::string medium_payload(5 * 1024 * 1024,
  12302. 'A'); // 5MB payload, within 10MB limit
  12303. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12305. EXPECT_EQ(StatusCode::OK_200, res->status);
  12306. }
  12307. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12308. // Test chunked encoding with payload exceeding 10MB limit
  12309. std::string large_payload(12 * 1024 * 1024,
  12310. 'B'); // 12MB payload, exceeds 10MB limit
  12311. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12312. // Server may either return 413 or close the connection
  12313. if (res) {
  12314. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12315. } else {
  12316. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12317. }
  12318. }
  12319. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12320. Server svr;
  12321. svr.Get("/", [](const Request &, Response &res) {
  12322. // Claims the most the client accepts, far more than it sends, then drops
  12323. // the connection.
  12324. res.set_content_provider(std::string().max_size(), "text/plain",
  12325. [](size_t, size_t, DataSink &sink) {
  12326. sink.write("abc", 3);
  12327. return false;
  12328. });
  12329. });
  12330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12331. auto se = detail::scope_exit([&] {
  12332. svr.stop();
  12333. thread.join();
  12334. ASSERT_FALSE(svr.is_running());
  12335. });
  12336. svr.wait_until_ready();
  12337. Client cli(HOST, PORT);
  12338. cli.set_payload_max_length(0);
  12339. EXPECT_FALSE(cli.Get("/"));
  12340. }
  12341. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12342. // Stream API does, not as a plain read failure
  12343. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12344. Server svr;
  12345. svr.Get("/big", [](const Request &, Response &res) {
  12346. res.set_content(std::string(100000, 'b'), "text/plain");
  12347. });
  12348. auto port = svr.bind_to_any_port(HOST);
  12349. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12350. auto se = detail::scope_exit([&] {
  12351. svr.stop();
  12352. thread.join();
  12353. });
  12354. svr.wait_until_ready();
  12355. Client cli(HOST, port);
  12356. cli.set_payload_max_length(1000);
  12357. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12358. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12359. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12360. [](const char *, size_t) { return true; });
  12361. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12362. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12363. // Small on the wire, over the limit once decompressed
  12364. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12365. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12366. #endif
  12367. }
  12368. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12369. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12370. // path.
  12371. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12372. Server svr;
  12373. const size_t LIMIT = 64 * 1024; // 64KB
  12374. svr.set_payload_max_length(LIMIT);
  12375. size_t total = 0;
  12376. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12377. const ContentReader &content_reader) {
  12378. content_reader([&](const char * /*data*/, size_t len) {
  12379. total += len;
  12380. return true;
  12381. });
  12382. res.status = 200;
  12383. res.set_content("stream_ok", "text/plain");
  12384. });
  12385. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12386. auto se = detail::scope_exit([&] {
  12387. svr.stop();
  12388. thread.join();
  12389. ASSERT_FALSE(svr.is_running());
  12390. });
  12391. svr.wait_until_ready();
  12392. // Prepare 256KB raw data and gzip-compress it
  12393. std::string raw(256 * 1024, 'A');
  12394. std::string gz;
  12395. {
  12396. z_stream zs{};
  12397. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12398. Z_DEFAULT_STRATEGY);
  12399. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12400. zs.avail_in = static_cast<uInt>(raw.size());
  12401. char outbuf[4096];
  12402. int ret;
  12403. do {
  12404. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12405. zs.avail_out = sizeof(outbuf);
  12406. ret = deflate(&zs, Z_FINISH);
  12407. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12408. } while (ret != Z_STREAM_END);
  12409. deflateEnd(&zs);
  12410. }
  12411. Client cli(HOST, PORT);
  12412. cli.set_connection_timeout(std::chrono::seconds(5));
  12413. Headers headers = {{"Content-Encoding", "gzip"}};
  12414. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12415. "application/octet-stream");
  12416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12417. // Server must reject oversized decompressed payloads with 413.
  12418. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12419. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12420. EXPECT_LE(total, LIMIT);
  12421. }
  12422. #endif
  12423. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12424. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12425. // the payload must be passed through untouched instead of being rejected.
  12426. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12427. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12428. Server svr;
  12429. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12430. res.set_content(body, "image/jpeg");
  12431. res.set_header("Content-Encoding", "UTF-8");
  12432. });
  12433. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12434. res.set_content(body, "image/jpeg");
  12435. res.set_header("Content-Encoding", "identity");
  12436. });
  12437. svr.Post("/echo", [](const Request &req, Response &res) {
  12438. res.set_content(req.body, "image/jpeg");
  12439. });
  12440. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12441. auto se = detail::scope_exit([&] {
  12442. svr.stop();
  12443. t.join();
  12444. ASSERT_FALSE(svr.is_running());
  12445. });
  12446. svr.wait_until_ready();
  12447. Client cli(HOST, PORT);
  12448. {
  12449. auto res = cli.Get("/image");
  12450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12451. EXPECT_EQ(StatusCode::OK_200, res->status);
  12452. EXPECT_EQ(body, res->body);
  12453. }
  12454. {
  12455. auto res = cli.Get("/identity");
  12456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12457. EXPECT_EQ(StatusCode::OK_200, res->status);
  12458. EXPECT_EQ(body, res->body);
  12459. }
  12460. {
  12461. // The same applies to a request body reaching the server.
  12462. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12463. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12465. EXPECT_EQ(StatusCode::OK_200, res->status);
  12466. EXPECT_EQ(body, res->body);
  12467. }
  12468. }
  12469. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12470. // gzip-encoded response even when the build has no zlib support.
  12471. static const char GZIPPED_HELLO_WORLD[] = {
  12472. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12473. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12474. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12475. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12476. // A content coding is a whole token, not something the field value merely
  12477. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12478. // as "fibre" look like Brotli, and turned a multi-coding value like
  12479. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12480. // it was never meant to see.
  12481. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12482. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12483. Server svr;
  12484. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12485. res.set_content(body, "image/jpeg");
  12486. res.set_header("Content-Encoding", "fibre");
  12487. });
  12488. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12489. res.set_content(body, "image/jpeg");
  12490. res.set_header("Content-Encoding", "gzip, br");
  12491. });
  12492. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12493. res.set_content(body, "image/jpeg");
  12494. res.set_header("Content-Encoding", "x-zstd-ish");
  12495. });
  12496. auto port = svr.bind_to_any_port(HOST);
  12497. thread t = thread([&]() { svr.listen_after_bind(); });
  12498. auto se = detail::scope_exit([&] {
  12499. svr.stop();
  12500. t.join();
  12501. ASSERT_FALSE(svr.is_running());
  12502. });
  12503. svr.wait_until_ready();
  12504. Client cli(HOST, port);
  12505. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12506. auto res = cli.Get(path);
  12507. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12508. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12509. // Not a coding we recognize, so the payload comes back untouched
  12510. EXPECT_EQ(body, res->body) << path;
  12511. }
  12512. }
  12513. // A content coding cpp-httplib recognizes but was not built with must be
  12514. // reported as such. Handing the still-compressed payload back to the caller
  12515. // would silently corrupt it.
  12516. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12517. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12518. Server svr;
  12519. // "image/jpeg" keeps the server from applying a content coding of its own,
  12520. // so the hand-crafted Content-Encoding below survives.
  12521. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12522. res.set_content(gzipped, "image/jpeg");
  12523. res.set_header("Content-Encoding", "gzip");
  12524. });
  12525. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12526. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12527. res.set_content(gzipped, "image/jpeg");
  12528. res.set_header("Content-Encoding", "GZIP");
  12529. });
  12530. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12531. auto se = detail::scope_exit([&] {
  12532. svr.stop();
  12533. t.join();
  12534. ASSERT_FALSE(svr.is_running());
  12535. });
  12536. svr.wait_until_ready();
  12537. Client cli(HOST, PORT);
  12538. {
  12539. auto res = cli.Get("/gzipped");
  12540. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12542. EXPECT_EQ("Hello World!", res->body);
  12543. #else
  12544. ASSERT_FALSE(res);
  12545. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12546. #endif
  12547. }
  12548. {
  12549. // open_stream() must behave the same way.
  12550. auto handle = cli.open_stream("GET", "/gzipped");
  12551. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12552. ASSERT_TRUE(handle.is_valid());
  12553. std::string received;
  12554. char buf[256];
  12555. ssize_t n;
  12556. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12557. received.append(buf, static_cast<size_t>(n));
  12558. }
  12559. EXPECT_EQ("Hello World!", received);
  12560. #else
  12561. EXPECT_FALSE(handle.is_valid());
  12562. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12563. #endif
  12564. }
  12565. {
  12566. // A differently-cased coding must not be mistaken for an unknown one, or
  12567. // the body would be handed back still compressed.
  12568. auto res = cli.Get("/gzipped-uppercase");
  12569. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12571. EXPECT_EQ("Hello World!", res->body);
  12572. #else
  12573. ASSERT_FALSE(res);
  12574. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12575. #endif
  12576. }
  12577. }
  12578. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12579. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12580. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12581. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12582. // body a second time and appending a second Content-Encoding field line, so
  12583. // clients that decode one coding per listed value handed back raw gzip bytes.
  12584. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12585. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12586. Server svr;
  12587. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12588. // keeps the server from applying a coding of its own.
  12589. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12590. res.set_content(gzipped, "text/plain");
  12591. res.set_header("Content-Encoding", "gzip");
  12592. });
  12593. auto port = svr.bind_to_any_port(HOST);
  12594. thread t = thread([&]() { svr.listen_after_bind(); });
  12595. auto se = detail::scope_exit([&] {
  12596. svr.stop();
  12597. t.join();
  12598. ASSERT_FALSE(svr.is_running());
  12599. });
  12600. svr.wait_until_ready();
  12601. Client cli(HOST, port);
  12602. Headers headers = {{"Accept-Encoding", "gzip"}};
  12603. auto res = cli.Get("/pre-gzipped", headers);
  12604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12605. EXPECT_EQ(StatusCode::OK_200, res->status);
  12606. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12607. EXPECT_EQ("Hello World!", res->body);
  12608. }
  12609. // set_compress(false) sends every handler response as it is, buffered or
  12610. // streamed
  12611. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12612. const std::string text(1000, 'a');
  12613. Server svr;
  12614. svr.set_compress(false);
  12615. svr.Get("/buffered", [&](const Request &, Response &res) {
  12616. res.set_content(text, "text/plain");
  12617. });
  12618. svr.Get("/streamed", [&](const Request &, Response &res) {
  12619. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12620. sink.write(text.data(), text.size());
  12621. sink.done();
  12622. return true;
  12623. });
  12624. });
  12625. auto port = svr.bind_to_any_port(HOST);
  12626. ASSERT_LT(0, port);
  12627. thread t = thread([&] { svr.listen_after_bind(); });
  12628. auto se = detail::scope_exit([&] {
  12629. svr.stop();
  12630. t.join();
  12631. ASSERT_FALSE(svr.is_running());
  12632. });
  12633. svr.wait_until_ready();
  12634. Client cli(HOST, port);
  12635. cli.set_decompress(false);
  12636. for (auto path : {"/buffered", "/streamed"}) {
  12637. SCOPED_TRACE(path);
  12638. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12640. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12641. EXPECT_EQ(text, res->body);
  12642. }
  12643. }
  12644. // A chunked provider settles its coding where the headers are written and
  12645. // reuses it at write time. Both ends of that have to hold: a handler's own
  12646. // Content-Encoding suppresses the coding, and a response without one is still
  12647. // compressed as it always was.
  12648. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12649. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12650. const std::string plain = "Hello World! Hello World! Hello World!";
  12651. Server svr;
  12652. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12653. res.set_header("Content-Encoding", "gzip");
  12654. res.set_chunked_content_provider(
  12655. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12656. sink.write(gzipped.data(), gzipped.size());
  12657. sink.done();
  12658. return true;
  12659. });
  12660. });
  12661. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12662. res.set_chunked_content_provider(
  12663. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12664. sink.write(plain.data(), plain.size());
  12665. sink.done();
  12666. return true;
  12667. });
  12668. });
  12669. auto port = svr.bind_to_any_port(HOST);
  12670. thread t = thread([&]() { svr.listen_after_bind(); });
  12671. auto se = detail::scope_exit([&] {
  12672. svr.stop();
  12673. t.join();
  12674. ASSERT_FALSE(svr.is_running());
  12675. });
  12676. svr.wait_until_ready();
  12677. Client cli(HOST, port);
  12678. Headers headers = {{"Accept-Encoding", "gzip"}};
  12679. {
  12680. auto res = cli.Get("/pre-gzipped", headers);
  12681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12682. EXPECT_EQ(StatusCode::OK_200, res->status);
  12683. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12684. EXPECT_EQ("Hello World!", res->body);
  12685. }
  12686. {
  12687. auto res = cli.Get("/negotiated", headers);
  12688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12689. EXPECT_EQ(StatusCode::OK_200, res->status);
  12690. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12691. EXPECT_EQ(plain, res->body);
  12692. }
  12693. }
  12694. #endif
  12695. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12696. // the same message as the comma-joined one, so both have to be read the same
  12697. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12698. // single gzip coding, and a body the sender says was encoded twice was handed
  12699. // back after one pass, still compressed but presented as decoded.
  12700. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12701. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12702. Server svr;
  12703. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12704. res.set_content(body, "image/jpeg");
  12705. res.headers.emplace("Content-Encoding", "gzip");
  12706. res.headers.emplace("Content-Encoding", "gzip");
  12707. });
  12708. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12709. res.set_content(body, "image/jpeg");
  12710. res.set_header("Content-Encoding", "gzip, gzip");
  12711. });
  12712. auto port = svr.bind_to_any_port(HOST);
  12713. thread t = thread([&]() { svr.listen_after_bind(); });
  12714. auto se = detail::scope_exit([&] {
  12715. svr.stop();
  12716. t.join();
  12717. ASSERT_FALSE(svr.is_running());
  12718. });
  12719. svr.wait_until_ready();
  12720. Client cli(HOST, port);
  12721. // Two codings is not something cpp-httplib decodes, so both representations
  12722. // take the pass-through path rather than one of them being gunzipped once.
  12723. for (const char *path : {"/split", "/joined"}) {
  12724. auto res = cli.Get(path);
  12725. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12726. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12727. EXPECT_EQ(body, res->body) << path;
  12728. }
  12729. }
  12730. // Regression test for DoS vulnerability: a malicious server sending a response
  12731. // without Content-Length header must not cause unbounded memory consumption on
  12732. // the client side. The client should stop reading after a reasonable limit,
  12733. // similar to the server-side set_payload_max_length protection.
  12734. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12735. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12736. #ifndef _WIN32
  12737. signal(SIGPIPE, SIG_IGN);
  12738. #endif
  12739. auto server_thread = std::thread([] {
  12740. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12741. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12742. default_socket_options(srv);
  12743. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12744. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12745. sockaddr_in addr{};
  12746. addr.sin_family = AF_INET;
  12747. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12748. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12749. int opt = 1;
  12750. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12751. #ifdef _WIN32
  12752. reinterpret_cast<const char *>(&opt),
  12753. #else
  12754. &opt,
  12755. #endif
  12756. sizeof(opt));
  12757. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12758. ::listen(srv, 1);
  12759. sockaddr_in cli_addr{};
  12760. socklen_t cli_len = sizeof(cli_addr);
  12761. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12762. if (cli != INVALID_SOCKET) {
  12763. char buf[4096];
  12764. ::recv(cli, buf, sizeof(buf), 0);
  12765. // Malicious response: no Content-Length, no chunked encoding
  12766. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12767. "Connection: close\r\n"
  12768. "\r\n";
  12769. ::send(cli,
  12770. #ifdef _WIN32
  12771. static_cast<const char *>(response_header.c_str()),
  12772. static_cast<int>(response_header.size()),
  12773. #else
  12774. response_header.c_str(), response_header.size(),
  12775. #endif
  12776. 0);
  12777. // Send 10MB of data
  12778. std::string chunk(64 * 1024, 'A');
  12779. size_t total_sent = 0;
  12780. while (total_sent < MALICIOUS_DATA_SIZE) {
  12781. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12782. auto sent = ::send(cli,
  12783. #ifdef _WIN32
  12784. static_cast<const char *>(chunk.c_str()),
  12785. static_cast<int>(to_send),
  12786. #else
  12787. chunk.c_str(), to_send,
  12788. #endif
  12789. 0);
  12790. if (sent <= 0) break;
  12791. total_sent += static_cast<size_t>(sent);
  12792. }
  12793. detail::close_socket(cli);
  12794. }
  12795. detail::close_socket(srv);
  12796. });
  12797. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12798. size_t total_read = 0;
  12799. {
  12800. Client cli("127.0.0.1", PORT + 2);
  12801. cli.set_read_timeout(5, 0);
  12802. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12803. auto stream = cli.open_stream("GET", "/malicious");
  12804. ASSERT_TRUE(stream.is_valid());
  12805. char buffer[64 * 1024];
  12806. ssize_t n;
  12807. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12808. total_read += static_cast<size_t>(n);
  12809. }
  12810. } // StreamHandle and Client destroyed here, closing the socket
  12811. server_thread.join();
  12812. // With set_payload_max_length, the client must stop reading before consuming
  12813. // all 10MB. The read loop should be cut off at or near the configured limit.
  12814. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12815. << "Client read " << total_read << " bytes, exceeding the configured "
  12816. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12817. }
  12818. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12819. // the entire response body without truncation.
  12820. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12821. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12822. #ifndef _WIN32
  12823. signal(SIGPIPE, SIG_IGN);
  12824. #endif
  12825. auto server_thread = std::thread([] {
  12826. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12827. default_socket_options(srv);
  12828. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12829. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12830. sockaddr_in addr{};
  12831. addr.sin_family = AF_INET;
  12832. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12833. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12834. int opt = 1;
  12835. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12836. #ifdef _WIN32
  12837. reinterpret_cast<const char *>(&opt),
  12838. #else
  12839. &opt,
  12840. #endif
  12841. sizeof(opt));
  12842. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12843. ::listen(srv, 1);
  12844. sockaddr_in cli_addr{};
  12845. socklen_t cli_len = sizeof(cli_addr);
  12846. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12847. if (cli != INVALID_SOCKET) {
  12848. char buf[4096];
  12849. ::recv(cli, buf, sizeof(buf), 0);
  12850. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12851. "Connection: close\r\n"
  12852. "\r\n";
  12853. ::send(cli,
  12854. #ifdef _WIN32
  12855. static_cast<const char *>(response_header.c_str()),
  12856. static_cast<int>(response_header.size()),
  12857. #else
  12858. response_header.c_str(), response_header.size(),
  12859. #endif
  12860. 0);
  12861. std::string chunk(64 * 1024, 'A');
  12862. size_t total_sent = 0;
  12863. while (total_sent < DATA_SIZE) {
  12864. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12865. auto sent = ::send(cli,
  12866. #ifdef _WIN32
  12867. static_cast<const char *>(chunk.c_str()),
  12868. static_cast<int>(to_send),
  12869. #else
  12870. chunk.c_str(), to_send,
  12871. #endif
  12872. 0);
  12873. if (sent <= 0) break;
  12874. total_sent += static_cast<size_t>(sent);
  12875. }
  12876. #ifdef _WIN32
  12877. ::shutdown(cli, SD_SEND);
  12878. #else
  12879. ::shutdown(cli, SHUT_WR);
  12880. #endif
  12881. // Drain until the client closes its end, ensuring all data is delivered
  12882. char drain[1024];
  12883. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12884. detail::close_socket(cli);
  12885. }
  12886. detail::close_socket(srv);
  12887. });
  12888. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12889. size_t total_read = 0;
  12890. {
  12891. Client cli("127.0.0.1", PORT + 2);
  12892. cli.set_read_timeout(5, 0);
  12893. cli.set_payload_max_length(0); // 0 means no limit
  12894. auto stream = cli.open_stream("GET", "/data");
  12895. ASSERT_TRUE(stream.is_valid());
  12896. char buffer[64 * 1024];
  12897. ssize_t n;
  12898. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12899. total_read += static_cast<size_t>(n);
  12900. }
  12901. }
  12902. server_thread.join();
  12903. EXPECT_EQ(total_read, DATA_SIZE)
  12904. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12905. << " bytes without truncation, but only read " << total_read << " bytes.";
  12906. }
  12907. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12908. // enormous Content-Length must not cause the client to pre-allocate a huge
  12909. // response body buffer. The reservation is capped at payload_max_length_, and
  12910. // the read itself fails when the body exceeds the limit.
  12911. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12912. #ifndef _WIN32
  12913. signal(SIGPIPE, SIG_IGN);
  12914. #endif
  12915. auto server_thread = std::thread([] {
  12916. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12917. default_socket_options(srv);
  12918. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12919. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12920. sockaddr_in addr{};
  12921. addr.sin_family = AF_INET;
  12922. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12923. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12924. int opt = 1;
  12925. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12926. #ifdef _WIN32
  12927. reinterpret_cast<const char *>(&opt),
  12928. #else
  12929. &opt,
  12930. #endif
  12931. sizeof(opt));
  12932. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12933. ::listen(srv, 1);
  12934. sockaddr_in cli_addr{};
  12935. socklen_t cli_len = sizeof(cli_addr);
  12936. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12937. if (cli != INVALID_SOCKET) {
  12938. char buf[4096];
  12939. ::recv(cli, buf, sizeof(buf), 0);
  12940. // Malicious response: claim a 20GB body but send only a tiny payload.
  12941. std::string response = "HTTP/1.1 200 OK\r\n"
  12942. "Content-Length: 20000000000\r\n"
  12943. "\r\n"
  12944. "abc";
  12945. ::send(cli,
  12946. #ifdef _WIN32
  12947. static_cast<const char *>(response.c_str()),
  12948. static_cast<int>(response.size()),
  12949. #else
  12950. response.c_str(), response.size(),
  12951. #endif
  12952. 0);
  12953. detail::close_socket(cli);
  12954. }
  12955. detail::close_socket(srv);
  12956. });
  12957. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12958. {
  12959. Client cli("127.0.0.1", PORT + 2);
  12960. cli.set_read_timeout(5, 0);
  12961. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12962. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12963. // (server claims more bytes than payload_max_length permits), but it must
  12964. // not exhaust memory before getting there.
  12965. auto res = cli.Get("/malicious");
  12966. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12967. }
  12968. server_thread.join();
  12969. }
  12970. // Verify that content_receiver bypasses the default payload_max_length,
  12971. // allowing streaming downloads larger than 100MB without requiring an explicit
  12972. // set_payload_max_length call.
  12973. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12974. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12975. #ifndef _WIN32
  12976. signal(SIGPIPE, SIG_IGN);
  12977. #endif
  12978. auto server_thread = std::thread([] {
  12979. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12980. default_socket_options(srv);
  12981. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12982. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12983. sockaddr_in addr{};
  12984. addr.sin_family = AF_INET;
  12985. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12986. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12987. int opt = 1;
  12988. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12989. #ifdef _WIN32
  12990. reinterpret_cast<const char *>(&opt),
  12991. #else
  12992. &opt,
  12993. #endif
  12994. sizeof(opt));
  12995. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12996. ::listen(srv, 1);
  12997. sockaddr_in cli_addr{};
  12998. socklen_t cli_len = sizeof(cli_addr);
  12999. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13000. if (cli != INVALID_SOCKET) {
  13001. char buf[4096];
  13002. ::recv(cli, buf, sizeof(buf), 0);
  13003. // Response with Content-Length larger than default 100MB limit
  13004. auto content_length = std::to_string(DATA_SIZE);
  13005. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13006. "Content-Length: " +
  13007. content_length +
  13008. "\r\n"
  13009. "Connection: close\r\n"
  13010. "\r\n";
  13011. ::send(cli,
  13012. #ifdef _WIN32
  13013. static_cast<const char *>(response_header.c_str()),
  13014. static_cast<int>(response_header.size()),
  13015. #else
  13016. response_header.c_str(), response_header.size(),
  13017. #endif
  13018. 0);
  13019. std::string chunk(64 * 1024, 'A');
  13020. size_t total_sent = 0;
  13021. while (total_sent < DATA_SIZE) {
  13022. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13023. auto sent = ::send(cli,
  13024. #ifdef _WIN32
  13025. static_cast<const char *>(chunk.c_str()),
  13026. static_cast<int>(to_send),
  13027. #else
  13028. chunk.c_str(), to_send,
  13029. #endif
  13030. 0);
  13031. if (sent <= 0) break;
  13032. total_sent += static_cast<size_t>(sent);
  13033. }
  13034. detail::close_socket(cli);
  13035. }
  13036. detail::close_socket(srv);
  13037. });
  13038. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13039. size_t total_received = 0;
  13040. {
  13041. Client cli("127.0.0.1", PORT + 2);
  13042. cli.set_read_timeout(10, 0);
  13043. // Do NOT call set_payload_max_length — use the default 100MB limit
  13044. auto res =
  13045. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13046. total_received += data_length;
  13047. return true;
  13048. });
  13049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13050. EXPECT_EQ(StatusCode::OK_200, res->status);
  13051. }
  13052. server_thread.join();
  13053. EXPECT_EQ(total_received, DATA_SIZE)
  13054. << "With content_receiver, the client should read all " << DATA_SIZE
  13055. << " bytes despite the default 100MB payload_max_length, but only read "
  13056. << total_received << " bytes.";
  13057. }
  13058. // Verify that an explicit set_payload_max_length smaller than the response is
  13059. // enforced even when a content_receiver is used.
  13060. TEST(ClientVulnerabilityTest,
  13061. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13062. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13063. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13064. #ifndef _WIN32
  13065. signal(SIGPIPE, SIG_IGN);
  13066. #endif
  13067. auto server_thread = std::thread([] {
  13068. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13069. default_socket_options(srv);
  13070. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13071. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13072. sockaddr_in addr{};
  13073. addr.sin_family = AF_INET;
  13074. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13075. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13076. int opt = 1;
  13077. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13078. #ifdef _WIN32
  13079. reinterpret_cast<const char *>(&opt),
  13080. #else
  13081. &opt,
  13082. #endif
  13083. sizeof(opt));
  13084. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13085. ::listen(srv, 1);
  13086. sockaddr_in cli_addr{};
  13087. socklen_t cli_len = sizeof(cli_addr);
  13088. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13089. if (cli != INVALID_SOCKET) {
  13090. char buf[4096];
  13091. ::recv(cli, buf, sizeof(buf), 0);
  13092. auto content_length = std::to_string(DATA_SIZE);
  13093. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13094. "Content-Length: " +
  13095. content_length +
  13096. "\r\n"
  13097. "Connection: close\r\n"
  13098. "\r\n";
  13099. ::send(cli,
  13100. #ifdef _WIN32
  13101. static_cast<const char *>(response_header.c_str()),
  13102. static_cast<int>(response_header.size()),
  13103. #else
  13104. response_header.c_str(), response_header.size(),
  13105. #endif
  13106. 0);
  13107. std::string chunk(64 * 1024, 'A');
  13108. size_t total_sent = 0;
  13109. while (total_sent < DATA_SIZE) {
  13110. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13111. auto sent = ::send(cli,
  13112. #ifdef _WIN32
  13113. static_cast<const char *>(chunk.c_str()),
  13114. static_cast<int>(to_send),
  13115. #else
  13116. chunk.c_str(), to_send,
  13117. #endif
  13118. 0);
  13119. if (sent <= 0) break;
  13120. total_sent += static_cast<size_t>(sent);
  13121. }
  13122. detail::close_socket(cli);
  13123. }
  13124. detail::close_socket(srv);
  13125. });
  13126. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13127. size_t total_received = 0;
  13128. {
  13129. Client cli("127.0.0.1", PORT + 2);
  13130. cli.set_read_timeout(10, 0);
  13131. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13132. auto res =
  13133. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13134. total_received += data_length;
  13135. return true;
  13136. });
  13137. // Should fail because 200MB exceeds the explicit 150MB limit
  13138. EXPECT_FALSE(res);
  13139. }
  13140. server_thread.join();
  13141. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13142. << "Client with content_receiver should respect the explicit "
  13143. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13144. << total_received << " bytes.";
  13145. }
  13146. // Verify that an explicit set_payload_max_length larger than the response
  13147. // allows the content_receiver to read all data successfully.
  13148. TEST(ClientVulnerabilityTest,
  13149. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13150. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13151. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13152. #ifndef _WIN32
  13153. signal(SIGPIPE, SIG_IGN);
  13154. #endif
  13155. auto server_thread = std::thread([] {
  13156. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13157. default_socket_options(srv);
  13158. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13159. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13160. sockaddr_in addr{};
  13161. addr.sin_family = AF_INET;
  13162. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13163. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13164. int opt = 1;
  13165. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13166. #ifdef _WIN32
  13167. reinterpret_cast<const char *>(&opt),
  13168. #else
  13169. &opt,
  13170. #endif
  13171. sizeof(opt));
  13172. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13173. ::listen(srv, 1);
  13174. sockaddr_in cli_addr{};
  13175. socklen_t cli_len = sizeof(cli_addr);
  13176. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13177. if (cli != INVALID_SOCKET) {
  13178. char buf[4096];
  13179. ::recv(cli, buf, sizeof(buf), 0);
  13180. auto content_length = std::to_string(DATA_SIZE);
  13181. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13182. "Content-Length: " +
  13183. content_length +
  13184. "\r\n"
  13185. "Connection: close\r\n"
  13186. "\r\n";
  13187. ::send(cli,
  13188. #ifdef _WIN32
  13189. static_cast<const char *>(response_header.c_str()),
  13190. static_cast<int>(response_header.size()),
  13191. #else
  13192. response_header.c_str(), response_header.size(),
  13193. #endif
  13194. 0);
  13195. std::string chunk(64 * 1024, 'A');
  13196. size_t total_sent = 0;
  13197. while (total_sent < DATA_SIZE) {
  13198. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13199. auto sent = ::send(cli,
  13200. #ifdef _WIN32
  13201. static_cast<const char *>(chunk.c_str()),
  13202. static_cast<int>(to_send),
  13203. #else
  13204. chunk.c_str(), to_send,
  13205. #endif
  13206. 0);
  13207. if (sent <= 0) break;
  13208. total_sent += static_cast<size_t>(sent);
  13209. }
  13210. #ifdef _WIN32
  13211. ::shutdown(cli, SD_SEND);
  13212. #else
  13213. ::shutdown(cli, SHUT_WR);
  13214. #endif
  13215. char drain[1024];
  13216. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13217. detail::close_socket(cli);
  13218. }
  13219. detail::close_socket(srv);
  13220. });
  13221. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13222. size_t total_received = 0;
  13223. {
  13224. Client cli("127.0.0.1", PORT + 2);
  13225. cli.set_read_timeout(10, 0);
  13226. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13227. auto res =
  13228. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13229. total_received += data_length;
  13230. return true;
  13231. });
  13232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13233. EXPECT_EQ(StatusCode::OK_200, res->status);
  13234. }
  13235. server_thread.join();
  13236. EXPECT_EQ(total_received, DATA_SIZE)
  13237. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13238. << " bytes (larger than " << DATA_SIZE
  13239. << " bytes response), content_receiver should read all data, but only "
  13240. "read "
  13241. << total_received << " bytes.";
  13242. }
  13243. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13244. // Regression test for "zip bomb" attack on the client side: a malicious server
  13245. // sends a small gzip-compressed response that decompresses to a huge payload.
  13246. // The client must enforce payload_max_length on the decompressed size.
  13247. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13248. constexpr size_t DECOMPRESSED_SIZE =
  13249. 10 * 1024 * 1024; // 10MB after decompression
  13250. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13251. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13252. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13253. std::string compressed;
  13254. {
  13255. httplib::detail::gzip_compressor compressor;
  13256. bool ok =
  13257. compressor.compress(uncompressed.data(), uncompressed.size(),
  13258. /*last=*/true, [&](const char *buf, size_t len) {
  13259. compressed.append(buf, len);
  13260. return true;
  13261. });
  13262. ASSERT_TRUE(ok);
  13263. }
  13264. // Sanity: compressed data should be much smaller than the decompressed size
  13265. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13266. #ifndef _WIN32
  13267. signal(SIGPIPE, SIG_IGN);
  13268. #endif
  13269. // Set up the listening socket in the main thread so the server is guaranteed
  13270. // to be ready before the client connects (eliminates race condition).
  13271. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13272. default_socket_options(srv);
  13273. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13274. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13275. sockaddr_in addr{};
  13276. addr.sin_family = AF_INET;
  13277. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13278. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13279. int opt = 1;
  13280. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13281. #ifdef _WIN32
  13282. reinterpret_cast<const char *>(&opt),
  13283. #else
  13284. &opt,
  13285. #endif
  13286. sizeof(opt));
  13287. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13288. ASSERT_EQ(0, ::listen(srv, 1));
  13289. auto server_thread = std::thread([&compressed, srv] {
  13290. sockaddr_in cli_addr{};
  13291. socklen_t cli_len = sizeof(cli_addr);
  13292. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13293. if (cli != INVALID_SOCKET) {
  13294. // Read the full HTTP request (until \r\n\r\n)
  13295. char buf[4096];
  13296. size_t total = 0;
  13297. while (total < sizeof(buf)) {
  13298. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13299. if (n <= 0) break;
  13300. total += static_cast<size_t>(n);
  13301. // Check for end of headers
  13302. if (total >= 4) {
  13303. std::string req(buf, total);
  13304. if (req.find("\r\n\r\n") != std::string::npos) break;
  13305. }
  13306. }
  13307. // Malicious response: gzip-compressed body, no Content-Length
  13308. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13309. "Content-Encoding: gzip\r\n"
  13310. "Connection: close\r\n"
  13311. "\r\n";
  13312. ::send(cli,
  13313. #ifdef _WIN32
  13314. static_cast<const char *>(response_header.c_str()),
  13315. static_cast<int>(response_header.size()),
  13316. #else
  13317. response_header.c_str(), response_header.size(),
  13318. #endif
  13319. 0);
  13320. // Send the compressed payload (small on the wire, huge when decompressed)
  13321. size_t total_sent = 0;
  13322. while (total_sent < compressed.size()) {
  13323. auto to_send = std::min(compressed.size() - total_sent,
  13324. static_cast<size_t>(64 * 1024));
  13325. auto sent =
  13326. ::send(cli,
  13327. #ifdef _WIN32
  13328. static_cast<const char *>(compressed.c_str() + total_sent),
  13329. static_cast<int>(to_send),
  13330. #else
  13331. compressed.c_str() + total_sent, to_send,
  13332. #endif
  13333. 0);
  13334. if (sent <= 0) break;
  13335. total_sent += static_cast<size_t>(sent);
  13336. }
  13337. detail::close_socket(cli);
  13338. }
  13339. });
  13340. auto se = detail::scope_exit([&] {
  13341. detail::close_socket(srv);
  13342. server_thread.join();
  13343. });
  13344. size_t total_decompressed = 0;
  13345. {
  13346. Client cli("127.0.0.1", PORT + 3);
  13347. cli.set_read_timeout(5, 0);
  13348. cli.set_decompress(true);
  13349. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13350. auto stream = cli.open_stream("GET", "/zipbomb");
  13351. ASSERT_TRUE(stream.is_valid());
  13352. char buffer[64 * 1024];
  13353. ssize_t n;
  13354. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13355. total_decompressed += static_cast<size_t>(n);
  13356. }
  13357. }
  13358. // The decompressed size must be capped by payload_max_length. Without
  13359. // protection, the client would decompress the full 10MB from a tiny
  13360. // compressed payload, enabling a zip bomb DoS attack.
  13361. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13362. << "Client decompressed " << total_decompressed
  13363. << " bytes from a gzip response. The decompressed size should be "
  13364. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13365. }
  13366. #endif
  13367. TEST(HostAndPortPropertiesTest, NoSSL) {
  13368. httplib::Client cli("www.google.com", 1234);
  13369. ASSERT_EQ("www.google.com", cli.host());
  13370. ASSERT_EQ(1234, cli.port());
  13371. }
  13372. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13373. httplib::Client cli("www.google.com:1234");
  13374. ASSERT_EQ("www.google.com", cli.host());
  13375. ASSERT_EQ(1234, cli.port());
  13376. }
  13377. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13378. // Port number that overflows int — should not crash, client becomes invalid
  13379. httplib::Client cli("http://www.google.com:99999999999999999999");
  13380. ASSERT_FALSE(cli.is_valid());
  13381. }
  13382. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13383. // Port 99999 exceeds valid range (1-65535) — should not crash
  13384. httplib::Client cli("http://www.google.com:99999");
  13385. ASSERT_FALSE(cli.is_valid());
  13386. auto res = cli.Get("/");
  13387. EXPECT_FALSE(res);
  13388. EXPECT_EQ(Error::Connection, res.error());
  13389. }
  13390. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13391. httplib::Client cli("http://user:pass@localhost:1234");
  13392. ASSERT_FALSE(cli.is_valid());
  13393. EXPECT_FALSE(cli.Get("/"));
  13394. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13395. }
  13396. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13397. httplib::Client cli("http://www.google.com:80abc");
  13398. ASSERT_FALSE(cli.is_valid());
  13399. }
  13400. #ifdef CPPHTTPLIB_SSL_ENABLED
  13401. TEST(HostAndPortPropertiesTest, SSL) {
  13402. httplib::SSLClient cli("www.google.com");
  13403. ASSERT_EQ("www.google.com", cli.host());
  13404. ASSERT_EQ(443, cli.port());
  13405. }
  13406. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13407. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13408. std::string cert;
  13409. read_file(CA_CERT_FILE, cert);
  13410. httplib::SSLClient httplib_client("www.google.com");
  13411. // Load CA store first time
  13412. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13413. // Load CA store second time (update)
  13414. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13415. // Verify client is still valid and can make connections
  13416. httplib_client.enable_server_certificate_verification(true);
  13417. auto res = httplib_client.Get("/");
  13418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13419. // Google may return 200 or 301 depending on various factors
  13420. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13421. res->status == StatusCode::MovedPermanently_301);
  13422. }
  13423. TEST(SSLClientTest, ServerNameIndication_Online) {
  13424. auto host = "httpbingo.org";
  13425. auto path = std::string{"/get"};
  13426. SSLClient cli(host, 443);
  13427. auto res = cli.Get(path);
  13428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13429. ASSERT_EQ(StatusCode::OK_200, res->status);
  13430. }
  13431. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13432. // Use a site that will cause SSL verification failure due to self-signed cert
  13433. SSLClient cli("self-signed.badssl.com", 443);
  13434. cli.enable_server_certificate_verification(true);
  13435. auto res = cli.Get("/");
  13436. ASSERT_TRUE(!res);
  13437. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13438. // Verify backend error is captured for SSLServerVerification
  13439. // This occurs when certificate verification fails
  13440. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13441. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13442. EXPECT_NE(0UL, res.ssl_backend_error());
  13443. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13444. res.ssl_error());
  13445. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13446. #if !defined(_WIN32) || \
  13447. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13448. // On non-Windows or when Windows Schannel is disabled, the error comes
  13449. // from OpenSSL's verification
  13450. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13451. res.ssl_backend_error());
  13452. #endif
  13453. #endif
  13454. }
  13455. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13456. // Use a site where hostname doesn't match the certificate
  13457. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13458. SSLClient cli("wrong.host.badssl.com", 443);
  13459. cli.enable_server_certificate_verification(true);
  13460. cli.enable_server_hostname_verification(true);
  13461. auto res = cli.Get("/");
  13462. ASSERT_TRUE(!res);
  13463. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13464. // Verify backend error is captured for hostname verification failure
  13465. EXPECT_NE(0UL, res.ssl_backend_error());
  13466. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13467. res.ssl_error());
  13468. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13469. #if !defined(_WIN32) || \
  13470. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13471. // On non-Windows or when Windows Schannel is disabled, the error comes
  13472. // from OpenSSL's hostname verification
  13473. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13474. res.ssl_backend_error());
  13475. #endif
  13476. #endif
  13477. }
  13478. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13479. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13480. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13481. SSLClient cli("www.google.com", 443);
  13482. cli.enable_server_certificate_verification(true);
  13483. auto res = cli.Get("/");
  13484. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13485. }
  13486. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13487. SSLClient cli("www.google.com", 443);
  13488. cli.enable_server_certificate_verification(true);
  13489. cli.enable_windows_certificate_verification(false);
  13490. auto res = cli.Get("/");
  13491. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13492. }
  13493. // The server sends an intermediate cross-signed by a root Windows trusts,
  13494. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13495. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13496. SSLClient cli("accounts.spotify.com", 443);
  13497. auto res = cli.Get("/");
  13498. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13499. << " ssl_backend_error=" << res.ssl_backend_error();
  13500. }
  13501. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13502. // policy status, which no backend reports for a self-signed certificate.
  13503. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13504. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13505. ASSERT_TRUE(svr.is_valid());
  13506. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13507. auto se = detail::scope_exit([&] {
  13508. svr.stop();
  13509. t.join();
  13510. ASSERT_FALSE(svr.is_running());
  13511. });
  13512. svr.wait_until_ready();
  13513. SSLClient cli("127.0.0.1", PORT);
  13514. cli.set_connection_timeout(30);
  13515. auto res = cli.Get("/");
  13516. ASSERT_FALSE(res);
  13517. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13518. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13519. }
  13520. #endif
  13521. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13522. Client cli("https://google.com");
  13523. auto res = cli.Get("/");
  13524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13525. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13526. }
  13527. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13528. SSLClient cli("google.com");
  13529. cli.set_ca_cert_path(CA_CERT_FILE);
  13530. auto res = cli.Get("/");
  13531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13532. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13533. }
  13534. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13535. SSLClient cli("google.com");
  13536. cli.enable_server_certificate_verification(true);
  13537. cli.set_ca_cert_path("hello");
  13538. auto res = cli.Get("/");
  13539. ASSERT_TRUE(!res);
  13540. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13541. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13542. // should be set
  13543. EXPECT_EQ(0, res.ssl_error());
  13544. // Verify backend error is captured for SSLLoadingCerts
  13545. // This error occurs when loading CA certificates fails
  13546. EXPECT_NE(0UL, res.ssl_backend_error());
  13547. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13548. // OpenSSL specific error codes:
  13549. // > openssl errstr 0x80000002
  13550. // error:80000002:system library::No such file or directory
  13551. // > openssl errstr 0xA000126
  13552. // error:0A000126:SSL routines::unexpected eof while reading
  13553. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13554. res.ssl_backend_error() == 0xA000126);
  13555. #endif
  13556. }
  13557. TEST(SSLClientTest, ServerCertificateVerification4) {
  13558. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13559. ASSERT_TRUE(svr.is_valid());
  13560. svr.Get("/test", [&](const Request &, Response &res) {
  13561. res.set_content("test", "text/plain");
  13562. svr.stop();
  13563. ASSERT_TRUE(true);
  13564. });
  13565. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13566. auto se = detail::scope_exit([&] {
  13567. t.join();
  13568. ASSERT_FALSE(svr.is_running());
  13569. });
  13570. svr.wait_until_ready();
  13571. SSLClient cli("127.0.0.1", PORT);
  13572. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13573. cli.enable_server_certificate_verification(true);
  13574. cli.set_connection_timeout(30);
  13575. auto res = cli.Get("/test");
  13576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13577. ASSERT_EQ(StatusCode::OK_200, res->status);
  13578. }
  13579. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13580. std::string cert;
  13581. read_file(CA_CERT_FILE, cert);
  13582. SSLClient cli("google.com");
  13583. cli.load_ca_cert_store(cert.data(), cert.size());
  13584. const auto res = cli.Get("/");
  13585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13586. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13587. }
  13588. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13589. // clang-format off
  13590. static constexpr char cert[] =
  13591. "GlobalSign Root CA\n"
  13592. "==================\n"
  13593. "-----BEGIN CERTIFICATE-----\n"
  13594. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13595. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13596. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13597. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13598. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13599. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13600. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13601. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13602. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13603. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13604. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13605. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13606. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13607. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13608. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13609. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13610. "-----END CERTIFICATE-----\n";
  13611. // clang-format on
  13612. SSLClient cli("google.com");
  13613. cli.load_ca_cert_store(cert, sizeof(cert));
  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, WildcardHostNameMatch_Online) {
  13619. SSLClient cli("www.youtube.com");
  13620. cli.set_ca_cert_path(CA_CERT_FILE);
  13621. cli.enable_server_certificate_verification(true);
  13622. cli.set_follow_location(true);
  13623. auto res = cli.Get("/");
  13624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13625. ASSERT_EQ(StatusCode::OK_200, res->status);
  13626. }
  13627. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13628. SSLClient cli("wWw.YouTube.Com");
  13629. cli.set_ca_cert_path(CA_CERT_FILE);
  13630. cli.enable_server_certificate_verification(true);
  13631. cli.enable_server_hostname_verification(true);
  13632. cli.set_follow_location(true);
  13633. auto res = cli.Get("/");
  13634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13635. ASSERT_EQ(StatusCode::OK_200, res->status);
  13636. }
  13637. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13638. SSLClient cli("gOoGlE.COm");
  13639. cli.enable_server_certificate_verification(true);
  13640. cli.enable_server_hostname_verification(true);
  13641. cli.set_follow_location(true);
  13642. auto res = cli.Get("/");
  13643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13644. ASSERT_EQ(StatusCode::OK_200, res->status);
  13645. }
  13646. TEST(SSLClientTest, Issue2004_Online) {
  13647. Client client("https://google.com");
  13648. client.set_follow_location(true);
  13649. auto res = client.Get("/");
  13650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13651. ASSERT_EQ(StatusCode::OK_200, res->status);
  13652. auto body = res->body;
  13653. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13654. }
  13655. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13656. // Create SSLClient with invalid cert/key to make is_valid() return false
  13657. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13658. "nonexistent_key.pem");
  13659. // is_valid() should be false due to cert loading failure
  13660. ASSERT_FALSE(cli.is_valid());
  13661. auto res = cli.Get("/");
  13662. ASSERT_FALSE(res);
  13663. EXPECT_EQ(Error::SSLConnection, res.error());
  13664. }
  13665. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13666. // Test for Issue #2251: SSL error not properly reported when client cert
  13667. // and key paths are swapped or mismatched
  13668. // This simulates the scenario where user accidentally swaps the cert and key
  13669. // files
  13670. // Using client cert file as private key and vice versa (completely wrong)
  13671. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13672. // Should fail validation due to cert/key mismatch
  13673. ASSERT_FALSE(cli.is_valid());
  13674. // Attempt to make a request should fail with proper error
  13675. auto res = cli.Get("/");
  13676. ASSERT_FALSE(res);
  13677. EXPECT_EQ(Error::SSLConnection, res.error());
  13678. // SSL error should be recorded in the Result object (this is the key fix for
  13679. // Issue #2251)
  13680. auto backend_error = res.ssl_backend_error();
  13681. EXPECT_NE(0u, backend_error);
  13682. }
  13683. // Tests cert/key mismatch detection at the TLS context level
  13684. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13685. // Test that using mismatched cert/key causes connection failure.
  13686. // We verify this at the SSLClient level rather than through internal
  13687. // TLS API functions.
  13688. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13689. cli.enable_server_certificate_verification(false);
  13690. cli.set_connection_timeout(2);
  13691. // The mismatch should cause a connection or handshake error
  13692. auto res = cli.Get("/test");
  13693. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13694. // Either way, the request should fail
  13695. EXPECT_FALSE(res);
  13696. }
  13697. #endif
  13698. #if 0
  13699. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13700. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13701. ASSERT_TRUE(cli != nullptr);
  13702. cli->set_address_family(AF_INET6);
  13703. cli->set_interface("en0");
  13704. auto res = cli->Get("/get");
  13705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13706. ASSERT_EQ(StatusCode::OK_200, res->status);
  13707. }
  13708. #endif
  13709. // Client certificate tests - work with all TLS backends
  13710. #ifdef CPPHTTPLIB_SSL_ENABLED
  13711. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13712. void ClientCertPresent(
  13713. const std::string &client_cert_file,
  13714. const std::string &client_private_key_file,
  13715. const std::string &client_encrypted_private_key_pass = std::string(),
  13716. const ClientCertServerSetup &setup = nullptr) {
  13717. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13718. ASSERT_TRUE(svr.is_valid());
  13719. if (setup) { setup(svr); }
  13720. svr.Get("/test", [&](const Request &req, Response &res) {
  13721. res.set_content("test", "text/plain");
  13722. auto cert = req.peer_cert();
  13723. ASSERT_TRUE(static_cast<bool>(cert));
  13724. std::string common_name = cert.subject_cn();
  13725. EXPECT_EQ("Common Name", common_name);
  13726. });
  13727. auto port = svr.bind_to_any_port(HOST);
  13728. ASSERT_LT(0, port);
  13729. thread t = thread([&]() { svr.listen_after_bind(); });
  13730. auto se = detail::scope_exit([&] {
  13731. svr.stop();
  13732. t.join();
  13733. ASSERT_FALSE(svr.is_running());
  13734. });
  13735. svr.wait_until_ready();
  13736. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13737. client_encrypted_private_key_pass);
  13738. cli.enable_server_certificate_verification(false);
  13739. cli.set_connection_timeout(30);
  13740. auto res = cli.Get("/test");
  13741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13742. ASSERT_EQ(StatusCode::OK_200, res->status);
  13743. }
  13744. TEST(SSLClientServerTest, ClientCertPresent) {
  13745. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13746. }
  13747. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13748. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13749. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13750. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13751. }
  13752. // Expects svr, which must require client certificates, to reject a client
  13753. // that has none
  13754. void RejectsClientWithoutCert(SSLServer &svr) {
  13755. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13756. auto port = svr.bind_to_any_port(HOST);
  13757. ASSERT_LT(0, port);
  13758. thread t = thread([&]() { svr.listen_after_bind(); });
  13759. auto se = detail::scope_exit([&] {
  13760. svr.stop();
  13761. t.join();
  13762. ASSERT_FALSE(svr.is_running());
  13763. });
  13764. svr.wait_until_ready();
  13765. SSLClient cli(HOST, port);
  13766. cli.set_connection_timeout(30);
  13767. // Skip the server certificate check, so that the request fails because the
  13768. // client certificate is missing rather than because cert.pem is not trusted
  13769. cli.enable_server_certificate_verification(false);
  13770. auto res = cli.Get("/test");
  13771. ASSERT_FALSE(res);
  13772. // The server rejects the client during the handshake, or on TLS 1.3 right
  13773. // after it, which the client notices on its first write or read
  13774. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13775. res.error() == Error::Write || res.error() == Error::Read)
  13776. << to_string(res.error());
  13777. if (res.error() == Error::SSLConnection) {
  13778. EXPECT_NE(0UL, res.ssl_backend_error());
  13779. }
  13780. // A rejection noticed on the write keeps the TLS error the write hit
  13781. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13782. }
  13783. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13784. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13785. ASSERT_TRUE(svr.is_valid());
  13786. if (setup) { setup(svr); }
  13787. RejectsClientWithoutCert(svr);
  13788. }
  13789. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13790. // A server that requires client certificates must keep requiring them after
  13791. // setup changes it, and keep accepting a client that has one
  13792. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13793. ClientCertMissing(setup);
  13794. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13795. setup);
  13796. }
  13797. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13798. ClientCertStillRequired([](SSLServer &svr) {
  13799. ASSERT_TRUE(tls::set_verify_callback(
  13800. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13801. });
  13802. }
  13803. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13804. ClientCertStillRequired([](SSLServer &svr) {
  13805. ASSERT_TRUE(tls::set_verify_callback(
  13806. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13807. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13808. });
  13809. }
  13810. // The client verifies the server certificate during the handshake, so a
  13811. // server that fails the check never gets the client certificate, even when a
  13812. // verifier of the client's own accepts it
  13813. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13814. struct Case {
  13815. const char *trusted_ca;
  13816. const char *host;
  13817. Error error;
  13818. };
  13819. // cert2.pem names localhost: the first client does not trust it, and the
  13820. // second trusts it but asks for another name
  13821. for (const auto &c :
  13822. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13823. Case{SERVER_CERT2_FILE, "example.com",
  13824. Error::SSLServerHostnameVerification}}) {
  13825. for (auto with_verifier : {false, true}) {
  13826. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13827. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13828. CLIENT_CA_CERT_FILE);
  13829. ASSERT_TRUE(svr.is_valid());
  13830. std::atomic<bool> got_client_cert{false};
  13831. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13832. [&](const tls::VerifyContext &) {
  13833. got_client_cert = true;
  13834. return true;
  13835. }));
  13836. auto port = svr.bind_to_any_port("127.0.0.1");
  13837. ASSERT_LT(0, port);
  13838. thread t = thread([&] { svr.listen_after_bind(); });
  13839. svr.wait_until_ready();
  13840. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13841. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13842. cli.set_ca_cert_path(c.trusted_ca);
  13843. if (with_verifier) {
  13844. cli.set_server_certificate_verifier(
  13845. [](const tls::VerifyContext &) { return true; });
  13846. }
  13847. auto res = cli.Get("/");
  13848. EXPECT_FALSE(res);
  13849. EXPECT_EQ(c.error, res.error());
  13850. svr.stop();
  13851. t.join();
  13852. EXPECT_FALSE(got_client_cert);
  13853. }
  13854. }
  13855. }
  13856. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13857. std::string cert_pem, key_pem, ca_pem;
  13858. read_file(SERVER_CERT_FILE, cert_pem);
  13859. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13860. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13861. ASSERT_TRUE(
  13862. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13863. }
  13864. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13866. ASSERT_TRUE(svr.is_valid());
  13867. UpdateCertsPemWithClientCA(svr);
  13868. RejectsClientWithoutCert(svr);
  13869. }
  13870. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13871. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13872. }
  13873. // A TLS error from one request must not show up in a later request's Result
  13874. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13876. ASSERT_TRUE(svr.is_valid());
  13877. svr.Get("/test", [](const Request &, Response &res) {
  13878. res.set_content("test", "text/plain");
  13879. });
  13880. auto port = svr.bind_to_any_port(HOST);
  13881. ASSERT_LT(0, port);
  13882. thread t = thread([&]() { svr.listen_after_bind(); });
  13883. auto se = detail::scope_exit([&] {
  13884. svr.stop();
  13885. t.join();
  13886. ASSERT_FALSE(svr.is_running());
  13887. });
  13888. svr.wait_until_ready();
  13889. SSLClient cli(HOST, port);
  13890. cli.set_connection_timeout(30);
  13891. cli.enable_server_hostname_verification(false);
  13892. // cert.pem is not trusted, so the handshake fails
  13893. ASSERT_FALSE(cli.Get("/test"));
  13894. cli.enable_server_certificate_verification(false);
  13895. auto res = cli.Get("/test");
  13896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13897. EXPECT_EQ(0, res.ssl_error());
  13898. EXPECT_EQ(0UL, res.ssl_backend_error());
  13899. }
  13900. // PEM memory-based constructor tests (works with all TLS backends).
  13901. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13902. // terminator after it.
  13903. void PemMemoryClientCertPresent(
  13904. const std::string &client_cert_file,
  13905. const std::string &client_private_key_file,
  13906. const std::string &client_encrypted_private_key_pass = std::string(),
  13907. bool exact_size = false) {
  13908. // Read PEM files into memory
  13909. std::string server_cert_pem, server_key_pem;
  13910. std::string client_ca_pem;
  13911. std::string client_cert_pem, client_key_pem;
  13912. read_file(SERVER_CERT_FILE, server_cert_pem);
  13913. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13914. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13915. read_file(client_cert_file, client_cert_pem);
  13916. read_file(client_private_key_file, client_key_pem);
  13917. std::list<std::vector<char>> exact_copies;
  13918. auto data = [&](const std::string &pem) -> const char * {
  13919. if (!exact_size) { return pem.c_str(); }
  13920. exact_copies.emplace_back(pem.begin(), pem.end());
  13921. return exact_copies.back().data();
  13922. };
  13923. // Create server with PEM memory
  13924. SSLServer::PemMemory server_pem = {
  13925. data(server_cert_pem),
  13926. server_cert_pem.size(),
  13927. data(server_key_pem),
  13928. server_key_pem.size(),
  13929. data(client_ca_pem),
  13930. client_ca_pem.size(),
  13931. nullptr // no password for server key
  13932. };
  13933. SSLServer svr(server_pem);
  13934. ASSERT_TRUE(svr.is_valid());
  13935. svr.Get("/test", [&](const Request &req, Response &res) {
  13936. res.set_content("test", "text/plain");
  13937. auto cert = req.peer_cert();
  13938. ASSERT_TRUE(static_cast<bool>(cert));
  13939. EXPECT_EQ("Common Name", cert.subject_cn());
  13940. });
  13941. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13942. auto se = detail::scope_exit([&] {
  13943. svr.stop();
  13944. t.join();
  13945. ASSERT_FALSE(svr.is_running());
  13946. });
  13947. svr.wait_until_ready();
  13948. // Create client with PEM memory
  13949. const char *password = client_encrypted_private_key_pass.empty()
  13950. ? nullptr
  13951. : client_encrypted_private_key_pass.c_str();
  13952. SSLClient::PemMemory client_pem = {
  13953. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13954. client_key_pem.size(), password};
  13955. SSLClient cli(HOST, PORT, client_pem);
  13956. cli.enable_server_certificate_verification(false);
  13957. cli.set_connection_timeout(30);
  13958. auto res = cli.Get("/test");
  13959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13960. ASSERT_EQ(StatusCode::OK_200, res->status);
  13961. }
  13962. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13963. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13964. }
  13965. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13966. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13967. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13968. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13969. }
  13970. // A server built from PEM memory with a client CA requires client certificates,
  13971. // also when the CA is a NUL-terminated string passed with a length of 0
  13972. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13973. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13974. read_file(SERVER_CERT_FILE, server_cert_pem);
  13975. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13976. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13977. SSLServer::PemMemory server_pem = {
  13978. server_cert_pem.c_str(),
  13979. server_cert_pem.size(),
  13980. server_key_pem.c_str(),
  13981. server_key_pem.size(),
  13982. client_ca_pem.c_str(),
  13983. client_ca_pem.size(),
  13984. nullptr // no password for server key
  13985. };
  13986. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13987. SCOPED_TRACE(client_ca_pem_len);
  13988. server_pem.client_ca_pem_len = client_ca_pem_len;
  13989. SSLServer svr(server_pem);
  13990. ASSERT_TRUE(svr.is_valid());
  13991. RejectsClientWithoutCert(svr);
  13992. }
  13993. // An empty CA fails to load instead of turning the check off
  13994. server_pem.client_ca_pem = "";
  13995. server_pem.client_ca_pem_len = 0;
  13996. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13997. }
  13998. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13999. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14000. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14001. true);
  14002. }
  14003. // A length shorter than the PEM cuts it short, so it no longer loads
  14004. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14005. std::string cert, key;
  14006. read_file(SERVER_CERT_FILE, cert);
  14007. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14008. for (auto cut_cert : {true, false}) {
  14009. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14010. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14011. SSLServer::PemMemory server_pem = {
  14012. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14013. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14014. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14015. key_len, nullptr};
  14016. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14017. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14018. key.c_str(), key_len, nullptr};
  14019. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14020. }
  14021. }
  14022. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14023. class NoListenSSLServer : public SSLServer {
  14024. public:
  14025. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14026. const char *client_ca_cert_file_path,
  14027. const char *client_ca_cert_dir_path = nullptr)
  14028. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14029. client_ca_cert_dir_path),
  14030. stop_(false) {}
  14031. std::atomic_bool stop_;
  14032. private:
  14033. bool process_and_close_socket(socket_t /*sock*/) override {
  14034. // Don't create SSL context
  14035. while (!stop_.load()) {
  14036. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14037. }
  14038. return true;
  14039. }
  14040. };
  14041. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14042. CLIENT_CA_CERT_FILE);
  14043. ASSERT_TRUE(svr.is_valid());
  14044. svr.Get("/test", [&](const Request &, Response &res) {
  14045. res.set_content("test", "text/plain");
  14046. });
  14047. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14048. auto se = detail::scope_exit([&] {
  14049. svr.stop_ = true;
  14050. svr.stop();
  14051. t.join();
  14052. ASSERT_FALSE(svr.is_running());
  14053. });
  14054. svr.wait_until_ready();
  14055. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14056. cli.enable_server_certificate_verification(false);
  14057. cli.set_connection_timeout(1);
  14058. auto res = cli.Get("/test");
  14059. ASSERT_TRUE(!res);
  14060. EXPECT_EQ(Error::SSLConnection, res.error());
  14061. // Timeout results in WantRead error code (maps to backend-specific value)
  14062. EXPECT_NE(0, res.ssl_error());
  14063. }
  14064. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14065. // Test SSLServer with client certificate verification using the standard
  14066. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14067. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14068. CLIENT_CA_CERT_DIR);
  14069. ASSERT_TRUE(svr.is_valid());
  14070. svr.Get("/test", [&](const Request &req, Response &res) {
  14071. res.set_content("test", "text/plain");
  14072. auto cert = req.peer_cert();
  14073. ASSERT_TRUE(static_cast<bool>(cert));
  14074. auto common_name = cert.subject_cn();
  14075. EXPECT_EQ("Common Name", common_name);
  14076. });
  14077. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14078. auto se = detail::scope_exit([&] {
  14079. svr.stop();
  14080. t.join();
  14081. ASSERT_FALSE(svr.is_running());
  14082. });
  14083. svr.wait_until_ready();
  14084. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14085. cli.enable_server_certificate_verification(false);
  14086. cli.set_connection_timeout(30);
  14087. auto res = cli.Get("/test");
  14088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14089. ASSERT_EQ(StatusCode::OK_200, res->status);
  14090. }
  14091. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14092. // Verifies that wildcard matching and exact matching work consistently
  14093. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14094. using namespace httplib::tls;
  14095. // We need a running server to test against
  14096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14097. ASSERT_TRUE(svr.is_valid());
  14098. svr.Get("/test", [](const Request &, Response &res) {
  14099. res.set_content("ok", "text/plain");
  14100. });
  14101. thread t([&]() { svr.listen(HOST, PORT); });
  14102. auto se = detail::scope_exit([&] {
  14103. svr.stop();
  14104. t.join();
  14105. });
  14106. svr.wait_until_ready();
  14107. bool verify_callback_called = false;
  14108. bool verify_result_wrong = false;
  14109. SSLClient cli(HOST, PORT);
  14110. cli.enable_server_certificate_verification(true);
  14111. cli.set_ca_cert_path(CA_CERT_FILE);
  14112. cli.set_connection_timeout(5);
  14113. // Note: Test certificate has CN="Common Name", not "localhost"
  14114. bool verify_result_cn = false;
  14115. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14116. verify_callback_called = true;
  14117. if (!ctx.cert) return false;
  14118. // Test 1: "Common Name" should match (our test server cert CN)
  14119. verify_result_cn = ctx.check_hostname("Common Name");
  14120. // Test 2: wrong hostname should not match
  14121. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14122. return true; // Accept for the purpose of this test
  14123. });
  14124. auto res = cli.Get("/test");
  14125. // The request may succeed or fail depending on cert configuration
  14126. // but the callback should have been called
  14127. ASSERT_TRUE(verify_callback_called)
  14128. << "Verify callback should have been called";
  14129. // CN="Common Name" should match our test certificate
  14130. //
  14131. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14132. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14133. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14134. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14135. // <openssl/base.h>, which is included transitively when
  14136. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14137. #if defined(OPENSSL_IS_BORINGSSL)
  14138. EXPECT_FALSE(verify_result_cn)
  14139. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14140. #else
  14141. EXPECT_TRUE(verify_result_cn)
  14142. << "verify_hostname should match 'Common Name' (certificate CN)";
  14143. #endif
  14144. // Wrong hostname should not match
  14145. EXPECT_FALSE(verify_result_wrong)
  14146. << "verify_hostname should not match 'wronghost.example.com'";
  14147. }
  14148. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14149. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14150. // X509_check_ip behavior and must hold for every backend.
  14151. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14152. using namespace httplib::tls;
  14153. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14154. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14155. ASSERT_TRUE(svr.is_valid());
  14156. svr.Get("/test", [](const Request &, Response &res) {
  14157. res.set_content("ok", "text/plain");
  14158. });
  14159. thread t([&]() { svr.listen(HOST, PORT); });
  14160. auto se = detail::scope_exit([&] {
  14161. svr.stop();
  14162. t.join();
  14163. });
  14164. svr.wait_until_ready();
  14165. bool verify_callback_called = false;
  14166. bool ip_matched_via_cn = true;
  14167. SSLClient cli(HOST, PORT);
  14168. cli.enable_server_certificate_verification(true);
  14169. cli.set_ca_cert_path(CA_CERT_FILE);
  14170. cli.set_connection_timeout(5);
  14171. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14172. verify_callback_called = true;
  14173. if (!ctx.cert) return false;
  14174. // The IP appears only in the CN, so it must NOT be accepted.
  14175. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14176. return true; // Accept for the purpose of this test
  14177. });
  14178. cli.Get("/test");
  14179. ASSERT_TRUE(verify_callback_called)
  14180. << "Verify callback should have been called";
  14181. EXPECT_FALSE(ip_matched_via_cn)
  14182. << "An IP host must not be authenticated via the certificate CN";
  14183. }
  14184. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14185. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14186. using namespace httplib::tls;
  14187. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14188. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14189. ASSERT_TRUE(svr.is_valid());
  14190. svr.Get("/test", [](const Request &, Response &res) {
  14191. res.set_content("ok", "text/plain");
  14192. });
  14193. thread t([&]() { svr.listen(HOST, PORT); });
  14194. auto se = detail::scope_exit([&] {
  14195. svr.stop();
  14196. t.join();
  14197. });
  14198. svr.wait_until_ready();
  14199. bool verify_callback_called = false;
  14200. bool san_matched = false;
  14201. bool wrong_ipv6_matched = true;
  14202. bool cn_ipv6_matched = true;
  14203. SSLClient cli(HOST, PORT);
  14204. cli.enable_server_certificate_verification(true);
  14205. cli.set_ca_cert_path(CA_CERT_FILE);
  14206. cli.set_connection_timeout(5);
  14207. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14208. verify_callback_called = true;
  14209. if (!ctx.cert) return false;
  14210. // Matches the IPv6 iPAddress SAN.
  14211. san_matched = ctx.check_hostname("2001:db8::1");
  14212. // A different IPv6 address must not match.
  14213. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14214. // "::1" lives only in the CN, so it must not be accepted.
  14215. cn_ipv6_matched = ctx.check_hostname("::1");
  14216. return true; // Accept for the purpose of this test
  14217. });
  14218. cli.Get("/test");
  14219. ASSERT_TRUE(verify_callback_called)
  14220. << "Verify callback should have been called";
  14221. EXPECT_TRUE(san_matched)
  14222. << "verify_hostname should match an IPv6 iPAddress SAN";
  14223. EXPECT_FALSE(wrong_ipv6_matched)
  14224. << "verify_hostname should not match a non-matching IPv6 address";
  14225. EXPECT_FALSE(cn_ipv6_matched)
  14226. << "An IPv6 host must not be authenticated via the certificate CN";
  14227. }
  14228. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14229. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14230. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14231. using namespace httplib::tls;
  14232. // SANs: DNS:a.zz, IP:42.46.122.122
  14233. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14234. ASSERT_TRUE(svr.is_valid());
  14235. svr.Get("/test", [](const Request &, Response &res) {
  14236. res.set_content("ok", "text/plain");
  14237. });
  14238. auto port = svr.bind_to_any_port(HOST);
  14239. thread t([&]() { svr.listen_after_bind(); });
  14240. auto se = detail::scope_exit([&] {
  14241. svr.stop();
  14242. t.join();
  14243. });
  14244. svr.wait_until_ready();
  14245. bool verify_callback_called = false;
  14246. bool dns_san_matched = false;
  14247. bool ip_san_matched = false;
  14248. bool ip_matched_via_dns_san = true;
  14249. bool dns_matched_via_ip_san = true;
  14250. bool cn_matched_next_to_dns_san = true;
  14251. SSLClient cli(HOST, port);
  14252. cli.enable_server_certificate_verification(true);
  14253. cli.set_ca_cert_path(CA_CERT_FILE);
  14254. cli.set_connection_timeout(5);
  14255. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14256. verify_callback_called = true;
  14257. if (!ctx.cert) return false;
  14258. dns_san_matched = ctx.check_hostname("a.zz");
  14259. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14260. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14261. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14262. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14263. return true; // Accept for the purpose of this test
  14264. });
  14265. cli.Get("/test");
  14266. ASSERT_TRUE(verify_callback_called)
  14267. << "Verify callback should have been called";
  14268. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14269. EXPECT_TRUE(ip_san_matched)
  14270. << "verify_hostname should match an iPAddress SAN";
  14271. EXPECT_FALSE(ip_matched_via_dns_san)
  14272. << "An IP host must not be authenticated via a dNSName SAN";
  14273. EXPECT_FALSE(dns_matched_via_ip_san)
  14274. << "A DNS host must not be authenticated via an iPAddress SAN";
  14275. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14276. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14277. }
  14278. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14279. // "www.*.example.test" names one host and not every host under example.test.
  14280. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14281. using namespace httplib::tls;
  14282. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14283. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14284. ASSERT_TRUE(svr.is_valid());
  14285. svr.Get("/test", [](const Request &, Response &res) {
  14286. res.set_content("ok", "text/plain");
  14287. });
  14288. auto port = svr.bind_to_any_port(HOST);
  14289. thread t([&]() { svr.listen_after_bind(); });
  14290. auto se = detail::scope_exit([&] {
  14291. svr.stop();
  14292. t.join();
  14293. });
  14294. svr.wait_until_ready();
  14295. bool verify_callback_called = false;
  14296. bool leftmost_wildcard_matched = false;
  14297. bool wildcard_spanned_labels = true;
  14298. bool inner_wildcard_matched = true;
  14299. SSLClient cli(HOST, port);
  14300. cli.enable_server_certificate_verification(true);
  14301. cli.set_ca_cert_path(CA_CERT_FILE);
  14302. cli.set_connection_timeout(5);
  14303. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14304. verify_callback_called = true;
  14305. if (!ctx.cert) return false;
  14306. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14307. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14308. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14309. return true; // Accept for the purpose of this test
  14310. });
  14311. cli.Get("/test");
  14312. ASSERT_TRUE(verify_callback_called)
  14313. << "Verify callback should have been called";
  14314. EXPECT_TRUE(leftmost_wildcard_matched)
  14315. << "A leftmost wildcard should match a single label";
  14316. EXPECT_FALSE(wildcard_spanned_labels)
  14317. << "A wildcard label must not match more than one label";
  14318. EXPECT_FALSE(inner_wildcard_matched)
  14319. << "A wildcard outside the leftmost label must not be honoured";
  14320. }
  14321. // sans() must report each SAN entry under its own type.
  14322. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14323. using namespace httplib::tls;
  14324. // SANs: DNS:a.zz, IP:42.46.122.122
  14325. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14326. ASSERT_TRUE(svr.is_valid());
  14327. svr.Get("/test", [](const Request &, Response &res) {
  14328. res.set_content("ok", "text/plain");
  14329. });
  14330. auto port = svr.bind_to_any_port(HOST);
  14331. thread t([&]() { svr.listen_after_bind(); });
  14332. auto se = detail::scope_exit([&] {
  14333. svr.stop();
  14334. t.join();
  14335. });
  14336. svr.wait_until_ready();
  14337. bool verify_callback_called = false;
  14338. std::vector<SanEntry> sans;
  14339. SSLClient cli(HOST, port);
  14340. cli.enable_server_certificate_verification(true);
  14341. cli.set_ca_cert_path(CA_CERT_FILE);
  14342. cli.set_connection_timeout(5);
  14343. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14344. verify_callback_called = true;
  14345. if (!ctx.cert) return false;
  14346. sans = ctx.sans();
  14347. return true; // Accept for the purpose of this test
  14348. });
  14349. cli.Get("/test");
  14350. ASSERT_TRUE(verify_callback_called)
  14351. << "Verify callback should have been called";
  14352. auto has_san = [&](SanType type, const std::string &value) {
  14353. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14354. return san.type == type && san.value == value;
  14355. });
  14356. };
  14357. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14358. << "sans() should report the dNSName SAN";
  14359. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14360. << "sans() should report the iPAddress SAN";
  14361. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14362. << "sans() must not report the dNSName SAN as an address";
  14363. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14364. << "sans() must not report the iPAddress SAN as a DNS name";
  14365. }
  14366. #endif
  14367. // mbedTLS-specific callback constructor test
  14368. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14369. #ifdef CPPHTTPLIB_SSL_ENABLED
  14370. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14372. ASSERT_TRUE(svr.is_valid());
  14373. // Set up a handler to verify client certificate is present
  14374. bool client_cert_verified = false;
  14375. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14376. // Verify that client certificate was provided
  14377. client_cert_verified = true;
  14378. res.set_content("success", "text/plain");
  14379. });
  14380. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14381. auto se = detail::scope_exit([&] {
  14382. svr.stop();
  14383. t.join();
  14384. ASSERT_FALSE(svr.is_running());
  14385. });
  14386. svr.wait_until_ready();
  14387. // Client with certificate
  14388. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14389. cli.enable_server_certificate_verification(false);
  14390. cli.set_connection_timeout(30);
  14391. auto res = cli.Get("/test");
  14392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14393. ASSERT_EQ(StatusCode::OK_200, res->status);
  14394. ASSERT_TRUE(client_cert_verified);
  14395. EXPECT_EQ("success", res->body);
  14396. }
  14397. #endif
  14398. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14399. // backends
  14400. #ifdef CPPHTTPLIB_SSL_ENABLED
  14401. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14402. using namespace httplib::tls;
  14403. // Test that when client CA cert file is provided,
  14404. // the server properly requests and validates client certificates
  14405. // Create a server with client authentication
  14406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14407. ASSERT_TRUE(svr.is_valid());
  14408. bool handler_called = false;
  14409. svr.Get("/test", [&](const Request &req, Response &res) {
  14410. handler_called = true;
  14411. // Verify that a client certificate was provided
  14412. auto cert = req.peer_cert();
  14413. ASSERT_TRUE(static_cast<bool>(cert));
  14414. // Get the issuer name
  14415. std::string issuer_str = cert.issuer_name();
  14416. ASSERT_FALSE(issuer_str.empty());
  14417. // The client certificate should be issued by our test CA
  14418. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14419. res.set_content("authenticated", "text/plain");
  14420. });
  14421. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14422. auto se = detail::scope_exit([&] {
  14423. svr.stop();
  14424. t.join();
  14425. ASSERT_FALSE(svr.is_running());
  14426. });
  14427. svr.wait_until_ready();
  14428. // Connect with a client certificate issued by the CA
  14429. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14430. cli.enable_server_certificate_verification(false);
  14431. cli.set_connection_timeout(30);
  14432. auto res = cli.Get("/test");
  14433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14434. ASSERT_EQ(StatusCode::OK_200, res->status);
  14435. ASSERT_TRUE(handler_called);
  14436. EXPECT_EQ("authenticated", res->body);
  14437. }
  14438. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14439. using namespace httplib::tls;
  14440. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14441. ASSERT_TRUE(svr.is_valid());
  14442. svr.Get("/test", [](const Request &, Response &res) {
  14443. res.set_content("ok", "text/plain");
  14444. });
  14445. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14446. auto se = detail::scope_exit([&] {
  14447. svr.stop();
  14448. t.join();
  14449. });
  14450. svr.wait_until_ready();
  14451. SSLClient cli(HOST, PORT);
  14452. cli.enable_server_certificate_verification(false);
  14453. cli.set_connection_timeout(30);
  14454. bool cert_checked = false;
  14455. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14456. if (ctx.cert) {
  14457. auto sans = ctx.sans();
  14458. // Test certificate may or may not have SANs - just verify the API
  14459. // works If SANs exist, verify the types are valid
  14460. for (const auto &san : sans) {
  14461. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14462. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14463. san.type == SanType::OTHER);
  14464. EXPECT_FALSE(san.value.empty());
  14465. }
  14466. cert_checked = true;
  14467. }
  14468. return true;
  14469. });
  14470. auto res = cli.Get("/test");
  14471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14472. EXPECT_TRUE(cert_checked);
  14473. }
  14474. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14475. using namespace httplib::tls;
  14476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14477. ASSERT_TRUE(svr.is_valid());
  14478. svr.Get("/test", [](const Request &, Response &res) {
  14479. res.set_content("ok", "text/plain");
  14480. });
  14481. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14482. auto se = detail::scope_exit([&] {
  14483. svr.stop();
  14484. t.join();
  14485. });
  14486. svr.wait_until_ready();
  14487. SSLClient cli(HOST, PORT);
  14488. cli.enable_server_certificate_verification(false);
  14489. cli.set_connection_timeout(30);
  14490. bool validity_checked = false;
  14491. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14492. if (ctx.cert) {
  14493. time_t not_before = 0, not_after = 0;
  14494. bool result = ctx.validity(not_before, not_after);
  14495. EXPECT_TRUE(result);
  14496. // Verify that not_before < now < not_after for a valid cert
  14497. time_t now = time(nullptr);
  14498. EXPECT_LT(not_before, now);
  14499. EXPECT_GT(not_after, now);
  14500. validity_checked = true;
  14501. }
  14502. return true;
  14503. });
  14504. auto res = cli.Get("/test");
  14505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14506. EXPECT_TRUE(validity_checked);
  14507. }
  14508. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14509. using namespace httplib::tls;
  14510. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14511. ASSERT_TRUE(svr.is_valid());
  14512. svr.Get("/test", [](const Request &, Response &res) {
  14513. res.set_content("ok", "text/plain");
  14514. });
  14515. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14516. auto se = detail::scope_exit([&] {
  14517. svr.stop();
  14518. t.join();
  14519. });
  14520. svr.wait_until_ready();
  14521. SSLClient cli(HOST, PORT);
  14522. cli.enable_server_certificate_verification(false);
  14523. cli.set_connection_timeout(30);
  14524. bool serial_checked = false;
  14525. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14526. if (ctx.cert) {
  14527. std::string serial = ctx.serial();
  14528. EXPECT_FALSE(serial.empty());
  14529. // Serial should be a hex string
  14530. for (char c : serial) {
  14531. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14532. (c >= 'a' && c <= 'f'));
  14533. }
  14534. serial_checked = true;
  14535. }
  14536. return true;
  14537. });
  14538. auto res = cli.Get("/test");
  14539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14540. EXPECT_TRUE(serial_checked);
  14541. }
  14542. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14543. // Test 1: Valid CA file - no error should be recorded
  14544. {
  14545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14546. CLIENT_CA_CERT_FILE);
  14547. ASSERT_TRUE(svr.is_valid());
  14548. // With valid setup, last_ssl_error should be 0
  14549. EXPECT_EQ(0, svr.ssl_last_error());
  14550. }
  14551. // Test 2: Invalid CA file content
  14552. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14553. {
  14554. // Create a temporary file with completely invalid content
  14555. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14556. {
  14557. std::ofstream ofs(temp_invalid_ca);
  14558. ofs << "This is not a certificate file at all\n";
  14559. ofs << "Just plain text content\n";
  14560. }
  14561. // Create server with invalid CA file
  14562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14563. // Clean up temporary file
  14564. std::remove(temp_invalid_ca);
  14565. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14566. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14567. // Note: SSL_CTX_load_verify_locations typically fails first,
  14568. // but our error handling code path is still exercised
  14569. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14570. }
  14571. }
  14572. TEST(VerifyCallbackTest, VerifyContextFields) {
  14573. using namespace httplib::tls;
  14574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14575. ASSERT_TRUE(svr.is_valid());
  14576. svr.Get("/test", [](const Request &, Response &res) {
  14577. res.set_content("ok", "text/plain");
  14578. });
  14579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14580. auto se = detail::scope_exit([&] {
  14581. svr.stop();
  14582. t.join();
  14583. });
  14584. svr.wait_until_ready();
  14585. SSLClient cli(HOST, PORT);
  14586. cli.enable_server_certificate_verification(false);
  14587. cli.set_connection_timeout(30);
  14588. int callback_count = 0;
  14589. bool saw_leaf_cert = false;
  14590. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14591. if (ctx.cert) {
  14592. callback_count++;
  14593. // We should see at least one certificate (the leaf)
  14594. std::string cn = ctx.subject_cn();
  14595. if (!cn.empty()) { saw_leaf_cert = true; }
  14596. // Verify context fields are populated
  14597. EXPECT_NE(ctx.session, nullptr);
  14598. EXPECT_GE(ctx.depth, 0);
  14599. }
  14600. return true;
  14601. });
  14602. auto res = cli.Get("/test");
  14603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14604. EXPECT_GT(callback_count, 0);
  14605. EXPECT_TRUE(saw_leaf_cert);
  14606. }
  14607. // A verifier that accepts runs alongside the built-in verification, and is the
  14608. // only check once that is turned off.
  14609. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14610. using namespace httplib::tls;
  14611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14612. ASSERT_TRUE(svr.is_valid());
  14613. svr.Get("/test", [](const Request &, Response &res) {
  14614. res.set_content("ok", "text/plain");
  14615. });
  14616. auto port = svr.bind_to_any_port(HOST);
  14617. thread t([&]() { svr.listen_after_bind(); });
  14618. auto se = detail::scope_exit([&] {
  14619. svr.stop();
  14620. t.join();
  14621. });
  14622. svr.wait_until_ready();
  14623. SSLClient cli(HOST, port);
  14624. cli.enable_server_hostname_verification(false);
  14625. auto calls = 0;
  14626. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14627. calls++;
  14628. return true;
  14629. });
  14630. // cert.pem is not trusted
  14631. auto res = cli.Get("/test");
  14632. ASSERT_FALSE(res);
  14633. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14634. EXPECT_GT(calls, 0);
  14635. cli.enable_server_certificate_verification(false);
  14636. res = cli.Get("/test");
  14637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14638. EXPECT_EQ("ok", res->body);
  14639. }
  14640. // A verifier belongs to the client that set it, not to the thread that set it.
  14641. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14642. using namespace httplib::tls;
  14643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14644. ASSERT_TRUE(svr.is_valid());
  14645. svr.Get("/test", [](const Request &, Response &res) {
  14646. res.set_content("ok", "text/plain");
  14647. });
  14648. auto port = svr.bind_to_any_port(HOST);
  14649. thread t([&]() { svr.listen_after_bind(); });
  14650. auto se = detail::scope_exit([&] {
  14651. svr.stop();
  14652. t.join();
  14653. });
  14654. svr.wait_until_ready();
  14655. auto rejecting_calls = 0;
  14656. SSLClient rejecting(HOST, port);
  14657. rejecting.enable_server_certificate_verification(false);
  14658. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14659. rejecting_calls++;
  14660. return false;
  14661. });
  14662. auto accepting_calls = 0;
  14663. SSLClient accepting(HOST, port);
  14664. accepting.enable_server_certificate_verification(false);
  14665. // Set on another thread than the requests below.
  14666. thread([&]() {
  14667. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14668. accepting_calls++;
  14669. return true;
  14670. });
  14671. }).join();
  14672. // Requested on another thread than the verifier was set on.
  14673. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14674. EXPECT_GT(rejecting_calls, 0);
  14675. auto res = accepting.Get("/test");
  14676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14677. EXPECT_GT(accepting_calls, 0);
  14678. }
  14679. // A verifier replaced while a handshake runs it lives until it returns.
  14680. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14681. using namespace httplib::tls;
  14682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14683. ASSERT_TRUE(svr.is_valid());
  14684. svr.Get("/test", [](const Request &, Response &res) {
  14685. res.set_content("ok", "text/plain");
  14686. });
  14687. auto port = svr.bind_to_any_port(HOST);
  14688. thread t([&]() { svr.listen_after_bind(); });
  14689. auto se = detail::scope_exit([&] {
  14690. svr.stop();
  14691. t.join();
  14692. });
  14693. svr.wait_until_ready();
  14694. SSLClient cli(HOST, port);
  14695. cli.enable_server_certificate_verification(false);
  14696. std::promise<void> entered;
  14697. std::promise<void> replaced;
  14698. auto replaced_future = replaced.get_future();
  14699. auto first_call = true;
  14700. // Long enough to live on the heap
  14701. std::string expected(64, 'v');
  14702. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14703. if (first_call) {
  14704. first_call = false;
  14705. entered.set_value();
  14706. replaced_future.wait();
  14707. }
  14708. return expected == std::string(64, 'v');
  14709. });
  14710. thread request([&]() {
  14711. auto res = cli.Get("/test");
  14712. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14713. });
  14714. entered.get_future().wait();
  14715. cli.set_server_certificate_verifier(
  14716. [](const VerifyContext &) { return true; });
  14717. replaced.set_value();
  14718. request.join();
  14719. }
  14720. // VerifyContext::session is the same handle the other tls:: functions take.
  14721. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14722. using namespace httplib::tls;
  14723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14724. ASSERT_TRUE(svr.is_valid());
  14725. svr.Get("/test", [](const Request &, Response &res) {
  14726. res.set_content("ok", "text/plain");
  14727. });
  14728. auto port = svr.bind_to_any_port(HOST);
  14729. thread t([&]() { svr.listen_after_bind(); });
  14730. auto se = detail::scope_exit([&] {
  14731. svr.stop();
  14732. t.join();
  14733. });
  14734. svr.wait_until_ready();
  14735. SSLClient cli(HOST, port);
  14736. cli.enable_server_certificate_verification(false);
  14737. session_t verifier_session = nullptr;
  14738. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14739. verifier_session = ctx.session;
  14740. return true;
  14741. });
  14742. session_t session_verifier_session = nullptr;
  14743. cli.set_session_verifier([&](session_t session) {
  14744. session_verifier_session = session;
  14745. return SSLVerifierResponse::NoDecisionMade;
  14746. });
  14747. auto res = cli.Get("/test");
  14748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14749. EXPECT_NE(nullptr, verifier_session);
  14750. EXPECT_EQ(session_verifier_session, verifier_session);
  14751. }
  14752. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14753. using httplib::tls::TlsError;
  14754. // Test that verify_error_to_string returns empty for success
  14755. std::string success_str = TlsError::verify_error_to_string(0);
  14756. EXPECT_TRUE(success_str.empty());
  14757. // Test that verify_error_to_string returns non-empty for error codes
  14758. // Using a common error code (certificate expired)
  14759. std::string error_str =
  14760. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14761. EXPECT_FALSE(error_str.empty());
  14762. }
  14763. TEST(SessionVerifierTest, CertificateAccepted) {
  14764. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14765. ASSERT_TRUE(svr.is_valid());
  14766. svr.Get("/test", [](const Request &, Response &res) {
  14767. res.set_content("ok", "text/plain");
  14768. });
  14769. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14770. auto se = detail::scope_exit([&] {
  14771. svr.stop();
  14772. t.join();
  14773. });
  14774. svr.wait_until_ready();
  14775. SSLClient cli(HOST, PORT);
  14776. cli.enable_server_certificate_verification(false);
  14777. cli.set_connection_timeout(30);
  14778. bool callback_called = false;
  14779. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14780. EXPECT_NE(session, nullptr);
  14781. callback_called = true;
  14782. return SSLVerifierResponse::CertificateAccepted;
  14783. });
  14784. auto res = cli.Get("/test");
  14785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14786. EXPECT_EQ(200, res->status);
  14787. EXPECT_TRUE(callback_called);
  14788. }
  14789. TEST(SessionVerifierTest, CertificateRejected) {
  14790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14791. ASSERT_TRUE(svr.is_valid());
  14792. svr.Get("/test", [](const Request &, Response &res) {
  14793. res.set_content("ok", "text/plain");
  14794. });
  14795. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14796. auto se = detail::scope_exit([&] {
  14797. svr.stop();
  14798. t.join();
  14799. });
  14800. svr.wait_until_ready();
  14801. SSLClient cli(HOST, PORT);
  14802. cli.enable_server_certificate_verification(false);
  14803. cli.set_connection_timeout(30);
  14804. bool callback_called = false;
  14805. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14806. EXPECT_NE(session, nullptr);
  14807. callback_called = true;
  14808. return SSLVerifierResponse::CertificateRejected;
  14809. });
  14810. auto res = cli.Get("/test");
  14811. EXPECT_FALSE(res);
  14812. EXPECT_TRUE(callback_called);
  14813. }
  14814. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14816. ASSERT_TRUE(svr.is_valid());
  14817. svr.Get("/test", [](const Request &, Response &res) {
  14818. res.set_content("ok", "text/plain");
  14819. });
  14820. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14821. auto se = detail::scope_exit([&] {
  14822. svr.stop();
  14823. t.join();
  14824. });
  14825. svr.wait_until_ready();
  14826. // NoDecisionMade with verification disabled should succeed (no default check)
  14827. SSLClient cli(HOST, PORT);
  14828. cli.enable_server_certificate_verification(false);
  14829. cli.set_connection_timeout(30);
  14830. bool callback_called = false;
  14831. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14832. EXPECT_NE(session, nullptr);
  14833. callback_called = true;
  14834. return SSLVerifierResponse::NoDecisionMade;
  14835. });
  14836. auto res = cli.Get("/test");
  14837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14838. EXPECT_EQ(200, res->status);
  14839. EXPECT_TRUE(callback_called);
  14840. }
  14841. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14842. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14843. ASSERT_TRUE(svr.is_valid());
  14844. svr.Get("/test", [](const Request &, Response &res) {
  14845. res.set_content("ok", "text/plain");
  14846. });
  14847. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14848. auto se = detail::scope_exit([&] {
  14849. svr.stop();
  14850. t.join();
  14851. });
  14852. svr.wait_until_ready();
  14853. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14854. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14855. // so we only check that the request fails, not whether the callback was
  14856. // called.
  14857. SSLClient cli(HOST, PORT);
  14858. cli.enable_server_certificate_verification(true);
  14859. cli.set_connection_timeout(30);
  14860. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14861. EXPECT_NE(session, nullptr);
  14862. return SSLVerifierResponse::NoDecisionMade;
  14863. });
  14864. auto res = cli.Get("/test");
  14865. EXPECT_FALSE(res);
  14866. }
  14867. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14868. // Test SSL server using PemMemory constructor with client CA certificates
  14869. // Read PEM files
  14870. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14871. read_file(SERVER_CERT_FILE, server_cert_pem);
  14872. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14873. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14874. // Create SSLServer with PemMemory constructor including client CA
  14875. SSLServer::PemMemory server_pem = {
  14876. server_cert_pem.c_str(),
  14877. server_cert_pem.size(),
  14878. server_key_pem.c_str(),
  14879. server_key_pem.size(),
  14880. client_ca_pem.c_str(),
  14881. client_ca_pem.size(),
  14882. nullptr // no password for server key
  14883. };
  14884. SSLServer svr(server_pem);
  14885. ASSERT_TRUE(svr.is_valid());
  14886. // No SSL error should be recorded for valid setup
  14887. EXPECT_EQ(0, svr.ssl_last_error());
  14888. // Set up server endpoints
  14889. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14890. res.set_content("ok", "text/plain");
  14891. });
  14892. // Start server in a thread
  14893. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14894. svr.wait_until_ready();
  14895. // Connect with client certificate (using constructor with paths)
  14896. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14897. cli.enable_server_certificate_verification(false);
  14898. auto res = cli.Get("/test-pem-ca");
  14899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14900. EXPECT_EQ(200, res->status);
  14901. EXPECT_EQ("ok", res->body);
  14902. svr.stop();
  14903. server_thread.join();
  14904. }
  14905. #endif
  14906. #ifdef _WIN32
  14907. TEST(CleanupTest, WSACleanup) {
  14908. int ret = WSACleanup();
  14909. ASSERT_EQ(0, ret);
  14910. }
  14911. #endif
  14912. #ifndef CPPHTTPLIB_SSL_ENABLED
  14913. TEST(NoSSLSupport, SimpleInterface) {
  14914. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14915. }
  14916. #endif
  14917. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14918. TEST(InvalidScheme, SimpleInterface) {
  14919. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14920. }
  14921. #endif
  14922. TEST(NoScheme, SimpleInterface) {
  14923. Client cli("yahoo.com:80");
  14924. ASSERT_TRUE(cli.is_valid());
  14925. }
  14926. TEST(SendAPI, SimpleInterface_Online) {
  14927. Client cli("http://yahoo.com");
  14928. Request req;
  14929. req.method = "GET";
  14930. req.path = "/";
  14931. auto res = cli.send(req);
  14932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14933. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14934. }
  14935. TEST(SendAPI, WithParamsInRequest) {
  14936. Server svr;
  14937. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14938. EXPECT_TRUE(req.has_param("test"));
  14939. EXPECT_EQ("test_value", req.get_param_value("test"));
  14940. });
  14941. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14942. auto se = detail::scope_exit([&] {
  14943. svr.stop();
  14944. t.join();
  14945. ASSERT_FALSE(svr.is_running());
  14946. });
  14947. svr.wait_until_ready();
  14948. Client cli(HOST, PORT);
  14949. {
  14950. Request req;
  14951. req.method = "GET";
  14952. req.path = "/";
  14953. req.params.emplace("test", "test_value");
  14954. auto res = cli.send(req);
  14955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14956. }
  14957. {
  14958. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14960. }
  14961. }
  14962. TEST(ClientImplMethods, GetSocketTest) {
  14963. httplib::Server svr;
  14964. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14965. res.status = StatusCode::OK_200;
  14966. });
  14967. auto port = svr.bind_to_any_port("127.0.0.1");
  14968. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14969. auto se = detail::scope_exit([&] {
  14970. svr.stop();
  14971. thread.join();
  14972. ASSERT_FALSE(svr.is_running());
  14973. });
  14974. svr.wait_until_ready();
  14975. {
  14976. httplib::Client cli("127.0.0.1", port);
  14977. cli.set_keep_alive(true);
  14978. // Use the behavior of cpp-httplib of opening the connection
  14979. // only when the first request happens. If that changes,
  14980. // this test would be obsolete.
  14981. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14982. // This also implicitly tests the server. But other tests would fail much
  14983. // earlier than this one to be considered.
  14984. auto res = cli.Get("/");
  14985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14986. EXPECT_EQ(StatusCode::OK_200, res->status);
  14987. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14988. }
  14989. }
  14990. #ifdef CPPHTTPLIB_SSL_ENABLED
  14991. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14992. Client cli("http://yahoo.com");
  14993. auto res = cli.Get("/");
  14994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14995. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14996. cli.set_follow_location(true);
  14997. res = cli.Get("/");
  14998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14999. EXPECT_EQ(StatusCode::OK_200, res->status);
  15000. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15001. }
  15002. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15003. Client cli("https://yahoo.com");
  15004. auto res = cli.Get("/");
  15005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15006. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15007. cli.set_follow_location(true);
  15008. res = cli.Get("/");
  15009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15010. EXPECT_EQ(StatusCode::OK_200, res->status);
  15011. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15012. }
  15013. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15014. Client cli("https://yahoo.com");
  15015. auto res = cli.Get("/");
  15016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15017. ASSERT_FALSE(!res);
  15018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15019. ASSERT_FALSE(res == nullptr);
  15020. ASSERT_TRUE(res != nullptr);
  15021. EXPECT_EQ(Error::Success, res.error());
  15022. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15023. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15024. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15025. cli.set_follow_location(true);
  15026. res = cli.Get("/");
  15027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15028. EXPECT_EQ(Error::Success, res.error());
  15029. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15030. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15031. EXPECT_EQ(StatusCode::OK_200, res->status);
  15032. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15033. }
  15034. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15035. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15036. Client cli("https://cdnjs.cloudflare.com");
  15037. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15038. Headers{{"Accept-Encoding", "br"}});
  15039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15040. EXPECT_EQ(StatusCode::OK_200, res->status);
  15041. EXPECT_EQ(287630U, res->body.size());
  15042. EXPECT_EQ("application/javascript; charset=utf-8",
  15043. res->get_header_value("Content-Type"));
  15044. }
  15045. #endif
  15046. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15047. #undef REDIR_HOST // Silence compiler warning
  15048. #define REDIR_HOST "https://httpbingo.org"
  15049. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15050. Client cli(REDIR_HOST);
  15051. cli.set_follow_location(true);
  15052. auto res =
  15053. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15055. EXPECT_EQ(StatusCode::OK_200, res->status);
  15056. }
  15057. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15058. Client cli(REDIR_HOST);
  15059. cli.set_follow_location(true);
  15060. Params params;
  15061. params.emplace("url", "http://example.com");
  15062. params.emplace("status_code", "302");
  15063. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15065. EXPECT_EQ(StatusCode::OK_200, res->status);
  15066. }
  15067. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15068. Client cli(REDIR_HOST);
  15069. cli.set_follow_location(true);
  15070. Params params;
  15071. params.emplace("url", "http://example.com");
  15072. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15074. EXPECT_EQ(StatusCode::OK_200, res->status);
  15075. }
  15076. TEST(HttpToHttpsRedirectTest, CertFile) {
  15077. auto ssl_port = PORT + 1;
  15078. Server svr;
  15079. ASSERT_TRUE(svr.is_valid());
  15080. svr.Get("/index", [&](const Request &, Response &res) {
  15081. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15082. "/index");
  15083. svr.stop();
  15084. });
  15085. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15086. ASSERT_TRUE(ssl_svr.is_valid());
  15087. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15088. res.set_content("test", "text/plain");
  15089. ssl_svr.stop();
  15090. });
  15091. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15092. thread t2 =
  15093. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15094. auto se = detail::scope_exit([&] {
  15095. t2.join();
  15096. t.join();
  15097. ASSERT_FALSE(svr.is_running());
  15098. });
  15099. svr.wait_until_ready();
  15100. ssl_svr.wait_until_ready();
  15101. Client cli("127.0.0.1", PORT);
  15102. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15103. cli.enable_server_certificate_verification(true);
  15104. cli.set_follow_location(true);
  15105. cli.set_connection_timeout(30);
  15106. auto res = cli.Get("/index");
  15107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15108. ASSERT_EQ(StatusCode::OK_200, res->status);
  15109. }
  15110. TEST(SSLClientRedirectTest, CertFile) {
  15111. auto ssl_port = PORT + 1;
  15112. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15113. ASSERT_TRUE(ssl_svr1.is_valid());
  15114. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15115. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15116. "/index");
  15117. ssl_svr1.stop();
  15118. });
  15119. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15120. ASSERT_TRUE(ssl_svr2.is_valid());
  15121. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15122. res.set_content("test", "text/plain");
  15123. ssl_svr2.stop();
  15124. });
  15125. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15126. thread t2 =
  15127. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15128. auto se = detail::scope_exit([&] {
  15129. t2.join();
  15130. t.join();
  15131. ASSERT_FALSE(ssl_svr1.is_running());
  15132. });
  15133. ssl_svr1.wait_until_ready();
  15134. ssl_svr2.wait_until_ready();
  15135. SSLClient cli("127.0.0.1", PORT);
  15136. std::string cert;
  15137. read_file(SERVER_CERT2_FILE, cert);
  15138. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15139. cli.enable_server_certificate_verification(true);
  15140. cli.set_follow_location(true);
  15141. cli.set_connection_timeout(30);
  15142. auto res = cli.Get("/index");
  15143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15144. ASSERT_EQ(StatusCode::OK_200, res->status);
  15145. }
  15146. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15147. // another port, so the client follows it with a new client.
  15148. static Result GetThroughTlsRedirectToDifferentPort(
  15149. const std::function<void(SSLClient &)> &setup,
  15150. const char *target_cert = SERVER_CERT2_FILE,
  15151. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15152. auto ssl_port = PORT + 1;
  15153. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15154. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15155. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15156. "/index");
  15157. });
  15158. SSLServer ssl_svr2(target_cert, target_key);
  15159. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15160. res.set_content("test", "text/plain");
  15161. });
  15162. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15163. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15164. auto se = detail::scope_exit([&] {
  15165. ssl_svr2.stop();
  15166. ssl_svr1.stop();
  15167. t2.join();
  15168. t.join();
  15169. });
  15170. ssl_svr1.wait_until_ready();
  15171. ssl_svr2.wait_until_ready();
  15172. SSLClient cli("127.0.0.1", PORT);
  15173. cli.set_follow_location(true);
  15174. cli.set_connection_timeout(30);
  15175. setup(cli);
  15176. return cli.Get("/index");
  15177. }
  15178. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15179. auto calls = 0;
  15180. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15181. cli.enable_server_certificate_verification(false);
  15182. // Accept the first server only.
  15183. cli.set_session_verifier([&](tls::session_t) {
  15184. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15185. : SSLVerifierResponse::CertificateRejected;
  15186. });
  15187. });
  15188. ASSERT_FALSE(res);
  15189. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15190. EXPECT_EQ(2, calls);
  15191. }
  15192. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15193. std::string pinned;
  15194. auto res = GetThroughTlsRedirectToDifferentPort(
  15195. [&](SSLClient &cli) {
  15196. cli.enable_server_certificate_verification(false);
  15197. // Pin the first certificate seen.
  15198. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15199. if (pinned.empty()) { pinned = ctx.serial(); }
  15200. return ctx.serial() == pinned;
  15201. });
  15202. },
  15203. // A certificate other than the first server's.
  15204. SERVER_CERT_FILE);
  15205. EXPECT_FALSE(res);
  15206. EXPECT_FALSE(pinned.empty());
  15207. }
  15208. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15209. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15210. std::string cert;
  15211. read_file(SERVER_CERT2_FILE, cert);
  15212. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15213. });
  15214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15215. EXPECT_EQ(StatusCode::OK_200, res->status);
  15216. }
  15217. // The target's certificate is signed by the root CA, which the first server's
  15218. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15219. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15220. auto res = GetThroughTlsRedirectToDifferentPort(
  15221. [](SSLClient &cli) {
  15222. std::string root_ca, cert;
  15223. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15224. read_file(SERVER_CERT2_FILE, cert);
  15225. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15226. cli.load_ca_cert_store(cert.data(), cert.size());
  15227. cli.enable_server_hostname_verification(false);
  15228. },
  15229. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15231. EXPECT_EQ(StatusCode::OK_200, res->status);
  15232. }
  15233. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15234. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15235. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15236. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15237. auto res = GetThroughTlsRedirectToDifferentPort(
  15238. [](SSLClient &cli) {
  15239. std::string root_ca, cert;
  15240. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15241. read_file(SERVER_CERT2_FILE, cert);
  15242. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15243. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15244. cli.enable_server_hostname_verification(false);
  15245. },
  15246. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15247. ASSERT_FALSE(res);
  15248. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15249. }
  15250. #endif
  15251. #endif
  15252. #ifdef CPPHTTPLIB_SSL_ENABLED
  15253. // Test that set_ca_cert_store() skips system certs (consistent with
  15254. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15255. // should be trusted - system certs should NOT be loaded.
  15256. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15257. // Load a specific cert that is NOT a system CA cert
  15258. std::string cert;
  15259. read_file(SERVER_CERT2_FILE, cert);
  15260. SSLClient cli("google.com");
  15261. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15262. cli.enable_server_certificate_verification(true);
  15263. // This should FAIL because:
  15264. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15265. // 2. System certs should NOT be loaded when custom store is set
  15266. // If system certs WERE loaded, this would succeed
  15267. auto res = cli.Get("/");
  15268. ASSERT_FALSE(res);
  15269. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15270. }
  15271. // Same as above, but through the native store handle path. Regression test:
  15272. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15273. // merged system certs into the user-provided store.
  15274. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15275. std::string cert;
  15276. read_file(SERVER_CERT2_FILE, cert);
  15277. SSLClient cli("google.com");
  15278. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15279. cli.enable_server_certificate_verification(true);
  15280. auto res = cli.Get("/");
  15281. ASSERT_FALSE(res);
  15282. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15283. }
  15284. // A custom store set via the native handle must still verify a server whose
  15285. // cert it does contain.
  15286. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15287. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15288. ASSERT_TRUE(svr.is_valid());
  15289. svr.Get("/test", [&](const Request &, Response &res) {
  15290. res.set_content("test", "text/plain");
  15291. });
  15292. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15293. auto se = detail::scope_exit([&] {
  15294. svr.stop();
  15295. t.join();
  15296. ASSERT_FALSE(svr.is_running());
  15297. });
  15298. svr.wait_until_ready();
  15299. SSLClient cli("127.0.0.1", PORT);
  15300. std::string cert;
  15301. read_file(SERVER_CERT2_FILE, cert);
  15302. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15303. cli.enable_server_certificate_verification(true);
  15304. cli.set_connection_timeout(30);
  15305. auto res = cli.Get("/test");
  15306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15307. ASSERT_EQ(StatusCode::OK_200, res->status);
  15308. }
  15309. // CA certs loaded through the universal Client must be transferred to the
  15310. // client created internally for following an HTTPS redirect. Regression test:
  15311. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15312. // the CA data for redirect transfer.
  15313. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15314. auto ssl_port = PORT + 1;
  15315. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15316. ASSERT_TRUE(ssl_svr1.is_valid());
  15317. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15318. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15319. "/index");
  15320. });
  15321. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15322. ASSERT_TRUE(ssl_svr2.is_valid());
  15323. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15324. res.set_content("test", "text/plain");
  15325. });
  15326. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15327. thread t2 =
  15328. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15329. auto se = detail::scope_exit([&] {
  15330. ssl_svr2.stop();
  15331. ssl_svr1.stop();
  15332. t2.join();
  15333. t.join();
  15334. ASSERT_FALSE(ssl_svr1.is_running());
  15335. });
  15336. ssl_svr1.wait_until_ready();
  15337. ssl_svr2.wait_until_ready();
  15338. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15339. std::string cert;
  15340. read_file(SERVER_CERT2_FILE, cert);
  15341. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15342. cli.enable_server_certificate_verification(true);
  15343. cli.set_follow_location(true);
  15344. cli.set_connection_timeout(30);
  15345. auto res = cli.Get("/index");
  15346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15347. ASSERT_EQ(StatusCode::OK_200, res->status);
  15348. }
  15349. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15350. // so a host signed by a system CA verifies even though a custom CA is set
  15351. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15352. std::string cert;
  15353. read_file(SERVER_CERT2_FILE, cert);
  15354. SSLClient cli("google.com");
  15355. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15356. cli.enable_system_ca(true);
  15357. cli.enable_server_certificate_verification(true);
  15358. auto res = cli.Get("/");
  15359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15360. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15361. }
  15362. // The custom CA remains effective when combined with the system CA
  15363. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15364. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15365. ASSERT_TRUE(svr.is_valid());
  15366. svr.Get("/test", [&](const Request &, Response &res) {
  15367. res.set_content("test", "text/plain");
  15368. });
  15369. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15370. auto se = detail::scope_exit([&] {
  15371. svr.stop();
  15372. t.join();
  15373. ASSERT_FALSE(svr.is_running());
  15374. });
  15375. svr.wait_until_ready();
  15376. SSLClient cli("127.0.0.1", PORT);
  15377. std::string cert;
  15378. read_file(SERVER_CERT2_FILE, cert);
  15379. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15380. cli.enable_system_ca(true);
  15381. cli.enable_server_certificate_verification(true);
  15382. cli.set_connection_timeout(30);
  15383. auto res = cli.Get("/test");
  15384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15385. ASSERT_EQ(StatusCode::OK_200, res->status);
  15386. }
  15387. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15388. // skip chain verification entirely (only the certificate identity was
  15389. // checked), so a server presenting an untrusted certificate with a matching
  15390. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15391. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15392. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15393. ASSERT_TRUE(svr.is_valid());
  15394. svr.Get("/test", [&](const Request &, Response &res) {
  15395. res.set_content("test", "text/plain");
  15396. });
  15397. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15398. auto se = detail::scope_exit([&] {
  15399. svr.stop();
  15400. t.join();
  15401. ASSERT_FALSE(svr.is_running());
  15402. });
  15403. svr.wait_until_ready();
  15404. SSLClient cli("127.0.0.1", PORT);
  15405. std::string cert;
  15406. // A trusted CA that did not sign the server certificate. The server cert
  15407. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15408. // this connection.
  15409. read_file(CLIENT_CA_CERT_FILE, cert);
  15410. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15411. cli.enable_server_certificate_verification(true);
  15412. cli.set_connection_timeout(30);
  15413. auto res = cli.Get("/test");
  15414. ASSERT_FALSE(res);
  15415. }
  15416. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15417. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15418. // CA that failed to come through fails verification instead of trusting them.
  15419. // (wolfSSL does not list the system CAs it loaded.)
  15420. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15421. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15422. ASSERT_TRUE(svr.is_valid());
  15423. auto port = svr.bind_to_any_port("127.0.0.1");
  15424. ASSERT_LT(0, port);
  15425. thread t = thread([&] { svr.listen_after_bind(); });
  15426. auto se = detail::scope_exit([&] {
  15427. svr.stop();
  15428. t.join();
  15429. ASSERT_FALSE(svr.is_running());
  15430. });
  15431. svr.wait_until_ready();
  15432. // The CAs a client trusts once its first request has loaded them
  15433. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15434. Client cli("https://127.0.0.1:" + std::to_string(port));
  15435. setup(cli);
  15436. cli.Get("/");
  15437. return tls::get_ca_names(cli.tls_context()).size();
  15438. };
  15439. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15440. EXPECT_EQ(0u,
  15441. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15442. }
  15443. #endif
  15444. // A TLS setting changed between requests applies to the next one, not just to
  15445. // the next connection
  15446. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15447. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15448. ASSERT_TRUE(svr.is_valid());
  15449. svr.Get("/", [](const Request &req, Response &res) {
  15450. res.set_content(std::to_string(req.remote_port), "text/plain");
  15451. });
  15452. auto port = svr.bind_to_any_port("127.0.0.1");
  15453. ASSERT_LT(0, port);
  15454. thread t = thread([&] { svr.listen_after_bind(); });
  15455. auto se = detail::scope_exit([&] {
  15456. svr.stop();
  15457. t.join();
  15458. ASSERT_FALSE(svr.is_running());
  15459. });
  15460. svr.wait_until_ready();
  15461. SSLClient cli("127.0.0.1", port);
  15462. cli.set_keep_alive(true);
  15463. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15464. cli.enable_server_certificate_verification(false);
  15465. // The port the request went out from, so a new one means a new connection
  15466. auto client_port = [&] {
  15467. auto res = cli.Get("/");
  15468. return res ? res->body : std::string();
  15469. };
  15470. auto last = client_port();
  15471. ASSERT_FALSE(last.empty());
  15472. // Setting a value it already has keeps the connection
  15473. cli.enable_server_certificate_verification(false);
  15474. cli.enable_server_hostname_verification(true);
  15475. EXPECT_EQ(last, client_port());
  15476. cli.enable_server_certificate_verification(true);
  15477. auto res = cli.Get("/");
  15478. EXPECT_FALSE(res);
  15479. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15480. std::string ca;
  15481. read_file(SERVER_CERT2_FILE, ca);
  15482. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15483. last = client_port();
  15484. ASSERT_FALSE(last.empty());
  15485. std::vector<std::function<void()>> setters = {
  15486. [&] { cli.enable_server_hostname_verification(false); },
  15487. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15488. [&] {
  15489. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15490. },
  15491. [&] {
  15492. cli.set_server_certificate_verifier(
  15493. [](const tls::VerifyContext &) { return true; });
  15494. },
  15495. [&] {
  15496. cli.set_session_verifier(
  15497. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15498. },
  15499. };
  15500. for (const auto &setter : setters) {
  15501. setter();
  15502. auto next = client_port();
  15503. ASSERT_FALSE(next.empty());
  15504. EXPECT_NE(last, next);
  15505. last = next;
  15506. }
  15507. cli.set_session_verifier(
  15508. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15509. auto handle = cli.open_stream("GET", "/");
  15510. EXPECT_FALSE(handle.is_valid());
  15511. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15512. }
  15513. // A PEM given to create_ca_store() needs no NUL after it
  15514. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15515. std::string pem;
  15516. read_file(SERVER_CERT2_FILE, pem);
  15517. auto buf = pem + "X";
  15518. auto store = tls::create_ca_store(buf.data(), pem.size());
  15519. EXPECT_TRUE(store != nullptr);
  15520. SSLClient cli("localhost");
  15521. cli.set_ca_cert_store(store);
  15522. }
  15523. // enable_system_ca(false) prevents system CA loading entirely
  15524. TEST(SSLClientTest, DisableSystemCa_Online) {
  15525. SSLClient cli("google.com");
  15526. cli.enable_system_ca(false);
  15527. cli.enable_server_certificate_verification(true);
  15528. auto res = cli.Get("/");
  15529. ASSERT_FALSE(res);
  15530. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15531. // itself when the CA chain is empty
  15532. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15533. res.error() == Error::SSLConnection);
  15534. }
  15535. // The universal Client forwards enable_system_ca()
  15536. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15537. std::string cert;
  15538. read_file(SERVER_CERT2_FILE, cert);
  15539. Client cli("https://google.com");
  15540. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15541. cli.enable_system_ca(true);
  15542. cli.enable_server_certificate_verification(true);
  15543. auto res = cli.Get("/");
  15544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15545. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15546. }
  15547. // The system CA policy must carry over to the client created internally for
  15548. // following a cross-host HTTPS redirect
  15549. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15550. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15551. ASSERT_TRUE(svr.is_valid());
  15552. svr.Get("/index", [&](const Request &, Response &res) {
  15553. res.set_redirect("https://www.google.com/");
  15554. });
  15555. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15556. auto se = detail::scope_exit([&] {
  15557. svr.stop();
  15558. t.join();
  15559. ASSERT_FALSE(svr.is_running());
  15560. });
  15561. svr.wait_until_ready();
  15562. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15563. std::string cert;
  15564. read_file(SERVER_CERT2_FILE, cert);
  15565. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15566. cli.enable_system_ca(true);
  15567. cli.enable_server_certificate_verification(true);
  15568. cli.set_follow_location(true);
  15569. cli.set_connection_timeout(30);
  15570. // Receiving any response proves the redirect client completed the TLS
  15571. // handshake with a system-CA-signed host
  15572. auto res = cli.Get("/index");
  15573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15574. }
  15575. TEST(MultipartFormDataTest, LargeData) {
  15576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15577. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15578. const ContentReader &content_reader) {
  15579. if (req.is_multipart_form_data()) {
  15580. std::vector<FormData> items;
  15581. content_reader(
  15582. [&](const FormData &file) {
  15583. items.push_back(file);
  15584. return true;
  15585. },
  15586. [&](const char *data, size_t data_length) {
  15587. items.back().content.append(data, data_length);
  15588. return true;
  15589. });
  15590. EXPECT_TRUE(std::string(items[0].name) == "document");
  15591. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15592. EXPECT_TRUE(items[0].filename == "2MB_data");
  15593. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15594. EXPECT_TRUE(items[1].name == "hello");
  15595. EXPECT_TRUE(items[1].content == "world");
  15596. EXPECT_TRUE(items[1].filename == "");
  15597. EXPECT_TRUE(items[1].content_type == "");
  15598. } else {
  15599. std::string body;
  15600. content_reader([&](const char *data, size_t data_length) {
  15601. body.append(data, data_length);
  15602. return true;
  15603. });
  15604. }
  15605. });
  15606. auto port = svr.bind_to_any_port(HOST);
  15607. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15608. auto se = detail::scope_exit([&] {
  15609. svr.stop();
  15610. t.join();
  15611. ASSERT_FALSE(svr.is_running());
  15612. });
  15613. svr.wait_until_ready();
  15614. {
  15615. std::string data(1024 * 1024 * 2, '.');
  15616. std::stringstream buffer;
  15617. buffer << data;
  15618. SSLClient cli(HOST, port);
  15619. cli.enable_server_certificate_verification(false);
  15620. UploadFormDataItems items{
  15621. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15622. {"hello", "world", "", ""},
  15623. };
  15624. auto res = cli.Post("/post", items);
  15625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15626. ASSERT_EQ(StatusCode::OK_200, res->status);
  15627. }
  15628. }
  15629. TEST(MultipartFormDataTest, DataProviderItems) {
  15630. std::random_device seed_gen;
  15631. std::mt19937 random(seed_gen());
  15632. std::string rand1;
  15633. rand1.resize(1000);
  15634. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15635. std::string rand2;
  15636. rand2.resize(3000);
  15637. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15638. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15639. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15640. const ContentReader &content_reader) {
  15641. ASSERT_FALSE(req.is_multipart_form_data());
  15642. std::string body;
  15643. content_reader([&](const char *data, size_t data_length) {
  15644. body.append(data, data_length);
  15645. return true;
  15646. });
  15647. EXPECT_EQ(body, "");
  15648. });
  15649. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15650. const ContentReader &content_reader) {
  15651. ASSERT_TRUE(req.is_multipart_form_data());
  15652. std::vector<FormData> items;
  15653. content_reader(
  15654. [&](const FormData &file) {
  15655. items.push_back(file);
  15656. return true;
  15657. },
  15658. [&](const char *data, size_t data_length) {
  15659. items.back().content.append(data, data_length);
  15660. return true;
  15661. });
  15662. ASSERT_TRUE(items.size() == 2);
  15663. EXPECT_EQ(std::string(items[0].name), "name1");
  15664. EXPECT_EQ(items[0].content, "Testing123");
  15665. EXPECT_EQ(items[0].filename, "filename1");
  15666. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15667. EXPECT_EQ(items[1].name, "name2");
  15668. EXPECT_EQ(items[1].content, "Testing456");
  15669. EXPECT_EQ(items[1].filename, "");
  15670. EXPECT_EQ(items[1].content_type, "");
  15671. });
  15672. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15673. const ContentReader &content_reader) {
  15674. ASSERT_TRUE(req.is_multipart_form_data());
  15675. std::vector<FormData> items;
  15676. content_reader(
  15677. [&](const FormData &file) {
  15678. items.push_back(file);
  15679. return true;
  15680. },
  15681. [&](const char *data, size_t data_length) {
  15682. items.back().content.append(data, data_length);
  15683. return true;
  15684. });
  15685. ASSERT_TRUE(items.size() == 2);
  15686. EXPECT_EQ(items[0].name, "name3");
  15687. EXPECT_EQ(items[0].content, rand1);
  15688. EXPECT_EQ(items[0].filename, "filename3");
  15689. EXPECT_EQ(items[0].content_type, "");
  15690. EXPECT_EQ(items[1].name, "name4");
  15691. EXPECT_EQ(items[1].content, rand2);
  15692. EXPECT_EQ(items[1].filename, "filename4");
  15693. EXPECT_EQ(items[1].content_type, "");
  15694. });
  15695. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15696. const ContentReader &content_reader) {
  15697. ASSERT_TRUE(req.is_multipart_form_data());
  15698. std::vector<FormData> items;
  15699. content_reader(
  15700. [&](const FormData &file) {
  15701. items.push_back(file);
  15702. return true;
  15703. },
  15704. [&](const char *data, size_t data_length) {
  15705. items.back().content.append(data, data_length);
  15706. return true;
  15707. });
  15708. ASSERT_TRUE(items.size() == 4);
  15709. EXPECT_EQ(std::string(items[0].name), "name1");
  15710. EXPECT_EQ(items[0].content, "Testing123");
  15711. EXPECT_EQ(items[0].filename, "filename1");
  15712. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15713. EXPECT_EQ(items[1].name, "name2");
  15714. EXPECT_EQ(items[1].content, "Testing456");
  15715. EXPECT_EQ(items[1].filename, "");
  15716. EXPECT_EQ(items[1].content_type, "");
  15717. EXPECT_EQ(items[2].name, "name3");
  15718. EXPECT_EQ(items[2].content, rand1);
  15719. EXPECT_EQ(items[2].filename, "filename3");
  15720. EXPECT_EQ(items[2].content_type, "");
  15721. EXPECT_EQ(items[3].name, "name4");
  15722. EXPECT_EQ(items[3].content, rand2);
  15723. EXPECT_EQ(items[3].filename, "filename4");
  15724. EXPECT_EQ(items[3].content_type, "");
  15725. });
  15726. auto port = svr.bind_to_any_port("localhost");
  15727. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15728. auto se = detail::scope_exit([&] {
  15729. svr.stop();
  15730. t.join();
  15731. ASSERT_FALSE(svr.is_running());
  15732. });
  15733. svr.wait_until_ready();
  15734. {
  15735. SSLClient cli("localhost", port);
  15736. cli.enable_server_certificate_verification(false);
  15737. UploadFormDataItems items{
  15738. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15739. {"name2", "Testing456", "", ""}, // not a file
  15740. };
  15741. {
  15742. auto res = cli.Post("/post-none", {}, {}, {});
  15743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15744. ASSERT_EQ(StatusCode::OK_200, res->status);
  15745. }
  15746. FormDataProviderItems providers;
  15747. {
  15748. auto res =
  15749. cli.Post("/post-items", {}, items, providers); // empty providers
  15750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15751. ASSERT_EQ(StatusCode::OK_200, res->status);
  15752. }
  15753. providers.push_back({"name3",
  15754. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15755. // test the offset is given correctly at each step
  15756. if (!offset)
  15757. sink.os.write(rand1.data(), 30);
  15758. else if (offset == 30)
  15759. sink.os.write(rand1.data() + 30, 300);
  15760. else if (offset == 330)
  15761. sink.os.write(rand1.data() + 330, 670);
  15762. else if (offset == rand1.size())
  15763. sink.done();
  15764. return true;
  15765. },
  15766. "filename3",
  15767. {}});
  15768. providers.push_back({"name4",
  15769. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15770. // test the offset is given correctly at each step
  15771. if (!offset)
  15772. sink.os.write(rand2.data(), 2000);
  15773. else if (offset == 2000)
  15774. sink.os.write(rand2.data() + 2000, 1);
  15775. else if (offset == 2001)
  15776. sink.os.write(rand2.data() + 2001, 999);
  15777. else if (offset == rand2.size())
  15778. sink.done();
  15779. return true;
  15780. },
  15781. "filename4",
  15782. {}});
  15783. {
  15784. auto res = cli.Post("/post-providers", {}, {}, providers);
  15785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15786. ASSERT_EQ(StatusCode::OK_200, res->status);
  15787. }
  15788. {
  15789. auto res = cli.Post("/post-both", {}, items, providers);
  15790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15791. ASSERT_EQ(StatusCode::OK_200, res->status);
  15792. }
  15793. }
  15794. }
  15795. TEST(MultipartFormDataTest, BadHeader) {
  15796. Server svr;
  15797. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15798. res.set_content("ok", "text/plain");
  15799. });
  15800. thread t = thread([&] { svr.listen(HOST, PORT); });
  15801. auto se = detail::scope_exit([&] {
  15802. svr.stop();
  15803. t.join();
  15804. ASSERT_FALSE(svr.is_running());
  15805. });
  15806. svr.wait_until_ready();
  15807. const std::string body =
  15808. "This is the preamble. It is to be ignored, though it\r\n"
  15809. "is a handy place for composition agents to include an\r\n"
  15810. "explanatory note to non-MIME conformant readers.\r\n"
  15811. "\r\n"
  15812. "\r\n"
  15813. "--simple boundary\r\n"
  15814. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15815. ": BAD...\r\n"
  15816. "\r\n"
  15817. "value1\r\n"
  15818. "--simple boundary\r\n"
  15819. "Content-Disposition: form-data; name=\"field2\"; "
  15820. "filename=\"example.txt\"\r\n"
  15821. "\r\n"
  15822. "value2\r\n"
  15823. "--simple boundary--\r\n"
  15824. "This is the epilogue. It is also to be ignored.\r\n";
  15825. std::string content_type =
  15826. R"(multipart/form-data; boundary="simple boundary")";
  15827. Client cli(HOST, PORT);
  15828. auto res = cli.Post("/post", body, content_type.c_str());
  15829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15830. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15831. }
  15832. TEST(MultipartFormDataTest, WithPreamble) {
  15833. Server svr;
  15834. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15835. res.set_content("ok", "text/plain");
  15836. });
  15837. thread t = thread([&] { svr.listen(HOST, PORT); });
  15838. auto se = detail::scope_exit([&] {
  15839. svr.stop();
  15840. t.join();
  15841. ASSERT_FALSE(svr.is_running());
  15842. });
  15843. svr.wait_until_ready();
  15844. const std::string body =
  15845. "This is the preamble. It is to be ignored, though it\r\n"
  15846. "is a handy place for composition agents to include an\r\n"
  15847. "explanatory note to non-MIME conformant readers.\r\n"
  15848. "\r\n"
  15849. "\r\n"
  15850. "--simple boundary\r\n"
  15851. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15852. "\r\n"
  15853. "value1\r\n"
  15854. "--simple boundary\r\n"
  15855. "Content-Disposition: form-data; name=\"field2\"; "
  15856. "filename=\"example.txt\"\r\n"
  15857. "\r\n"
  15858. "value2\r\n"
  15859. "--simple boundary--\r\n"
  15860. "This is the epilogue. It is also to be ignored.\r\n";
  15861. std::string content_type =
  15862. R"(multipart/form-data; boundary="simple boundary")";
  15863. Client cli(HOST, PORT);
  15864. auto res = cli.Post("/post", body, content_type.c_str());
  15865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15866. EXPECT_EQ(StatusCode::OK_200, res->status);
  15867. }
  15868. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15870. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15871. const ContentReader &content_reader) {
  15872. if (req.is_multipart_form_data()) {
  15873. std::vector<FormData> items;
  15874. content_reader(
  15875. [&](const FormData &file) {
  15876. items.push_back(file);
  15877. return true;
  15878. },
  15879. [&](const char *data, size_t data_length) {
  15880. items.back().content.append(data, data_length);
  15881. return true;
  15882. });
  15883. EXPECT_TRUE(std::string(items[0].name) == "document");
  15884. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15885. EXPECT_TRUE(items[0].filename == "2MB_data");
  15886. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15887. EXPECT_TRUE(items[1].name == "hello");
  15888. EXPECT_TRUE(items[1].content == "world");
  15889. EXPECT_TRUE(items[1].filename == "");
  15890. EXPECT_TRUE(items[1].content_type == "");
  15891. } else {
  15892. std::string body;
  15893. content_reader([&](const char *data, size_t data_length) {
  15894. body.append(data, data_length);
  15895. return true;
  15896. });
  15897. }
  15898. });
  15899. auto port = svr.bind_to_any_port("localhost");
  15900. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15901. auto se = detail::scope_exit([&] {
  15902. svr.stop();
  15903. t.join();
  15904. ASSERT_FALSE(svr.is_running());
  15905. });
  15906. svr.wait_until_ready();
  15907. {
  15908. std::string data(1024 * 1024 * 2, '.');
  15909. std::stringstream buffer;
  15910. buffer << data;
  15911. SSLClient cli("localhost", port);
  15912. cli.enable_server_certificate_verification(false);
  15913. UploadFormDataItems items{
  15914. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15915. {"hello", "world", "", ""},
  15916. };
  15917. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15919. ASSERT_EQ(StatusCode::OK_200, res->status);
  15920. }
  15921. }
  15922. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15923. std::string data(1024 * 1024 * 2, '&');
  15924. std::stringstream buffer;
  15925. buffer << data;
  15926. Client cli("https://localhost:8080");
  15927. UploadFormDataItems items{
  15928. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15929. {"hello", "world", "", ""},
  15930. };
  15931. for (const char &c : " \t\r\n") {
  15932. auto res =
  15933. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15934. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15935. ASSERT_FALSE(res);
  15936. }
  15937. }
  15938. TEST(MultipartFormDataTest, PutFormData) {
  15939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15940. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15941. const ContentReader &content_reader) {
  15942. if (req.is_multipart_form_data()) {
  15943. std::vector<FormData> items;
  15944. content_reader(
  15945. [&](const FormData &file) {
  15946. items.push_back(file);
  15947. return true;
  15948. },
  15949. [&](const char *data, size_t data_length) {
  15950. items.back().content.append(data, data_length);
  15951. return true;
  15952. });
  15953. EXPECT_TRUE(std::string(items[0].name) == "document");
  15954. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15955. EXPECT_TRUE(items[0].filename == "2MB_data");
  15956. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15957. EXPECT_TRUE(items[1].name == "hello");
  15958. EXPECT_TRUE(items[1].content == "world");
  15959. EXPECT_TRUE(items[1].filename == "");
  15960. EXPECT_TRUE(items[1].content_type == "");
  15961. } else {
  15962. std::string body;
  15963. content_reader([&](const char *data, size_t data_length) {
  15964. body.append(data, data_length);
  15965. return true;
  15966. });
  15967. }
  15968. });
  15969. auto port = svr.bind_to_any_port("localhost");
  15970. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15971. auto se = detail::scope_exit([&] {
  15972. svr.stop();
  15973. t.join();
  15974. ASSERT_FALSE(svr.is_running());
  15975. });
  15976. svr.wait_until_ready();
  15977. {
  15978. std::string data(1024 * 1024 * 2, '&');
  15979. std::stringstream buffer;
  15980. buffer << data;
  15981. SSLClient cli("localhost", port);
  15982. cli.enable_server_certificate_verification(false);
  15983. UploadFormDataItems items{
  15984. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15985. {"hello", "world", "", ""},
  15986. };
  15987. auto res = cli.Put("/put", items);
  15988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15989. ASSERT_EQ(StatusCode::OK_200, res->status);
  15990. }
  15991. }
  15992. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15993. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15994. svr.Put("/put_customboundary",
  15995. [&](const Request &req, const Response & /*res*/,
  15996. const ContentReader &content_reader) {
  15997. if (req.is_multipart_form_data()) {
  15998. std::vector<FormData> items;
  15999. content_reader(
  16000. [&](const FormData &file) {
  16001. items.push_back(file);
  16002. return true;
  16003. },
  16004. [&](const char *data, size_t data_length) {
  16005. items.back().content.append(data, data_length);
  16006. return true;
  16007. });
  16008. EXPECT_TRUE(std::string(items[0].name) == "document");
  16009. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16010. EXPECT_TRUE(items[0].filename == "2MB_data");
  16011. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16012. EXPECT_TRUE(items[1].name == "hello");
  16013. EXPECT_TRUE(items[1].content == "world");
  16014. EXPECT_TRUE(items[1].filename == "");
  16015. EXPECT_TRUE(items[1].content_type == "");
  16016. } else {
  16017. std::string body;
  16018. content_reader([&](const char *data, size_t data_length) {
  16019. body.append(data, data_length);
  16020. return true;
  16021. });
  16022. }
  16023. });
  16024. auto port = svr.bind_to_any_port("localhost");
  16025. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16026. auto se = detail::scope_exit([&] {
  16027. svr.stop();
  16028. t.join();
  16029. ASSERT_FALSE(svr.is_running());
  16030. });
  16031. svr.wait_until_ready();
  16032. {
  16033. std::string data(1024 * 1024 * 2, '&');
  16034. std::stringstream buffer;
  16035. buffer << data;
  16036. SSLClient cli("localhost", port);
  16037. cli.enable_server_certificate_verification(false);
  16038. UploadFormDataItems items{
  16039. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16040. {"hello", "world", "", ""},
  16041. };
  16042. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16044. ASSERT_EQ(StatusCode::OK_200, res->status);
  16045. }
  16046. }
  16047. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16048. std::string data(1024 * 1024 * 2, '&');
  16049. std::stringstream buffer;
  16050. buffer << data;
  16051. Client cli("https://localhost:8080");
  16052. cli.enable_server_certificate_verification(false);
  16053. UploadFormDataItems items{
  16054. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16055. {"hello", "world", "", ""},
  16056. };
  16057. for (const char &c : " \t\r\n") {
  16058. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16059. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16060. ASSERT_FALSE(res);
  16061. }
  16062. }
  16063. TEST(MultipartFormDataTest, AlternateFilename) {
  16064. auto handled = false;
  16065. Server svr;
  16066. svr.Post("/test", [&](const Request &req, Response &res) {
  16067. ASSERT_EQ(2u, req.form.files.size());
  16068. ASSERT_EQ(1u, req.form.fields.size());
  16069. // Test files
  16070. const auto &file1 = req.form.get_file("file1");
  16071. ASSERT_EQ("file1", file1.name);
  16072. ASSERT_EQ("A.txt", file1.filename);
  16073. ASSERT_EQ("text/plain", file1.content_type);
  16074. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16075. const auto &file2 = req.form.get_file("file2");
  16076. ASSERT_EQ("file2", file2.name);
  16077. ASSERT_EQ("a.html", file2.filename);
  16078. ASSERT_EQ("text/html", file2.content_type);
  16079. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16080. file2.content);
  16081. // Test text field
  16082. const auto &text = req.form.get_field("text");
  16083. ASSERT_EQ("text default", text);
  16084. res.set_content("ok", "text/plain");
  16085. handled = true;
  16086. });
  16087. thread t = thread([&] { svr.listen(HOST, PORT); });
  16088. auto se = detail::scope_exit([&] {
  16089. svr.stop();
  16090. t.join();
  16091. ASSERT_FALSE(svr.is_running());
  16092. ASSERT_TRUE(handled);
  16093. });
  16094. svr.wait_until_ready();
  16095. auto req = "POST /test HTTP/1.1\r\n"
  16096. "Host: localhost\r\n"
  16097. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16098. "Content-Length: 399\r\n"
  16099. "\r\n"
  16100. "----------\r\n"
  16101. "Content-Disposition: form-data; name=\"text\"\r\n"
  16102. "\r\n"
  16103. "text default\r\n"
  16104. "----------\r\n"
  16105. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16106. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16107. "Content-Type: text/plain\r\n"
  16108. "\r\n"
  16109. "Content of a.txt.\r\n"
  16110. "\r\n"
  16111. "----------\r\n"
  16112. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16113. "\"a.html\"\r\n"
  16114. "Content-Type: text/html\r\n"
  16115. "\r\n"
  16116. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16117. "\r\n"
  16118. "------------\r\n";
  16119. ASSERT_TRUE(send_request(1, req));
  16120. }
  16121. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16122. auto handled = false;
  16123. Server svr;
  16124. svr.Post("/test", [&](const Request &req, Response &res) {
  16125. // Case-insensitive "utf-8''" prefix with a long value
  16126. const auto &file = req.form.get_file("file1");
  16127. ASSERT_EQ("file1", file.name);
  16128. // 8000 chars exercises both the Content-Disposition parser and the
  16129. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16130. // Prior to the fix, std::regex_match on this header would cause O(N)
  16131. // stack recursion in libstdc++, leading to SIGSEGV.
  16132. std::string expected_filename(8000, 'A');
  16133. ASSERT_EQ(expected_filename, file.filename);
  16134. res.set_content("ok", "text/plain");
  16135. handled = true;
  16136. });
  16137. thread t = thread([&] { svr.listen(HOST, PORT); });
  16138. auto se = detail::scope_exit([&] {
  16139. svr.stop();
  16140. t.join();
  16141. ASSERT_FALSE(svr.is_running());
  16142. ASSERT_TRUE(handled);
  16143. });
  16144. svr.wait_until_ready();
  16145. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16146. // Regression test for GHSA-qq6v-r583-3h69
  16147. std::string long_filename(8000, 'A');
  16148. std::string body = "----------\r\n"
  16149. "Content-Disposition: form-data; name=\"file1\"; "
  16150. "filename*=\"Utf-8''" +
  16151. long_filename +
  16152. "\"\r\n"
  16153. "\r\n"
  16154. "hello\r\n"
  16155. "------------\r\n";
  16156. auto req = "POST /test HTTP/1.1\r\n"
  16157. "Host: localhost\r\n"
  16158. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16159. "Content-Length: " +
  16160. std::to_string(body.size()) + "\r\n\r\n" + body;
  16161. ASSERT_TRUE(send_request(1, req));
  16162. }
  16163. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16164. auto handled = false;
  16165. Server svr;
  16166. svr.Post("/test", [&](const Request &req, Response &) {
  16167. ASSERT_EQ(2u, req.form.fields.size());
  16168. const auto &text1 = req.form.get_field("text1");
  16169. ASSERT_EQ("text1", text1);
  16170. const auto &text2 = req.form.get_field("text2");
  16171. ASSERT_EQ("text2", text2);
  16172. handled = true;
  16173. });
  16174. thread t = thread([&] { svr.listen(HOST, PORT); });
  16175. auto se = detail::scope_exit([&] {
  16176. svr.stop();
  16177. t.join();
  16178. ASSERT_FALSE(svr.is_running());
  16179. ASSERT_TRUE(handled);
  16180. });
  16181. svr.wait_until_ready();
  16182. auto req = "POST /test HTTP/1.1\r\n"
  16183. "Host: localhost\r\n"
  16184. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16185. "Content-Length: 146\r\n"
  16186. "\r\n----------\r\n"
  16187. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16188. "\r\n"
  16189. "text1"
  16190. "\r\n----------\r\n"
  16191. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16192. "\r\n"
  16193. "text2"
  16194. "\r\n------------";
  16195. std::string response;
  16196. ASSERT_TRUE(send_request(1, req, &response));
  16197. ASSERT_EQ("200", response.substr(9, 3));
  16198. }
  16199. TEST(MultipartFormDataTest, ContentLength) {
  16200. auto handled = false;
  16201. Server svr;
  16202. svr.Post("/test", [&](const Request &req, Response &) {
  16203. ASSERT_EQ(2u, req.form.fields.size());
  16204. const auto &text1 = req.form.get_field("text1");
  16205. ASSERT_EQ("text1", text1);
  16206. const auto &text2 = req.form.get_field("text2");
  16207. ASSERT_EQ("text2", text2);
  16208. handled = true;
  16209. });
  16210. thread t = thread([&] { svr.listen(HOST, PORT); });
  16211. auto se = detail::scope_exit([&] {
  16212. svr.stop();
  16213. t.join();
  16214. ASSERT_FALSE(svr.is_running());
  16215. ASSERT_TRUE(handled);
  16216. });
  16217. svr.wait_until_ready();
  16218. auto req = "POST /test HTTP/1.1\r\n"
  16219. "Host: localhost\r\n"
  16220. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16221. "Content-Length: 167\r\n"
  16222. "\r\n----------\r\n"
  16223. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16224. "Content-Length: 5\r\n"
  16225. "\r\n"
  16226. "text1"
  16227. "\r\n----------\r\n"
  16228. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16229. "\r\n"
  16230. "text2"
  16231. "\r\n------------\r\n";
  16232. std::string response;
  16233. ASSERT_TRUE(send_request(1, req, &response));
  16234. ASSERT_EQ("200", response.substr(9, 3));
  16235. }
  16236. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16237. auto handled = false;
  16238. Server svr;
  16239. svr.Post("/test", [&](const Request &req, Response &) {
  16240. ASSERT_EQ(2u, req.form.fields.size());
  16241. const auto &text1 = req.form.get_field("text1");
  16242. ASSERT_EQ("text1", text1);
  16243. // TODO: Add header access for text fields if needed
  16244. const auto &text2 = req.form.get_field("text2");
  16245. ASSERT_EQ("text2", text2);
  16246. // TODO: Header access for text fields needs to be implemented
  16247. // auto &headers = it->second.headers;
  16248. // ASSERT_EQ(3U, headers.size());
  16249. // auto custom_header = headers.find("x-whatever");
  16250. // ASSERT_TRUE(custom_header != headers.end());
  16251. // ASSERT_NE("customvalue", custom_header->second);
  16252. // ASSERT_EQ("CustomValue", custom_header->second);
  16253. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16254. handled = true;
  16255. });
  16256. thread t = thread([&] { svr.listen(HOST, PORT); });
  16257. auto se = detail::scope_exit([&] {
  16258. svr.stop();
  16259. t.join();
  16260. ASSERT_FALSE(svr.is_running());
  16261. ASSERT_TRUE(handled);
  16262. });
  16263. svr.wait_until_ready();
  16264. auto req = "POST /test HTTP/1.1\r\n"
  16265. "Host: localhost\r\n"
  16266. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16267. "Content-Length: 232\r\n"
  16268. "\r\n----------\r\n"
  16269. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16270. "Content-Length: 5\r\n"
  16271. "X-Test: 1\r\n"
  16272. "\r\n"
  16273. "text1"
  16274. "\r\n----------\r\n"
  16275. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16276. "Content-Type: text/plain\r\n"
  16277. "X-Whatever: CustomValue\r\n"
  16278. "\r\n"
  16279. "text2"
  16280. "\r\n------------\r\n"
  16281. "That should be disregarded. Not even read";
  16282. std::string response;
  16283. ASSERT_TRUE(send_request(1, req, &response));
  16284. ASSERT_EQ("200", response.substr(9, 3));
  16285. }
  16286. TEST(MultipartFormDataTest, LargeHeader) {
  16287. auto handled = false;
  16288. Server svr;
  16289. svr.Post("/test", [&](const Request &req, Response &) {
  16290. ASSERT_EQ(1u, req.form.fields.size());
  16291. const auto &text = req.form.get_field("name1");
  16292. ASSERT_EQ("text1", text);
  16293. handled = true;
  16294. });
  16295. thread t = thread([&] { svr.listen(HOST, PORT); });
  16296. auto se = detail::scope_exit([&] {
  16297. svr.stop();
  16298. t.join();
  16299. ASSERT_FALSE(svr.is_running());
  16300. ASSERT_TRUE(handled);
  16301. });
  16302. svr.wait_until_ready();
  16303. auto boundary = std::string("cpp-httplib-multipart-data");
  16304. std::string content = "--" + boundary +
  16305. "\r\n"
  16306. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16307. "\r\n"
  16308. "text1\r\n"
  16309. "--" +
  16310. boundary + "--\r\n";
  16311. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16312. "Host: localhost\r\n"
  16313. "Content-Type: multipart/form-data;boundary=" +
  16314. boundary +
  16315. "\r\n"
  16316. "Content-Length: " +
  16317. std::to_string(content.size()) +
  16318. "\r\n"
  16319. "Dummy-Header: ";
  16320. std::string header_suffix = "\r\n"
  16321. "\r\n";
  16322. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16323. size_t header_dummy_size =
  16324. read_buff_size -
  16325. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16326. auto header_dummy = std::string(header_dummy_size, '@');
  16327. auto req = header_prefix + header_dummy + header_suffix + content;
  16328. std::string response;
  16329. ASSERT_TRUE(send_request(1, req, &response));
  16330. ASSERT_EQ("200", response.substr(9, 3));
  16331. }
  16332. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16333. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16334. // (not chunked Transfer-Encoding) after the streaming refactor.
  16335. auto handled = false;
  16336. Server svr;
  16337. svr.Post("/upload", [&](const Request &req, Response &res) {
  16338. auto cl_it = req.headers.find("Content-Length");
  16339. EXPECT_TRUE(cl_it != req.headers.end());
  16340. auto te_it = req.headers.find("Transfer-Encoding");
  16341. EXPECT_TRUE(te_it == req.headers.end());
  16342. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16343. res.set_content("ok", "text/plain");
  16344. handled = true;
  16345. });
  16346. auto port = svr.bind_to_any_port(HOST);
  16347. auto t = thread([&] { svr.listen_after_bind(); });
  16348. auto se = detail::scope_exit([&] {
  16349. svr.stop();
  16350. t.join();
  16351. ASSERT_FALSE(svr.is_running());
  16352. ASSERT_TRUE(handled);
  16353. });
  16354. svr.wait_until_ready();
  16355. UploadFormDataItems items = {
  16356. {"field1", "hello", "", "text/plain"},
  16357. {"file1", "world", "test.txt", "application/octet-stream"},
  16358. };
  16359. Client cli(HOST, port);
  16360. auto res = cli.Post("/upload", {}, items);
  16361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16362. EXPECT_EQ(StatusCode::OK_200, res->status);
  16363. }
  16364. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16365. // Verify that make_multipart_content_provider coalesces many small segments
  16366. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16367. constexpr size_t kItemCount = 1000;
  16368. UploadFormDataItems items;
  16369. items.reserve(kItemCount);
  16370. for (size_t i = 0; i < kItemCount; i++) {
  16371. items.push_back(
  16372. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16373. }
  16374. const std::string boundary = "----test-boundary";
  16375. auto content_length = detail::get_multipart_content_length(items, boundary);
  16376. auto provider = detail::make_multipart_content_provider(items, boundary);
  16377. // Drive the provider the same way write_content_with_progress does
  16378. size_t write_count = 0;
  16379. size_t total_bytes = 0;
  16380. DataSink sink;
  16381. size_t offset = 0;
  16382. sink.write = [&](const char *d, size_t l) -> bool {
  16383. (void)d;
  16384. write_count++;
  16385. total_bytes += l;
  16386. offset += l;
  16387. return true;
  16388. };
  16389. sink.is_writable = []() -> bool { return true; };
  16390. while (offset < content_length) {
  16391. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16392. }
  16393. EXPECT_EQ(content_length, total_bytes);
  16394. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16395. // With buffering into 64KB blocks, write_count should be much smaller.
  16396. auto segment_count = 3 * kItemCount + 1;
  16397. EXPECT_LT(write_count, segment_count / 10);
  16398. }
  16399. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16400. // Integration test: send many UploadFormDataItems and verify the server
  16401. // receives all of them correctly (#2410).
  16402. constexpr size_t kItemCount = 500;
  16403. auto handled = false;
  16404. Server svr;
  16405. svr.Post("/upload", [&](const Request &req, Response &res) {
  16406. EXPECT_EQ(kItemCount, req.form.fields.size());
  16407. for (size_t i = 0; i < kItemCount; i++) {
  16408. auto key = "field" + std::to_string(i);
  16409. auto val = "value" + std::to_string(i);
  16410. auto it = req.form.fields.find(key);
  16411. if (it != req.form.fields.end()) {
  16412. EXPECT_EQ(val, it->second.content);
  16413. } else {
  16414. ADD_FAILURE() << "Missing field: " << key;
  16415. }
  16416. }
  16417. res.set_content("ok", "text/plain");
  16418. handled = true;
  16419. });
  16420. auto port = svr.bind_to_any_port(HOST);
  16421. auto t = thread([&] { svr.listen_after_bind(); });
  16422. auto se = detail::scope_exit([&] {
  16423. svr.stop();
  16424. t.join();
  16425. ASSERT_FALSE(svr.is_running());
  16426. ASSERT_TRUE(handled);
  16427. });
  16428. svr.wait_until_ready();
  16429. UploadFormDataItems items;
  16430. items.reserve(kItemCount);
  16431. for (size_t i = 0; i < kItemCount; i++) {
  16432. items.push_back(
  16433. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16434. }
  16435. Client cli(HOST, port);
  16436. auto res = cli.Post("/upload", items);
  16437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16438. EXPECT_EQ(StatusCode::OK_200, res->status);
  16439. }
  16440. TEST(MultipartFormDataTest, MakeFileProvider) {
  16441. // Verify make_file_provider sends a file's contents correctly.
  16442. const std::string file_content(4096, 'Z');
  16443. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16444. {
  16445. std::ofstream ofs(tmp_path, std::ios::binary);
  16446. ofs.write(file_content.data(),
  16447. static_cast<std::streamsize>(file_content.size()));
  16448. }
  16449. auto handled = false;
  16450. Server svr;
  16451. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16452. const ContentReader &content_reader) {
  16453. ASSERT_TRUE(req.is_multipart_form_data());
  16454. std::vector<FormData> items;
  16455. content_reader(
  16456. [&](const FormData &file) {
  16457. items.push_back(file);
  16458. return true;
  16459. },
  16460. [&](const char *data, size_t data_length) {
  16461. items.back().content.append(data, data_length);
  16462. return true;
  16463. });
  16464. ASSERT_EQ(1u, items.size());
  16465. EXPECT_EQ("myfile", items[0].name);
  16466. EXPECT_EQ("data.bin", items[0].filename);
  16467. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16468. EXPECT_EQ(file_content, items[0].content);
  16469. handled = true;
  16470. });
  16471. auto port = svr.bind_to_any_port(HOST);
  16472. auto t = thread([&] { svr.listen_after_bind(); });
  16473. auto se = detail::scope_exit([&] {
  16474. svr.stop();
  16475. t.join();
  16476. ASSERT_FALSE(svr.is_running());
  16477. ASSERT_TRUE(handled);
  16478. std::remove(tmp_path.c_str());
  16479. });
  16480. svr.wait_until_ready();
  16481. FormDataProviderItems providers;
  16482. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16483. "application/octet-stream"));
  16484. Client cli(HOST, port);
  16485. auto res = cli.Post("/upload", {}, {}, providers);
  16486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16487. EXPECT_EQ(StatusCode::OK_200, res->status);
  16488. }
  16489. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16490. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16491. // (100) headers is rejected with a 400 Bad Request response.
  16492. Server svr;
  16493. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16494. res.set_content("ok", "text/plain");
  16495. });
  16496. thread t = thread([&] { svr.listen(HOST, PORT); });
  16497. auto se = detail::scope_exit([&] {
  16498. svr.stop();
  16499. t.join();
  16500. ASSERT_FALSE(svr.is_running());
  16501. });
  16502. svr.wait_until_ready();
  16503. // Build a multipart part with 101 custom headers (exceeding
  16504. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16505. std::stringstream body;
  16506. body << "--simpleboundary\r\n"
  16507. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16508. for (int i = 0; i < 101; i++) {
  16509. body << "X-Custom-Header-" << i << ": value\r\n";
  16510. }
  16511. body << "\r\n"
  16512. << "value1\r\n"
  16513. << "--simpleboundary--\r\n";
  16514. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16515. Client cli(HOST, PORT);
  16516. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16518. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16519. }
  16520. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16521. // A body that never contains the declared boundary must not be accumulated
  16522. // while the parser waits for it. Buffering it would also make every read
  16523. // rescan everything seen so far, which is quadratic in the body size.
  16524. Server svr;
  16525. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16526. res.set_content("ok", "text/plain");
  16527. });
  16528. auto port = svr.bind_to_any_port(HOST);
  16529. thread t = thread([&] { svr.listen_after_bind(); });
  16530. auto se = detail::scope_exit([&] {
  16531. svr.stop();
  16532. t.join();
  16533. ASSERT_FALSE(svr.is_running());
  16534. });
  16535. svr.wait_until_ready();
  16536. Client cli(HOST, port);
  16537. cli.set_read_timeout(60, 0);
  16538. cli.set_write_timeout(60, 0);
  16539. // '-' is the worst case: it matches the first character of the boundary, so
  16540. // every position has to be checked against it.
  16541. auto post_dashes = [&](size_t size) {
  16542. const std::string body(size, '-');
  16543. auto start = std::chrono::steady_clock::now();
  16544. auto res =
  16545. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16546. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16547. std::chrono::steady_clock::now() - start)
  16548. .count();
  16549. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16550. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16551. return ms;
  16552. };
  16553. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16554. // Windows.
  16555. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16556. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16557. // Comparing the two sizes rather than checking an absolute duration keeps
  16558. // this meaningful across build types and CI load, both of which move the
  16559. // absolute numbers by more than an order of magnitude. Four times the bytes
  16560. // costs about four times the time when parsing is linear, and about sixteen
  16561. // times when the body is buffered and rescanned.
  16562. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16563. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16564. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16565. << "ms, which suggests the body is being buffered and rescanned";
  16566. }
  16567. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16568. // A boundary can only be followed by CRLF or by "--", so anything else is
  16569. // malformed no matter what comes next. The parser must say so right away
  16570. // instead of buffering the rest of the declared body.
  16571. Server svr;
  16572. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16573. res.set_content("ok", "text/plain");
  16574. });
  16575. auto port = svr.bind_to_any_port(HOST);
  16576. thread t = thread([&] { svr.listen_after_bind(); });
  16577. auto se = detail::scope_exit([&] {
  16578. svr.stop();
  16579. t.join();
  16580. ASSERT_FALSE(svr.is_running());
  16581. });
  16582. svr.wait_until_ready();
  16583. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16584. // buffers instead of failing would still be waiting for the remaining bytes.
  16585. const std::string body = "--zzzz\r\n"
  16586. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16587. "\r\n"
  16588. "text1"
  16589. "\r\n--zzzzXX";
  16590. const std::string req = "POST /post HTTP/1.1\r\n"
  16591. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16592. "Content-Length: 1048576\r\n"
  16593. "\r\n" +
  16594. body;
  16595. std::string response;
  16596. ASSERT_TRUE(send_request(3, req, &response, port));
  16597. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16598. EXPECT_EQ("400", response.substr(9, 3));
  16599. }
  16600. // Posts a multipart body split into two writes, so that the server sees the
  16601. // split at whatever offset the caller chose, and expects the single "text1"
  16602. // field to come through.
  16603. static void expect_split_multipart_ok(const std::string &body1,
  16604. const std::string &body2) {
  16605. auto handled = false;
  16606. Server svr;
  16607. svr.Post("/post", [&](const Request &req, Response &) {
  16608. EXPECT_EQ(1u, req.form.fields.size());
  16609. EXPECT_EQ("text1", req.form.get_field("text1"));
  16610. handled = true;
  16611. });
  16612. auto port = svr.bind_to_any_port(HOST);
  16613. thread t = thread([&] { svr.listen_after_bind(); });
  16614. auto se = detail::scope_exit([&] {
  16615. svr.stop();
  16616. t.join();
  16617. ASSERT_FALSE(svr.is_running());
  16618. ASSERT_TRUE(handled);
  16619. });
  16620. svr.wait_until_ready();
  16621. // "Connection: close" makes the server close once it has answered, so the
  16622. // response drain ends immediately instead of idling until the read timeout.
  16623. const std::string head =
  16624. "POST /post HTTP/1.1\r\n"
  16625. "Host: localhost\r\n"
  16626. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16627. "Connection: close\r\n"
  16628. "Content-Length: " +
  16629. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16630. std::string response;
  16631. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16632. ASSERT_GE(response.size(), 12u) << "no response";
  16633. EXPECT_EQ("200", response.substr(9, 3));
  16634. }
  16635. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16636. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16637. // ignored, including when it does not arrive in the same read as the
  16638. // close-delimiter itself.
  16639. expect_split_multipart_ok("--zzzz\r\n"
  16640. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16641. "\r\n"
  16642. "text1"
  16643. "\r\n--zzzz--",
  16644. "\r\nthis epilogue must be ignored\r\n");
  16645. }
  16646. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16647. // The initial boundary may be preceded by a preamble of any length and may
  16648. // straddle a read boundary. Discarding data while waiting for it must not
  16649. // throw away a partial boundary sitting at the end of the buffer.
  16650. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16651. "zz\r\n"
  16652. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16653. "\r\n"
  16654. "text1"
  16655. "\r\n--zzzz--\r\n");
  16656. }
  16657. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16658. // The received boundary was only checked for being non-empty, so it could be
  16659. // as long as a header is allowed to be. The parser scans the body for
  16660. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16661. // costs a nearly full comparison at nearly every position, making the
  16662. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16663. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16664. Server svr;
  16665. svr.Post("/post", [](const Request &req, Response &res) {
  16666. EXPECT_EQ(1u, req.form.fields.size());
  16667. EXPECT_EQ("text1", req.form.get_field("text1"));
  16668. res.set_content("ok", "text/plain");
  16669. });
  16670. auto port = svr.bind_to_any_port(HOST);
  16671. thread t = thread([&] { svr.listen_after_bind(); });
  16672. auto se = detail::scope_exit([&] {
  16673. svr.stop();
  16674. t.join();
  16675. ASSERT_FALSE(svr.is_running());
  16676. });
  16677. svr.wait_until_ready();
  16678. Client cli(HOST, port);
  16679. auto post_with_boundary_of_length = [&](size_t len) {
  16680. const std::string boundary(len, 'a');
  16681. const std::string body =
  16682. "--" + boundary +
  16683. "\r\n"
  16684. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16685. "\r\n"
  16686. "text1"
  16687. "\r\n--" +
  16688. boundary + "--\r\n";
  16689. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16690. };
  16691. auto res = post_with_boundary_of_length(70);
  16692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16693. EXPECT_EQ(StatusCode::OK_200, res->status);
  16694. res = post_with_boundary_of_length(71);
  16695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16696. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16697. }
  16698. TEST(MakeFileBodyTest, Basic) {
  16699. const std::string file_content(4096, 'Z');
  16700. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16701. {
  16702. std::ofstream ofs(tmp_path, std::ios::binary);
  16703. ofs.write(file_content.data(),
  16704. static_cast<std::streamsize>(file_content.size()));
  16705. }
  16706. auto handled = false;
  16707. Server svr;
  16708. svr.Post("/upload", [&](const Request &req, Response &res) {
  16709. EXPECT_EQ(file_content, req.body);
  16710. handled = true;
  16711. res.status = StatusCode::OK_200;
  16712. });
  16713. auto port = svr.bind_to_any_port(HOST);
  16714. auto t = thread([&] { svr.listen_after_bind(); });
  16715. auto se = detail::scope_exit([&] {
  16716. svr.stop();
  16717. t.join();
  16718. ASSERT_FALSE(svr.is_running());
  16719. ASSERT_TRUE(handled);
  16720. std::remove(tmp_path.c_str());
  16721. });
  16722. svr.wait_until_ready();
  16723. auto fb = make_file_body(tmp_path);
  16724. ASSERT_GT(fb.first, 0u);
  16725. Client cli(HOST, port);
  16726. auto res =
  16727. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16729. EXPECT_EQ(StatusCode::OK_200, res->status);
  16730. }
  16731. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16732. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16733. {
  16734. std::ofstream ofs(path, std::ios::binary);
  16735. const std::string content(100, 'A');
  16736. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16737. }
  16738. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16739. auto body = make_file_body(path);
  16740. ASSERT_EQ(100u, body.first);
  16741. ASSERT_TRUE(static_cast<bool>(body.second));
  16742. // Rewritten shorter after its length was measured - and, on a server, after
  16743. // that length has already gone out as Content-Length.
  16744. {
  16745. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16746. const std::string content(10, 'A');
  16747. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16748. }
  16749. std::string written;
  16750. DataSink sink;
  16751. sink.write = [&](const char *d, size_t l) {
  16752. written.append(d, l);
  16753. return true;
  16754. };
  16755. // The provider has to report failure. write_content_with_progress() advances
  16756. // its offset only by what was written, so a provider that returns true
  16757. // without completing the length it promised is called again straight away,
  16758. // and again.
  16759. EXPECT_FALSE(body.second(0, body.first, sink));
  16760. EXPECT_EQ(std::string(10, 'A'), written);
  16761. }
  16762. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16763. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16764. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16765. {
  16766. std::ofstream ofs(path, std::ios::binary);
  16767. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16768. }
  16769. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16770. auto body = make_file_body(path);
  16771. ASSERT_EQ(content.size(), body.first);
  16772. ASSERT_TRUE(static_cast<bool>(body.second));
  16773. std::string written;
  16774. DataSink sink;
  16775. sink.write = [&](const char *d, size_t l) {
  16776. written.append(d, l);
  16777. return true;
  16778. };
  16779. EXPECT_TRUE(body.second(0, body.first, sink));
  16780. EXPECT_EQ(content, written);
  16781. }
  16782. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16783. static constexpr unsigned int number_of_tasks{1000000};
  16784. std::atomic_uint count{0};
  16785. std::unique_ptr<TaskQueue> task_queue{
  16786. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16787. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16788. auto queued = task_queue->enqueue(
  16789. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16790. EXPECT_TRUE(queued);
  16791. }
  16792. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16793. task_queue->shutdown();
  16794. #else
  16795. EXPECT_NO_THROW(task_queue->shutdown());
  16796. #endif
  16797. EXPECT_EQ(number_of_tasks, count.load());
  16798. }
  16799. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16800. static constexpr unsigned int number_of_tasks{1000000};
  16801. static constexpr unsigned int qlimit{2};
  16802. unsigned int queued_count{0};
  16803. std::atomic_uint count{0};
  16804. std::unique_ptr<TaskQueue> task_queue{
  16805. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16806. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16807. if (task_queue->enqueue(
  16808. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16809. queued_count++;
  16810. }
  16811. }
  16812. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16813. task_queue->shutdown();
  16814. #else
  16815. EXPECT_NO_THROW(task_queue->shutdown());
  16816. #endif
  16817. EXPECT_EQ(queued_count, count.load());
  16818. EXPECT_TRUE(queued_count <= number_of_tasks);
  16819. EXPECT_TRUE(queued_count >= qlimit);
  16820. }
  16821. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16822. // Use a short idle timeout so a dynamic thread spawns, times out and
  16823. // exits during the test, and the pool keeps working afterwards.
  16824. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16825. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16826. /*idle_timeout_sec=*/1}};
  16827. std::atomic_uint count{0};
  16828. std::condition_variable cv;
  16829. std::mutex mtx;
  16830. bool release = false;
  16831. // Block the base thread so the second task spawns a dynamic thread.
  16832. EXPECT_TRUE(task_queue->enqueue([&] {
  16833. std::unique_lock<std::mutex> lock(mtx);
  16834. while (!release) {
  16835. cv.wait(lock);
  16836. }
  16837. count++;
  16838. }));
  16839. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16840. // Let the dynamic thread finish its task and exceed the idle timeout.
  16841. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16842. {
  16843. std::unique_lock<std::mutex> lock(mtx);
  16844. release = true;
  16845. }
  16846. cv.notify_all();
  16847. // The pool must still accept and run tasks after the dynamic thread exited.
  16848. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16849. task_queue->shutdown();
  16850. EXPECT_EQ(3u, count.load());
  16851. }
  16852. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16853. static constexpr size_t number_of_tasks{32};
  16854. std::unique_ptr<TaskQueue> task_queue{
  16855. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16856. // Let the base threads go idle so the burst below finds them waiting.
  16857. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16858. std::mutex mtx;
  16859. std::condition_variable cv;
  16860. size_t running = 0;
  16861. bool release = false;
  16862. for (size_t i = 0; i < number_of_tasks; i++) {
  16863. EXPECT_TRUE(task_queue->enqueue([&] {
  16864. std::unique_lock<std::mutex> lock(mtx);
  16865. running++;
  16866. cv.notify_all();
  16867. cv.wait(lock, [&] { return release; });
  16868. }));
  16869. }
  16870. {
  16871. std::unique_lock<std::mutex> lock(mtx);
  16872. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16873. [&] { return running == number_of_tasks; }));
  16874. release = true;
  16875. }
  16876. cv.notify_all();
  16877. task_queue->shutdown();
  16878. }
  16879. TEST(TaskQueueTest, MaxQueuedRequests) {
  16880. static constexpr unsigned int qlimit{3};
  16881. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16882. std::condition_variable sem_cv;
  16883. std::mutex sem_mtx;
  16884. int credits = 0;
  16885. bool queued;
  16886. /* Fill up the queue with tasks that will block until we give them credits to
  16887. * complete. */
  16888. for (unsigned int n = 0; n <= qlimit;) {
  16889. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16890. std::unique_lock<std::mutex> lock(sem_mtx);
  16891. while (credits <= 0) {
  16892. sem_cv.wait(lock);
  16893. }
  16894. /* Consume the credit and signal the test code if they are all gone. */
  16895. if (--credits == 0) { sem_cv.notify_one(); }
  16896. });
  16897. if (n < qlimit) {
  16898. /* The first qlimit enqueues must succeed. */
  16899. EXPECT_TRUE(queued);
  16900. } else {
  16901. /* The last one will succeed only when the worker thread
  16902. * starts and dequeues the first blocking task. Although
  16903. * not necessary for the correctness of this test, we sleep for
  16904. * a short while to avoid busy waiting. */
  16905. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16906. }
  16907. if (queued) { n++; }
  16908. }
  16909. /* Further enqueues must fail since the queue is full. */
  16910. for (auto i = 0; i < 4; i++) {
  16911. queued = task_queue->enqueue([] {});
  16912. EXPECT_FALSE(queued);
  16913. }
  16914. /* Give the credits to allow the previous tasks to complete. */
  16915. {
  16916. std::unique_lock<std::mutex> lock(sem_mtx);
  16917. credits += qlimit + 1;
  16918. }
  16919. sem_cv.notify_all();
  16920. /* Wait for all the credits to be consumed. */
  16921. {
  16922. std::unique_lock<std::mutex> lock(sem_mtx);
  16923. while (credits > 0) {
  16924. sem_cv.wait(lock);
  16925. }
  16926. }
  16927. /* Check that we are able again to enqueue at least qlimit tasks. */
  16928. for (unsigned int i = 0; i < qlimit; i++) {
  16929. queued = task_queue->enqueue([] {});
  16930. EXPECT_TRUE(queued);
  16931. }
  16932. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16933. task_queue->shutdown();
  16934. #else
  16935. EXPECT_NO_THROW(task_queue->shutdown());
  16936. #endif
  16937. }
  16938. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16939. Server svr;
  16940. std::string method;
  16941. std::string body;
  16942. auto has_content_length = false;
  16943. auto has_transfer_encoding = false;
  16944. std::atomic<int> bad_requests{0};
  16945. // Leftover body bytes get parsed as a malformed request and answered with
  16946. // 400
  16947. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16948. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16949. });
  16950. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16951. res.set_redirect("/down", StatusCode::SeeOther_303);
  16952. });
  16953. svr.Get("/down", [&](const Request &req, Response &res) {
  16954. method = req.method;
  16955. body = req.body;
  16956. has_content_length = req.has_header("Content-Length");
  16957. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16958. res.set_content("ok", "text/plain");
  16959. });
  16960. auto port = svr.bind_to_any_port(HOST);
  16961. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16962. auto se = detail::scope_exit([&] {
  16963. svr.stop();
  16964. thread.join();
  16965. ASSERT_FALSE(svr.is_running());
  16966. });
  16967. svr.wait_until_ready();
  16968. const std::string payload = "SECRET-BODY";
  16969. auto check = [&](Client &cli, const Result &res) {
  16970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16971. EXPECT_EQ(StatusCode::OK_200, res->status);
  16972. EXPECT_EQ("ok", res->body);
  16973. EXPECT_EQ("GET", method);
  16974. EXPECT_TRUE(body.empty());
  16975. EXPECT_FALSE(has_content_length);
  16976. EXPECT_FALSE(has_transfer_encoding);
  16977. // Nothing of the original body may be left on the connection
  16978. auto res2 = cli.Get("/down");
  16979. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16980. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16981. EXPECT_EQ("ok", res2->body);
  16982. EXPECT_EQ(0, bad_requests);
  16983. };
  16984. // With content length
  16985. {
  16986. Client cli(HOST, port);
  16987. cli.set_keep_alive(true);
  16988. cli.set_follow_location(true);
  16989. auto res = cli.Post(
  16990. "/up", payload.size(),
  16991. [&](size_t offset, size_t length, DataSink &sink) {
  16992. return sink.write(payload.data() + offset, length);
  16993. },
  16994. "text/plain");
  16995. check(cli, res);
  16996. }
  16997. // Without content length (chunked)
  16998. {
  16999. Client cli(HOST, port);
  17000. cli.set_keep_alive(true);
  17001. cli.set_follow_location(true);
  17002. auto res = cli.Post(
  17003. "/up",
  17004. [&](size_t /*offset*/, DataSink &sink) {
  17005. sink.write(payload.data(), payload.size());
  17006. sink.done();
  17007. return true;
  17008. },
  17009. "text/plain");
  17010. check(cli, res);
  17011. }
  17012. }
  17013. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17014. Server svr;
  17015. std::string target;
  17016. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17017. // Echo the still-encoded name back in the Location
  17018. const std::string prefix = "/start/";
  17019. res.status = StatusCode::Found_302;
  17020. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17021. });
  17022. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17023. target = req.target;
  17024. res.set_content("ok", "text/plain");
  17025. });
  17026. auto port = svr.bind_to_any_port(HOST);
  17027. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17028. auto se = detail::scope_exit([&] {
  17029. svr.stop();
  17030. thread.join();
  17031. ASSERT_FALSE(svr.is_running());
  17032. });
  17033. svr.wait_until_ready();
  17034. // Decoding the Location path would turn the first four into a path
  17035. // separator, a query delimiter, a fragment delimiter and a different
  17036. // percent-encoded octet. The rest must keep reaching the server as they are.
  17037. const std::vector<std::string> names = {
  17038. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17039. };
  17040. for (auto path_encode : {true, false}) {
  17041. Client cli(HOST, port);
  17042. cli.set_follow_location(true);
  17043. cli.set_path_encode(path_encode);
  17044. for (const auto &name : names) {
  17045. target.clear();
  17046. auto res = cli.Get("/start/" + name);
  17047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17048. EXPECT_EQ(StatusCode::OK_200, res->status);
  17049. EXPECT_EQ("/dest/" + name, target);
  17050. }
  17051. }
  17052. }
  17053. TEST(RedirectTest, NotModifiedIsReturned) {
  17054. Server svr;
  17055. svr.Get("/cached", [](const Request &, Response &res) {
  17056. res.status = StatusCode::NotModified_304;
  17057. });
  17058. auto port = svr.bind_to_any_port(HOST);
  17059. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17060. auto se = detail::scope_exit([&] {
  17061. svr.stop();
  17062. thread.join();
  17063. ASSERT_FALSE(svr.is_running());
  17064. });
  17065. svr.wait_until_ready();
  17066. Client cli(HOST, port);
  17067. cli.set_follow_location(true);
  17068. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17070. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17071. }
  17072. TEST(RedirectTest, NoLocationIsReturned) {
  17073. Server svr;
  17074. svr.Get("/no-location", [](const Request &, Response &res) {
  17075. res.status = StatusCode::Found_302;
  17076. res.set_content("no location", "text/plain");
  17077. });
  17078. auto port = svr.bind_to_any_port(HOST);
  17079. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17080. auto se = detail::scope_exit([&] {
  17081. svr.stop();
  17082. thread.join();
  17083. ASSERT_FALSE(svr.is_running());
  17084. });
  17085. svr.wait_until_ready();
  17086. Client cli(HOST, port);
  17087. cli.set_follow_location(true);
  17088. auto res = cli.Get("/no-location");
  17089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17090. EXPECT_EQ(StatusCode::Found_302, res->status);
  17091. EXPECT_EQ("no location", res->body);
  17092. // The callbacks see the body of the response that is returned
  17093. auto handler_called = false;
  17094. auto progress_called = false;
  17095. std::string body;
  17096. auto res2 = cli.Get(
  17097. "/no-location",
  17098. [&](const Response &) {
  17099. handler_called = true;
  17100. return true;
  17101. },
  17102. [&](const char *data, size_t data_length) {
  17103. body.append(data, data_length);
  17104. return true;
  17105. },
  17106. [&](size_t, size_t) {
  17107. progress_called = true;
  17108. return true;
  17109. });
  17110. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17111. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17112. EXPECT_TRUE(handler_called);
  17113. EXPECT_TRUE(progress_called);
  17114. EXPECT_EQ("no location", body);
  17115. }
  17116. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17117. Server svr;
  17118. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17119. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17120. });
  17121. svr.Get("/hello", [](const Request &req, Response &res) {
  17122. res.set_content(req.get_param_value("key"), "text/plain");
  17123. });
  17124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17125. auto se = detail::scope_exit([&] {
  17126. svr.stop();
  17127. thread.join();
  17128. ASSERT_FALSE(svr.is_running());
  17129. });
  17130. svr.wait_until_ready();
  17131. {
  17132. Client cli(HOST, PORT);
  17133. cli.set_follow_location(true);
  17134. auto res = cli.Get("/");
  17135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17136. EXPECT_EQ(StatusCode::OK_200, res->status);
  17137. EXPECT_EQ("val&key2=val2", res->body);
  17138. }
  17139. }
  17140. #endif
  17141. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17142. Server svr;
  17143. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17144. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17145. });
  17146. svr.Get("/hello", [](const Request &req, Response &res) {
  17147. res.set_content(req.get_param_value("key"), "text/plain");
  17148. });
  17149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17150. auto se = detail::scope_exit([&] {
  17151. svr.stop();
  17152. thread.join();
  17153. ASSERT_FALSE(svr.is_running());
  17154. });
  17155. svr.wait_until_ready();
  17156. {
  17157. Client cli(HOST, PORT);
  17158. cli.set_follow_location(true);
  17159. auto res = cli.Get("/");
  17160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17161. EXPECT_EQ(StatusCode::OK_200, res->status);
  17162. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17163. }
  17164. }
  17165. TEST(RedirectTest, RedirectWithPlusInPath) {
  17166. Server svr;
  17167. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17168. res.set_redirect("/a+b");
  17169. });
  17170. // Route pattern uses regex; escape + as \\+
  17171. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17172. res.set_content(req.path, "text/plain");
  17173. });
  17174. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17175. auto se = detail::scope_exit([&] {
  17176. svr.stop();
  17177. thread.join();
  17178. ASSERT_FALSE(svr.is_running());
  17179. });
  17180. svr.wait_until_ready();
  17181. {
  17182. Client cli(HOST, PORT);
  17183. cli.set_follow_location(true);
  17184. auto res = cli.Get("/");
  17185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17186. EXPECT_EQ(StatusCode::OK_200, res->status);
  17187. EXPECT_EQ("/a+b", res->body);
  17188. }
  17189. }
  17190. TEST(RedirectTest, ResolveRelativeLocation) {
  17191. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17192. const std::vector<std::pair<std::string, std::string>> cases = {
  17193. {"g", "/b/c/g"},
  17194. {"./g", "/b/c/g"},
  17195. {"g/", "/b/c/g/"},
  17196. {"?y", "/b/c/d;p?y"},
  17197. {"g?y", "/b/c/g?y"},
  17198. {"#s", "/b/c/d;p?q#s"},
  17199. {"g#s", "/b/c/g#s"},
  17200. {"g?y#s", "/b/c/g?y#s"},
  17201. {";x", "/b/c/;x"},
  17202. {"g;x", "/b/c/g;x"},
  17203. {".", "/b/c/"},
  17204. {"./", "/b/c/"},
  17205. {"..", "/b/"},
  17206. {"../", "/b/"},
  17207. {"../g", "/b/g"},
  17208. {"../..", "/"},
  17209. {"../../", "/"},
  17210. {"../../g", "/g"},
  17211. {"../../../g", "/g"},
  17212. {"g.", "/b/c/g."},
  17213. {".g", "/b/c/.g"},
  17214. {"g..", "/b/c/g.."},
  17215. {"..g", "/b/c/..g"},
  17216. {"./../g", "/b/g"},
  17217. {"./g/.", "/b/c/g/"},
  17218. {"g/./h", "/b/c/g/h"},
  17219. {"g/../h", "/b/c/h"},
  17220. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17221. {"g;x=1/../y", "/b/c/y"},
  17222. {"g?y/./x", "/b/c/g?y/./x"},
  17223. {"g#s/../x", "/b/c/g#s/../x"},
  17224. // Not relative-path references, so left for parse_url.
  17225. {"/g", "/g"},
  17226. {"//g", "//g"},
  17227. {"http://g/x", "http://g/x"},
  17228. {"g:h", "g:h"},
  17229. };
  17230. for (const auto &c : cases) {
  17231. EXPECT_EQ(c.second,
  17232. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17233. << c.first;
  17234. }
  17235. }
  17236. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17237. Server svr;
  17238. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17239. res.set_redirect(req.get_param_value("to"));
  17240. });
  17241. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17242. res.set_content(req.target, "text/plain");
  17243. });
  17244. svr.Get("/other", [](const Request &req, Response &res) {
  17245. res.set_content(req.target, "text/plain");
  17246. });
  17247. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17248. auto se = detail::scope_exit([&] {
  17249. svr.stop();
  17250. thread.join();
  17251. ASSERT_FALSE(svr.is_running());
  17252. });
  17253. svr.wait_until_ready();
  17254. const std::vector<std::pair<std::string, std::string>> cases = {
  17255. {"next", "/dir/next"},
  17256. {"./next?x=1", "/dir/next?x=1"},
  17257. {"../other", "/other"},
  17258. };
  17259. for (const auto &c : cases) {
  17260. Client cli(HOST, PORT);
  17261. cli.set_follow_location(true);
  17262. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17263. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17264. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17265. EXPECT_EQ(c.second, res->body) << c.first;
  17266. }
  17267. }
  17268. #ifdef CPPHTTPLIB_SSL_ENABLED
  17269. TEST(RedirectTest, Issue2185_Online) {
  17270. SSLClient client("github.com");
  17271. client.set_follow_location(true);
  17272. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17273. "Coollab-Windows.zip");
  17274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17275. EXPECT_EQ(StatusCode::OK_200, res->status);
  17276. EXPECT_EQ(9920427U, res->body.size());
  17277. }
  17278. #endif
  17279. TEST(VulnerabilityTest, CRLFInjection) {
  17280. Server svr;
  17281. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17282. res.set_content("Hello 1", "text/plain");
  17283. });
  17284. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17285. res.set_content("Hello 2", "text/plain");
  17286. });
  17287. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17288. res.set_content("Hello 3", "text/plain");
  17289. });
  17290. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17291. res.set_content("Hello 4", "text/plain");
  17292. });
  17293. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17294. for (const auto &x : req.headers) {
  17295. auto key = x.first;
  17296. EXPECT_STRNE("evil", key.c_str());
  17297. }
  17298. });
  17299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17300. auto se = detail::scope_exit([&] {
  17301. svr.stop();
  17302. thread.join();
  17303. ASSERT_FALSE(svr.is_running());
  17304. });
  17305. svr.wait_until_ready();
  17306. {
  17307. Client cli(HOST, PORT);
  17308. cli.Post("/test1", "A=B",
  17309. "application/x-www-form-urlencoded\r\nevil: hello1");
  17310. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17311. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17312. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17313. }
  17314. }
  17315. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17316. auto server_thread = std::thread([] {
  17317. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17318. default_socket_options(srv);
  17319. sockaddr_in addr{};
  17320. addr.sin_family = AF_INET;
  17321. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17322. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17323. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17324. ::listen(srv, 1);
  17325. sockaddr_in cli_addr{};
  17326. socklen_t cli_len = sizeof(cli_addr);
  17327. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17328. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17329. std::string buf_all;
  17330. char buf[2048];
  17331. ssize_t n;
  17332. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17333. buf_all.append(buf, static_cast<size_t>(n));
  17334. size_t pos;
  17335. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17336. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17337. auto e = request_block.find("\r\n");
  17338. if (e != std::string::npos) {
  17339. auto request_line = request_block.substr(0, e);
  17340. std::string msg =
  17341. "CRLF injection detected in request line: '" + request_line + "'";
  17342. EXPECT_FALSE(true) << msg;
  17343. }
  17344. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17345. ::send(cli,
  17346. #ifdef _WIN32
  17347. static_cast<const char *>(resp.c_str()),
  17348. static_cast<int>(resp.size()),
  17349. #else
  17350. resp.c_str(), resp.size(),
  17351. #endif
  17352. 0);
  17353. buf_all.erase(0, pos + 4);
  17354. }
  17355. }
  17356. detail::close_socket(cli);
  17357. detail::close_socket(srv);
  17358. });
  17359. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17360. auto cli = Client("127.0.0.1", PORT + 1);
  17361. auto headers = Headers{
  17362. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17363. {"Connection", "keep-alive"}};
  17364. auto res = cli.Get("/hi", headers);
  17365. EXPECT_FALSE(res);
  17366. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17367. server_thread.join();
  17368. }
  17369. // A request rejected before any byte reaches the socket must fail right away
  17370. // instead of waiting for a response the server will never send.
  17371. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17372. // The kernel completes the TCP handshake from the listen backlog, so the
  17373. // client connects, but nothing ever reads, responds or closes.
  17374. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17375. default_socket_options(srv);
  17376. sockaddr_in addr{};
  17377. addr.sin_family = AF_INET;
  17378. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17379. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17380. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17381. ASSERT_EQ(0, ::listen(srv, 8));
  17382. auto cli = Client("127.0.0.1", PORT + 1);
  17383. cli.set_read_timeout(10, 0);
  17384. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17385. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17386. std::chrono::steady_clock::now() - start)
  17387. .count();
  17388. };
  17389. {
  17390. Request req;
  17391. req.method = "GE T";
  17392. req.path = "/";
  17393. auto start = std::chrono::steady_clock::now();
  17394. auto res = cli.send(req);
  17395. EXPECT_FALSE(res);
  17396. EXPECT_EQ(Error::Write, res.error());
  17397. EXPECT_LT(elapsed_ms(start), 1000);
  17398. }
  17399. {
  17400. auto start = std::chrono::steady_clock::now();
  17401. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17402. EXPECT_FALSE(res);
  17403. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17404. EXPECT_LT(elapsed_ms(start), 1000);
  17405. }
  17406. EXPECT_FALSE(cli.is_socket_open());
  17407. detail::close_socket(srv);
  17408. }
  17409. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17410. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17411. default_socket_options(srv);
  17412. sockaddr_in addr{};
  17413. addr.sin_family = AF_INET;
  17414. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17415. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17416. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17417. ASSERT_EQ(0, ::listen(srv, 1));
  17418. std::string received;
  17419. auto server_thread = std::thread([&] {
  17420. auto sock = ::accept(srv, nullptr, nullptr);
  17421. if (sock == INVALID_SOCKET) { return; }
  17422. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17423. char buf[2048];
  17424. ssize_t n;
  17425. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17426. received.append(buf, static_cast<size_t>(n));
  17427. }
  17428. detail::close_socket(sock);
  17429. });
  17430. {
  17431. auto cli = Client("127.0.0.1", PORT + 1);
  17432. // "Z" sorts after the default headers, so writing straight to the socket
  17433. // would have sent the request line and those headers before the rejection.
  17434. auto handle =
  17435. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17436. EXPECT_FALSE(handle.is_valid());
  17437. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17438. }
  17439. server_thread.join();
  17440. detail::close_socket(srv);
  17441. EXPECT_TRUE(received.empty()) << received;
  17442. }
  17443. TEST(PathParamsTest, StaticMatch) {
  17444. const auto pattern = "/users/all";
  17445. detail::PathParamsMatcher matcher(pattern);
  17446. Request request;
  17447. request.path = "/users/all";
  17448. ASSERT_TRUE(matcher.match(request));
  17449. std::unordered_map<std::string, std::string> expected_params = {};
  17450. EXPECT_EQ(request.path_params, expected_params);
  17451. }
  17452. TEST(PathParamsTest, StaticMismatch) {
  17453. const auto pattern = "/users/all";
  17454. detail::PathParamsMatcher matcher(pattern);
  17455. Request request;
  17456. request.path = "/users/1";
  17457. ASSERT_FALSE(matcher.match(request));
  17458. }
  17459. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17460. const auto pattern = "/users/:id/subscriptions";
  17461. detail::PathParamsMatcher matcher(pattern);
  17462. Request request;
  17463. request.path = "/users/42/subscriptions";
  17464. ASSERT_TRUE(matcher.match(request));
  17465. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17466. EXPECT_EQ(request.path_params, expected_params);
  17467. }
  17468. TEST(PathParamsTest, SingleParamInTheEnd) {
  17469. const auto pattern = "/users/:id";
  17470. detail::PathParamsMatcher matcher(pattern);
  17471. Request request;
  17472. request.path = "/users/24";
  17473. ASSERT_TRUE(matcher.match(request));
  17474. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17475. EXPECT_EQ(request.path_params, expected_params);
  17476. }
  17477. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17478. const auto pattern = "/users/:id/";
  17479. detail::PathParamsMatcher matcher(pattern);
  17480. Request request;
  17481. request.path = "/users/42/";
  17482. ASSERT_TRUE(matcher.match(request));
  17483. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17484. EXPECT_EQ(request.path_params, expected_params);
  17485. }
  17486. TEST(PathParamsTest, EmptyParam) {
  17487. const auto pattern = "/users/:id/";
  17488. detail::PathParamsMatcher matcher(pattern);
  17489. Request request;
  17490. request.path = "/users//";
  17491. ASSERT_TRUE(matcher.match(request));
  17492. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17493. EXPECT_EQ(request.path_params, expected_params);
  17494. }
  17495. TEST(PathParamsTest, FragmentMismatch) {
  17496. const auto pattern = "/users/:id/";
  17497. detail::PathParamsMatcher matcher(pattern);
  17498. Request request;
  17499. request.path = "/admins/24/";
  17500. ASSERT_FALSE(matcher.match(request));
  17501. }
  17502. TEST(PathParamsTest, ExtraFragments) {
  17503. const auto pattern = "/users/:id";
  17504. detail::PathParamsMatcher matcher(pattern);
  17505. Request request;
  17506. request.path = "/users/42/subscriptions";
  17507. ASSERT_FALSE(matcher.match(request));
  17508. }
  17509. TEST(PathParamsTest, MissingTrailingParam) {
  17510. const auto pattern = "/users/:id";
  17511. detail::PathParamsMatcher matcher(pattern);
  17512. Request request;
  17513. request.path = "/users";
  17514. ASSERT_FALSE(matcher.match(request));
  17515. }
  17516. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17517. const auto pattern = "/users/:id/subscriptions";
  17518. detail::PathParamsMatcher matcher(pattern);
  17519. Request request;
  17520. request.path = "/users/subscriptions";
  17521. ASSERT_FALSE(matcher.match(request));
  17522. }
  17523. TEST(PathParamsTest, MultipleParams) {
  17524. const auto pattern = "/users/:userid/subscriptions/:subid";
  17525. detail::PathParamsMatcher matcher(pattern);
  17526. Request request;
  17527. request.path = "/users/42/subscriptions/2";
  17528. ASSERT_TRUE(matcher.match(request));
  17529. std::unordered_map<std::string, std::string> expected_params = {
  17530. {"userid", "42"}, {"subid", "2"}};
  17531. EXPECT_EQ(request.path_params, expected_params);
  17532. }
  17533. TEST(PathParamsTest, SequenceOfParams) {
  17534. const auto pattern = "/values/:x/:y/:z";
  17535. detail::PathParamsMatcher matcher(pattern);
  17536. Request request;
  17537. request.path = "/values/1/2/3";
  17538. ASSERT_TRUE(matcher.match(request));
  17539. std::unordered_map<std::string, std::string> expected_params = {
  17540. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17541. EXPECT_EQ(request.path_params, expected_params);
  17542. }
  17543. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17544. const auto pattern = "/prefix:suffix";
  17545. detail::PathParamsMatcher matcher(pattern);
  17546. Request request;
  17547. request.path = "/prefix:suffix";
  17548. ASSERT_TRUE(matcher.match(request));
  17549. const std::unordered_map<std::string, std::string> expected_params = {};
  17550. EXPECT_EQ(request.path_params, expected_params);
  17551. }
  17552. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17553. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17554. // calling thread's stack on a long enough path for a quantified pattern;
  17555. // RegexMatcher must refuse to run regex matching on paths beyond
  17556. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17557. detail::RegexMatcher matcher("/files/(.*)");
  17558. Request within_limit;
  17559. within_limit.path = "/files/" + std::string(10, 'A');
  17560. EXPECT_TRUE(matcher.match(within_limit));
  17561. Request over_limit;
  17562. over_limit.path =
  17563. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17564. EXPECT_FALSE(matcher.match(over_limit));
  17565. }
  17566. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17567. Server svr;
  17568. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17569. res.set_content("ok", "text/plain");
  17570. });
  17571. auto port = svr.bind_to_any_port(HOST);
  17572. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17573. auto se = detail::scope_exit([&] {
  17574. svr.stop();
  17575. thread.join();
  17576. ASSERT_FALSE(svr.is_running());
  17577. });
  17578. svr.wait_until_ready();
  17579. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17580. // request URI limit; this used to be able to crash the process.
  17581. std::string path =
  17582. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17583. std::string req = "GET " + path +
  17584. " HTTP/1.1\r\n"
  17585. "Host: " +
  17586. std::string(HOST) + ":" + std::to_string(port) +
  17587. "\r\n"
  17588. "Connection: close\r\n"
  17589. "\r\n";
  17590. std::string response;
  17591. ASSERT_TRUE(send_request(5, req, &response, port));
  17592. EXPECT_NE(std::string::npos, response.find("404"));
  17593. }
  17594. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17595. Server svr;
  17596. auto handler = [](const Request & /*req*/, Response &res) {
  17597. res.set_content("hit", "text/plain");
  17598. };
  17599. // No regex metacharacter, so this one is compared literally
  17600. svr.Get("/literal/route", handler);
  17601. // '.' is a regex metacharacter, so this one must keep regex semantics
  17602. svr.Get("/a.c", handler);
  17603. auto port = svr.bind_to_any_port(HOST);
  17604. std::thread t([&]() { svr.listen_after_bind(); });
  17605. auto se = detail::scope_exit([&] {
  17606. svr.stop();
  17607. t.join();
  17608. ASSERT_FALSE(svr.is_running());
  17609. });
  17610. svr.wait_until_ready();
  17611. Client cli(HOST, port);
  17612. struct {
  17613. const char *path;
  17614. int status;
  17615. } cases[] = {
  17616. {"/literal/route", StatusCode::OK_200},
  17617. {"/literal/routes", StatusCode::NotFound_404},
  17618. {"/literal/rout", StatusCode::NotFound_404},
  17619. {"/abc", StatusCode::OK_200},
  17620. {"/a.c", StatusCode::OK_200},
  17621. };
  17622. for (const auto &x : cases) {
  17623. auto res = cli.Get(x.path);
  17624. ASSERT_TRUE(res) << x.path;
  17625. EXPECT_EQ(x.status, res->status) << x.path;
  17626. }
  17627. }
  17628. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17629. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17630. // from exhausting the stack, so it must only constrain routes that actually
  17631. // run a regular expression. A literal route is matched by comparison and
  17632. // stays usable at any length.
  17633. Server svr;
  17634. const std::string pattern =
  17635. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17636. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17637. res.set_content("hit", "text/plain");
  17638. });
  17639. auto port = svr.bind_to_any_port(HOST);
  17640. std::thread t([&]() { svr.listen_after_bind(); });
  17641. auto se = detail::scope_exit([&] {
  17642. svr.stop();
  17643. t.join();
  17644. ASSERT_FALSE(svr.is_running());
  17645. });
  17646. svr.wait_until_ready();
  17647. Client cli(HOST, port);
  17648. auto res = cli.Get(pattern);
  17649. ASSERT_TRUE(res);
  17650. EXPECT_EQ(StatusCode::OK_200, res->status);
  17651. }
  17652. TEST(ParseUrlTest, VariousPatterns) {
  17653. {
  17654. detail::UrlComponents uc;
  17655. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17656. EXPECT_EQ("http", uc.scheme);
  17657. EXPECT_EQ("example.com", uc.host);
  17658. EXPECT_EQ("8080", uc.port);
  17659. EXPECT_EQ("/path", uc.path);
  17660. EXPECT_EQ("?q=1", uc.query);
  17661. }
  17662. {
  17663. detail::UrlComponents uc;
  17664. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17665. EXPECT_EQ("https", uc.scheme);
  17666. EXPECT_EQ("example.com", uc.host);
  17667. EXPECT_TRUE(uc.port.empty());
  17668. EXPECT_EQ("/path", uc.path);
  17669. }
  17670. {
  17671. detail::UrlComponents uc;
  17672. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17673. EXPECT_EQ("::1", uc.host);
  17674. EXPECT_EQ("8080", uc.port);
  17675. EXPECT_EQ("/path", uc.path);
  17676. }
  17677. {
  17678. detail::UrlComponents uc;
  17679. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17680. }
  17681. {
  17682. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17683. // the path while the connection still targets the bracketed host.
  17684. detail::UrlComponents uc;
  17685. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17686. }
  17687. {
  17688. detail::UrlComponents uc;
  17689. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17690. }
  17691. {
  17692. detail::UrlComponents uc;
  17693. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17694. EXPECT_EQ("::1", uc.host);
  17695. EXPECT_TRUE(uc.port.empty());
  17696. EXPECT_EQ("/path", uc.path);
  17697. }
  17698. {
  17699. detail::UrlComponents uc;
  17700. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17701. EXPECT_TRUE(uc.scheme.empty());
  17702. EXPECT_EQ("example.com", uc.host);
  17703. EXPECT_EQ("/path", uc.path);
  17704. EXPECT_EQ("?q=1", uc.query);
  17705. }
  17706. {
  17707. detail::UrlComponents uc;
  17708. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17709. EXPECT_TRUE(uc.host.empty());
  17710. EXPECT_EQ("/path", uc.path);
  17711. EXPECT_EQ("?q=1", uc.query);
  17712. }
  17713. {
  17714. detail::UrlComponents uc;
  17715. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17716. EXPECT_EQ("example.com", uc.host);
  17717. EXPECT_EQ("8080", uc.port);
  17718. }
  17719. {
  17720. // Unix socket path — must not be parsed as host
  17721. detail::UrlComponents uc;
  17722. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17723. EXPECT_TRUE(uc.host.empty());
  17724. }
  17725. {
  17726. detail::UrlComponents uc;
  17727. ASSERT_TRUE(detail::parse_url("", uc));
  17728. EXPECT_TRUE(uc.host.empty());
  17729. EXPECT_TRUE(uc.path.empty());
  17730. }
  17731. {
  17732. detail::UrlComponents uc;
  17733. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17734. }
  17735. {
  17736. detail::UrlComponents uc;
  17737. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17738. }
  17739. {
  17740. // Accepted by parse_url; callers restrict to http/https
  17741. detail::UrlComponents uc;
  17742. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17743. EXPECT_EQ("ftp", uc.scheme);
  17744. }
  17745. {
  17746. detail::UrlComponents uc;
  17747. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17748. }
  17749. {
  17750. detail::UrlComponents uc;
  17751. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17752. }
  17753. }
  17754. TEST(ParseUrlTest, FragmentHandling) {
  17755. {
  17756. detail::UrlComponents uc;
  17757. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17758. EXPECT_EQ("/path", uc.path);
  17759. EXPECT_TRUE(uc.query.empty());
  17760. }
  17761. {
  17762. detail::UrlComponents uc;
  17763. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17764. EXPECT_TRUE(uc.path.empty());
  17765. EXPECT_TRUE(uc.query.empty());
  17766. }
  17767. }
  17768. TEST(ParseUrlTest, UserinfoHandling) {
  17769. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17770. // parsers would see evil.com as the host.
  17771. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17772. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17773. for (auto url : urls) {
  17774. detail::UrlComponents uc;
  17775. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17776. }
  17777. }
  17778. TEST(ParseUrlTest, IPv6EdgeCases) {
  17779. {
  17780. detail::UrlComponents uc;
  17781. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17782. EXPECT_TRUE(uc.scheme.empty());
  17783. EXPECT_EQ("::1", uc.host);
  17784. EXPECT_EQ("8080", uc.port);
  17785. }
  17786. {
  17787. // Zone ID '%25' is not in [a-fA-F0-9:]
  17788. detail::UrlComponents uc;
  17789. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17790. }
  17791. }
  17792. TEST(ParseUrlTest, SchemeEdgeCases) {
  17793. {
  17794. detail::UrlComponents uc;
  17795. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17796. }
  17797. {
  17798. detail::UrlComponents uc;
  17799. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17800. }
  17801. {
  17802. detail::UrlComponents uc;
  17803. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17804. }
  17805. }
  17806. TEST(ParseUrlTest, PortEdgeCases) {
  17807. {
  17808. detail::UrlComponents uc;
  17809. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17810. EXPECT_TRUE(uc.port.empty());
  17811. EXPECT_EQ("/path", uc.path);
  17812. }
  17813. {
  17814. // parse_url accepts any port string; validation is done by parse_port
  17815. detail::UrlComponents uc;
  17816. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17817. EXPECT_EQ("abc", uc.port);
  17818. }
  17819. }
  17820. TEST(ParseUrlTest, WebSocketPatterns) {
  17821. {
  17822. detail::UrlComponents uc;
  17823. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17824. EXPECT_EQ("ws", uc.scheme);
  17825. EXPECT_EQ("echo.example.com", uc.host);
  17826. EXPECT_EQ("8080", uc.port);
  17827. EXPECT_EQ("/ws", uc.path);
  17828. }
  17829. {
  17830. detail::UrlComponents uc;
  17831. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17832. EXPECT_EQ("wss", uc.scheme);
  17833. EXPECT_EQ("echo.example.com", uc.host);
  17834. EXPECT_TRUE(uc.port.empty());
  17835. EXPECT_EQ("/ws", uc.path);
  17836. }
  17837. }
  17838. TEST(ParseUrlTest, QueryOnly) {
  17839. detail::UrlComponents uc;
  17840. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17841. EXPECT_TRUE(uc.host.empty());
  17842. EXPECT_TRUE(uc.path.empty());
  17843. EXPECT_EQ("?q=1&r=2", uc.query);
  17844. }
  17845. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17846. detail::UrlComponents uc;
  17847. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17848. EXPECT_TRUE(uc.scheme.empty());
  17849. EXPECT_EQ("example.com", uc.host);
  17850. EXPECT_EQ("443", uc.port);
  17851. EXPECT_EQ("/path", uc.path);
  17852. }
  17853. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17854. // If ipv6 regex working, regex match codepath is taken.
  17855. // else port will default to 80 in Client impl
  17856. int clientImplMagicPort = 80;
  17857. int port = 4321;
  17858. // above ports must be different to avoid false negative
  17859. EXPECT_NE(clientImplMagicPort, port);
  17860. std::string ipV6TestURL = "http://[ff06::c3]";
  17861. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17862. CLIENT_PRIVATE_KEY_FILE);
  17863. EXPECT_EQ(cli.port(), port);
  17864. }
  17865. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17866. auto file_path = "./www/dir/index.html";
  17867. auto dir_path = "./www/dir";
  17868. detail::FileStat stat_file(file_path);
  17869. EXPECT_TRUE(stat_file.is_file());
  17870. EXPECT_FALSE(stat_file.is_dir());
  17871. detail::FileStat stat_dir(dir_path);
  17872. EXPECT_FALSE(stat_dir.is_file());
  17873. EXPECT_TRUE(stat_dir.is_dir());
  17874. }
  17875. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17876. // IPv4 with default HTTP port (80)
  17877. EXPECT_EQ("example.com",
  17878. detail::make_host_and_port_string("example.com", 80, false));
  17879. // IPv4 with default HTTPS port (443)
  17880. EXPECT_EQ("example.com",
  17881. detail::make_host_and_port_string("example.com", 443, true));
  17882. // IPv4 with non-default HTTP port
  17883. EXPECT_EQ("example.com:8080",
  17884. detail::make_host_and_port_string("example.com", 8080, false));
  17885. // IPv4 with non-default HTTPS port
  17886. EXPECT_EQ("example.com:8443",
  17887. detail::make_host_and_port_string("example.com", 8443, true));
  17888. // IPv6 with default HTTP port (80)
  17889. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17890. // IPv6 with default HTTPS port (443)
  17891. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17892. // IPv6 with non-default HTTP port
  17893. EXPECT_EQ("[::1]:8080",
  17894. detail::make_host_and_port_string("::1", 8080, false));
  17895. // IPv6 with non-default HTTPS port
  17896. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17897. // IPv6 full address with default port
  17898. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17899. detail::make_host_and_port_string(
  17900. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17901. // IPv6 full address with non-default port
  17902. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17903. detail::make_host_and_port_string(
  17904. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17905. // IPv6 localhost with non-default port
  17906. EXPECT_EQ("[::1]:3000",
  17907. detail::make_host_and_port_string("::1", 3000, false));
  17908. // IPv6 with zone ID (link-local address) with default port
  17909. EXPECT_EQ("[fe80::1%eth0]",
  17910. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17911. // IPv6 with zone ID (link-local address) with non-default port
  17912. EXPECT_EQ("[fe80::1%eth0]:8080",
  17913. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17914. // Edge case: Port 443 with is_ssl=false (should add port)
  17915. EXPECT_EQ("example.com:443",
  17916. detail::make_host_and_port_string("example.com", 443, false));
  17917. // Edge case: Port 80 with is_ssl=true (should add port)
  17918. EXPECT_EQ("example.com:80",
  17919. detail::make_host_and_port_string("example.com", 80, true));
  17920. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17921. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17922. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17923. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17924. // Security fix: Already bracketed IPv6 should not get double brackets
  17925. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17926. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17927. EXPECT_EQ("[::1]:8080",
  17928. detail::make_host_and_port_string("[::1]", 8080, false));
  17929. EXPECT_EQ("[2001:db8::1]:8080",
  17930. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17931. EXPECT_EQ("[fe80::1%eth0]",
  17932. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17933. EXPECT_EQ("[fe80::1%eth0]:8080",
  17934. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17935. // Edge case: Empty host (should return as-is)
  17936. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17937. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17938. // This is a known limitation but shouldn't crash
  17939. EXPECT_EQ("[host:name]",
  17940. detail::make_host_and_port_string("host:name", 80, false));
  17941. // Port number edge cases (no validation, but should not crash)
  17942. EXPECT_EQ("example.com:0",
  17943. detail::make_host_and_port_string("example.com", 0, false));
  17944. EXPECT_EQ("example.com:-1",
  17945. detail::make_host_and_port_string("example.com", -1, false));
  17946. EXPECT_EQ("example.com:65535",
  17947. detail::make_host_and_port_string("example.com", 65535, false));
  17948. EXPECT_EQ("example.com:65536",
  17949. detail::make_host_and_port_string("example.com", 65536, false));
  17950. }
  17951. #ifdef CPPHTTPLIB_SSL_ENABLED
  17952. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17953. httplib::SSLClient cli("roblox.com", 443);
  17954. cli.set_follow_location(true);
  17955. auto res = cli.Get("/");
  17956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17957. EXPECT_EQ(StatusCode::OK_200, res->status);
  17958. }
  17959. #endif
  17960. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17961. Server svr;
  17962. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17963. EXPECT_EQ(res.status, 400);
  17964. });
  17965. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17966. auto se = detail::scope_exit([&] {
  17967. svr.stop();
  17968. thread.join();
  17969. ASSERT_FALSE(svr.is_running());
  17970. });
  17971. svr.wait_until_ready();
  17972. Client cli(HOST, PORT);
  17973. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17974. }
  17975. TEST(InvalidHeaderCharsTest, is_field_name) {
  17976. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17977. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17978. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17979. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17980. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17981. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17982. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17983. EXPECT_FALSE(detail::fields::is_field_name(""));
  17984. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17985. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17986. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17987. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17988. }
  17989. TEST(InvalidHeaderCharsTest, is_field_value) {
  17990. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17991. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17992. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17993. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17994. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17995. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17996. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17997. EXPECT_TRUE(detail::fields::is_field_value(""));
  17998. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17999. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18000. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18001. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18002. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18003. }
  18004. TEST(InvalidHeaderCharsTest, OnServer) {
  18005. Server svr;
  18006. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18007. std::string header = "Not Set";
  18008. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18009. res.set_header(header, "value");
  18010. res.set_content("Page Content Page Content", "text/plain");
  18011. });
  18012. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18013. std::string header = "Not Set";
  18014. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18015. res.set_header("X-Test", header);
  18016. res.set_content("Page Content Page Content", "text/plain");
  18017. });
  18018. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18019. auto se = detail::scope_exit([&] {
  18020. svr.stop();
  18021. thread.join();
  18022. ASSERT_FALSE(svr.is_running());
  18023. });
  18024. svr.wait_until_ready();
  18025. Client cli(HOST, PORT);
  18026. {
  18027. auto res = cli.Get(
  18028. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18030. EXPECT_EQ("Page Content Page Content", res->body);
  18031. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18032. }
  18033. {
  18034. auto res = cli.Get(
  18035. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18037. EXPECT_EQ("Page Content Page Content", res->body);
  18038. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18039. }
  18040. }
  18041. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18042. auto handled = false;
  18043. Server svr;
  18044. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18045. thread t = thread([&] { svr.listen(HOST, PORT); });
  18046. auto se = detail::scope_exit([&] {
  18047. svr.stop();
  18048. t.join();
  18049. ASSERT_FALSE(svr.is_running());
  18050. ASSERT_FALSE(handled);
  18051. });
  18052. svr.wait_until_ready();
  18053. auto req = "POST /test HTTP/1.1\r\n"
  18054. "Content-Length: x\r\n"
  18055. "\r\n";
  18056. std::string response;
  18057. ASSERT_TRUE(send_request(1, req, &response));
  18058. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18059. response.substr(0, response.find("\r\n")));
  18060. }
  18061. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18062. // case-insensitive, and a server that receives a 100-continue expectation in
  18063. // an HTTP/1.0 request MUST ignore it.
  18064. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18065. std::string response;
  18066. ASSERT_TRUE(send_request(1, req, &response, port));
  18067. *got_100 = response.find("100 Continue") != std::string::npos;
  18068. }
  18069. class ExpectTokenTest : public ::testing::Test {
  18070. protected:
  18071. void SetUp() override {
  18072. svr_.Post("/p", [](const Request &, Response &res) {
  18073. res.set_content("ok", "text/plain");
  18074. });
  18075. port_ = svr_.bind_to_any_port(HOST);
  18076. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18077. svr_.wait_until_ready();
  18078. }
  18079. void TearDown() override {
  18080. svr_.stop();
  18081. if (thread_.joinable()) { thread_.join(); }
  18082. }
  18083. std::string request(const char *version, const char *expect_value) const {
  18084. return std::string("POST /p ") + version +
  18085. "\r\n"
  18086. "Host: localhost\r\n"
  18087. "Content-Length: 2\r\n"
  18088. "Connection: close\r\n"
  18089. "Expect: " +
  18090. expect_value +
  18091. "\r\n"
  18092. "\r\n"
  18093. "hi";
  18094. }
  18095. Server svr_;
  18096. int port_ = 0;
  18097. thread thread_;
  18098. };
  18099. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18100. bool got_100 = false;
  18101. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18102. EXPECT_TRUE(got_100);
  18103. }
  18104. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18105. bool got_100 = true;
  18106. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18107. EXPECT_FALSE(got_100);
  18108. }
  18109. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18110. bool got_100 = false;
  18111. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18112. EXPECT_TRUE(got_100);
  18113. }
  18114. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18115. bool got_100 = false;
  18116. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18117. EXPECT_TRUE(got_100);
  18118. }
  18119. // `100 Continue` is sent only when the server starts reading the body, so a
  18120. // request rejected before that never invites the client to send it. The
  18121. // requests below carry the expectation but withhold the body, as a client
  18122. // waiting for `100 Continue` would.
  18123. // A POST that expects `100 Continue` and withholds its two-byte body.
  18124. static std::string expect_headers_only(const std::string &path) {
  18125. return "POST " + path +
  18126. " HTTP/1.1\r\n"
  18127. "Host: localhost\r\n"
  18128. "Content-Length: 2\r\n"
  18129. "Expect: 100-continue\r\n"
  18130. "\r\n";
  18131. }
  18132. class ExpectLazyContinueTest : public ::testing::Test {
  18133. protected:
  18134. void SetUp() override {
  18135. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18136. if (req.path == "/pre-routing") {
  18137. res.status = StatusCode::Unauthorized_401;
  18138. return Server::HandlerResponse::Handled;
  18139. }
  18140. return Server::HandlerResponse::Unhandled;
  18141. });
  18142. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18143. if (req.matched_route == "/pre-request") {
  18144. res.status = StatusCode::Forbidden_403;
  18145. return Server::HandlerResponse::Handled;
  18146. }
  18147. return Server::HandlerResponse::Unhandled;
  18148. });
  18149. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18150. res.set_content("ok", "text/plain");
  18151. });
  18152. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18153. res.set_content("ok", "text/plain");
  18154. });
  18155. svr_.Post("/reader-used", [](const Request &, Response &res,
  18156. const ContentReader &content_reader) {
  18157. std::string body;
  18158. content_reader([&](const char *data, size_t len) {
  18159. body.append(data, len);
  18160. return true;
  18161. });
  18162. res.set_content(body, "text/plain");
  18163. });
  18164. svr_.Post("/reader-unused",
  18165. [](const Request &, Response &res, const ContentReader &) {
  18166. res.set_content("ignored", "text/plain");
  18167. });
  18168. port_ = svr_.bind_to_any_port(HOST);
  18169. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18170. svr_.wait_until_ready();
  18171. }
  18172. void TearDown() override {
  18173. svr_.stop();
  18174. if (thread_.joinable()) { thread_.join(); }
  18175. }
  18176. // Sends `req` and reads until the server closes the connection. Returns
  18177. // false if the read had to wait for the client-side timeout instead.
  18178. bool send_until_closed(const std::string &req, std::string *resp) const {
  18179. auto start = std::chrono::steady_clock::now();
  18180. if (!send_request(3, req, resp, port_)) { return false; }
  18181. auto elapsed = std::chrono::steady_clock::now() - start;
  18182. return elapsed < std::chrono::seconds(2);
  18183. }
  18184. // The final response comes without `100 Continue`, and the server closes
  18185. // the connection since the body may or may not follow.
  18186. void expect_final_without_interim(const std::string &path,
  18187. const char *status_line) const {
  18188. std::string resp;
  18189. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18190. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18191. EXPECT_EQ(0u, resp.find(status_line));
  18192. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18193. }
  18194. Server svr_;
  18195. int port_ = 0;
  18196. thread thread_;
  18197. };
  18198. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18199. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18200. }
  18201. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18202. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18203. }
  18204. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18205. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18206. }
  18207. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18208. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18209. }
  18210. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18211. // The body follows once `100 Continue` has had time to arrive.
  18212. auto req = expect_headers_only("/reader-used");
  18213. req.insert(req.size() - 2, "Connection: close\r\n");
  18214. std::string resp;
  18215. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18216. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18217. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18218. EXPECT_NE(std::string::npos, resp.find("hi"));
  18219. }
  18220. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18221. // Large enough for the client to add `Expect: 100-continue` itself.
  18222. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18223. std::atomic<bool> body_sent{false};
  18224. Client cli(HOST, port_);
  18225. auto res = cli.Post(
  18226. "/pre-request", length,
  18227. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18228. body_sent = true;
  18229. std::string chunk(len, 'x');
  18230. sink.write(chunk.data(), chunk.size());
  18231. return true;
  18232. },
  18233. "application/octet-stream");
  18234. ASSERT_TRUE(res);
  18235. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18236. EXPECT_FALSE(body_sent);
  18237. }
  18238. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18239. Server svr;
  18240. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18241. return StatusCode::ExpectationFailed_417;
  18242. });
  18243. svr.Post("/p", [](const Request &, Response &res) {
  18244. res.set_content("ok", "text/plain");
  18245. });
  18246. auto port = svr.bind_to_any_port(HOST);
  18247. thread t = thread([&] { svr.listen_after_bind(); });
  18248. auto se = detail::scope_exit([&] {
  18249. svr.stop();
  18250. t.join();
  18251. });
  18252. svr.wait_until_ready();
  18253. std::string resp;
  18254. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18255. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18256. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18257. // Exactly one response: the route handler must not run after the 417.
  18258. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18259. }
  18260. #ifndef _WIN32
  18261. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18262. static constexpr char reject[] = "Unauthorized";
  18263. static constexpr char accept[] = "Upload accepted";
  18264. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18265. Server svr;
  18266. svr.set_expect_100_continue_handler(
  18267. [](const Request & /*req*/, Response &res) {
  18268. res.status = StatusCode::Unauthorized_401;
  18269. res.set_content(reject, "text/plain");
  18270. return res.status;
  18271. });
  18272. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18273. res.set_content(accept, "text/plain");
  18274. });
  18275. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18276. auto se = detail::scope_exit([&] {
  18277. svr.stop();
  18278. thread.join();
  18279. ASSERT_FALSE(svr.is_running());
  18280. });
  18281. svr.wait_until_ready();
  18282. {
  18283. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18284. curl_easy_init(), &curl_easy_cleanup};
  18285. ASSERT_NE(curl, nullptr);
  18286. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18287. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18288. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18289. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18290. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18291. &curl_slist_free_all};
  18292. ASSERT_NE(list, nullptr);
  18293. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18294. struct read_data {
  18295. uint64_t read_size;
  18296. uint64_t total_size;
  18297. } data = {0, total_size};
  18298. using read_callback_t =
  18299. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18300. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18301. void *userdata) -> size_t {
  18302. read_data *d = (read_data *)userdata;
  18303. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18304. std::fill_n(ptr, size * nmemb, 'A');
  18305. d->read_size += size * nmemb;
  18306. return size * nmemb;
  18307. };
  18308. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18309. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18310. std::vector<char> buffer;
  18311. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18312. using write_callback_t =
  18313. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18314. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18315. void *userdata) -> size_t {
  18316. std::vector<char> *buf = (std::vector<char> *)userdata;
  18317. buf->reserve(buf->size() + size * nmemb + 1);
  18318. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18319. return size * nmemb;
  18320. };
  18321. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18322. {
  18323. const auto res = curl_easy_perform(curl.get());
  18324. ASSERT_EQ(res, CURLE_OK);
  18325. }
  18326. {
  18327. auto response_code = long{};
  18328. const auto res =
  18329. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18330. ASSERT_EQ(res, CURLE_OK);
  18331. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18332. }
  18333. {
  18334. auto dl = curl_off_t{};
  18335. const auto res =
  18336. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18337. ASSERT_EQ(res, CURLE_OK);
  18338. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18339. }
  18340. {
  18341. buffer.push_back('\0');
  18342. ASSERT_STRCASEEQ(buffer.data(), reject);
  18343. }
  18344. }
  18345. }
  18346. #endif
  18347. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18348. // Regression test for #2458.
  18349. //
  18350. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18351. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18352. // ticket can make the client socket spuriously readable during the
  18353. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18354. // the client withholds the body and then blocks reading a response that never
  18355. // comes, failing with `Failed to read connection`.
  18356. //
  18357. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18358. // within the timeout. This raw OpenSSL server deliberately never sends
  18359. // `100 Continue`; the client must still deliver the body and receive 200.
  18360. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18361. signal(SIGPIPE, SIG_IGN);
  18362. const auto port = PORT + 4;
  18363. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18364. ASSERT_NE(srv, INVALID_SOCKET);
  18365. int opt = 1;
  18366. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18367. sockaddr_in addr{};
  18368. addr.sin_family = AF_INET;
  18369. addr.sin_port = htons(static_cast<uint16_t>(port));
  18370. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18371. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18372. ASSERT_EQ(0, ::listen(srv, 1));
  18373. std::atomic<size_t> server_body_bytes{0};
  18374. auto server_thread = std::thread([&] {
  18375. sockaddr_in cli_addr{};
  18376. socklen_t cli_len = sizeof(cli_addr);
  18377. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18378. if (cli == INVALID_SOCKET) { return; }
  18379. // Bound the lifetime of the server side so a buggy client (which never
  18380. // sends the body) cannot make this thread block forever on join.
  18381. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18382. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18383. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18384. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18385. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18386. SSL *ssl = SSL_new(ctx);
  18387. SSL_set_fd(ssl, static_cast<int>(cli));
  18388. if (SSL_accept(ssl) > 0) {
  18389. // Read the request headers. Reading here also flushes the TLS 1.3
  18390. // session tickets to the client. Deliberately do NOT send
  18391. // `100 Continue`.
  18392. std::string buf;
  18393. char tmp[1024];
  18394. while (buf.find("\r\n\r\n") == std::string::npos) {
  18395. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18396. if (n <= 0) { break; }
  18397. buf.append(tmp, static_cast<size_t>(n));
  18398. }
  18399. // A correct client sends the body now; count what arrives.
  18400. auto pos = buf.find("\r\n\r\n");
  18401. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18402. while (body < 4096) {
  18403. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18404. if (n <= 0) { break; }
  18405. body += static_cast<size_t>(n);
  18406. }
  18407. server_body_bytes = body;
  18408. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18409. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18410. SSL_shutdown(ssl);
  18411. }
  18412. SSL_free(ssl);
  18413. detail::close_socket(cli);
  18414. SSL_CTX_free(ctx);
  18415. });
  18416. auto se = detail::scope_exit([&] {
  18417. server_thread.join();
  18418. detail::close_socket(srv);
  18419. });
  18420. SSLClient cli("127.0.0.1", port);
  18421. cli.enable_server_certificate_verification(false);
  18422. cli.set_connection_timeout(5, 0);
  18423. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18424. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18425. std::string body(4096, 'A');
  18426. auto res = cli.Put("/api/test", body, "application/json");
  18427. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18428. EXPECT_EQ(StatusCode::OK_200, res->status);
  18429. EXPECT_EQ(body.size(), server_body_bytes.load());
  18430. }
  18431. #endif
  18432. template <typename S, typename C>
  18433. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18434. svr.Get("/stream", [&](const Request &, Response &res) {
  18435. auto data = new std::string("01234567890123456789");
  18436. res.set_content_provider(
  18437. data->size(), "text/plain",
  18438. [&, data](size_t offset, size_t length, DataSink &sink) {
  18439. const size_t DATA_CHUNK_SIZE = 4;
  18440. const auto &d = *data;
  18441. std::this_thread::sleep_for(std::chrono::seconds(1));
  18442. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18443. return true;
  18444. },
  18445. [data](bool success) {
  18446. EXPECT_FALSE(success);
  18447. delete data;
  18448. });
  18449. });
  18450. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18451. auto i = new size_t(0);
  18452. res.set_content_provider(
  18453. "text/plain",
  18454. [i](size_t, DataSink &sink) {
  18455. if (*i < 5) {
  18456. std::this_thread::sleep_for(std::chrono::seconds(1));
  18457. sink.write("abcd", 4);
  18458. (*i)++;
  18459. } else {
  18460. sink.done();
  18461. }
  18462. return true;
  18463. },
  18464. [i](bool success) {
  18465. EXPECT_FALSE(success);
  18466. delete i;
  18467. });
  18468. });
  18469. svr.Get("/chunked", [&](const Request &, Response &res) {
  18470. auto i = new size_t(0);
  18471. res.set_chunked_content_provider(
  18472. "text/plain",
  18473. [i](size_t, DataSink &sink) {
  18474. if (*i < 5) {
  18475. std::this_thread::sleep_for(std::chrono::seconds(1));
  18476. sink.os << "abcd";
  18477. (*i)++;
  18478. } else {
  18479. sink.done();
  18480. }
  18481. return true;
  18482. },
  18483. [i](bool success) {
  18484. EXPECT_FALSE(success);
  18485. delete i;
  18486. });
  18487. });
  18488. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18489. auto se = detail::scope_exit([&] {
  18490. svr.stop();
  18491. listen_thread.join();
  18492. ASSERT_FALSE(svr.is_running());
  18493. });
  18494. svr.wait_until_ready();
  18495. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18496. {
  18497. auto start = std::chrono::steady_clock::now();
  18498. auto res = cli.Get("/stream");
  18499. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18500. std::chrono::steady_clock::now() - start)
  18501. .count();
  18502. ASSERT_FALSE(res);
  18503. EXPECT_EQ(Error::Read, res.error());
  18504. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18505. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18506. }
  18507. {
  18508. auto start = std::chrono::steady_clock::now();
  18509. auto res = cli.Get("/stream_without_length");
  18510. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18511. std::chrono::steady_clock::now() - start)
  18512. .count();
  18513. ASSERT_FALSE(res);
  18514. EXPECT_EQ(Error::Read, res.error());
  18515. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18516. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18517. }
  18518. {
  18519. auto start = std::chrono::steady_clock::now();
  18520. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18521. EXPECT_EQ("abcd", string(data, data_length));
  18522. return true;
  18523. });
  18524. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18525. std::chrono::steady_clock::now() - start)
  18526. .count();
  18527. ASSERT_FALSE(res);
  18528. EXPECT_EQ(Error::Read, res.error());
  18529. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18530. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18531. }
  18532. }
  18533. TEST(MaxTimeoutTest, ContentStream) {
  18534. time_t timeout = 2000;
  18535. time_t threshold = 200;
  18536. Server svr;
  18537. Client cli("localhost", PORT);
  18538. max_timeout_test(svr, cli, timeout, threshold);
  18539. }
  18540. #ifdef CPPHTTPLIB_SSL_ENABLED
  18541. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18542. time_t timeout = 2000;
  18543. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18544. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18545. SSLClient cli("localhost", PORT);
  18546. cli.enable_server_certificate_verification(false);
  18547. max_timeout_test(svr, cli, timeout, threshold);
  18548. }
  18549. #endif
  18550. class EventDispatcher {
  18551. public:
  18552. EventDispatcher() {}
  18553. bool wait_event(DataSink *sink) {
  18554. unique_lock<mutex> lk(m_);
  18555. int id = id_;
  18556. // Wait with timeout to prevent hanging if client disconnects
  18557. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18558. [&] { return cid_ == id; })) {
  18559. return false; // Timeout occurred
  18560. }
  18561. sink->write(message_.data(), message_.size());
  18562. return true;
  18563. }
  18564. void send_event(const string &message) {
  18565. lock_guard<mutex> lk(m_);
  18566. cid_ = id_++;
  18567. message_ = message;
  18568. cv_.notify_all();
  18569. }
  18570. private:
  18571. mutex m_;
  18572. condition_variable cv_;
  18573. atomic_int id_{0};
  18574. atomic_int cid_{-1};
  18575. string message_;
  18576. };
  18577. TEST(ClientInThreadTest, Issue2068) {
  18578. EventDispatcher ed;
  18579. Server svr;
  18580. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18581. res.set_chunked_content_provider("text/event-stream",
  18582. [&](size_t /*offset*/, DataSink &sink) {
  18583. return ed.wait_event(&sink);
  18584. });
  18585. });
  18586. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18587. svr.wait_until_ready();
  18588. thread event_thread([&] {
  18589. int id = 0;
  18590. while (svr.is_running()) {
  18591. this_thread::sleep_for(chrono::milliseconds(500));
  18592. std::stringstream ss;
  18593. ss << "data: " << id << "\n\n";
  18594. ed.send_event(ss.str());
  18595. id++;
  18596. }
  18597. });
  18598. auto se = detail::scope_exit([&] {
  18599. svr.stop();
  18600. listen_thread.join();
  18601. event_thread.join();
  18602. ASSERT_FALSE(svr.is_running());
  18603. });
  18604. {
  18605. auto client = detail::make_unique<Client>(HOST, PORT);
  18606. client->set_read_timeout(std::chrono::minutes(10));
  18607. std::atomic<bool> stop{false};
  18608. std::thread t([&] {
  18609. client->Get("/event1",
  18610. [&](const char *, size_t) -> bool { return !stop; });
  18611. });
  18612. std::this_thread::sleep_for(std::chrono::seconds(2));
  18613. stop = true;
  18614. client->stop();
  18615. t.join();
  18616. // Reset client after thread has finished
  18617. client.reset();
  18618. }
  18619. }
  18620. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18621. auto handled = false;
  18622. Server svr;
  18623. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18624. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18625. auto se = detail::scope_exit([&] {
  18626. svr.stop();
  18627. t.join();
  18628. ASSERT_FALSE(svr.is_running());
  18629. ASSERT_FALSE(handled);
  18630. });
  18631. svr.wait_until_ready();
  18632. // Two Content-Length headers with different values — must be rejected
  18633. auto req = "POST /test HTTP/1.1\r\n"
  18634. "Content-Length: 5\r\n"
  18635. "Content-Length: 10\r\n"
  18636. "\r\n"
  18637. "hello";
  18638. std::string response;
  18639. ASSERT_TRUE(send_request(1, req, &response));
  18640. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18641. response.substr(0, response.find("\r\n")));
  18642. }
  18643. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18644. auto handled = false;
  18645. Server svr;
  18646. svr.Post("/test", [&](const Request &, Response &res) {
  18647. handled = true;
  18648. res.set_content("ok", "text/plain");
  18649. });
  18650. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18651. auto se = detail::scope_exit([&] {
  18652. svr.stop();
  18653. t.join();
  18654. ASSERT_FALSE(svr.is_running());
  18655. ASSERT_TRUE(handled);
  18656. });
  18657. svr.wait_until_ready();
  18658. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18659. auto req = "POST /test HTTP/1.1\r\n"
  18660. "Host: localhost\r\n"
  18661. "Content-Length: 5\r\n"
  18662. "Content-Length: 5\r\n"
  18663. "\r\n"
  18664. "hello";
  18665. std::string response;
  18666. ASSERT_TRUE(send_request(1, req, &response));
  18667. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18668. }
  18669. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18670. Server svr;
  18671. svr.Get("/test", [](const Request &, Response &res) {
  18672. res.set_content("ok", "text/plain");
  18673. });
  18674. auto port = svr.bind_to_any_port(HOST);
  18675. thread t = thread([&] { svr.listen_after_bind(); });
  18676. auto se = detail::scope_exit([&] {
  18677. svr.stop();
  18678. t.join();
  18679. ASSERT_FALSE(svr.is_running());
  18680. });
  18681. svr.wait_until_ready();
  18682. auto status_line = [&](const std::string &host_lines) {
  18683. std::string res;
  18684. send_request(
  18685. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18686. &res, port);
  18687. return res.substr(0, res.find("\r\n"));
  18688. };
  18689. const char *accepted[] = {
  18690. "Host: localhost\r\n",
  18691. "Host: a.example:8080\r\n",
  18692. "Host: my_service\r\n",
  18693. "Host: [::1]:8080\r\n",
  18694. "Host: [fe80::1%25eth0]\r\n",
  18695. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18696. };
  18697. for (auto host_lines : accepted) {
  18698. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18699. }
  18700. const char *rejected[] = {
  18701. "Host: a.example\r\nHost: b.example\r\n",
  18702. "Host: a.example\r\nHost: a.example\r\n",
  18703. "Host: a@b.example\r\n",
  18704. "Host: a.example/b\r\n",
  18705. "Host: a.example\\b\r\n",
  18706. "Host: a.example?b\r\n",
  18707. "Host: a.example#b\r\n",
  18708. "Host: a.example b.example\r\n",
  18709. };
  18710. for (auto host_lines : rejected) {
  18711. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18712. << host_lines;
  18713. }
  18714. }
  18715. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18716. Server svr;
  18717. svr.Get("/", [](const Request &req, Response &res) {
  18718. EXPECT_EQ(2U, req.trailers.size());
  18719. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18720. // Denied
  18721. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18722. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18723. // Accepted
  18724. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18725. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18726. EXPECT_TRUE(req.has_trailer("X-World"));
  18727. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18728. res.set_content("ok", "text/plain");
  18729. });
  18730. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18731. auto se = detail::scope_exit([&] {
  18732. svr.stop();
  18733. t.join();
  18734. ASSERT_FALSE(svr.is_running());
  18735. });
  18736. svr.wait_until_ready();
  18737. const std::string req = "GET / HTTP/1.1\r\n"
  18738. "Transfer-Encoding: chunked\r\n"
  18739. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18740. "\r\n"
  18741. "0\r\n"
  18742. "Content-Length: 10\r\n"
  18743. "Host: internal.local\r\n"
  18744. "Content-Type: malicious/content\r\n"
  18745. "Cookie: any\r\n"
  18746. "Set-Cookie: any\r\n"
  18747. "X-Forwarded-For: attacker.com\r\n"
  18748. "X-Real-Ip: 1.1.1.1\r\n"
  18749. "X-Hello: hello\r\n"
  18750. "X-World: world\r\n"
  18751. "\r\n";
  18752. std::string res;
  18753. ASSERT_TRUE(send_request(1, req, &res));
  18754. }
  18755. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18756. // several field lines, and the combined value is what has to be parsed. A
  18757. // Trailer field split across lines therefore declares every name it lists;
  18758. // reading only the first line silently drops the trailers the later lines
  18759. // declare. The prohibited-trailer filter still applies to every line.
  18760. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18761. Server svr;
  18762. size_t observed_trailer_count = 0;
  18763. std::string observed_hello;
  18764. std::string observed_world;
  18765. bool observed_content_length = true;
  18766. svr.Get("/", [&](const Request &req, Response &res) {
  18767. observed_trailer_count = req.trailers.size();
  18768. observed_hello = req.get_trailer_value("X-Hello");
  18769. observed_world = req.get_trailer_value("X-World");
  18770. observed_content_length = req.has_trailer("Content-Length");
  18771. res.set_content("ok", "text/plain");
  18772. });
  18773. auto port = svr.bind_to_any_port(HOST);
  18774. thread t = thread([&]() { svr.listen_after_bind(); });
  18775. auto se = detail::scope_exit([&] {
  18776. svr.stop();
  18777. t.join();
  18778. ASSERT_FALSE(svr.is_running());
  18779. });
  18780. svr.wait_until_ready();
  18781. const std::string req = "GET / HTTP/1.1\r\n"
  18782. "Host: localhost\r\n"
  18783. "Transfer-Encoding: chunked\r\n"
  18784. "Trailer: X-Hello\r\n"
  18785. "Trailer: X-World, Content-Length\r\n"
  18786. "\r\n"
  18787. "0\r\n"
  18788. "X-Hello: hello\r\n"
  18789. "X-World: world\r\n"
  18790. "Content-Length: 10\r\n"
  18791. "\r\n";
  18792. std::string res;
  18793. ASSERT_TRUE(send_request(1, req, &res, port));
  18794. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18795. // Accepted: both field lines contribute to the declared set
  18796. EXPECT_EQ(2U, observed_trailer_count);
  18797. EXPECT_EQ(observed_hello, "hello");
  18798. EXPECT_EQ(observed_world, "world");
  18799. // Denied: a prohibited name stays prohibited on a later field line
  18800. EXPECT_FALSE(observed_content_length);
  18801. }
  18802. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18803. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18804. // unbounded run of fields that are never declared, because the counter would
  18805. // only advance for declared fields.
  18806. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18807. Server svr;
  18808. bool handler_called = false;
  18809. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18810. handler_called = true;
  18811. res.set_content("ok", "text/plain");
  18812. });
  18813. auto port = svr.bind_to_any_port(HOST);
  18814. thread t = thread([&]() { svr.listen_after_bind(); });
  18815. auto se = detail::scope_exit([&] {
  18816. svr.stop();
  18817. t.join();
  18818. ASSERT_FALSE(svr.is_running());
  18819. });
  18820. svr.wait_until_ready();
  18821. // Declare nothing, then send far more undeclared trailer fields than the
  18822. // header-count limit. Parsing must stop and reject the request rather than
  18823. // read every line.
  18824. std::string req = "GET / HTTP/1.1\r\n"
  18825. "Transfer-Encoding: chunked\r\n"
  18826. "\r\n"
  18827. "0\r\n";
  18828. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18829. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18830. }
  18831. req += "\r\n";
  18832. std::string res;
  18833. ASSERT_TRUE(send_request(1, req, &res, port));
  18834. // The request is rejected before the handler runs.
  18835. EXPECT_FALSE(handler_called);
  18836. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18837. }
  18838. // The set of declared trailer names is capped so a peer cannot grow it without
  18839. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18840. // declared past the cap is not honored, even if the field is actually sent.
  18841. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18842. Server svr;
  18843. // One name inside the cap and one past it, so the test tracks the cap rather
  18844. // than a fixed count.
  18845. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18846. const std::string within_cap_name = "X-T-0";
  18847. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18848. bool observed_within_cap = false;
  18849. bool observed_past_cap = false;
  18850. svr.Get("/", [&](const Request &req, Response &res) {
  18851. observed_within_cap = req.has_trailer(within_cap_name);
  18852. observed_past_cap = req.has_trailer(past_cap_name);
  18853. res.set_content("ok", "text/plain");
  18854. });
  18855. auto port = svr.bind_to_any_port(HOST);
  18856. thread t = thread([&]() { svr.listen_after_bind(); });
  18857. auto se = detail::scope_exit([&] {
  18858. svr.stop();
  18859. t.join();
  18860. ASSERT_FALSE(svr.is_running());
  18861. });
  18862. svr.wait_until_ready();
  18863. // Declare more trailer names than the cap in a single Trailer field, then
  18864. // actually send the first (within the cap) and the last (past it).
  18865. std::string trailer_decl = "Trailer: ";
  18866. for (int i = 0; i < declared_count; i++) {
  18867. if (i != 0) { trailer_decl += ", "; }
  18868. trailer_decl += "X-T-" + std::to_string(i);
  18869. }
  18870. trailer_decl += "\r\n";
  18871. const std::string req = "GET / HTTP/1.1\r\n"
  18872. "Host: localhost\r\n"
  18873. "Transfer-Encoding: chunked\r\n" +
  18874. trailer_decl +
  18875. "\r\n"
  18876. "0\r\n" +
  18877. within_cap_name + ": a\r\n" + past_cap_name +
  18878. ": b\r\n"
  18879. "\r\n";
  18880. std::string res;
  18881. ASSERT_TRUE(send_request(1, req, &res, port));
  18882. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18883. // A name within the cap is honored; one declared past the cap is dropped.
  18884. EXPECT_TRUE(observed_within_cap);
  18885. EXPECT_FALSE(observed_past_cap);
  18886. }
  18887. // A direct client that is not listed in trusted_proxies must not be able to
  18888. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18889. // the peer address on the actual TCP connection determines whether the
  18890. // header is honored.
  18891. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18892. Server svr;
  18893. // Deliberately does NOT include the loopback address the test client
  18894. // actually connects from, so the direct connection is not a trusted proxy.
  18895. svr.set_trusted_proxies({"203.0.113.66"});
  18896. std::string observed_remote_addr;
  18897. svr.Get("/ip", [&](const Request &req, Response &res) {
  18898. observed_remote_addr = req.remote_addr;
  18899. res.set_content("ok", "text/plain");
  18900. });
  18901. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18902. auto se = detail::scope_exit([&] {
  18903. svr.stop();
  18904. t.join();
  18905. ASSERT_FALSE(svr.is_running());
  18906. });
  18907. svr.wait_until_ready();
  18908. Client cli(HOST, PORT);
  18909. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18911. EXPECT_EQ(StatusCode::OK_200, res->status);
  18912. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18913. // ignored entirely and the real connection-level address retained.
  18914. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18915. observed_remote_addr == "127.0.0.1");
  18916. }
  18917. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18918. Server svr;
  18919. std::string observed_remote_addr;
  18920. std::string observed_xff;
  18921. svr.Get("/ip", [&](const Request &req, Response &res) {
  18922. observed_remote_addr = req.remote_addr;
  18923. observed_xff = req.get_header_value("X-Forwarded-For");
  18924. res.set_content("ok", "text/plain");
  18925. });
  18926. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18927. auto se = detail::scope_exit([&] {
  18928. svr.stop();
  18929. t.join();
  18930. ASSERT_FALSE(svr.is_running());
  18931. });
  18932. svr.wait_until_ready();
  18933. Client cli(HOST, PORT);
  18934. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18936. EXPECT_EQ(StatusCode::OK_200, res->status);
  18937. EXPECT_EQ(observed_xff, "203.0.113.66");
  18938. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18939. observed_remote_addr == "127.0.0.1");
  18940. }
  18941. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18942. Server svr;
  18943. svr.set_trusted_proxies({"203.0.113.66"});
  18944. std::string observed_remote_addr;
  18945. std::string observed_xff;
  18946. svr.Get("/ip", [&](const Request &req, Response &res) {
  18947. observed_remote_addr = req.remote_addr;
  18948. observed_xff = req.get_header_value("X-Forwarded-For");
  18949. res.set_content("ok", "text/plain");
  18950. });
  18951. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18952. auto se = detail::scope_exit([&] {
  18953. svr.stop();
  18954. t.join();
  18955. ASSERT_FALSE(svr.is_running());
  18956. });
  18957. svr.wait_until_ready();
  18958. Client cli(HOST, PORT);
  18959. auto res = cli.Get("/ip");
  18960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18961. EXPECT_EQ(StatusCode::OK_200, res->status);
  18962. EXPECT_EQ(observed_xff, "");
  18963. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18964. observed_remote_addr == "127.0.0.1");
  18965. }
  18966. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18967. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18968. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18969. Server svr;
  18970. svr.set_trusted_proxies({"127.0.0.1"});
  18971. svr.Get("/ip", [](const Request &req, Response &res) {
  18972. res.set_content(req.remote_addr, "text/plain");
  18973. });
  18974. auto port = svr.bind_to_any_port("::");
  18975. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  18976. thread t = thread([&] { svr.listen_after_bind(); });
  18977. auto se = detail::scope_exit([&] {
  18978. svr.stop();
  18979. t.join();
  18980. ASSERT_FALSE(svr.is_running());
  18981. });
  18982. svr.wait_until_ready();
  18983. Client cli("127.0.0.1", port);
  18984. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  18985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18986. EXPECT_EQ("198.51.100.23", res->body);
  18987. }
  18988. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  18989. Server svr;
  18990. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18991. svr.Get("/ip", [](const Request &req, Response &res) {
  18992. res.set_content(req.remote_addr, "text/plain");
  18993. });
  18994. auto port = svr.bind_to_any_port(HOST);
  18995. ASSERT_GT(port, 0);
  18996. thread t = thread([&] { svr.listen_after_bind(); });
  18997. auto se = detail::scope_exit([&] {
  18998. svr.stop();
  18999. t.join();
  19000. ASSERT_FALSE(svr.is_running());
  19001. });
  19002. svr.wait_until_ready();
  19003. Client cli(HOST, port);
  19004. auto res = cli.Get(
  19005. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19007. EXPECT_EQ("198.51.100.23", res->body);
  19008. }
  19009. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19010. Server svr;
  19011. // Include the loopback address the test client actually connects from, so
  19012. // the direct connection itself is recognized as the trusted proxy hop.
  19013. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19014. std::string observed_remote_addr;
  19015. std::string observed_xff;
  19016. svr.Get("/ip", [&](const Request &req, Response &res) {
  19017. observed_remote_addr = req.remote_addr;
  19018. observed_xff = req.get_header_value("X-Forwarded-For");
  19019. res.set_content("ok", "text/plain");
  19020. });
  19021. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19022. auto se = detail::scope_exit([&] {
  19023. svr.stop();
  19024. t.join();
  19025. ASSERT_FALSE(svr.is_running());
  19026. });
  19027. svr.wait_until_ready();
  19028. Client cli(HOST, PORT);
  19029. auto res = cli.Get(
  19030. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19032. EXPECT_EQ(StatusCode::OK_200, res->status);
  19033. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19034. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19035. }
  19036. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19037. Server svr;
  19038. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19039. std::string observed_remote_addr;
  19040. std::string observed_xff;
  19041. svr.Get("/ip", [&](const Request &req, Response &res) {
  19042. observed_remote_addr = req.remote_addr;
  19043. observed_xff = req.get_header_value("X-Forwarded-For");
  19044. res.set_content("ok", "text/plain");
  19045. });
  19046. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19047. auto se = detail::scope_exit([&] {
  19048. svr.stop();
  19049. t.join();
  19050. ASSERT_FALSE(svr.is_running());
  19051. });
  19052. svr.wait_until_ready();
  19053. Client cli(HOST, PORT);
  19054. auto res = cli.Get(
  19055. "/ip",
  19056. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19058. EXPECT_EQ(StatusCode::OK_200, res->status);
  19059. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19060. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19061. }
  19062. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19063. Server svr;
  19064. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19065. std::string observed_remote_addr;
  19066. std::string observed_xff;
  19067. svr.Get("/ip", [&](const Request &req, Response &res) {
  19068. observed_remote_addr = req.remote_addr;
  19069. observed_xff = req.get_header_value("X-Forwarded-For");
  19070. res.set_content("ok", "text/plain");
  19071. });
  19072. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19073. auto se = detail::scope_exit([&] {
  19074. svr.stop();
  19075. t.join();
  19076. ASSERT_FALSE(svr.is_running());
  19077. });
  19078. svr.wait_until_ready();
  19079. Client cli(HOST, PORT);
  19080. auto res = cli.Get(
  19081. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19083. EXPECT_EQ(StatusCode::OK_200, res->status);
  19084. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19085. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19086. // and must not be selected.
  19087. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19088. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19089. }
  19090. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19091. Server svr;
  19092. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19093. std::string observed_remote_addr;
  19094. svr.Get("/ip", [&](const Request &req, Response &res) {
  19095. observed_remote_addr = req.remote_addr;
  19096. res.set_content("ok", "text/plain");
  19097. });
  19098. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19099. auto se = detail::scope_exit([&] {
  19100. svr.stop();
  19101. t.join();
  19102. ASSERT_FALSE(svr.is_running());
  19103. });
  19104. svr.wait_until_ready();
  19105. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19106. // a forged address and the trusted proxy's own address; the forged value must
  19107. // not win over the address the trusted proxy actually recorded.
  19108. Client cli(HOST, PORT);
  19109. auto res = cli.Get(
  19110. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19112. EXPECT_EQ(StatusCode::OK_200, res->status);
  19113. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19114. }
  19115. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19116. Server svr;
  19117. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19118. std::string observed_remote_addr;
  19119. std::string observed_xff;
  19120. svr.Get("/ip", [&](const Request &req, Response &res) {
  19121. observed_remote_addr = req.remote_addr;
  19122. observed_xff = req.get_header_value("X-Forwarded-For");
  19123. res.set_content("ok", "text/plain");
  19124. });
  19125. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19126. auto se = detail::scope_exit([&] {
  19127. svr.stop();
  19128. t.join();
  19129. ASSERT_FALSE(svr.is_running());
  19130. });
  19131. svr.wait_until_ready();
  19132. Client cli(HOST, PORT);
  19133. auto res = cli.Get(
  19134. "/ip",
  19135. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19137. EXPECT_EQ(StatusCode::OK_200, res->status);
  19138. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19139. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19140. }
  19141. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19142. Server svr;
  19143. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19144. std::string observed_remote_addr;
  19145. std::string observed_xff;
  19146. svr.Get("/ip", [&](const Request &req, Response &res) {
  19147. observed_remote_addr = req.remote_addr;
  19148. observed_xff = req.get_header_value("X-Forwarded-For");
  19149. res.set_content("ok", "text/plain");
  19150. });
  19151. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19152. auto se = detail::scope_exit([&] {
  19153. svr.stop();
  19154. t.join();
  19155. ASSERT_FALSE(svr.is_running());
  19156. });
  19157. svr.wait_until_ready();
  19158. std::string raw_req =
  19159. "GET /ip HTTP/1.1\r\n"
  19160. "Host: localhost\r\n"
  19161. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19162. "Connection: close\r\n"
  19163. "\r\n";
  19164. std::string out;
  19165. ASSERT_TRUE(send_request(5, raw_req, &out));
  19166. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19167. // Header parser trims surrounding whitespace of the header value
  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. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19172. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19173. // their own X-Forwarded-For as a separate field line rather than extending the
  19174. // one the client sent, so every occurrence has to be taken into account.
  19175. // Reading only the first one hands back the address the client chose.
  19176. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19177. Server svr;
  19178. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19179. std::string observed_remote_addr;
  19180. size_t observed_xff_count = 0;
  19181. svr.Get("/ip", [&](const Request &req, Response &res) {
  19182. observed_remote_addr = req.remote_addr;
  19183. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19184. res.set_content("ok", "text/plain");
  19185. });
  19186. auto port = svr.bind_to_any_port(HOST);
  19187. thread t = thread([&]() { svr.listen_after_bind(); });
  19188. auto se = detail::scope_exit([&] {
  19189. svr.stop();
  19190. t.join();
  19191. ASSERT_FALSE(svr.is_running());
  19192. });
  19193. svr.wait_until_ready();
  19194. // The client supplies the first field line; the trusted proxy appends the
  19195. // address it observed as a second one.
  19196. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19197. "Host: localhost\r\n"
  19198. "X-Forwarded-For: 1.2.3.4\r\n"
  19199. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19200. "Connection: close\r\n"
  19201. "\r\n";
  19202. std::string out;
  19203. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19204. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19205. EXPECT_EQ(observed_xff_count, 2U);
  19206. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19207. // The same chain spread over one field line per hop derives the same client
  19208. // address, i.e. the split and the comma-joined representations agree.
  19209. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19210. "Host: localhost\r\n"
  19211. "X-Forwarded-For: 1.2.3.4\r\n"
  19212. "X-Forwarded-For: 198.51.100.23\r\n"
  19213. "X-Forwarded-For: 192.0.2.45\r\n"
  19214. "Connection: close\r\n"
  19215. "\r\n";
  19216. out.clear();
  19217. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19218. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19219. EXPECT_EQ(observed_xff_count, 3U);
  19220. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19221. }
  19222. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19223. // crash the server (it used to call front() on an empty vector inside
  19224. // get_client_ip). The connection-level remote address must be retained instead.
  19225. static void run_malformed_xff_test(const std::string &xff_value) {
  19226. Server svr;
  19227. svr.set_trusted_proxies({"192.0.2.45"});
  19228. std::string observed_remote_addr;
  19229. svr.Get("/ip", [&](const Request &req, Response &res) {
  19230. observed_remote_addr = req.remote_addr;
  19231. res.set_content("ok", "text/plain");
  19232. });
  19233. int port = 0;
  19234. thread t = thread([&]() {
  19235. port = svr.bind_to_any_port(HOST);
  19236. svr.listen_after_bind();
  19237. });
  19238. auto se = detail::scope_exit([&] {
  19239. svr.stop();
  19240. t.join();
  19241. ASSERT_FALSE(svr.is_running());
  19242. });
  19243. svr.wait_until_ready();
  19244. Client cli(HOST, port);
  19245. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19247. EXPECT_EQ(StatusCode::OK_200, res->status);
  19248. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19249. observed_remote_addr == "127.0.0.1");
  19250. }
  19251. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19252. run_malformed_xff_test("");
  19253. }
  19254. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19255. run_malformed_xff_test(",");
  19256. }
  19257. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19258. run_malformed_xff_test(", , ,");
  19259. }
  19260. // The same rule applies to Accept: a request whose acceptable types are spread
  19261. // over several field lines must be negotiated against all of them.
  19262. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19263. // case-insensitive connection options. Comparing the whole field value against
  19264. // one option misses a client that sends several of them, and misses every
  19265. // casing but the one written in the comparison.
  19266. //
  19267. // Sends req, reads the response, then reuses the same socket for a second
  19268. // request to find out whether the server kept the connection.
  19269. static void probe_connection_reuse(int port, const std::string &req,
  19270. bool *announced_close, bool *reusable) {
  19271. auto error = Error::Success;
  19272. auto sock = detail::create_client_socket(
  19273. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19274. /*connection_timeout_sec=*/5, 0,
  19275. /*read_timeout_sec=*/1, 0,
  19276. /*write_timeout_sec=*/5, 0, std::string(), error);
  19277. ASSERT_NE(sock, INVALID_SOCKET);
  19278. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19279. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19280. "Host: localhost\r\n"
  19281. "Connection: close\r\n"
  19282. "\r\n";
  19283. std::string first_response;
  19284. std::string second_response;
  19285. detail::process_client_socket(
  19286. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19287. [&](Stream &strm) {
  19288. if (strm.write(req.data(), req.size()) !=
  19289. static_cast<ssize_t>(req.size())) {
  19290. return false;
  19291. }
  19292. char buf[512];
  19293. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19294. // Headers plus the two-byte body of the handler below
  19295. while (reader.getline()) {
  19296. first_response += reader.ptr();
  19297. if (first_response.find("ok") != std::string::npos) { break; }
  19298. }
  19299. if (strm.write(second.data(), second.size()) !=
  19300. static_cast<ssize_t>(second.size())) {
  19301. return true;
  19302. }
  19303. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19304. while (reader2.getline()) {
  19305. second_response += reader2.ptr();
  19306. if (second_response.find("ok") != std::string::npos) { break; }
  19307. }
  19308. return true;
  19309. });
  19310. *announced_close =
  19311. first_response.find("Connection: close") != std::string::npos;
  19312. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19313. }
  19314. class ConnectionTokenTest : public ::testing::Test {
  19315. protected:
  19316. void SetUp() override {
  19317. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19318. res.set_content("ok", "text/plain");
  19319. });
  19320. port_ = svr_.bind_to_any_port(HOST);
  19321. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19322. svr_.wait_until_ready();
  19323. }
  19324. void TearDown() override {
  19325. svr_.stop();
  19326. if (thread_.joinable()) { thread_.join(); }
  19327. }
  19328. Server svr_;
  19329. int port_ = 0;
  19330. thread thread_;
  19331. };
  19332. // "close" alongside another option still closes the connection, and the
  19333. // response says so rather than leaving the peer to discover it.
  19334. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19335. bool announced_close = false;
  19336. bool reusable = true;
  19337. probe_connection_reuse(port_,
  19338. "GET /keepalive HTTP/1.1\r\n"
  19339. "Host: localhost\r\n"
  19340. "Connection: keep-alive, close\r\n"
  19341. "\r\n",
  19342. &announced_close, &reusable);
  19343. EXPECT_TRUE(announced_close);
  19344. EXPECT_FALSE(reusable);
  19345. }
  19346. // "close" split over two field lines is the same list, so it is honored too.
  19347. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19348. bool announced_close = false;
  19349. bool reusable = true;
  19350. probe_connection_reuse(port_,
  19351. "GET /keepalive HTTP/1.1\r\n"
  19352. "Host: localhost\r\n"
  19353. "Connection: keep-alive\r\n"
  19354. "Connection: close\r\n"
  19355. "\r\n",
  19356. &announced_close, &reusable);
  19357. EXPECT_TRUE(announced_close);
  19358. EXPECT_FALSE(reusable);
  19359. }
  19360. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19361. // keep-alive in the spelling everyone actually sends keeps its connection.
  19362. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19363. bool announced_close = false;
  19364. bool reusable = false;
  19365. probe_connection_reuse(port_,
  19366. "GET /keepalive HTTP/1.0\r\n"
  19367. "Host: localhost\r\n"
  19368. "Connection: keep-alive\r\n"
  19369. "\r\n",
  19370. &announced_close, &reusable);
  19371. EXPECT_FALSE(announced_close);
  19372. EXPECT_TRUE(reusable);
  19373. }
  19374. // A token the value merely contains is not the token itself.
  19375. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19376. bool announced_close = false;
  19377. bool reusable = false;
  19378. probe_connection_reuse(port_,
  19379. "GET /keepalive HTTP/1.1\r\n"
  19380. "Host: localhost\r\n"
  19381. "Connection: notclose\r\n"
  19382. "\r\n",
  19383. &announced_close, &reusable);
  19384. EXPECT_FALSE(announced_close);
  19385. EXPECT_TRUE(reusable);
  19386. }
  19387. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19388. Server svr;
  19389. std::vector<std::string> observed_types;
  19390. svr.Get("/", [&](const Request &req, Response &res) {
  19391. observed_types = req.accept_content_types;
  19392. res.set_content("ok", "text/plain");
  19393. });
  19394. auto port = svr.bind_to_any_port(HOST);
  19395. thread t = thread([&]() { svr.listen_after_bind(); });
  19396. auto se = detail::scope_exit([&] {
  19397. svr.stop();
  19398. t.join();
  19399. ASSERT_FALSE(svr.is_running());
  19400. });
  19401. svr.wait_until_ready();
  19402. Client cli(HOST, port);
  19403. Headers headers;
  19404. headers.emplace("Accept", "text/plain;q=0.5");
  19405. headers.emplace("Accept", "application/json");
  19406. auto res = cli.Get("/", headers);
  19407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19408. EXPECT_EQ(StatusCode::OK_200, res->status);
  19409. // Sorted by q-value, so the second field line's type comes first
  19410. ASSERT_EQ(2U, observed_types.size());
  19411. EXPECT_EQ("application/json", observed_types[0]);
  19412. EXPECT_EQ("text/plain", observed_types[1]);
  19413. }
  19414. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19415. // empty field line must not contribute a bare comma to the combined value.
  19416. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19417. Server svr;
  19418. std::vector<std::string> observed_types;
  19419. svr.Get("/", [&](const Request &req, Response &res) {
  19420. observed_types = req.accept_content_types;
  19421. res.set_content("ok", "text/plain");
  19422. });
  19423. auto port = svr.bind_to_any_port(HOST);
  19424. thread t = thread([&]() { svr.listen_after_bind(); });
  19425. auto se = detail::scope_exit([&] {
  19426. svr.stop();
  19427. t.join();
  19428. ASSERT_FALSE(svr.is_running());
  19429. });
  19430. svr.wait_until_ready();
  19431. // Empty first field line, then a real one
  19432. std::string raw_req = "GET / HTTP/1.1\r\n"
  19433. "Host: localhost\r\n"
  19434. "Accept:\r\n"
  19435. "Accept: application/json\r\n"
  19436. "Connection: close\r\n"
  19437. "\r\n";
  19438. std::string out;
  19439. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19440. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19441. ASSERT_EQ(1U, observed_types.size());
  19442. EXPECT_EQ("application/json", observed_types[0]);
  19443. }
  19444. // The skip in get_combined_header_value() is what keeps an empty field line
  19445. // from contributing a bare comma. Only a trailing empty field line exercises
  19446. // it: a leading one is already covered by the "combined is still empty" check,
  19447. // and parse_accept_header() now ignores the empty element either way, so the
  19448. // request-level test above can no longer tell the two apart.
  19449. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19450. Headers headers;
  19451. headers.emplace("Accept", "text/html");
  19452. headers.emplace("Accept", "");
  19453. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19454. headers.clear();
  19455. headers.emplace("Accept", "");
  19456. headers.emplace("Accept", "application/json");
  19457. EXPECT_EQ("application/json",
  19458. detail::get_combined_header_value(headers, "Accept"));
  19459. }
  19460. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19461. // An encoding offered on a later Accept-Encoding field line is still offered.
  19462. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19463. Server svr;
  19464. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19465. res.set_content(std::string(1024, 'x'), "text/plain");
  19466. });
  19467. auto port = svr.bind_to_any_port(HOST);
  19468. thread t = thread([&]() { svr.listen_after_bind(); });
  19469. auto se = detail::scope_exit([&] {
  19470. svr.stop();
  19471. t.join();
  19472. ASSERT_FALSE(svr.is_running());
  19473. });
  19474. svr.wait_until_ready();
  19475. Client cli(HOST, port);
  19476. cli.set_decompress(false);
  19477. Headers headers;
  19478. headers.emplace("Accept-Encoding", "identity");
  19479. headers.emplace("Accept-Encoding", "gzip");
  19480. auto res = cli.Get("/", headers);
  19481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19482. EXPECT_EQ(StatusCode::OK_200, res->status);
  19483. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19484. }
  19485. #endif
  19486. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19487. // Transfer-Encoding is not its body.
  19488. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19489. Server svr;
  19490. svr.set_payload_max_length(8);
  19491. svr.Post("/test", [](const Request &, Response &res) {
  19492. res.set_content("ok", "text/plain");
  19493. });
  19494. auto port = svr.bind_to_any_port(HOST);
  19495. ASSERT_GT(port, 0);
  19496. thread t = thread([&] { svr.listen_after_bind(); });
  19497. auto se = detail::scope_exit([&] {
  19498. svr.stop();
  19499. t.join();
  19500. ASSERT_FALSE(svr.is_running());
  19501. });
  19502. svr.wait_until_ready();
  19503. std::string resp;
  19504. ASSERT_TRUE(send_request(1,
  19505. "POST /test HTTP/1.1\r\n"
  19506. "Host: localhost\r\n"
  19507. "Connection: close\r\n"
  19508. "\r\n" +
  19509. std::string(16, 'X'),
  19510. &resp, port));
  19511. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19512. }
  19513. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19514. Server svr;
  19515. svr.Post("/post", [&](const Request &req, Response &res) {
  19516. res.set_content(req.body, "text/plain");
  19517. });
  19518. svr.Put("/put", [&](const Request &req, Response &res) {
  19519. res.set_content(req.body, "text/plain");
  19520. });
  19521. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19522. res.set_content(req.body, "text/plain");
  19523. });
  19524. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19525. res.set_content(req.body, "text/plain");
  19526. });
  19527. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19528. auto se = detail::scope_exit([&] {
  19529. svr.stop();
  19530. t.join();
  19531. ASSERT_FALSE(svr.is_running());
  19532. });
  19533. svr.wait_until_ready();
  19534. std::string resp;
  19535. // POST without Content-Length
  19536. ASSERT_TRUE(send_request(5,
  19537. "POST /post HTTP/1.1\r\n"
  19538. "Host: localhost\r\n"
  19539. "Connection: close\r\n"
  19540. "\r\n",
  19541. &resp));
  19542. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19543. // PUT without Content-Length
  19544. resp.clear();
  19545. ASSERT_TRUE(send_request(5,
  19546. "PUT /put HTTP/1.1\r\n"
  19547. "Host: localhost\r\n"
  19548. "Connection: close\r\n"
  19549. "\r\n",
  19550. &resp));
  19551. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19552. // PATCH without Content-Length
  19553. resp.clear();
  19554. ASSERT_TRUE(send_request(5,
  19555. "PATCH /patch HTTP/1.1\r\n"
  19556. "Host: localhost\r\n"
  19557. "Connection: close\r\n"
  19558. "\r\n",
  19559. &resp));
  19560. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19561. // DELETE without Content-Length
  19562. resp.clear();
  19563. ASSERT_TRUE(send_request(5,
  19564. "DELETE /delete HTTP/1.1\r\n"
  19565. "Host: localhost\r\n"
  19566. "Connection: close\r\n"
  19567. "\r\n",
  19568. &resp));
  19569. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19570. }
  19571. //==============================================================================
  19572. // open_stream() Tests
  19573. //==============================================================================
  19574. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19575. std::string result;
  19576. char buf[8192];
  19577. ssize_t n;
  19578. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19579. result.append(buf, static_cast<size_t>(n));
  19580. }
  19581. return result;
  19582. }
  19583. // Mock stream for unit tests
  19584. class MockStream : public Stream {
  19585. public:
  19586. std::string data;
  19587. size_t pos = 0;
  19588. ssize_t error_after = -1; // -1 = no error
  19589. explicit MockStream(const std::string &d, ssize_t err = -1)
  19590. : data(d), error_after(err) {}
  19591. bool is_readable() const override { return true; }
  19592. bool wait_readable() const override { return true; }
  19593. bool wait_writable() const override { return true; }
  19594. ssize_t read(char *ptr, size_t size) override {
  19595. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19596. if (pos >= data.size()) return 0;
  19597. size_t limit =
  19598. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19599. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19600. std::memcpy(ptr, data.data() + pos, to_read);
  19601. pos += to_read;
  19602. return static_cast<ssize_t>(to_read);
  19603. }
  19604. ssize_t write(const char *, size_t) override { return -1; }
  19605. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19606. ip = "127.0.0.1";
  19607. port = 0;
  19608. }
  19609. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19610. ip = "127.0.0.1";
  19611. port = 0;
  19612. }
  19613. socket_t socket() const override { return INVALID_SOCKET; }
  19614. time_t duration() const override { return 0; }
  19615. };
  19616. TEST(StreamHandleTest, Basic) {
  19617. ClientImpl::StreamHandle handle;
  19618. EXPECT_FALSE(handle.is_valid());
  19619. handle.response = detail::make_unique<Response>();
  19620. handle.error = Error::Connection;
  19621. EXPECT_FALSE(handle.is_valid());
  19622. handle.error = Error::Success;
  19623. EXPECT_TRUE(handle.is_valid());
  19624. }
  19625. TEST(BodyReaderTest, Basic) {
  19626. MockStream stream("Hello, World!");
  19627. detail::BodyReader reader;
  19628. reader.stream = &stream;
  19629. reader.content_length = 13;
  19630. char buf[32];
  19631. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19632. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19633. EXPECT_TRUE(reader.eof);
  19634. }
  19635. TEST(BodyReaderTest, NoStream) {
  19636. detail::BodyReader reader;
  19637. char buf[32];
  19638. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19639. EXPECT_EQ(Error::Connection, reader.last_error);
  19640. }
  19641. TEST(BodyReaderTest, Error) {
  19642. MockStream stream("Hello, World!", 5);
  19643. detail::BodyReader reader;
  19644. reader.stream = &stream;
  19645. reader.content_length = 13;
  19646. char buf[32];
  19647. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19648. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19649. EXPECT_EQ(Error::Read, reader.last_error);
  19650. }
  19651. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19652. // Mock-based StreamHandle tests relying on private internals are removed.
  19653. class OpenStreamTest : public ::testing::Test {
  19654. protected:
  19655. void SetUp() override {
  19656. svr_.Get("/hello", [](const Request &, Response &res) {
  19657. res.set_content("Hello World!", "text/plain");
  19658. });
  19659. svr_.Get("/large", [](const Request &, Response &res) {
  19660. res.set_content(std::string(10000, 'X'), "text/plain");
  19661. });
  19662. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19663. res.set_content("Hello World!", "image/jpeg");
  19664. res.set_header("Content-Encoding", "UTF-8");
  19665. });
  19666. svr_.Get("/chunked", [](const Request &, Response &res) {
  19667. res.set_chunked_content_provider("text/plain",
  19668. [](size_t offset, DataSink &sink) {
  19669. if (offset < 15) {
  19670. sink.write("chunk", 5);
  19671. return true;
  19672. }
  19673. sink.done();
  19674. return true;
  19675. });
  19676. });
  19677. svr_.Get("/compressible", [](const Request &, Response &res) {
  19678. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19679. DataSink &sink) {
  19680. if (offset < 100 * 1024) {
  19681. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19682. sink.write(chunk.data(), chunk.size());
  19683. return true;
  19684. }
  19685. sink.done();
  19686. return true;
  19687. });
  19688. });
  19689. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19690. [](const Request & /*req*/, Response &res) {
  19691. auto i = new int(0);
  19692. res.set_header("Trailer", "Content-Length, X-Allowed");
  19693. res.set_chunked_content_provider(
  19694. "text/plain",
  19695. [i](size_t /*offset*/, DataSink &sink) {
  19696. switch (*i) {
  19697. case 0: sink.os << "123"; break;
  19698. case 1: sink.os << "456"; break;
  19699. case 2: sink.os << "789"; break;
  19700. case 3: {
  19701. sink.done_with_trailer(
  19702. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19703. } break;
  19704. }
  19705. (*i)++;
  19706. return true;
  19707. },
  19708. [i](bool success) {
  19709. EXPECT_TRUE(success);
  19710. delete i;
  19711. });
  19712. });
  19713. // Echo headers endpoint for header-related tests
  19714. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19715. std::string body;
  19716. for (const auto &h : req.headers) {
  19717. body.append(h.first);
  19718. body.push_back(':');
  19719. body.append(h.second);
  19720. body.push_back('\n');
  19721. }
  19722. res.set_content(body, "text/plain");
  19723. });
  19724. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19725. std::string body;
  19726. for (const auto &h : req.headers) {
  19727. body.append(h.first);
  19728. body.push_back(':');
  19729. body.append(h.second);
  19730. body.push_back('\n');
  19731. }
  19732. res.set_content(body, "text/plain");
  19733. });
  19734. port_ = svr_.bind_to_any_port("127.0.0.1");
  19735. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19736. svr_.wait_until_ready();
  19737. }
  19738. void TearDown() override {
  19739. svr_.stop();
  19740. if (thread_.joinable()) thread_.join();
  19741. }
  19742. Server svr_;
  19743. std::thread thread_;
  19744. int port_ = 0;
  19745. };
  19746. TEST_F(OpenStreamTest, Basic) {
  19747. Client cli("127.0.0.1", port_);
  19748. auto handle = cli.open_stream("GET", "/hello");
  19749. EXPECT_TRUE(handle.is_valid());
  19750. EXPECT_EQ("Hello World!", read_all(handle));
  19751. }
  19752. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19753. Client cli("127.0.0.1", port_);
  19754. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19755. ASSERT_TRUE(handle.is_valid());
  19756. EXPECT_EQ("Hello World!", read_all(handle));
  19757. }
  19758. TEST_F(OpenStreamTest, SmallBuffer) {
  19759. Client cli("127.0.0.1", port_);
  19760. auto handle = cli.open_stream("GET", "/hello");
  19761. std::string result;
  19762. char buf[4];
  19763. ssize_t n;
  19764. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19765. result.append(buf, static_cast<size_t>(n));
  19766. EXPECT_EQ("Hello World!", result);
  19767. }
  19768. TEST_F(OpenStreamTest, DefaultHeaders) {
  19769. Client cli("127.0.0.1", port_);
  19770. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19771. {
  19772. auto handle = cli.open_stream("GET", "/echo-headers");
  19773. ASSERT_TRUE(handle.is_valid());
  19774. auto body = read_all(handle);
  19775. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19776. std::string::npos);
  19777. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19778. std::string::npos);
  19779. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19780. }
  19781. // open_stream POST with body and no explicit content_type should NOT add
  19782. // text/plain Content-Type (behavior differs from non-streaming path), but
  19783. // should include Content-Length
  19784. {
  19785. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19786. ASSERT_TRUE(handle.is_valid());
  19787. auto body = read_all(handle);
  19788. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19789. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19790. }
  19791. // open_stream POST with explicit Content-Type should preserve it
  19792. {
  19793. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19794. {{"Content-Type", "application/custom"}},
  19795. "{}", "application/custom");
  19796. ASSERT_TRUE(handle.is_valid());
  19797. auto body = read_all(handle);
  19798. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19799. }
  19800. // User-specified User-Agent must not be overwritten for stream API
  19801. {
  19802. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19803. {{"User-Agent", "MyAgent/1.2"}});
  19804. ASSERT_TRUE(handle.is_valid());
  19805. auto body = read_all(handle);
  19806. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19807. }
  19808. }
  19809. TEST_F(OpenStreamTest, Large) {
  19810. Client cli("127.0.0.1", port_);
  19811. auto handle = cli.open_stream("GET", "/large");
  19812. EXPECT_EQ(10000u, read_all(handle).size());
  19813. }
  19814. TEST_F(OpenStreamTest, ConnectionError) {
  19815. Client cli("127.0.0.1", 9999);
  19816. auto handle = cli.open_stream("GET", "/hello");
  19817. EXPECT_FALSE(handle.is_valid());
  19818. }
  19819. TEST_F(OpenStreamTest, Chunked) {
  19820. Client cli("127.0.0.1", port_);
  19821. auto handle = cli.open_stream("GET", "/chunked");
  19822. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19823. "Transfer-Encoding") == "chunked");
  19824. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19825. }
  19826. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19827. Client cli("127.0.0.1", port_);
  19828. auto handle =
  19829. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19830. ASSERT_TRUE(handle.is_valid());
  19831. // Consume body to allow trailers to be received/parsed
  19832. auto body = read_all(handle);
  19833. // Explicitly parse trailers (ensure trailers are available for assertion)
  19834. handle.parse_trailers_if_needed();
  19835. EXPECT_EQ(std::string("123456789"), body);
  19836. // The response should include a Trailer header declaring both names
  19837. ASSERT_TRUE(handle.response);
  19838. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19839. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19840. handle.response->get_header_value("Trailer"));
  19841. // Prohibited trailer must not be present
  19842. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19843. // Allowed trailer should be present
  19844. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19845. EXPECT_EQ(std::string("yes"),
  19846. handle.response->get_trailer_value("X-Allowed"));
  19847. // Verify trailers are NOT present as regular headers
  19848. EXPECT_EQ(std::string(""),
  19849. handle.response->get_header_value("Content-Length"));
  19850. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19851. }
  19852. // Accepts one connection on an OS-assigned port, which it hands over through
  19853. // port_promise, reads the request head and sends back response. after_send,
  19854. // if given, runs on the connection before it is closed.
  19855. static std::thread
  19856. serve_single_response(std::promise<int> &port_promise,
  19857. const std::string &response,
  19858. std::function<void(socket_t)> after_send = nullptr) {
  19859. return std::thread([&port_promise, response, after_send] {
  19860. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19861. default_socket_options(srv);
  19862. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19863. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19864. sockaddr_in addr{};
  19865. addr.sin_family = AF_INET;
  19866. addr.sin_port = htons(0); // Let OS assign a free port
  19867. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19868. int opt = 1;
  19869. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19870. #ifdef _WIN32
  19871. reinterpret_cast<const char *>(&opt),
  19872. #else
  19873. &opt,
  19874. #endif
  19875. sizeof(opt));
  19876. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19877. ::listen(srv, 1) != 0) {
  19878. port_promise.set_value(-1);
  19879. detail::close_socket(srv);
  19880. return;
  19881. }
  19882. socklen_t addr_len = sizeof(addr);
  19883. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19884. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19885. sockaddr_in cli_addr{};
  19886. socklen_t cli_len = sizeof(cli_addr);
  19887. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19888. if (cli != INVALID_SOCKET) {
  19889. // Read the complete HTTP request (until the blank line that terminates
  19890. // headers) before sending the response. If the server closes the socket
  19891. // while the client's request data is still unread in the kernel receive
  19892. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19893. // connection on both sides: it discards the client's receive buffer
  19894. // (which already holds our response) and causes any in-progress write on
  19895. // the client to fail with ECONNRESET. Reading all request data first
  19896. // ensures close() emits a graceful FIN.
  19897. {
  19898. char rbuf[256];
  19899. std::string req;
  19900. while (req.find("\r\n\r\n") == std::string::npos) {
  19901. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19902. if (n <= 0) { break; }
  19903. req.append(rbuf, static_cast<size_t>(n));
  19904. }
  19905. }
  19906. ::send(cli,
  19907. #ifdef _WIN32
  19908. static_cast<const char *>(response.c_str()),
  19909. static_cast<int>(response.size()),
  19910. #else
  19911. response.c_str(), response.size(),
  19912. #endif
  19913. 0);
  19914. if (after_send) { after_send(cli); }
  19915. detail::close_socket(cli);
  19916. }
  19917. detail::close_socket(srv);
  19918. });
  19919. }
  19920. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19921. #ifndef _WIN32
  19922. signal(SIGPIPE, SIG_IGN);
  19923. #endif
  19924. std::promise<int> port_promise;
  19925. auto port_future = port_promise.get_future();
  19926. auto server_thread =
  19927. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19928. "Content-Type: text/plain\r\n"
  19929. "Content-Length: not-a-number\r\n"
  19930. "Connection: close\r\n"
  19931. "\r\n"
  19932. "hello");
  19933. auto port = port_future.get();
  19934. ASSERT_GT(port, 0);
  19935. Client cli("127.0.0.1", port);
  19936. auto handle = cli.open_stream("GET", "/");
  19937. EXPECT_FALSE(handle.is_valid());
  19938. server_thread.join();
  19939. }
  19940. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19941. #ifndef _WIN32
  19942. signal(SIGPIPE, SIG_IGN);
  19943. #endif
  19944. std::promise<int> port_promise;
  19945. auto port_future = port_promise.get_future();
  19946. auto server_thread = serve_single_response(
  19947. port_promise, "HTTP/1.1 200 OK\r\n"
  19948. "Content-Type: text/plain\r\n"
  19949. "Content-Length: 99999999999999999999999999\r\n"
  19950. "Connection: close\r\n"
  19951. "\r\n"
  19952. "hello");
  19953. auto port = port_future.get();
  19954. ASSERT_GT(port, 0);
  19955. // Historically std::stoull would throw std::out_of_range here and crash
  19956. // the process, then parsing silently clamped to a bogus framing length and
  19957. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19958. // so the stream fails to open, matching the not-a-number case above. The
  19959. // process still must NOT terminate.
  19960. Client cli("127.0.0.1", port);
  19961. auto handle = cli.open_stream("GET", "/");
  19962. EXPECT_FALSE(handle.is_valid());
  19963. server_thread.join();
  19964. }
  19965. // Serves `response` to the single request `fn` makes with a fresh client.
  19966. template <typename Fn>
  19967. static void with_single_response(const std::string &response, Fn fn) {
  19968. #ifndef _WIN32
  19969. signal(SIGPIPE, SIG_IGN);
  19970. #endif
  19971. std::promise<int> port_promise;
  19972. auto port_future = port_promise.get_future();
  19973. auto server_thread = serve_single_response(port_promise, response);
  19974. auto se = detail::scope_exit([&] { server_thread.join(); });
  19975. auto port = port_future.get();
  19976. ASSERT_GT(port, 0);
  19977. Client cli("127.0.0.1", port);
  19978. fn(cli);
  19979. }
  19980. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19981. // Neither Content-Length nor chunked: the body ends at the close
  19982. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19983. "Connection: close\r\n"
  19984. "\r\n"
  19985. "hello";
  19986. with_single_response(close_delimited, [](Client &cli) {
  19987. auto handle = cli.open_stream("GET", "/");
  19988. ASSERT_TRUE(handle.is_valid());
  19989. EXPECT_EQ("hello", read_all(handle));
  19990. EXPECT_FALSE(handle.has_read_error());
  19991. });
  19992. // A close before the end of the Content-Length is still an error
  19993. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19994. "Content-Length: 10\r\n"
  19995. "\r\n"
  19996. "hello";
  19997. with_single_response(short_content_length, [](Client &cli) {
  19998. auto handle = cli.open_stream("GET", "/");
  19999. ASSERT_TRUE(handle.is_valid());
  20000. read_all(handle);
  20001. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20002. });
  20003. // So is a close before the last chunk
  20004. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20005. "Transfer-Encoding: chunked\r\n"
  20006. "\r\n"
  20007. "5\r\nhello\r\n";
  20008. with_single_response(short_chunked, [](Client &cli) {
  20009. auto handle = cli.open_stream("GET", "/");
  20010. ASSERT_TRUE(handle.is_valid());
  20011. read_all(handle);
  20012. EXPECT_TRUE(handle.has_read_error());
  20013. });
  20014. }
  20015. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20016. const char *responses[] = {
  20017. "HTTP/1.1 103 Early Hints\r\n"
  20018. "Link: </style.css>; rel=preload\r\n"
  20019. "\r\n"
  20020. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20021. "HTTP/1.1 100 Continue\r\n"
  20022. "X-Note: interim\r\n"
  20023. "\r\n"
  20024. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20025. };
  20026. for (auto response : responses) {
  20027. with_single_response(response, [](Client &cli) {
  20028. auto res = cli.Get("/");
  20029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20030. EXPECT_EQ(StatusCode::OK_200, res->status);
  20031. EXPECT_EQ("ok", res->body);
  20032. });
  20033. }
  20034. }
  20035. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20036. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20037. const std::string final_response =
  20038. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20039. std::string interims;
  20040. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20041. interims += interim;
  20042. }
  20043. with_single_response(interims + final_response, [](Client &cli) {
  20044. auto res = cli.Get("/");
  20045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20046. EXPECT_EQ("ok", res->body);
  20047. });
  20048. with_single_response(interims + interim + final_response, [](Client &cli) {
  20049. auto res = cli.Get("/");
  20050. ASSERT_FALSE(res);
  20051. EXPECT_EQ(Error::Read, res.error());
  20052. });
  20053. }
  20054. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20055. #ifndef _WIN32
  20056. signal(SIGPIPE, SIG_IGN);
  20057. #endif
  20058. // The server answers the head without asking for the body. Bytes it then
  20059. // reads on the connection would be taken for the body the request declared.
  20060. auto closed_by_client = false;
  20061. std::promise<int> port_promise;
  20062. auto server_thread = serve_single_response(
  20063. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20064. [&](socket_t sock) {
  20065. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20066. char buf[256];
  20067. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20068. });
  20069. Client cli("127.0.0.1", port_promise.get_future().get());
  20070. cli.set_keep_alive(true);
  20071. cli.set_read_timeout(1, 0);
  20072. // Long enough for the client to send Expect: 100-continue.
  20073. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20075. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20076. cli.Get("/second");
  20077. server_thread.join();
  20078. EXPECT_TRUE(closed_by_client);
  20079. }
  20080. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20081. // Long enough for the client to send Expect: 100-continue
  20082. with_single_response(
  20083. "HTTP/1.1 103 Early Hints\r\n"
  20084. "Link: </style.css>; rel=preload\r\n"
  20085. "\r\n"
  20086. "HTTP/1.1 401 Unauthorized\r\n"
  20087. "Content-Length: 0\r\n\r\n",
  20088. [](Client &cli) {
  20089. cli.set_read_timeout(2, 0);
  20090. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20092. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20093. });
  20094. }
  20095. #ifdef CPPHTTPLIB_SSL_ENABLED
  20096. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20097. #ifndef _WIN32
  20098. signal(SIGPIPE, SIG_IGN);
  20099. #endif
  20100. auto reused = false;
  20101. std::promise<int> port_promise;
  20102. auto server_thread = serve_single_response(
  20103. port_promise,
  20104. "HTTP/1.1 401 Unauthorized\r\n"
  20105. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20106. "Content-Length: 0\r\n\r\n",
  20107. [&](socket_t sock) {
  20108. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20109. char buf[256];
  20110. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20111. });
  20112. Client cli("127.0.0.1", port_promise.get_future().get());
  20113. cli.set_keep_alive(true);
  20114. cli.set_digest_auth("user", "pass");
  20115. cli.set_read_timeout(1, 0);
  20116. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20117. server_thread.join();
  20118. EXPECT_FALSE(reused);
  20119. }
  20120. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20121. // Any other answer to CONNECT would read as the origin's response.
  20122. struct {
  20123. const char *response;
  20124. bool passed_on;
  20125. } cases[] = {
  20126. {"HTTP/1.1 201 Created\r\n"
  20127. "Set-Cookie: session=from-proxy\r\n"
  20128. "Content-Length: 0\r\n\r\n",
  20129. false},
  20130. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20131. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20132. "Content-Length: 0\r\n\r\n",
  20133. true},
  20134. };
  20135. for (const auto &c : cases) {
  20136. std::promise<int> port_promise;
  20137. auto server_thread = serve_single_response(port_promise, c.response);
  20138. SSLClient cli("example.com", 443);
  20139. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20140. auto res = cli.Get("/");
  20141. server_thread.join();
  20142. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20143. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20144. if (res) {
  20145. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20146. }
  20147. }
  20148. }
  20149. #endif
  20150. // Records the client's error logger calls as "error METHOD path", or
  20151. // "error null" for a call without a request
  20152. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20153. return [&log](const Error &err, const Request *req) {
  20154. log.push_back(to_string(err) + " " +
  20155. (req ? req->method + " " + req->path : "null"));
  20156. };
  20157. }
  20158. // A failed request is reported once, with the request the caller made
  20159. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20160. Server svr;
  20161. svr.Get("/big", [](const Request &, Response &res) {
  20162. res.set_content(std::string(100000, 'b'), "text/plain");
  20163. });
  20164. auto port = svr.bind_to_any_port(HOST);
  20165. std::thread t([&]() { svr.listen_after_bind(); });
  20166. auto se = detail::scope_exit([&] {
  20167. svr.stop();
  20168. t.join();
  20169. });
  20170. svr.wait_until_ready();
  20171. Client cli(HOST, port);
  20172. std::vector<std::string> log;
  20173. cli.set_error_logger(record_errors(log));
  20174. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20175. cli.Get("/big", [](const char *, size_t) { return false; });
  20176. EXPECT_EQ(expected, log);
  20177. log.clear();
  20178. cli.Get("/big", [](size_t, size_t) { return false; });
  20179. EXPECT_EQ(expected, log);
  20180. }
  20181. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20182. // Fails while the body is read
  20183. auto broken = [](const Request &, Response &res) {
  20184. res.set_content_provider(10, "text/plain",
  20185. [](size_t, size_t, DataSink &) { return false; });
  20186. };
  20187. Server other;
  20188. other.Get("/broken", broken);
  20189. auto other_port = other.bind_to_any_port(HOST);
  20190. std::thread other_t([&]() { other.listen_after_bind(); });
  20191. auto other_se = detail::scope_exit([&] {
  20192. other.stop();
  20193. other_t.join();
  20194. });
  20195. other.wait_until_ready();
  20196. Server svr;
  20197. svr.Get("/broken", broken);
  20198. svr.Get("/same-origin",
  20199. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20200. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20201. res.set_redirect("http://" + std::string(HOST) + ":" +
  20202. std::to_string(other_port) + "/broken");
  20203. });
  20204. auto port = svr.bind_to_any_port(HOST);
  20205. std::thread t([&]() { svr.listen_after_bind(); });
  20206. auto se = detail::scope_exit([&] {
  20207. svr.stop();
  20208. t.join();
  20209. });
  20210. svr.wait_until_ready();
  20211. Client cli(HOST, port);
  20212. cli.set_follow_location(true);
  20213. std::vector<std::string> log;
  20214. cli.set_error_logger(record_errors(log));
  20215. for (auto path : {"/same-origin", "/cross-origin"}) {
  20216. log.clear();
  20217. auto res = cli.Get(path);
  20218. ASSERT_FALSE(res);
  20219. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20220. log);
  20221. }
  20222. }
  20223. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20224. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20225. std::vector<std::string> log;
  20226. cli.set_error_logger(record_errors(log));
  20227. auto handle = cli.open_stream("GET", "/x");
  20228. EXPECT_FALSE(handle.is_valid());
  20229. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20230. log);
  20231. });
  20232. }
  20233. #ifdef CPPHTTPLIB_SSL_ENABLED
  20234. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20235. // Not a TLS server, so the handshake fails. It waits for a request line in
  20236. // the handshake bytes, so a short read timeout lets it close quickly.
  20237. Server svr;
  20238. svr.set_read_timeout(0, 100000);
  20239. svr.Get("/x", [](const Request &, Response &res) {
  20240. res.set_content("x", "text/plain");
  20241. });
  20242. auto port = svr.bind_to_any_port(HOST);
  20243. std::thread t([&]() { svr.listen_after_bind(); });
  20244. auto se = detail::scope_exit([&] {
  20245. svr.stop();
  20246. t.join();
  20247. });
  20248. svr.wait_until_ready();
  20249. std::vector<std::string> log;
  20250. SSLClient cli(HOST, port);
  20251. cli.enable_server_certificate_verification(false);
  20252. cli.set_error_logger(record_errors(log));
  20253. auto res = cli.Get("/x");
  20254. ASSERT_FALSE(res);
  20255. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20256. log.clear();
  20257. auto handle = cli.open_stream("GET", "/x");
  20258. EXPECT_FALSE(handle.is_valid());
  20259. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20260. log.clear();
  20261. SSLClient no_ca(HOST, port);
  20262. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20263. no_ca.set_error_logger(record_errors(log));
  20264. res = no_ca.Get("/x");
  20265. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20266. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20267. }
  20268. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20269. #ifndef _WIN32
  20270. signal(SIGPIPE, SIG_IGN);
  20271. #endif
  20272. // Refused, answered with a challenge, or closed without an answer
  20273. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20274. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20275. "Content-Length: 0\r\n\r\n",
  20276. ""}) {
  20277. std::promise<int> port_promise;
  20278. auto server_thread = serve_single_response(port_promise, response);
  20279. SSLClient cli("example.com", 443);
  20280. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20281. std::vector<std::string> log;
  20282. cli.set_error_logger(record_errors(log));
  20283. auto res = cli.Get("/");
  20284. server_thread.join();
  20285. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20286. << response;
  20287. }
  20288. }
  20289. #endif
  20290. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20291. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20292. // the chunked coding and drop Content-Length, so a front-end that trusts
  20293. // Content-Length would disagree about where the body ends (response
  20294. // smuggling). The client must reject such a response.
  20295. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20296. for (const char *te : {"chunked", "gzip, chunked"}) {
  20297. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20298. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20299. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20300. "5\r\nhello\r\n0\r\n\r\n";
  20301. with_single_response(response, [&](Client &cli) {
  20302. auto res = cli.Get("/");
  20303. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20304. EXPECT_EQ(Error::Read, res.error()) << te;
  20305. });
  20306. with_single_response(response, [&](Client &cli) {
  20307. auto handle = cli.open_stream("GET", "/");
  20308. EXPECT_FALSE(handle.is_valid()) << te;
  20309. EXPECT_EQ(Error::Read, handle.error) << te;
  20310. });
  20311. }
  20312. }
  20313. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20314. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20315. // closing the connection (unlike a request, which must be rejected).
  20316. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20317. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20318. "Transfer-Encoding: chunked\r\n"
  20319. "Connection: close\r\n"
  20320. "\r\n"
  20321. "5\r\nhello\r\n0\r\n\r\n",
  20322. "HTTP/1.1 200 OK\r\n"
  20323. "Transfer-Encoding: gzip\r\n"
  20324. "Connection: close\r\n"
  20325. "\r\n"
  20326. "hello"}) {
  20327. with_single_response(response, [&](Client &cli) {
  20328. auto res = cli.Get("/");
  20329. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20330. EXPECT_EQ("hello", res->body);
  20331. });
  20332. with_single_response(response, [&](Client &cli) {
  20333. auto handle = cli.open_stream("GET", "/");
  20334. ASSERT_TRUE(handle.is_valid()) << response;
  20335. EXPECT_EQ("hello", read_all(handle));
  20336. });
  20337. }
  20338. }
  20339. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20340. // framing headers describe nothing to read and must not be rejected.
  20341. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20342. const std::string framing = "Content-Length: 5\r\n"
  20343. "Transfer-Encoding: chunked\r\n"
  20344. "Connection: close\r\n"
  20345. "\r\n";
  20346. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20347. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20348. });
  20349. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20350. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20351. });
  20352. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20353. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20354. with_single_response(response, [&](Client &cli) {
  20355. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20356. });
  20357. with_single_response(response, [&](Client &cli) {
  20358. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20359. });
  20360. }
  20361. }
  20362. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20363. // header section, so a stream opened on one has nothing to read, whatever
  20364. // framing or coding headers it carries.
  20365. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20366. struct Case {
  20367. const char *method;
  20368. const char *status;
  20369. };
  20370. // A reader of the declared body reports an early close when nothing
  20371. // follows, and hands back what does.
  20372. struct Framing {
  20373. const char *headers;
  20374. const char *after;
  20375. };
  20376. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20377. Case{"GET", "304 Not Modified"}}) {
  20378. for (const auto &f :
  20379. {Framing{"Content-Length: 5\r\n", ""},
  20380. Framing{"Content-Length: 5\r\n", "hello"},
  20381. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20382. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20383. // Not decoded, so a build without Brotli opens it too
  20384. Framing{"Content-Encoding: br\r\n", ""}}) {
  20385. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20386. "Connection: close\r\n"
  20387. "\r\n" +
  20388. f.after;
  20389. with_single_response(response, [&](Client &cli) {
  20390. auto handle = cli.open_stream(c.method, "/");
  20391. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20392. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20393. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20394. });
  20395. }
  20396. }
  20397. }
  20398. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20399. // response, is faulty framing, so the connection is not reused after it.
  20400. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20401. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20402. "Content-Length: 0\r\n"
  20403. "Transfer-Encoding: chunked\r\n"
  20404. "\r\n"
  20405. "5\r\nhello\r\n0\r\n\r\n",
  20406. "HTTP/1.0 200 Connection established\r\n"
  20407. "Connection: keep-alive\r\n"
  20408. "Transfer-Encoding: chunked\r\n"
  20409. "\r\n"
  20410. "5\r\nhello\r\n0\r\n\r\n"}) {
  20411. with_single_response(response, [&](Client &cli) {
  20412. cli.set_keep_alive(true);
  20413. auto res = cli.Get("/");
  20414. ASSERT_TRUE(res) << response;
  20415. EXPECT_EQ("hello", res->body);
  20416. EXPECT_FALSE(cli.is_socket_open()) << response;
  20417. });
  20418. }
  20419. }
  20420. // A payload max length of 0 means no limit, however the body is framed.
  20421. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20422. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20423. "Transfer-Encoding: chunked\r\n"
  20424. "\r\n"
  20425. "5\r\nhello\r\n0\r\n\r\n",
  20426. "HTTP/1.1 200 OK\r\n"
  20427. "Connection: close\r\n"
  20428. "\r\n"
  20429. "hello"}) {
  20430. with_single_response(response, [&](Client &cli) {
  20431. cli.set_payload_max_length(0);
  20432. auto res = cli.Get("/");
  20433. ASSERT_TRUE(res) << response;
  20434. EXPECT_EQ("hello", res->body) << response;
  20435. });
  20436. }
  20437. }
  20438. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20439. Server svr;
  20440. svr.set_payload_max_length(0);
  20441. svr.Post("/echo", [](const Request &req, Response &res) {
  20442. res.set_content(req.body, "text/plain");
  20443. });
  20444. auto port = svr.bind_to_any_port(HOST);
  20445. thread t = thread([&] { svr.listen_after_bind(); });
  20446. auto se = detail::scope_exit([&] {
  20447. svr.stop();
  20448. t.join();
  20449. ASSERT_FALSE(svr.is_running());
  20450. });
  20451. svr.wait_until_ready();
  20452. Client cli(HOST, port);
  20453. auto res = cli.Post(
  20454. "/echo",
  20455. [](size_t /*offset*/, DataSink &sink) {
  20456. sink.write("hello", 5);
  20457. sink.done();
  20458. return true;
  20459. },
  20460. "text/plain");
  20461. ASSERT_TRUE(res);
  20462. EXPECT_EQ(StatusCode::OK_200, res->status);
  20463. EXPECT_EQ("hello", res->body);
  20464. }
  20465. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20466. TEST_F(OpenStreamTest, Gzip) {
  20467. Client cli("127.0.0.1", port_);
  20468. auto handle = cli.open_stream("GET", "/compressible", {},
  20469. {{"Accept-Encoding", "gzip"}});
  20470. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20471. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20472. }
  20473. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20474. Client cli("127.0.0.1", port_);
  20475. auto handle =
  20476. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20477. {{"Accept-Encoding", "gzip"}});
  20478. ASSERT_TRUE(handle.is_valid());
  20479. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20480. EXPECT_EQ("123456789", read_all(handle));
  20481. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20482. }
  20483. #endif
  20484. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20485. TEST_F(OpenStreamTest, Brotli) {
  20486. Client cli("127.0.0.1", port_);
  20487. auto handle =
  20488. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20489. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20490. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20491. }
  20492. #endif
  20493. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20494. TEST_F(OpenStreamTest, Zstd) {
  20495. Client cli("127.0.0.1", port_);
  20496. auto handle = cli.open_stream("GET", "/compressible", {},
  20497. {{"Accept-Encoding", "zstd"}});
  20498. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20499. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20500. }
  20501. #endif
  20502. #ifdef CPPHTTPLIB_SSL_ENABLED
  20503. class SSLOpenStreamTest : public ::testing::Test {
  20504. protected:
  20505. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20506. void SetUp() override {
  20507. svr_.Get("/hello", [](const Request &, Response &res) {
  20508. res.set_content("Hello SSL World!", "text/plain");
  20509. });
  20510. svr_.Get("/chunked", [](const Request &, Response &res) {
  20511. res.set_chunked_content_provider("text/plain",
  20512. [](size_t offset, DataSink &sink) {
  20513. if (offset < 15) {
  20514. sink.write("chunk", 5);
  20515. return true;
  20516. }
  20517. sink.done();
  20518. return true;
  20519. });
  20520. });
  20521. svr_.Post("/echo", [](const Request &req, Response &res) {
  20522. res.set_content(req.body, req.get_header_value("Content-Type"));
  20523. });
  20524. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20525. std::string body = req.body;
  20526. res.set_chunked_content_provider(
  20527. "text/plain", [body](size_t offset, DataSink &sink) {
  20528. if (offset < body.size()) {
  20529. sink.write(body.data() + offset, body.size() - offset);
  20530. }
  20531. sink.done();
  20532. return true;
  20533. });
  20534. });
  20535. port_ = svr_.bind_to_any_port("127.0.0.1");
  20536. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20537. svr_.wait_until_ready();
  20538. }
  20539. void TearDown() override {
  20540. svr_.stop();
  20541. if (thread_.joinable()) thread_.join();
  20542. }
  20543. SSLServer svr_;
  20544. std::thread thread_;
  20545. int port_ = 0;
  20546. };
  20547. TEST_F(SSLOpenStreamTest, Basic) {
  20548. SSLClient cli("127.0.0.1", port_);
  20549. cli.enable_server_certificate_verification(false);
  20550. auto handle = cli.open_stream("GET", "/hello");
  20551. ASSERT_TRUE(handle.is_valid());
  20552. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20553. }
  20554. TEST_F(SSLOpenStreamTest, Chunked) {
  20555. SSLClient cli("127.0.0.1", port_);
  20556. cli.enable_server_certificate_verification(false);
  20557. auto handle = cli.open_stream("GET", "/chunked");
  20558. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20559. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20560. "Transfer-Encoding") == "chunked");
  20561. auto body = read_all(handle);
  20562. EXPECT_EQ("chunkchunkchunk", body);
  20563. }
  20564. TEST_F(SSLOpenStreamTest, Post) {
  20565. SSLClient cli("127.0.0.1", port_);
  20566. cli.enable_server_certificate_verification(false);
  20567. auto handle =
  20568. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20569. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20570. EXPECT_EQ(200, handle.response->status);
  20571. auto body = read_all(handle);
  20572. EXPECT_EQ("Hello SSL POST", body);
  20573. }
  20574. TEST_F(SSLOpenStreamTest, PostChunked) {
  20575. SSLClient cli("127.0.0.1", port_);
  20576. cli.enable_server_certificate_verification(false);
  20577. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20578. "Chunked SSL Data", "text/plain");
  20579. ASSERT_TRUE(handle.is_valid());
  20580. EXPECT_EQ(200, handle.response->status);
  20581. auto body = read_all(handle);
  20582. EXPECT_EQ("Chunked SSL Data", body);
  20583. }
  20584. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20585. // Content-Length is terminated by the server closing the connection. When the
  20586. // SSL peer sends a close_notify after the body, the client must treat it as a
  20587. // clean EOF and return a successful response rather than an error.
  20588. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20589. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20590. ASSERT_TRUE(svr.is_valid());
  20591. svr.set_keep_alive_max_count(1);
  20592. const std::string expected_body = "Hello from connection-close response!";
  20593. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20594. res.set_content_provider("text/plain",
  20595. [&](size_t offset, DataSink &sink) -> bool {
  20596. if (offset < expected_body.size()) {
  20597. sink.write(expected_body.data() + offset,
  20598. expected_body.size() - offset);
  20599. }
  20600. sink.done();
  20601. return true;
  20602. });
  20603. });
  20604. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20605. auto se = detail::scope_exit([&] {
  20606. svr.stop();
  20607. listen_thread.join();
  20608. ASSERT_FALSE(svr.is_running());
  20609. });
  20610. svr.wait_until_ready();
  20611. SSLClient cli(HOST, PORT);
  20612. cli.enable_server_certificate_verification(false);
  20613. auto res = cli.Get("/no-content-length");
  20614. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20615. EXPECT_EQ(StatusCode::OK_200, res->status);
  20616. EXPECT_EQ(expected_body, res->body);
  20617. }
  20618. #endif // CPPHTTPLIB_SSL_ENABLED
  20619. //==============================================================================
  20620. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20621. // results for various scenarios.
  20622. //==============================================================================
  20623. TEST(ParityTest, GetVsOpenStream) {
  20624. Server svr;
  20625. const std::string path = "/parity";
  20626. const std::string content = "Parity test content: hello world";
  20627. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20628. res.set_content(content, "text/plain");
  20629. });
  20630. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20631. auto se = detail::scope_exit([&] {
  20632. svr.stop();
  20633. t.join();
  20634. ASSERT_FALSE(svr.is_running());
  20635. });
  20636. svr.wait_until_ready();
  20637. Client cli(HOST, PORT);
  20638. // Non-stream path
  20639. auto r1 = cli.Get(path);
  20640. ASSERT_TRUE(r1);
  20641. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20642. // Stream path
  20643. auto h = cli.open_stream("GET", path);
  20644. ASSERT_TRUE(h.is_valid());
  20645. EXPECT_EQ(r1->body, read_all(h));
  20646. }
  20647. // Helper to compress data with provided compressor type T
  20648. template <typename Compressor>
  20649. static std::string compress_payload_for_parity(const std::string &in) {
  20650. std::string out;
  20651. Compressor compressor;
  20652. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20653. [&](const char *data, size_t n) {
  20654. out.append(data, n);
  20655. return true;
  20656. });
  20657. EXPECT_TRUE(ok);
  20658. return out;
  20659. }
  20660. // Helper function for compression parity tests
  20661. template <typename Compressor>
  20662. static void test_compression_parity(const std::string &original,
  20663. const std::string &path,
  20664. const std::string &encoding) {
  20665. const std::string compressed =
  20666. compress_payload_for_parity<Compressor>(original);
  20667. Server svr;
  20668. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20669. res.set_content(compressed, "application/octet-stream");
  20670. res.set_header("Content-Encoding", encoding);
  20671. });
  20672. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20673. auto se = detail::scope_exit([&] {
  20674. svr.stop();
  20675. t.join();
  20676. ASSERT_FALSE(svr.is_running());
  20677. });
  20678. svr.wait_until_ready();
  20679. Client cli(HOST, PORT);
  20680. // Non-streaming
  20681. {
  20682. auto res = cli.Get(path);
  20683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20684. EXPECT_EQ(StatusCode::OK_200, res->status);
  20685. EXPECT_EQ(original, res->body);
  20686. }
  20687. // Streaming
  20688. {
  20689. auto h = cli.open_stream("GET", path);
  20690. ASSERT_TRUE(h.is_valid());
  20691. EXPECT_EQ(original, read_all(h));
  20692. }
  20693. }
  20694. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20695. TEST(ParityTest, Gzip) {
  20696. test_compression_parity<detail::gzip_compressor>(
  20697. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20698. }
  20699. #endif
  20700. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20701. TEST(ParityTest, Brotli) {
  20702. test_compression_parity<detail::brotli_compressor>(
  20703. "Hello, brotli parity test payload", "/parity-br", "br");
  20704. }
  20705. #endif
  20706. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20707. TEST(ParityTest, Zstd) {
  20708. test_compression_parity<detail::zstd_compressor>(
  20709. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20710. }
  20711. #endif
  20712. //==============================================================================
  20713. // New Stream API Tests
  20714. //==============================================================================
  20715. inline std::string read_body(httplib::stream::Result &result) {
  20716. std::string body;
  20717. while (result.next()) {
  20718. body.append(result.data(), result.size());
  20719. }
  20720. return body;
  20721. }
  20722. TEST(ClientConnectionTest, Basic) {
  20723. httplib::ClientConnection conn;
  20724. EXPECT_FALSE(conn.is_open());
  20725. conn.sock = 1;
  20726. EXPECT_TRUE(conn.is_open());
  20727. httplib::ClientConnection conn2(std::move(conn));
  20728. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20729. conn2.sock = INVALID_SOCKET;
  20730. }
  20731. // Unified test server for all stream::* tests
  20732. class StreamApiTest : public ::testing::Test {
  20733. protected:
  20734. void SetUp() override {
  20735. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20736. res.set_content("Hello World!", "text/plain");
  20737. });
  20738. svr_.Get("/echo-params",
  20739. [](const httplib::Request &req, httplib::Response &res) {
  20740. std::string r;
  20741. for (const auto &p : req.params) {
  20742. if (!r.empty()) r += "&";
  20743. r += p.first + "=" + p.second;
  20744. }
  20745. res.set_content(r, "text/plain");
  20746. });
  20747. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20748. res.set_content(req.body, req.get_header_value("Content-Type"));
  20749. });
  20750. svr_.Post("/echo-headers",
  20751. [](const httplib::Request &req, httplib::Response &res) {
  20752. std::string r;
  20753. for (const auto &h : req.headers)
  20754. r += h.first + ": " + h.second + "\n";
  20755. res.set_content(r, "text/plain");
  20756. });
  20757. svr_.Post("/echo-params",
  20758. [](const httplib::Request &req, httplib::Response &res) {
  20759. std::string r = "params:";
  20760. for (const auto &p : req.params)
  20761. r += p.first + "=" + p.second + ";";
  20762. res.set_content(r + " body:" + req.body, "text/plain");
  20763. });
  20764. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20765. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20766. });
  20767. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20768. res.set_content("PUT:" + req.body, "text/plain");
  20769. });
  20770. svr_.Patch("/echo",
  20771. [](const httplib::Request &req, httplib::Response &res) {
  20772. res.set_content("PATCH:" + req.body, "text/plain");
  20773. });
  20774. svr_.Delete(
  20775. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20776. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20777. "text/plain");
  20778. });
  20779. svr_.Get("/head-test",
  20780. [](const httplib::Request &, httplib::Response &res) {
  20781. res.set_content("body for HEAD", "text/plain");
  20782. });
  20783. svr_.Options("/options",
  20784. [](const httplib::Request &, httplib::Response &res) {
  20785. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20786. });
  20787. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20788. svr_.wait_until_ready();
  20789. }
  20790. void TearDown() override {
  20791. svr_.stop();
  20792. if (thread_.joinable()) thread_.join();
  20793. }
  20794. httplib::Server svr_;
  20795. std::thread thread_;
  20796. };
  20797. // stream::Get tests
  20798. TEST_F(StreamApiTest, GetBasic) {
  20799. httplib::Client cli(HOST, PORT);
  20800. auto result = httplib::stream::Get(cli, "/hello");
  20801. ASSERT_TRUE(result.is_valid());
  20802. EXPECT_EQ(200, result.status());
  20803. EXPECT_EQ("Hello World!", read_body(result));
  20804. }
  20805. TEST_F(StreamApiTest, GetWithParams) {
  20806. httplib::Client cli(HOST, PORT);
  20807. httplib::Params params{{"foo", "bar"}};
  20808. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20809. ASSERT_TRUE(result.is_valid());
  20810. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20811. }
  20812. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20813. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20814. httplib::Client cli(HOST, PORT);
  20815. cli.set_payload_max_length(0);
  20816. auto result = httplib::stream::Get(cli, "/hello");
  20817. ASSERT_TRUE(result.is_valid());
  20818. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20819. EXPECT_EQ("Hello World!", read_body(result));
  20820. }
  20821. #endif
  20822. TEST_F(StreamApiTest, GetConnectionError) {
  20823. httplib::Client cli(HOST, 9999);
  20824. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20825. }
  20826. TEST_F(StreamApiTest, Get404) {
  20827. httplib::Client cli(HOST, PORT);
  20828. auto result = httplib::stream::Get(cli, "/nonexistent");
  20829. EXPECT_TRUE(result.is_valid());
  20830. EXPECT_EQ(404, result.status());
  20831. }
  20832. // stream::Post tests
  20833. TEST_F(StreamApiTest, PostBasic) {
  20834. httplib::Client cli(HOST, PORT);
  20835. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20836. "application/json");
  20837. ASSERT_TRUE(result.is_valid());
  20838. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20839. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20840. }
  20841. TEST_F(StreamApiTest, PostWithHeaders) {
  20842. httplib::Client cli(HOST, PORT);
  20843. httplib::Headers headers{{"X-Custom", "value"}};
  20844. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20845. "text/plain");
  20846. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20847. }
  20848. TEST_F(StreamApiTest, PostWithParams) {
  20849. httplib::Client cli(HOST, PORT);
  20850. httplib::Params params{{"k", "v"}};
  20851. auto result =
  20852. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20853. auto body = read_body(result);
  20854. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20855. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20856. }
  20857. TEST_F(StreamApiTest, PostLarge) {
  20858. httplib::Client cli(HOST, PORT);
  20859. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20860. size_t total = 0;
  20861. while (result.next()) {
  20862. total += result.size();
  20863. }
  20864. EXPECT_EQ(100u * 1024u, total);
  20865. }
  20866. // stream::Put/Patch tests
  20867. TEST_F(StreamApiTest, PutAndPatch) {
  20868. httplib::Client cli(HOST, PORT);
  20869. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20870. EXPECT_EQ("PUT:test", read_body(put));
  20871. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20872. EXPECT_EQ("PATCH:test", read_body(patch));
  20873. }
  20874. // stream::Delete tests
  20875. TEST_F(StreamApiTest, Delete) {
  20876. httplib::Client cli(HOST, PORT);
  20877. auto del1 = httplib::stream::Delete(cli, "/resource");
  20878. EXPECT_EQ("Deleted", read_body(del1));
  20879. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20880. EXPECT_EQ("Deleted:data", read_body(del2));
  20881. }
  20882. // stream::Head/Options tests
  20883. TEST_F(StreamApiTest, HeadAndOptions) {
  20884. httplib::Client cli(HOST, PORT);
  20885. auto head = httplib::stream::Head(cli, "/head-test");
  20886. EXPECT_TRUE(head.is_valid());
  20887. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20888. auto opts = httplib::stream::Options(cli, "/options");
  20889. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20890. }
  20891. // SSL stream::* tests
  20892. #ifdef CPPHTTPLIB_SSL_ENABLED
  20893. class SSLStreamApiTest : public ::testing::Test {
  20894. protected:
  20895. void SetUp() override {
  20896. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20897. res.set_content("Hello SSL!", "text/plain");
  20898. });
  20899. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20900. res.set_content(req.body, "text/plain");
  20901. });
  20902. port_ = svr_.bind_to_any_port("127.0.0.1");
  20903. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20904. svr_.wait_until_ready();
  20905. }
  20906. void TearDown() override {
  20907. svr_.stop();
  20908. if (thread_.joinable()) thread_.join();
  20909. }
  20910. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20911. std::thread thread_;
  20912. int port_ = 0;
  20913. };
  20914. TEST_F(SSLStreamApiTest, GetAndPost) {
  20915. httplib::SSLClient cli("127.0.0.1", port_);
  20916. cli.enable_server_certificate_verification(false);
  20917. auto get = httplib::stream::Get(cli, "/hello");
  20918. EXPECT_EQ("Hello SSL!", read_body(get));
  20919. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20920. EXPECT_EQ("test", read_body(post));
  20921. }
  20922. #endif
  20923. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20924. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20925. // BodyReader
  20926. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20927. // Test that read timeout during streaming is detected
  20928. // Use a large content-length response where server delays mid-stream
  20929. Server svr;
  20930. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20931. // Send a large response with delay in the middle
  20932. res.set_content_provider(
  20933. 1000, // content_length
  20934. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20935. if (offset < 100) {
  20936. // Send first 100 bytes immediately
  20937. std::string data(100, 'A');
  20938. sink.write(data.c_str(), data.size());
  20939. return true;
  20940. }
  20941. // Then delay longer than client timeout
  20942. std::this_thread::sleep_for(std::chrono::seconds(3));
  20943. std::string data(900, 'B');
  20944. sink.write(data.c_str(), data.size());
  20945. return true;
  20946. });
  20947. });
  20948. auto port = 8091;
  20949. std::thread t([&]() { svr.listen("localhost", port); });
  20950. svr.wait_until_ready();
  20951. Client cli("localhost", port);
  20952. cli.set_read_timeout(1, 0); // 1 second timeout
  20953. auto handle = cli.open_stream("GET", "/slow-stream");
  20954. ASSERT_TRUE(handle.is_valid());
  20955. char buf[256];
  20956. ssize_t total = 0;
  20957. ssize_t n;
  20958. bool got_error = false;
  20959. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20960. total += n;
  20961. }
  20962. if (n < 0) {
  20963. got_error = true;
  20964. // Should be timeout or read error
  20965. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20966. handle.get_read_error() == Error::Read)
  20967. << "Actual error: " << to_string(handle.get_read_error());
  20968. }
  20969. // Either we got an error, or we got less data than expected
  20970. EXPECT_TRUE(got_error || total < 1000)
  20971. << "Expected timeout but got all " << total << " bytes";
  20972. svr.stop();
  20973. t.join();
  20974. }
  20975. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20976. // Test connection closed detection via BodyReader
  20977. Server svr;
  20978. std::atomic<bool> close_now{false};
  20979. svr.Get("/will-close", [&](const Request &, Response &res) {
  20980. res.set_content_provider(
  20981. 10000, // Large content_length that we won't fully send
  20982. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20983. if (offset < 100) {
  20984. std::string data(100, 'X');
  20985. sink.write(data.c_str(), data.size());
  20986. return true;
  20987. }
  20988. // Wait for signal then abort
  20989. while (!close_now) {
  20990. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20991. }
  20992. return false; // Abort - server will close connection
  20993. });
  20994. });
  20995. auto port = 8092;
  20996. std::thread t([&]() { svr.listen("localhost", port); });
  20997. svr.wait_until_ready();
  20998. Client cli("localhost", port);
  20999. auto handle = cli.open_stream("GET", "/will-close");
  21000. ASSERT_TRUE(handle.is_valid());
  21001. char buf[256];
  21002. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21003. EXPECT_GT(n, 0) << "First read should succeed";
  21004. // Signal server to close
  21005. close_now = true;
  21006. // Keep reading until error or EOF
  21007. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21008. // Keep reading
  21009. }
  21010. // Should get an error since content_length wasn't satisfied
  21011. if (n < 0) {
  21012. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21013. handle.get_read_error() == Error::Read)
  21014. << "Actual error: " << to_string(handle.get_read_error());
  21015. }
  21016. svr.stop();
  21017. t.join();
  21018. }
  21019. #ifdef CPPHTTPLIB_SSL_ENABLED
  21020. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21021. // Test that read timeout during SSL streaming is detected
  21022. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21023. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21024. res.set_content_provider(
  21025. 1000, "text/plain",
  21026. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21027. if (offset < 100) {
  21028. std::string data(100, 'A');
  21029. sink.write(data.c_str(), data.size());
  21030. return true;
  21031. }
  21032. std::this_thread::sleep_for(std::chrono::seconds(3));
  21033. std::string data(900, 'B');
  21034. sink.write(data.c_str(), data.size());
  21035. return true;
  21036. });
  21037. });
  21038. auto port = 8093;
  21039. std::thread t([&]() { svr.listen("localhost", port); });
  21040. svr.wait_until_ready();
  21041. SSLClient cli("localhost", port);
  21042. cli.enable_server_certificate_verification(false);
  21043. cli.set_read_timeout(1, 0); // 1 second timeout
  21044. auto handle = cli.open_stream("GET", "/slow-stream");
  21045. ASSERT_TRUE(handle.is_valid());
  21046. char buf[256];
  21047. ssize_t total = 0;
  21048. ssize_t n;
  21049. bool got_error = false;
  21050. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21051. total += n;
  21052. }
  21053. if (n < 0) {
  21054. got_error = true;
  21055. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21056. handle.get_read_error() == Error::Read)
  21057. << "Actual error: " << to_string(handle.get_read_error());
  21058. }
  21059. EXPECT_TRUE(got_error || total < 1000)
  21060. << "Expected timeout but got all " << total << " bytes";
  21061. svr.stop();
  21062. t.join();
  21063. }
  21064. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21065. // Test SSL connection closed detection
  21066. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21067. std::atomic<bool> close_now{false};
  21068. svr.Get("/will-close", [&](const Request &, Response &res) {
  21069. res.set_content_provider(
  21070. 10000, "text/plain",
  21071. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21072. if (offset < 100) {
  21073. std::string data(100, 'X');
  21074. sink.write(data.c_str(), data.size());
  21075. return true;
  21076. }
  21077. while (!close_now) {
  21078. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21079. }
  21080. return false;
  21081. });
  21082. });
  21083. auto port = 8094;
  21084. std::thread t([&]() { svr.listen("localhost", port); });
  21085. svr.wait_until_ready();
  21086. SSLClient cli("localhost", port);
  21087. cli.enable_server_certificate_verification(false);
  21088. auto handle = cli.open_stream("GET", "/will-close");
  21089. ASSERT_TRUE(handle.is_valid());
  21090. char buf[256];
  21091. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21092. EXPECT_GT(n, 0);
  21093. // Signal server to close
  21094. close_now = true;
  21095. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21096. // Keep reading
  21097. }
  21098. if (n < 0) {
  21099. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21100. handle.get_read_error() == Error::Read)
  21101. << "Actual error: " << to_string(handle.get_read_error());
  21102. }
  21103. svr.stop();
  21104. t.join();
  21105. }
  21106. #endif
  21107. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21108. using namespace httplib;
  21109. // Create a test file
  21110. const char *fname = "etag_testfile.txt";
  21111. const char *content = "etag-content";
  21112. {
  21113. std::ofstream ofs(fname);
  21114. ofs << content;
  21115. ASSERT_TRUE(ofs.good());
  21116. }
  21117. Server svr;
  21118. svr.set_mount_point("/static", ".");
  21119. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21120. svr.wait_until_ready();
  21121. Client cli(HOST, PORT);
  21122. // First request: should get 200 with ETag header
  21123. auto res1 = cli.Get("/static/etag_testfile.txt");
  21124. ASSERT_TRUE(res1);
  21125. ASSERT_EQ(200, res1->status);
  21126. ASSERT_TRUE(res1->has_header("ETag"));
  21127. std::string etag = res1->get_header_value("ETag");
  21128. EXPECT_FALSE(etag.empty());
  21129. // Verify ETag format: W/"hex-hex"
  21130. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21131. EXPECT_EQ('W', etag[0]);
  21132. EXPECT_EQ('/', etag[1]);
  21133. EXPECT_EQ('"', etag[2]);
  21134. EXPECT_EQ('"', etag.back());
  21135. // Exact match: expect 304 Not Modified
  21136. Headers h2 = {{"If-None-Match", etag}};
  21137. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21138. ASSERT_TRUE(res2);
  21139. EXPECT_EQ(304, res2->status);
  21140. // Wildcard match: expect 304 Not Modified
  21141. Headers h3 = {{"If-None-Match", "*"}};
  21142. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21143. ASSERT_TRUE(res3);
  21144. EXPECT_EQ(304, res3->status);
  21145. // Non-matching ETag: expect 200
  21146. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21147. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21148. ASSERT_TRUE(res4);
  21149. EXPECT_EQ(200, res4->status);
  21150. // Multiple ETags with one matching: expect 304
  21151. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21152. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21153. ASSERT_TRUE(res5);
  21154. EXPECT_EQ(304, res5->status);
  21155. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21156. // that equivalent to the single comma-separated list above, so the match on
  21157. // the second line must still be found.
  21158. Headers h6;
  21159. h6.emplace("If-None-Match", "W/\"other\"");
  21160. h6.emplace("If-None-Match", etag);
  21161. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21162. ASSERT_TRUE(res6);
  21163. EXPECT_EQ(304, res6->status);
  21164. svr.stop();
  21165. t.join();
  21166. std::remove(fname);
  21167. }
  21168. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21169. using namespace httplib;
  21170. Server svr;
  21171. svr.set_mount_point("/static", ".");
  21172. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21173. svr.wait_until_ready();
  21174. Client cli(HOST, PORT);
  21175. // Send If-None-Match: * to a non-existent file
  21176. Headers h = {{"If-None-Match", "*"}};
  21177. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21179. EXPECT_EQ(404, res->status);
  21180. svr.stop();
  21181. t.join();
  21182. }
  21183. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21184. using namespace httplib;
  21185. // Create a test file
  21186. const char *fname = "etag_boundary_testfile.txt";
  21187. const char *content = "boundary-test";
  21188. {
  21189. std::ofstream ofs(fname);
  21190. ofs << content;
  21191. ASSERT_TRUE(ofs.good());
  21192. }
  21193. Server svr;
  21194. svr.set_mount_point("/static", ".");
  21195. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21196. svr.wait_until_ready();
  21197. Client cli(HOST, PORT);
  21198. // Get the actual ETag
  21199. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21200. ASSERT_TRUE(res1);
  21201. ASSERT_EQ(200, res1->status);
  21202. ASSERT_TRUE(res1->has_header("ETag"));
  21203. std::string etag = res1->get_header_value("ETag");
  21204. // Test 1: Very long ETag value (longer than actual ETag)
  21205. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21206. Headers h1 = {{"If-None-Match", "W/"
  21207. "\"very-long-etag-value-that-is-much-longer-"
  21208. "than-the-actual-etag-value\""}};
  21209. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21210. ASSERT_TRUE(res2);
  21211. EXPECT_EQ(200, res2->status); // Should not match
  21212. // Test 2: Long string followed by wildcard
  21213. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21214. // string)
  21215. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21216. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21217. ASSERT_TRUE(res3);
  21218. EXPECT_EQ(304, res3->status); // Should match on "*"
  21219. // Test 3: Wildcard followed by long string
  21220. // Should match on "*" immediately and return 304
  21221. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21222. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21223. ASSERT_TRUE(res4);
  21224. EXPECT_EQ(304, res4->status); // Should match on "*"
  21225. // Test 4: Multiple long non-matching values
  21226. // Should NOT match and return 200 (test that all comparisons are safe)
  21227. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21228. "W/\"second-long-non-matching-value\", "
  21229. "W/\"third-long-non-matching-value\""}};
  21230. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21231. ASSERT_TRUE(res5);
  21232. EXPECT_EQ(200, res5->status); // Should not match
  21233. // Test 5: Single character that is not "*" (edge case)
  21234. Headers h5 = {{"If-None-Match", "X"}};
  21235. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21236. ASSERT_TRUE(res6);
  21237. EXPECT_EQ(200, res6->status); // Should not match
  21238. svr.stop();
  21239. t.join();
  21240. std::remove(fname);
  21241. }
  21242. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21243. using namespace httplib;
  21244. // Create a test file
  21245. const char *fname = "ims_testfile.txt";
  21246. const char *content = "if-modified-since-test";
  21247. {
  21248. std::ofstream ofs(fname);
  21249. ofs << content;
  21250. ASSERT_TRUE(ofs.good());
  21251. }
  21252. Server svr;
  21253. svr.set_mount_point("/static", ".");
  21254. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21255. svr.wait_until_ready();
  21256. Client cli(HOST, PORT);
  21257. // First request: should get 200 with Last-Modified header
  21258. auto res1 = cli.Get("/static/ims_testfile.txt");
  21259. ASSERT_TRUE(res1);
  21260. ASSERT_EQ(200, res1->status);
  21261. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21262. std::string last_modified = res1->get_header_value("Last-Modified");
  21263. EXPECT_FALSE(last_modified.empty());
  21264. // If-Modified-Since with same time: expect 304
  21265. Headers h2 = {{"If-Modified-Since", last_modified}};
  21266. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21267. ASSERT_TRUE(res2);
  21268. EXPECT_EQ(304, res2->status);
  21269. // If-Modified-Since with future time: expect 304
  21270. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21271. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21272. ASSERT_TRUE(res3);
  21273. EXPECT_EQ(304, res3->status);
  21274. // If-Modified-Since with past time: expect 200
  21275. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21276. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21277. ASSERT_TRUE(res4);
  21278. EXPECT_EQ(200, res4->status);
  21279. // If-None-Match takes precedence over If-Modified-Since
  21280. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21281. ASSERT_TRUE(res1->has_header("ETag"));
  21282. std::string etag = res1->get_header_value("ETag");
  21283. Headers h5 = {{"If-None-Match", etag},
  21284. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21285. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21286. ASSERT_TRUE(res5);
  21287. EXPECT_EQ(304, res5->status);
  21288. svr.stop();
  21289. t.join();
  21290. std::remove(fname);
  21291. }
  21292. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21293. using namespace httplib;
  21294. Server svr;
  21295. // Endpoint that returns compressible content
  21296. svr.Get("/compressible", [](const Request &, Response &res) {
  21297. // Return a large enough body to trigger compression
  21298. std::string body(1000, 'a');
  21299. res.set_content(body, "text/plain");
  21300. });
  21301. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21302. svr.wait_until_ready();
  21303. Client cli(HOST, PORT);
  21304. // Request with gzip support: should get Vary header when compressed
  21305. cli.set_compress(true);
  21306. auto res1 = cli.Get("/compressible");
  21307. ASSERT_TRUE(res1);
  21308. EXPECT_EQ(200, res1->status);
  21309. // If Content-Encoding is set, Vary should also be set
  21310. if (res1->has_header("Content-Encoding")) {
  21311. EXPECT_TRUE(res1->has_header("Vary"));
  21312. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21313. }
  21314. // Request without Accept-Encoding header: should not have compression
  21315. Headers h_no_compress;
  21316. auto res2 = cli.Get("/compressible", h_no_compress);
  21317. ASSERT_TRUE(res2);
  21318. EXPECT_EQ(200, res2->status);
  21319. // Verify Vary header is present when compression is applied
  21320. // (the exact behavior depends on server configuration)
  21321. svr.stop();
  21322. t.join();
  21323. }
  21324. TEST(ETagTest, IfRangeWithETag) {
  21325. using namespace httplib;
  21326. // Create a test file with known content
  21327. const char *fname = "if_range_testfile.txt";
  21328. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21329. {
  21330. std::ofstream ofs(fname);
  21331. ofs << content;
  21332. ASSERT_TRUE(ofs.good());
  21333. }
  21334. Server svr;
  21335. svr.set_mount_point("/static", ".");
  21336. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21337. svr.wait_until_ready();
  21338. Client cli(HOST, PORT);
  21339. // First request: get ETag
  21340. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21341. ASSERT_TRUE(res1);
  21342. ASSERT_EQ(200, res1->status);
  21343. ASSERT_TRUE(res1->has_header("ETag"));
  21344. std::string etag = res1->get_header_value("ETag");
  21345. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21346. // Since our server generates weak ETags (W/"..."), If-Range with our
  21347. // ETag should NOT result in partial content - it should return full content.
  21348. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21349. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21350. ASSERT_TRUE(res2);
  21351. // Weak ETag in If-Range -> full content (200), not partial (206)
  21352. EXPECT_EQ(200, res2->status);
  21353. EXPECT_EQ(content, res2->body);
  21354. EXPECT_FALSE(res2->has_header("Content-Range"));
  21355. // Range request with non-matching If-Range (ETag): should get 200 (full
  21356. // content)
  21357. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21358. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21359. ASSERT_TRUE(res3);
  21360. EXPECT_EQ(200, res3->status);
  21361. EXPECT_EQ(content, res3->body);
  21362. EXPECT_FALSE(res3->has_header("Content-Range"));
  21363. // Range request with strong ETag (hypothetical - our server doesn't generate
  21364. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21365. // should return full content)
  21366. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21367. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21368. ASSERT_TRUE(res4);
  21369. EXPECT_EQ(200, res4->status);
  21370. EXPECT_EQ(content, res4->body);
  21371. EXPECT_FALSE(res4->has_header("Content-Range"));
  21372. svr.stop();
  21373. t.join();
  21374. std::remove(fname);
  21375. }
  21376. TEST(ETagTest, IfRangeWithDate) {
  21377. using namespace httplib;
  21378. // Create a test file
  21379. const char *fname = "if_range_date_testfile.txt";
  21380. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21381. {
  21382. std::ofstream ofs(fname);
  21383. ofs << content;
  21384. ASSERT_TRUE(ofs.good());
  21385. }
  21386. Server svr;
  21387. svr.set_mount_point("/static", ".");
  21388. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21389. svr.wait_until_ready();
  21390. Client cli(HOST, PORT);
  21391. // First request: get Last-Modified
  21392. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21393. ASSERT_TRUE(res1);
  21394. ASSERT_EQ(200, res1->status);
  21395. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21396. std::string last_modified = res1->get_header_value("Last-Modified");
  21397. // Range request with matching If-Range (date): should get 206
  21398. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21399. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21400. ASSERT_TRUE(res2);
  21401. EXPECT_EQ(206, res2->status);
  21402. EXPECT_EQ("FGHIJ", res2->body);
  21403. // Range request with old If-Range date: should get 200 (full content)
  21404. Headers h3 = {{"Range", "bytes=5-9"},
  21405. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21406. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21407. ASSERT_TRUE(res3);
  21408. EXPECT_EQ(200, res3->status);
  21409. EXPECT_EQ(content, res3->body);
  21410. // Range request with future If-Range date: should get 206
  21411. Headers h4 = {{"Range", "bytes=0-4"},
  21412. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21413. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21414. ASSERT_TRUE(res4);
  21415. EXPECT_EQ(206, res4->status);
  21416. EXPECT_EQ("ABCDE", res4->body);
  21417. svr.stop();
  21418. t.join();
  21419. std::remove(fname);
  21420. }
  21421. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21422. using namespace httplib;
  21423. const char *fname = "etag_malformed.txt";
  21424. const char *content = "malformed-etag";
  21425. {
  21426. std::ofstream ofs(fname);
  21427. ofs << content;
  21428. ASSERT_TRUE(ofs.good());
  21429. }
  21430. Server svr;
  21431. svr.set_mount_point("/static", ".");
  21432. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21433. svr.wait_until_ready();
  21434. Client cli(HOST, PORT);
  21435. // baseline: should get 200 and an ETag
  21436. auto res1 = cli.Get("/static/etag_malformed.txt");
  21437. ASSERT_TRUE(res1);
  21438. ASSERT_EQ(200, res1->status);
  21439. ASSERT_TRUE(res1->has_header("ETag"));
  21440. // Malformed ETag value (missing quotes) should be treated as non-matching
  21441. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21442. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21443. ASSERT_TRUE(res_bad);
  21444. EXPECT_EQ(200, res_bad->status);
  21445. // Whitespace-only header value should be considered invalid / non-matching
  21446. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21447. "Host: localhost\r\n"
  21448. "If-None-Match: \r\n"
  21449. "Connection: close\r\n"
  21450. "\r\n";
  21451. std::string out;
  21452. ASSERT_TRUE(send_request(5, raw_req, &out));
  21453. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21454. svr.stop();
  21455. t.join();
  21456. std::remove(fname);
  21457. }
  21458. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21459. using namespace httplib;
  21460. const char *fname = "ims_invalid_format.txt";
  21461. const char *content = "ims-bad-format";
  21462. {
  21463. std::ofstream ofs(fname);
  21464. ofs << content;
  21465. ASSERT_TRUE(ofs.good());
  21466. }
  21467. Server svr;
  21468. svr.set_mount_point("/static", ".");
  21469. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21470. svr.wait_until_ready();
  21471. Client cli(HOST, PORT);
  21472. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21473. ASSERT_TRUE(res1);
  21474. ASSERT_EQ(200, res1->status);
  21475. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21476. // If-Modified-Since with invalid format should not result in 304
  21477. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21478. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21479. ASSERT_TRUE(res_bad);
  21480. EXPECT_EQ(200, res_bad->status);
  21481. // If-Range with invalid date format should be treated as mismatch -> full
  21482. // content (200)
  21483. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21484. {"If-Range", "invalid-date"}};
  21485. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21486. ASSERT_TRUE(res_ifrange);
  21487. EXPECT_EQ(200, res_ifrange->status);
  21488. svr.stop();
  21489. t.join();
  21490. std::remove(fname);
  21491. }
  21492. TEST(ETagTest, IfRangeWithMalformedETag) {
  21493. using namespace httplib;
  21494. const char *fname = "ifrange_malformed.txt";
  21495. const std::string content = "0123456789";
  21496. {
  21497. std::ofstream ofs(fname);
  21498. ofs << content;
  21499. ASSERT_TRUE(ofs.good());
  21500. }
  21501. Server svr;
  21502. svr.set_mount_point("/static", ".");
  21503. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21504. svr.wait_until_ready();
  21505. Client cli(HOST, PORT);
  21506. // First request: get ETag
  21507. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21508. ASSERT_TRUE(res1);
  21509. ASSERT_EQ(200, res1->status);
  21510. ASSERT_TRUE(res1->has_header("ETag"));
  21511. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21512. // full content (200)
  21513. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21514. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21515. ASSERT_TRUE(res2);
  21516. EXPECT_EQ(200, res2->status);
  21517. EXPECT_EQ(content, res2->body);
  21518. svr.stop();
  21519. t.join();
  21520. std::remove(fname);
  21521. }
  21522. TEST(ETagTest, ExtremeLargeDateValues) {
  21523. using namespace httplib;
  21524. const char *fname = "ims_extreme_date.txt";
  21525. const char *content = "ims-extreme-date";
  21526. {
  21527. std::ofstream ofs(fname);
  21528. ofs << content;
  21529. ASSERT_TRUE(ofs.good());
  21530. }
  21531. Server svr;
  21532. svr.set_mount_point("/static", ".");
  21533. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21534. svr.wait_until_ready();
  21535. Client cli(HOST, PORT);
  21536. auto res1 = cli.Get(std::string("/static/") + fname);
  21537. ASSERT_TRUE(res1);
  21538. ASSERT_EQ(200, res1->status);
  21539. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21540. // Extremely large year that may overflow date parsing routines.
  21541. Headers h_large_date = {
  21542. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21543. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21544. ASSERT_TRUE(res_bad);
  21545. // Expect server to treat this as invalid/mismatch and return full content
  21546. EXPECT_EQ(200, res_bad->status);
  21547. // If-Range with extremely large date should be treated as mismatch -> full
  21548. // content (200)
  21549. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21550. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21551. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21552. ASSERT_TRUE(res_ifrange);
  21553. EXPECT_EQ(200, res_ifrange->status);
  21554. svr.stop();
  21555. t.join();
  21556. std::remove(fname);
  21557. }
  21558. TEST(ETagTest, NegativeFileModificationTime) {
  21559. using namespace httplib;
  21560. const char *fname = "ims_negative_mtime.txt";
  21561. const std::string content = "negative-mtime";
  21562. {
  21563. std::ofstream ofs(fname);
  21564. ofs << content;
  21565. ASSERT_TRUE(ofs.good());
  21566. }
  21567. // Try to set file mtime to a negative value. This may fail on some
  21568. // platforms/filesystems; if it fails, the test will still verify server
  21569. // behaves safely by performing a regular conditional request.
  21570. #if defined(__APPLE__) || defined(__linux__)
  21571. bool set_negative = false;
  21572. do {
  21573. struct timeval times[2];
  21574. // access time: now
  21575. times[0].tv_sec = time(nullptr);
  21576. times[0].tv_usec = 0;
  21577. // modification time: negative (e.g., -1)
  21578. times[1].tv_sec = -1;
  21579. times[1].tv_usec = 0;
  21580. if (utimes(fname, times) == 0) { set_negative = true; }
  21581. } while (0);
  21582. #else
  21583. bool set_negative = false;
  21584. #endif
  21585. Server svr;
  21586. svr.set_mount_point("/static", ".");
  21587. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21588. svr.wait_until_ready();
  21589. Client cli(HOST, PORT);
  21590. auto res1 = cli.Get(std::string("/static/") + fname);
  21591. ASSERT_TRUE(res1);
  21592. ASSERT_EQ(200, res1->status);
  21593. bool has_last_modified = res1->has_header("Last-Modified");
  21594. std::string last_modified;
  21595. if (has_last_modified) {
  21596. last_modified = res1->get_header_value("Last-Modified");
  21597. }
  21598. if (set_negative) {
  21599. // If we successfully set a negative mtime, ensure server returns a
  21600. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21601. // with an old date and ensure server handles it without crash.
  21602. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21603. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21604. ASSERT_TRUE(res2);
  21605. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21606. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21607. } else {
  21608. // Could not set negative mtime on this platform; fall back to verifying
  21609. // that normal invalid/malformed dates are treated safely (non-304).
  21610. Headers h_bad_date = {
  21611. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21612. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21613. ASSERT_TRUE(res_bad);
  21614. EXPECT_EQ(200, res_bad->status);
  21615. }
  21616. svr.stop();
  21617. t.join();
  21618. std::remove(fname);
  21619. }
  21620. //==============================================================================
  21621. // Integration Tests with Server
  21622. //==============================================================================
  21623. class SSEIntegrationTest : public ::testing::Test {
  21624. protected:
  21625. void SetUp() override {
  21626. stop_server_.store(false);
  21627. events_.clear();
  21628. server_ = httplib::detail::make_unique<Server>();
  21629. setup_server();
  21630. start_server();
  21631. }
  21632. void TearDown() override {
  21633. stop_server_.store(true);
  21634. event_cv_.notify_all();
  21635. server_->stop();
  21636. if (server_thread_.joinable()) { server_thread_.join(); }
  21637. }
  21638. void setup_server() {
  21639. // Simple SSE endpoint
  21640. server_->Get("/events", [this](const Request &req, Response &res) {
  21641. auto last_id = req.get_header_value("Last-Event-ID");
  21642. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21643. res.set_chunked_content_provider(
  21644. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21645. std::unique_lock<std::mutex> lock(event_mutex_);
  21646. if (event_cv_.wait_for(
  21647. lock, std::chrono::milliseconds(200), [this] {
  21648. return !events_.empty() || stop_server_.load();
  21649. })) {
  21650. if (stop_server_.load()) { return false; }
  21651. if (!events_.empty()) {
  21652. std::string event = events_.front();
  21653. events_.erase(events_.begin());
  21654. sink.write(event.data(), event.size());
  21655. return true;
  21656. }
  21657. }
  21658. return !stop_server_.load();
  21659. });
  21660. });
  21661. // Endpoint that returns error
  21662. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21663. res.status = 500;
  21664. res.set_content("Internal Server Error", "text/plain");
  21665. });
  21666. // Endpoint for custom event types
  21667. server_->Get("/custom-events", [](const Request &, Response &res) {
  21668. res.set_chunked_content_provider(
  21669. "text/event-stream", [](size_t offset, DataSink &sink) {
  21670. if (offset == 0) {
  21671. std::string event = "event: update\ndata: updated\n\n"
  21672. "event: delete\ndata: deleted\n\n";
  21673. sink.write(event.data(), event.size());
  21674. }
  21675. return false; // End stream after sending
  21676. });
  21677. });
  21678. }
  21679. void start_server() {
  21680. port_ = server_->bind_to_any_port(HOST);
  21681. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21682. // Wait for server to start
  21683. while (!server_->is_running()) {
  21684. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21685. }
  21686. }
  21687. int get_port() const { return port_; }
  21688. void send_event(const std::string &event) {
  21689. std::lock_guard<std::mutex> lock(event_mutex_);
  21690. events_.push_back(event);
  21691. event_cv_.notify_all();
  21692. }
  21693. std::unique_ptr<Server> server_;
  21694. std::thread server_thread_;
  21695. std::mutex event_mutex_;
  21696. std::condition_variable event_cv_;
  21697. std::vector<std::string> events_;
  21698. std::atomic<bool> stop_server_{false};
  21699. std::string last_received_event_id_;
  21700. int port_ = 0;
  21701. };
  21702. //==============================================================================
  21703. // SSE Parsing Tests
  21704. //==============================================================================
  21705. class SSEParsingTest : public SSEIntegrationTest {
  21706. protected:
  21707. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21708. // A trailing sentinel event tells when the whole stream has been parsed.
  21709. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21710. auto body = stream + "event: end\ndata: end\n\n";
  21711. server_->Get("/parse", [body](const Request &, Response &res) {
  21712. res.set_content(body, "text/event-stream");
  21713. });
  21714. return collect("/parse");
  21715. }
  21716. // Runs SSEClient against path until an "end" event arrives and returns the
  21717. // messages dispatched before it
  21718. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21719. Client client(HOST, get_port());
  21720. sse::SSEClient sse(client, path);
  21721. std::mutex mutex;
  21722. std::condition_variable cv;
  21723. std::vector<sse::SSEMessage> messages;
  21724. auto done = false;
  21725. sse.on_message([&](const sse::SSEMessage &msg) {
  21726. std::lock_guard<std::mutex> lock(mutex);
  21727. // Ignore a replay from a reconnect that races with stop()
  21728. if (!done) { messages.push_back(msg); }
  21729. });
  21730. sse.on_event("end", [&](const sse::SSEMessage &) {
  21731. std::lock_guard<std::mutex> lock(mutex);
  21732. done = true;
  21733. cv.notify_all();
  21734. });
  21735. sse.set_reconnect_interval(100);
  21736. sse.start_async();
  21737. {
  21738. std::unique_lock<std::mutex> lock(mutex);
  21739. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21740. }
  21741. sse.stop();
  21742. EXPECT_TRUE(done);
  21743. return messages;
  21744. }
  21745. };
  21746. TEST_F(SSEParsingTest, SingleLineData) {
  21747. auto msgs = parse("data: hello\n\n");
  21748. ASSERT_EQ(msgs.size(), 1u);
  21749. EXPECT_EQ(msgs[0].data, "hello");
  21750. EXPECT_EQ(msgs[0].event, "message");
  21751. }
  21752. TEST_F(SSEParsingTest, MultiLineData) {
  21753. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21754. ASSERT_EQ(msgs.size(), 1u);
  21755. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21756. }
  21757. TEST_F(SSEParsingTest, CustomEventType) {
  21758. auto msgs = parse("event: update\ndata: payload\n\n");
  21759. ASSERT_EQ(msgs.size(), 1u);
  21760. EXPECT_EQ(msgs[0].event, "update");
  21761. EXPECT_EQ(msgs[0].data, "payload");
  21762. }
  21763. TEST_F(SSEParsingTest, EventIdHandling) {
  21764. auto msgs = parse("id: 12345\ndata: test\n\n");
  21765. ASSERT_EQ(msgs.size(), 1u);
  21766. EXPECT_EQ(msgs[0].id, "12345");
  21767. }
  21768. TEST_F(SSEParsingTest, EmptyEventId) {
  21769. auto msgs = parse("id:\ndata: test\n\n");
  21770. ASSERT_EQ(msgs.size(), 1u);
  21771. EXPECT_EQ(msgs[0].id, "");
  21772. }
  21773. TEST_F(SSEParsingTest, CommentsIgnored) {
  21774. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21775. ASSERT_EQ(msgs.size(), 1u);
  21776. EXPECT_EQ(msgs[0].data, "hello");
  21777. EXPECT_EQ(msgs[0].event, "message");
  21778. }
  21779. TEST_F(SSEParsingTest, ColonInValue) {
  21780. auto msgs = parse("data: hello:world:test\n\n");
  21781. ASSERT_EQ(msgs.size(), 1u);
  21782. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21783. }
  21784. TEST_F(SSEParsingTest, FieldNameOnly) {
  21785. // A line without a colon is a field name with an empty value
  21786. auto msgs = parse("data\n\n");
  21787. ASSERT_EQ(msgs.size(), 1u);
  21788. EXPECT_EQ(msgs[0].data, "");
  21789. }
  21790. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21791. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21792. ASSERT_EQ(msgs.size(), 1u);
  21793. EXPECT_EQ(msgs[0].event, "update");
  21794. EXPECT_EQ(msgs[0].data, "hello");
  21795. }
  21796. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21797. auto msgs = parse("data\r\n\r\n");
  21798. ASSERT_EQ(msgs.size(), 1u);
  21799. EXPECT_EQ(msgs[0].data, "");
  21800. }
  21801. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21802. auto msgs = parse("event: update\rdata: hello\r\r");
  21803. ASSERT_EQ(msgs.size(), 1u);
  21804. EXPECT_EQ(msgs[0].event, "update");
  21805. EXPECT_EQ(msgs[0].data, "hello");
  21806. }
  21807. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21808. // Chunk boundaries fall inside every \r\n and right before the first one
  21809. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21810. "\n\r", "\nevent: end\ndata: end\n\n"};
  21811. server_->Get("/split", [chunks](const Request &, Response &res) {
  21812. auto i = std::make_shared<size_t>(0);
  21813. res.set_chunked_content_provider(
  21814. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21815. if (*i == chunks.size()) {
  21816. sink.done();
  21817. } else {
  21818. sink.write(chunks[*i].data(), chunks[*i].size());
  21819. (*i)++;
  21820. }
  21821. return true;
  21822. });
  21823. });
  21824. auto msgs = collect("/split");
  21825. ASSERT_EQ(msgs.size(), 1u);
  21826. EXPECT_EQ(msgs[0].event, "update");
  21827. EXPECT_EQ(msgs[0].data, "hello");
  21828. }
  21829. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21830. // Only a BOM at the start of the stream is ignored
  21831. auto msgs = parse("\xEF\xBB\xBF"
  21832. "data: first\n\n"
  21833. "\xEF\xBB\xBF"
  21834. "data: second\n\n");
  21835. ASSERT_EQ(msgs.size(), 1u);
  21836. EXPECT_EQ(msgs[0].data, "first");
  21837. }
  21838. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21839. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21840. ASSERT_EQ(msgs.size(), 1u);
  21841. EXPECT_EQ(msgs[0].data, "hello");
  21842. EXPECT_EQ(msgs[0].event, "message");
  21843. }
  21844. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21845. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21846. ASSERT_EQ(msgs.size(), 2u);
  21847. EXPECT_EQ(msgs[0].data, "hello");
  21848. EXPECT_EQ(msgs[1].data, "hello");
  21849. }
  21850. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21851. // An event without data is not dispatched, and its type must not leak
  21852. // into the next event
  21853. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21854. ASSERT_EQ(msgs.size(), 1u);
  21855. EXPECT_EQ(msgs[0].event, "message");
  21856. EXPECT_EQ(msgs[0].data, "hello");
  21857. }
  21858. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21859. // Also when the empty field replaces an earlier type
  21860. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21861. ASSERT_EQ(msgs.size(), 2u);
  21862. EXPECT_EQ(msgs[0].event, "message");
  21863. EXPECT_EQ(msgs[1].event, "message");
  21864. }
  21865. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21866. // The first connection sends only an id; the second echoes back the
  21867. // Last-Event-ID it was reconnected with
  21868. std::atomic<int> connection_count{0};
  21869. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21870. if (connection_count++ == 0) {
  21871. res.set_content("id: 42\n\n", "text/event-stream");
  21872. } else {
  21873. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21874. "\n\nevent: end\ndata: end\n\n",
  21875. "text/event-stream");
  21876. }
  21877. });
  21878. auto msgs = collect("/id-only");
  21879. ASSERT_EQ(msgs.size(), 1u);
  21880. EXPECT_EQ(msgs[0].data, "42");
  21881. }
  21882. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21883. // The first connection sets an id and then clears it with an empty one; the
  21884. // second reports whether it was reconnected with a Last-Event-ID
  21885. std::atomic<int> connection_count{0};
  21886. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21887. if (connection_count++ == 0) {
  21888. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21889. "text/event-stream");
  21890. } else {
  21891. res.set_content(
  21892. std::string("data: ") +
  21893. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21894. "\n\nevent: end\ndata: end\n\n",
  21895. "text/event-stream");
  21896. }
  21897. });
  21898. auto msgs = collect("/id-clear");
  21899. ASSERT_EQ(msgs.size(), 3u);
  21900. EXPECT_EQ(msgs[0].id, "1");
  21901. EXPECT_EQ(msgs[1].id, "");
  21902. EXPECT_EQ(msgs[2].data, "not sent");
  21903. }
  21904. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21905. // The first connection sets an id and then sends ids that cannot be carried
  21906. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21907. // with
  21908. std::atomic<int> connection_count{0};
  21909. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21910. if (connection_count++ == 0) {
  21911. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21912. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21913. "text/event-stream");
  21914. } else {
  21915. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21916. "\n\nevent: end\ndata: end\n\n",
  21917. "text/event-stream");
  21918. }
  21919. });
  21920. auto msgs = collect("/id-unsendable");
  21921. ASSERT_EQ(msgs.size(), 1u);
  21922. EXPECT_EQ(msgs[0].data, "42");
  21923. }
  21924. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21925. auto msgs = parse("event: notification\nid: evt-42\n"
  21926. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21927. ASSERT_EQ(msgs.size(), 1u);
  21928. EXPECT_EQ(msgs[0].event, "notification");
  21929. EXPECT_EQ(msgs[0].id, "evt-42");
  21930. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21931. }
  21932. TEST(SSEMessageTest, Clear) {
  21933. sse::SSEMessage msg;
  21934. msg.event = "custom";
  21935. msg.data = "some data";
  21936. msg.id = "123";
  21937. msg.clear();
  21938. EXPECT_EQ(msg.event, "message");
  21939. EXPECT_EQ(msg.data, "");
  21940. EXPECT_EQ(msg.id, "");
  21941. }
  21942. //==============================================================================
  21943. // SSE Integration Tests
  21944. //==============================================================================
  21945. // Test: Successful connection and on_open callback
  21946. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21947. // Add a simple endpoint that sends one event and closes
  21948. server_->Get("/simple-event", [](const Request &, Response &res) {
  21949. res.set_chunked_content_provider(
  21950. "text/event-stream", [](size_t offset, DataSink &sink) {
  21951. if (offset == 0) {
  21952. std::string event = "data: hello\n\n";
  21953. sink.write(event.data(), event.size());
  21954. }
  21955. return false; // Close stream after sending
  21956. });
  21957. });
  21958. Client client("localhost", get_port());
  21959. sse::SSEClient sse(client, "/simple-event");
  21960. std::atomic<bool> open_called{false};
  21961. std::atomic<bool> message_received{false};
  21962. sse.on_open([&open_called]() { open_called.store(true); });
  21963. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21964. if (msg.data == "hello") { message_received.store(true); }
  21965. });
  21966. sse.set_reconnect_interval(100);
  21967. sse.set_max_reconnect_attempts(1);
  21968. // Start async
  21969. sse.start_async();
  21970. // Wait for message to be processed
  21971. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21972. sse.stop();
  21973. EXPECT_TRUE(open_called.load());
  21974. EXPECT_TRUE(message_received.load());
  21975. }
  21976. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21977. // A data line that never ends.
  21978. server_->Get("/endless-line", [](const Request &, Response &res) {
  21979. res.set_chunked_content_provider(
  21980. "text/event-stream", [](size_t offset, DataSink &sink) {
  21981. if (offset == 0) { sink.write("data: ", 6); }
  21982. std::string chunk(64 * 1024, 'A');
  21983. return sink.write(chunk.data(), chunk.size());
  21984. });
  21985. });
  21986. Client client("localhost", get_port());
  21987. sse::SSEClient sse(client, "/endless-line");
  21988. std::atomic<bool> too_long{false};
  21989. sse.on_error([&](Error err) {
  21990. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21991. });
  21992. sse.set_max_reconnect_attempts(1);
  21993. sse.start_async();
  21994. for (int i = 0; i < 500 && !too_long; i++) {
  21995. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21996. }
  21997. sse.stop();
  21998. EXPECT_TRUE(too_long);
  21999. }
  22000. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22001. // Far more in all than the client's payload limit below.
  22002. server_->Get("/many-events", [](const Request &, Response &res) {
  22003. res.set_chunked_content_provider(
  22004. "text/event-stream", [](size_t offset, DataSink &sink) {
  22005. if (offset == 0) {
  22006. std::string events;
  22007. for (int i = 0; i < 1000; i++) {
  22008. events += "data: message\n\n";
  22009. }
  22010. sink.write(events.data(), events.size());
  22011. }
  22012. return false;
  22013. });
  22014. });
  22015. Client client("localhost", get_port());
  22016. client.set_payload_max_length(1024);
  22017. sse::SSEClient sse(client, "/many-events");
  22018. std::atomic<int> messages{0};
  22019. std::atomic<bool> too_large{false};
  22020. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22021. sse.on_error([&](Error err) {
  22022. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22023. });
  22024. sse.set_max_reconnect_attempts(1);
  22025. sse.start_async();
  22026. for (int i = 0; i < 500 && messages < 1000; i++) {
  22027. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22028. }
  22029. sse.stop();
  22030. EXPECT_GE(messages.load(), 1000);
  22031. EXPECT_FALSE(too_large);
  22032. }
  22033. // Test: on_message callback
  22034. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22035. // Endpoint that sends multiple events then closes
  22036. server_->Get("/multi-event", [](const Request &, Response &res) {
  22037. res.set_chunked_content_provider(
  22038. "text/event-stream", [](size_t offset, DataSink &sink) {
  22039. if (offset == 0) {
  22040. std::string events = "data: message1\n\ndata: message2\n\n";
  22041. sink.write(events.data(), events.size());
  22042. }
  22043. return false;
  22044. });
  22045. });
  22046. Client client("localhost", get_port());
  22047. sse::SSEClient sse(client, "/multi-event");
  22048. std::vector<std::string> received_messages;
  22049. std::mutex messages_mutex;
  22050. sse.on_message([&](const sse::SSEMessage &msg) {
  22051. std::lock_guard<std::mutex> lock(messages_mutex);
  22052. received_messages.push_back(msg.data);
  22053. });
  22054. sse.set_reconnect_interval(100);
  22055. sse.set_max_reconnect_attempts(1);
  22056. sse.start_async();
  22057. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22058. sse.stop();
  22059. std::lock_guard<std::mutex> lock(messages_mutex);
  22060. EXPECT_GE(received_messages.size(), 2u);
  22061. if (received_messages.size() >= 2) {
  22062. EXPECT_EQ(received_messages[0], "message1");
  22063. EXPECT_EQ(received_messages[1], "message2");
  22064. }
  22065. }
  22066. // Test: on_event for specific types
  22067. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22068. Client client("localhost", get_port());
  22069. sse::SSEClient sse(client, "/custom-events");
  22070. std::atomic<bool> update_received{false};
  22071. std::atomic<bool> delete_received{false};
  22072. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22073. if (msg.data == "updated") { update_received.store(true); }
  22074. });
  22075. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22076. if (msg.data == "deleted") { delete_received.store(true); }
  22077. });
  22078. sse.set_max_reconnect_attempts(1);
  22079. sse.start_async();
  22080. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22081. sse.stop();
  22082. EXPECT_TRUE(update_received.load());
  22083. EXPECT_TRUE(delete_received.load());
  22084. }
  22085. // Test: on_error callback on connection failure
  22086. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22087. // Connect to a non-existent port
  22088. Client client("localhost", 59999);
  22089. sse::SSEClient sse(client, "/events");
  22090. std::atomic<bool> error_called{false};
  22091. Error received_error = Error::Success;
  22092. sse.on_error([&](Error err) {
  22093. error_called.store(true);
  22094. received_error = err;
  22095. });
  22096. sse.set_reconnect_interval(50);
  22097. sse.set_max_reconnect_attempts(1);
  22098. sse.start_async();
  22099. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22100. sse.stop();
  22101. EXPECT_TRUE(error_called.load());
  22102. EXPECT_NE(received_error, Error::Success);
  22103. }
  22104. // Test: Last-Event-ID header sent on reconnect
  22105. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22106. // Endpoint that sends event with ID
  22107. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22108. res.set_chunked_content_provider(
  22109. "text/event-stream", [](size_t offset, DataSink &sink) {
  22110. if (offset == 0) {
  22111. std::string event = "id: evt-123\ndata: test\n\n";
  22112. sink.write(event.data(), event.size());
  22113. }
  22114. return false;
  22115. });
  22116. });
  22117. Client client("localhost", get_port());
  22118. sse::SSEClient sse(client, "/event-with-id");
  22119. std::atomic<bool> id_received{false};
  22120. sse.on_message([&](const sse::SSEMessage &msg) {
  22121. if (!msg.id.empty()) { id_received.store(true); }
  22122. });
  22123. sse.set_reconnect_interval(100);
  22124. sse.set_max_reconnect_attempts(1);
  22125. sse.start_async();
  22126. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22127. sse.stop();
  22128. EXPECT_TRUE(id_received.load());
  22129. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22130. }
  22131. // Test: Manual stop
  22132. TEST_F(SSEIntegrationTest, ManualStop) {
  22133. // Endpoint that sends one event and stays open briefly. The server outlives
  22134. // this test body, so the provider uses the fixture's flag, not a local.
  22135. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22136. res.set_chunked_content_provider(
  22137. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22138. if (offset == 0) {
  22139. std::string event = "data: connected\n\n";
  22140. sink.write(event.data(), event.size());
  22141. }
  22142. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22143. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22144. }
  22145. return false;
  22146. });
  22147. });
  22148. Client client("localhost", get_port());
  22149. sse::SSEClient sse(client, "/stay-open");
  22150. std::atomic<bool> connected{false};
  22151. sse.on_open([&connected]() { connected.store(true); });
  22152. sse.set_reconnect_interval(100);
  22153. sse.set_max_reconnect_attempts(1);
  22154. sse.start_async();
  22155. // Wait for connection to establish
  22156. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22157. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22158. }
  22159. EXPECT_TRUE(connected.load());
  22160. EXPECT_TRUE(sse.is_connected());
  22161. // Signal handler to stop
  22162. stop_server_.store(true);
  22163. // Stop SSE client
  22164. sse.stop();
  22165. EXPECT_FALSE(sse.is_connected());
  22166. }
  22167. // Sends one event, then nothing until stop is set
  22168. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22169. return [&stop](const Request &, Response &res) {
  22170. res.set_chunked_content_provider(
  22171. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22172. if (offset == 0) {
  22173. std::string event = "data: hello\n\n";
  22174. sink.write(event.data(), event.size());
  22175. }
  22176. while (!stop.load()) {
  22177. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22178. }
  22179. return false;
  22180. });
  22181. };
  22182. }
  22183. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22184. static void check_stop_interrupts_blocked_read(Client &client) {
  22185. client.set_read_timeout(30, 0);
  22186. for (auto by_destructor : {false, true}) {
  22187. std::atomic<bool> received{false};
  22188. std::chrono::steady_clock::time_point start;
  22189. {
  22190. sse::SSEClient sse(client, "/idle-stream");
  22191. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22192. sse.start_async();
  22193. for (int i = 0; i < 500 && !received.load(); ++i) {
  22194. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22195. }
  22196. ASSERT_TRUE(received.load());
  22197. // Let the client block in the next read
  22198. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22199. start = std::chrono::steady_clock::now();
  22200. if (!by_destructor) { sse.stop(); }
  22201. }
  22202. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22203. std::chrono::seconds(2));
  22204. }
  22205. }
  22206. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22207. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22208. Client client("localhost", get_port());
  22209. check_stop_interrupts_blocked_read(client);
  22210. }
  22211. #ifdef CPPHTTPLIB_SSL_ENABLED
  22212. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22214. std::atomic<bool> done{false};
  22215. svr.Get("/idle-stream", idle_event_stream(done));
  22216. auto port = svr.bind_to_any_port(HOST);
  22217. std::thread t([&] { svr.listen_after_bind(); });
  22218. auto se = detail::scope_exit([&] {
  22219. done.store(true);
  22220. svr.stop();
  22221. t.join();
  22222. });
  22223. svr.wait_until_ready();
  22224. Client client("https://localhost:" + std::to_string(port));
  22225. client.enable_server_certificate_verification(false);
  22226. check_stop_interrupts_blocked_read(client);
  22227. }
  22228. #endif
  22229. // Test: SSEClient with custom headers
  22230. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22231. // Setup a server endpoint that checks for custom header
  22232. std::atomic<bool> header_received{false};
  22233. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22234. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22235. header_received.store(true);
  22236. }
  22237. res.set_chunked_content_provider("text/event-stream",
  22238. [](size_t, DataSink &) { return false; });
  22239. });
  22240. Client client("localhost", get_port());
  22241. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22242. sse::SSEClient sse(client, "/header-check", headers);
  22243. sse.set_max_reconnect_attempts(1);
  22244. sse.start_async();
  22245. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22246. sse.stop();
  22247. EXPECT_TRUE(header_received.load());
  22248. }
  22249. // Test: Reconnect interval configuration
  22250. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22251. Client client("localhost", get_port());
  22252. sse::SSEClient sse(client, "/events");
  22253. auto &result = sse.set_reconnect_interval(500);
  22254. // Builder pattern should return reference to self
  22255. EXPECT_EQ(&result, &sse);
  22256. }
  22257. // Test: Max reconnect attempts
  22258. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22259. // Connect to non-existent port to force reconnects
  22260. Client client("localhost", 59998);
  22261. sse::SSEClient sse(client, "/events");
  22262. std::atomic<int> error_count{0};
  22263. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22264. sse.set_reconnect_interval(50);
  22265. sse.set_max_reconnect_attempts(2);
  22266. auto start = std::chrono::steady_clock::now();
  22267. sse.start(); // Blocking call
  22268. auto end = std::chrono::steady_clock::now();
  22269. // Should have stopped after 2 failed attempts
  22270. EXPECT_GE(error_count.load(), 2);
  22271. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22272. auto duration =
  22273. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22274. #ifdef _WIN32
  22275. // Windows is much slower for socket connection failures
  22276. EXPECT_LT(duration.count(), 7000);
  22277. #else
  22278. EXPECT_LT(duration.count(), 1000);
  22279. #endif
  22280. }
  22281. // Test: Multi-line data in integration
  22282. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22283. // Endpoint with multi-line data
  22284. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22285. res.set_chunked_content_provider(
  22286. "text/event-stream", [](size_t offset, DataSink &sink) {
  22287. if (offset == 0) {
  22288. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22289. sink.write(event.data(), event.size());
  22290. }
  22291. return false;
  22292. });
  22293. });
  22294. Client client("localhost", get_port());
  22295. sse::SSEClient sse(client, "/multiline-data");
  22296. std::string received_data;
  22297. std::mutex data_mutex;
  22298. sse.on_message([&](const sse::SSEMessage &msg) {
  22299. std::lock_guard<std::mutex> lock(data_mutex);
  22300. received_data = msg.data;
  22301. });
  22302. sse.set_reconnect_interval(100);
  22303. sse.set_max_reconnect_attempts(1);
  22304. sse.start_async();
  22305. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22306. sse.stop();
  22307. std::lock_guard<std::mutex> lock(data_mutex);
  22308. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22309. }
  22310. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22311. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22312. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22313. DataSink &sink) {
  22314. if (offset == 0) {
  22315. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22316. sink.write(events.data(), events.size());
  22317. }
  22318. return false;
  22319. });
  22320. });
  22321. Client client("localhost", get_port());
  22322. sse::SSEClient sse(client, "/empty-data-lines");
  22323. std::mutex mutex;
  22324. std::condition_variable cv;
  22325. std::vector<std::string> received;
  22326. sse.on_message([&](const sse::SSEMessage &msg) {
  22327. std::lock_guard<std::mutex> lock(mutex);
  22328. received.push_back(msg.data);
  22329. cv.notify_all();
  22330. });
  22331. sse.set_max_reconnect_attempts(1);
  22332. sse.start_async();
  22333. {
  22334. std::unique_lock<std::mutex> lock(mutex);
  22335. cv.wait_for(lock, std::chrono::seconds(2),
  22336. [&] { return received.size() >= 3; });
  22337. }
  22338. sse.stop();
  22339. ASSERT_GE(received.size(), 3u);
  22340. EXPECT_EQ(received[0], "");
  22341. EXPECT_EQ(received[1], "\nhello");
  22342. EXPECT_EQ(received[2], "");
  22343. }
  22344. // Test: Auto-reconnect after server disconnection
  22345. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22346. std::atomic<int> connection_count{0};
  22347. std::atomic<int> message_count{0};
  22348. // Endpoint that sends one event and closes, forcing reconnect
  22349. server_->Get("/reconnect-test",
  22350. [&connection_count](const Request &, Response &res) {
  22351. connection_count.fetch_add(1);
  22352. res.set_chunked_content_provider(
  22353. "text/event-stream", [](size_t offset, DataSink &sink) {
  22354. if (offset == 0) {
  22355. std::string event = "data: hello\n\n";
  22356. sink.write(event.data(), event.size());
  22357. }
  22358. return false; // Close connection after sending
  22359. });
  22360. });
  22361. Client client("localhost", get_port());
  22362. sse::SSEClient sse(client, "/reconnect-test");
  22363. sse.on_message([&message_count](const sse::SSEMessage &) {
  22364. message_count.fetch_add(1);
  22365. });
  22366. sse.set_reconnect_interval(100);
  22367. sse.set_max_reconnect_attempts(3);
  22368. sse.start_async();
  22369. // Wait long enough for multiple reconnects
  22370. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22371. sse.stop();
  22372. // Should have connected multiple times (initial + reconnects)
  22373. EXPECT_GE(connection_count.load(), 2);
  22374. // Should have received messages from multiple connections
  22375. EXPECT_GE(message_count.load(), 2);
  22376. }
  22377. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22378. std::atomic<int> connection_count{0};
  22379. // Neither Content-Length nor chunked: the close ends the stream
  22380. server_->Get("/close-delimited",
  22381. [&connection_count](const Request &, Response &res) {
  22382. connection_count.fetch_add(1);
  22383. res.set_content_provider(
  22384. "text/event-stream", [](size_t offset, DataSink &sink) {
  22385. if (offset == 0) {
  22386. std::string event = "data: hello\n\n";
  22387. sink.write(event.data(), event.size());
  22388. } else {
  22389. sink.done();
  22390. }
  22391. return true;
  22392. });
  22393. });
  22394. Client client("localhost", get_port());
  22395. sse::SSEClient sse(client, "/close-delimited");
  22396. std::atomic<int> error_count{0};
  22397. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22398. sse.set_reconnect_interval(100);
  22399. sse.start_async();
  22400. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22401. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22402. }
  22403. sse.stop();
  22404. // Reconnects as after any end of the stream, but reports no error
  22405. EXPECT_GE(connection_count.load(), 2);
  22406. EXPECT_EQ(0, error_count.load());
  22407. }
  22408. // Test: A retry field that is not all ASCII digits is ignored
  22409. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22410. std::atomic<int> connection_count{0};
  22411. server_->Get("/bad-retry",
  22412. [&connection_count](const Request &, Response &res) {
  22413. connection_count.fetch_add(1);
  22414. res.set_chunked_content_provider(
  22415. "text/event-stream", [](size_t offset, DataSink &sink) {
  22416. if (offset == 0) {
  22417. std::string event = "retry: -1\ndata: hello\n\n";
  22418. sink.write(event.data(), event.size());
  22419. }
  22420. return false;
  22421. });
  22422. });
  22423. Client client("localhost", get_port());
  22424. sse::SSEClient sse(client, "/bad-retry");
  22425. sse.set_reconnect_interval(10000);
  22426. sse.start_async();
  22427. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22428. sse.stop();
  22429. EXPECT_EQ(connection_count.load(), 1);
  22430. }
  22431. // Test: A retry field of all ASCII digits sets the reconnection time
  22432. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22433. std::mutex mutex;
  22434. std::condition_variable cv;
  22435. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22436. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22437. {
  22438. std::lock_guard<std::mutex> lock(mutex);
  22439. connected_at.push_back(std::chrono::steady_clock::now());
  22440. cv.notify_all();
  22441. }
  22442. res.set_chunked_content_provider(
  22443. "text/event-stream", [](size_t offset, DataSink &sink) {
  22444. if (offset == 0) {
  22445. std::string event = "retry: 0\ndata: hello\n\n";
  22446. sink.write(event.data(), event.size());
  22447. }
  22448. return false;
  22449. });
  22450. });
  22451. Client client("localhost", get_port());
  22452. sse::SSEClient sse(client, "/zero-retry");
  22453. sse.set_reconnect_interval(10000);
  22454. sse.start_async();
  22455. {
  22456. std::unique_lock<std::mutex> lock(mutex);
  22457. cv.wait_for(lock, std::chrono::seconds(5),
  22458. [&] { return connected_at.size() >= 2; });
  22459. }
  22460. sse.stop();
  22461. // The server-supplied interval is applied, but never below 100ms, so
  22462. // "retry: 0" does not cause a busy reconnect loop
  22463. std::lock_guard<std::mutex> lock(mutex);
  22464. ASSERT_GE(connected_at.size(), 2u);
  22465. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22466. connected_at[1] - connected_at[0])
  22467. .count();
  22468. EXPECT_GE(interval_ms, 100);
  22469. }
  22470. // Test: Last-Event-ID sent on reconnect
  22471. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22472. std::atomic<int> connection_count{0};
  22473. std::vector<std::string> received_last_event_ids;
  22474. std::mutex id_mutex;
  22475. // Endpoint that checks Last-Event-ID header and sends event with ID
  22476. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22477. int conn = connection_count.fetch_add(1);
  22478. // Capture the Last-Event-ID header from each connection
  22479. {
  22480. std::lock_guard<std::mutex> lock(id_mutex);
  22481. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22482. }
  22483. res.set_chunked_content_provider(
  22484. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22485. if (offset == 0) {
  22486. std::string event =
  22487. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22488. sink.write(event.data(), event.size());
  22489. }
  22490. return false;
  22491. });
  22492. });
  22493. Client client("localhost", get_port());
  22494. sse::SSEClient sse(client, "/reconnect-with-id");
  22495. sse.set_reconnect_interval(100);
  22496. sse.set_max_reconnect_attempts(3);
  22497. sse.start_async();
  22498. // Wait for at least 2 connections
  22499. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22500. sse.stop();
  22501. // Verify behavior
  22502. std::lock_guard<std::mutex> lock(id_mutex);
  22503. EXPECT_GE(received_last_event_ids.size(), 2u);
  22504. // First connection should have no Last-Event-ID
  22505. if (!received_last_event_ids.empty()) {
  22506. EXPECT_EQ(received_last_event_ids[0], "");
  22507. }
  22508. // Second connection should have Last-Event-ID from first connection
  22509. if (received_last_event_ids.size() >= 2) {
  22510. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22511. }
  22512. }
  22513. // Test: set_headers updates headers used on reconnect
  22514. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22515. std::vector<std::string> received_tokens;
  22516. std::mutex token_mutex;
  22517. // Endpoint that captures Authorization header
  22518. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22519. {
  22520. std::lock_guard<std::mutex> lock(token_mutex);
  22521. received_tokens.push_back(req.get_header_value("Authorization"));
  22522. }
  22523. res.set_chunked_content_provider(
  22524. "text/event-stream", [](size_t offset, DataSink &sink) {
  22525. if (offset == 0) {
  22526. std::string event = "data: hello\n\n";
  22527. sink.write(event.data(), event.size());
  22528. }
  22529. return false; // Close connection to trigger reconnect
  22530. });
  22531. });
  22532. Client client("localhost", get_port());
  22533. Headers headers = {{"Authorization", "Bearer old-token"}};
  22534. sse::SSEClient sse(client, "/auth-check", headers);
  22535. // Update headers on each successful connection
  22536. sse.on_open(
  22537. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22538. sse.set_reconnect_interval(100);
  22539. sse.set_max_reconnect_attempts(3);
  22540. sse.start_async();
  22541. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22542. sse.stop();
  22543. std::lock_guard<std::mutex> lock(token_mutex);
  22544. ASSERT_GE(received_tokens.size(), 2u);
  22545. // First connection uses original header
  22546. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22547. // Second connection uses updated header from set_headers
  22548. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22549. }
  22550. // Test: 401 allows reconnection (so on_error can refresh headers)
  22551. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22552. std::atomic<int> connection_count{0};
  22553. // Endpoint: returns 401 on first attempt, 200 on second
  22554. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22555. int conn = connection_count.fetch_add(1);
  22556. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22557. res.status = StatusCode::Unauthorized_401;
  22558. res.set_content("Unauthorized", "text/plain");
  22559. return;
  22560. }
  22561. res.set_chunked_content_provider(
  22562. "text/event-stream", [](size_t offset, DataSink &sink) {
  22563. if (offset == 0) {
  22564. std::string event = "data: authenticated\n\n";
  22565. sink.write(event.data(), event.size());
  22566. }
  22567. return false;
  22568. });
  22569. });
  22570. Client client("localhost", get_port());
  22571. Headers headers = {{"Authorization", "Bearer expired"}};
  22572. sse::SSEClient sse(client, "/auth-retry", headers);
  22573. std::atomic<bool> message_received{false};
  22574. // Refresh token on error
  22575. sse.on_error(
  22576. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22577. sse.on_message([&](const sse::SSEMessage &msg) {
  22578. if (msg.data == "authenticated") { message_received.store(true); }
  22579. });
  22580. sse.set_reconnect_interval(100);
  22581. sse.set_max_reconnect_attempts(3);
  22582. sse.start_async();
  22583. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22584. sse.stop();
  22585. // Should have reconnected after 401 and succeeded with new token
  22586. EXPECT_GE(connection_count.load(), 2);
  22587. EXPECT_TRUE(message_received.load());
  22588. }
  22589. TEST(Issue2318Test, EmptyHostString) {
  22590. {
  22591. httplib::Client cli_empty("", PORT);
  22592. auto res = cli_empty.Get("/");
  22593. ASSERT_FALSE(res);
  22594. EXPECT_EQ(httplib::Error::Connection, res.error());
  22595. }
  22596. {
  22597. httplib::Client cli(" ", PORT);
  22598. auto res = cli.Get("/");
  22599. ASSERT_FALSE(res);
  22600. EXPECT_EQ(httplib::Error::Connection, res.error());
  22601. }
  22602. }
  22603. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22604. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22605. Server svr;
  22606. // Set a small payload limit (1KB)
  22607. svr.set_payload_max_length(1024);
  22608. svr.Post("/test", [&](const Request &req, Response &res) {
  22609. res.set_content("Body size: " + std::to_string(req.body.size()),
  22610. "text/plain");
  22611. });
  22612. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22613. auto se = detail::scope_exit([&] {
  22614. svr.stop();
  22615. listen_thread.join();
  22616. });
  22617. svr.wait_until_ready();
  22618. // Create data that compresses well but exceeds limit when decompressed
  22619. // 8KB of repeated null bytes compresses to a very small size
  22620. std::string original_data(8 * 1024, '\0');
  22621. // Compress the data using gzip
  22622. std::string compressed_data;
  22623. detail::gzip_compressor compressor;
  22624. compressor.compress(original_data.data(), original_data.size(), true,
  22625. [&](const char *data, size_t size) {
  22626. compressed_data.append(data, size);
  22627. return true;
  22628. });
  22629. // Verify compression worked (compressed should be much smaller)
  22630. ASSERT_LT(compressed_data.size(), original_data.size());
  22631. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22632. // Send compressed data with Content-Encoding: gzip
  22633. Client cli(HOST, PORT);
  22634. Headers headers = {{"Content-Encoding", "gzip"}};
  22635. auto res =
  22636. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22637. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22639. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22640. }
  22641. #endif
  22642. // ============================================================================
  22643. // OpenSSL-Specific Tests
  22644. // ============================================================================
  22645. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22646. X509 *readCertificate(const std::string &strFileName) {
  22647. std::ifstream inStream(strFileName);
  22648. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22649. std::istreambuf_iterator<char>());
  22650. if (strCertPEM.empty()) return (nullptr);
  22651. BIO *pbCert = BIO_new(BIO_s_mem());
  22652. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22653. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22654. BIO_free(pbCert);
  22655. return (pCert);
  22656. }
  22657. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22658. std::ifstream inStream(strFileName);
  22659. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22660. std::istreambuf_iterator<char>());
  22661. if (strPrivateKeyPEM.empty()) return (nullptr);
  22662. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22663. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22664. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22665. BIO_free(pbPrivKey);
  22666. return (pPrivateKey);
  22667. }
  22668. TEST(BindServerTest, UpdateCerts) {
  22669. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22670. int port = svr.bind_to_any_port("0.0.0.0");
  22671. ASSERT_TRUE(svr.is_valid());
  22672. ASSERT_TRUE(port > 0);
  22673. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22674. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22675. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22676. ASSERT_TRUE(cert != nullptr);
  22677. ASSERT_TRUE(ca_cert != nullptr);
  22678. ASSERT_TRUE(key != nullptr);
  22679. X509_STORE *cert_store = X509_STORE_new();
  22680. X509_STORE_add_cert(cert_store, ca_cert);
  22681. // svr.update_certs(cert, key, cert_store); // deprecated
  22682. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22683. CLIENT_CA_CERT_FILE);
  22684. ASSERT_TRUE(svr.is_valid());
  22685. svr.stop();
  22686. X509_STORE_free(cert_store);
  22687. X509_free(cert);
  22688. X509_free(ca_cert);
  22689. EVP_PKEY_free(key);
  22690. }
  22691. // Test that update_certs() updates client CA list correctly
  22692. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22693. // Start with file-based constructor
  22694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22695. ASSERT_TRUE(svr.is_valid());
  22696. // Initially no client CA list should be set
  22697. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22698. ASSERT_TRUE(ssl_ctx != nullptr);
  22699. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22700. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22701. // Now update with client CA (PEM string)
  22702. std::string cert_pem, key_pem, ca_pem;
  22703. read_file(SERVER_CERT_FILE, cert_pem);
  22704. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22705. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22706. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22707. ASSERT_TRUE(svr.is_valid());
  22708. // Now client CA list should be set
  22709. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22710. ASSERT_TRUE(ca_list_after != nullptr);
  22711. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22712. }
  22713. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22714. // Test that the file-path SSLServer constructor properly sets the client CA
  22715. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22717. ASSERT_TRUE(svr.is_valid());
  22718. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22719. ASSERT_TRUE(ssl_ctx != nullptr);
  22720. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22721. ASSERT_TRUE(ca_list != nullptr);
  22722. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22723. }
  22724. #endif
  22725. // ============================================================================
  22726. // MbedTLS-Specific Tests
  22727. // ============================================================================
  22728. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22729. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22730. using namespace httplib::tls;
  22731. // Track if callback was invoked
  22732. bool callback_invoked = false;
  22733. // The callback receives void* ctx which is actually MbedTlsContext*
  22734. // We can access the mbedtls_ssl_config via the context
  22735. auto setup_callback = [&callback_invoked](void *ctx) {
  22736. callback_invoked = true;
  22737. // Cast to MbedTlsContext* to access the ssl config
  22738. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22739. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22740. // Use static variables to hold certificate data (simplified for test)
  22741. static mbedtls_x509_crt own_cert;
  22742. static mbedtls_pk_context own_key;
  22743. static mbedtls_x509_crt ca_chain;
  22744. static bool initialized = false;
  22745. if (!initialized) {
  22746. mbedtls_x509_crt_init(&own_cert);
  22747. mbedtls_pk_init(&own_key);
  22748. mbedtls_x509_crt_init(&ca_chain);
  22749. // Load server certificate
  22750. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22751. return false;
  22752. }
  22753. // Load server private key.
  22754. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22755. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22756. #if MBEDTLS_VERSION_MAJOR == 3
  22757. ,
  22758. mbedtls_ctr_drbg_random, nullptr
  22759. #endif
  22760. ) != 0) {
  22761. return false;
  22762. }
  22763. // Load CA chain for client verification
  22764. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22765. return false;
  22766. }
  22767. initialized = true;
  22768. }
  22769. // Configure the SSL config
  22770. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22771. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22772. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22773. // Set minimum TLS version using mbedTLS native API
  22774. #if MBEDTLS_VERSION_MAJOR >= 3
  22775. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22776. #else
  22777. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22778. MBEDTLS_SSL_MINOR_VERSION_3);
  22779. #endif
  22780. return true;
  22781. };
  22782. SSLServer svr(setup_callback);
  22783. ASSERT_TRUE(svr.is_valid());
  22784. ASSERT_TRUE(callback_invoked);
  22785. svr.Get("/test", [&](const Request &req, Response &res) {
  22786. res.set_content("test", "text/plain");
  22787. auto cert = req.peer_cert();
  22788. ASSERT_TRUE(static_cast<bool>(cert));
  22789. auto common_name = cert.subject_cn();
  22790. EXPECT_EQ("Common Name", common_name);
  22791. });
  22792. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22793. auto se = detail::scope_exit([&] {
  22794. svr.stop();
  22795. t.join();
  22796. ASSERT_FALSE(svr.is_running());
  22797. });
  22798. svr.wait_until_ready();
  22799. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22800. cli.enable_server_certificate_verification(false);
  22801. cli.set_connection_timeout(30);
  22802. auto res = cli.Get("/test");
  22803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22804. ASSERT_EQ(StatusCode::OK_200, res->status);
  22805. }
  22806. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22807. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22808. // keep-alive SSL session, which reads through that config in
  22809. // mbedtls_ssl_close_notify.
  22810. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22811. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22812. ASSERT_TRUE(svr.is_valid());
  22813. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22814. res.set_content("test", "text/plain");
  22815. });
  22816. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22817. auto se = detail::scope_exit([&] {
  22818. svr.stop();
  22819. t.join();
  22820. ASSERT_FALSE(svr.is_running());
  22821. });
  22822. svr.wait_until_ready();
  22823. {
  22824. SSLClient cli(HOST, PORT);
  22825. cli.enable_server_certificate_verification(false);
  22826. cli.set_keep_alive(true);
  22827. auto res = cli.Get("/test");
  22828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22829. ASSERT_EQ(StatusCode::OK_200, res->status);
  22830. // cli is destructed here with the keep-alive SSL session still open.
  22831. }
  22832. }
  22833. #endif
  22834. // WebSocket Tests
  22835. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22836. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22837. // defining the meaning of these bits has been negotiated.
  22838. auto make_frame = [](uint8_t first_byte) {
  22839. std::string frame;
  22840. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22841. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22842. frame += "Hello";
  22843. return frame;
  22844. };
  22845. // RSV1 set (0x40)
  22846. {
  22847. detail::BufferStream strm;
  22848. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22849. ws::Opcode opcode;
  22850. std::string payload;
  22851. bool fin;
  22852. EXPECT_EQ(
  22853. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22854. ws::impl::FrameRead::Fail);
  22855. }
  22856. // RSV2 set (0x20)
  22857. {
  22858. detail::BufferStream strm;
  22859. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22860. ws::Opcode opcode;
  22861. std::string payload;
  22862. bool fin;
  22863. EXPECT_EQ(
  22864. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22865. ws::impl::FrameRead::Fail);
  22866. }
  22867. // RSV3 set (0x10)
  22868. {
  22869. detail::BufferStream strm;
  22870. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22871. ws::Opcode opcode;
  22872. std::string payload;
  22873. bool fin;
  22874. EXPECT_EQ(
  22875. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22876. ws::impl::FrameRead::Fail);
  22877. }
  22878. // No RSV bits set - should succeed
  22879. {
  22880. detail::BufferStream strm;
  22881. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22882. ws::Opcode opcode;
  22883. std::string payload;
  22884. bool fin;
  22885. EXPECT_EQ(
  22886. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22887. ws::impl::FrameRead::Ok);
  22888. EXPECT_EQ(ws::Opcode::Text, opcode);
  22889. EXPECT_EQ("Hello", payload);
  22890. EXPECT_TRUE(fin);
  22891. }
  22892. }
  22893. TEST(WebSocketTest, ControlFrameValidation) {
  22894. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22895. // payload length <= 125.
  22896. // Ping with FIN=0 - must be rejected
  22897. {
  22898. detail::BufferStream strm;
  22899. std::string frame;
  22900. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22901. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22902. strm.write(frame.data(), frame.size());
  22903. ws::Opcode opcode;
  22904. std::string payload;
  22905. bool fin;
  22906. EXPECT_EQ(
  22907. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22908. ws::impl::FrameRead::Fail);
  22909. }
  22910. // Close with FIN=0 - must be rejected
  22911. {
  22912. detail::BufferStream strm;
  22913. std::string frame;
  22914. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22915. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22916. strm.write(frame.data(), frame.size());
  22917. ws::Opcode opcode;
  22918. std::string payload;
  22919. bool fin;
  22920. EXPECT_EQ(
  22921. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22922. ws::impl::FrameRead::Fail);
  22923. }
  22924. // Ping with payload_len=126 (extended length) - must be rejected
  22925. {
  22926. detail::BufferStream strm;
  22927. std::string frame;
  22928. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22929. frame += static_cast<char>(126); // payload_len=126 (>125)
  22930. frame += static_cast<char>(0x00); // extended length high byte
  22931. frame += static_cast<char>(126); // extended length low byte
  22932. frame += std::string(126, 'x');
  22933. strm.write(frame.data(), frame.size());
  22934. ws::Opcode opcode;
  22935. std::string payload;
  22936. bool fin;
  22937. EXPECT_EQ(
  22938. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22939. ws::impl::FrameRead::Fail);
  22940. }
  22941. // Ping with FIN=1 and payload_len=125 - should succeed
  22942. {
  22943. detail::BufferStream strm;
  22944. std::string frame;
  22945. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22946. frame += static_cast<char>(125); // payload_len=125
  22947. frame += std::string(125, 'x');
  22948. strm.write(frame.data(), frame.size());
  22949. ws::Opcode opcode;
  22950. std::string payload;
  22951. bool fin;
  22952. EXPECT_EQ(
  22953. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22954. ws::impl::FrameRead::Ok);
  22955. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22956. EXPECT_EQ(125u, payload.size());
  22957. EXPECT_TRUE(fin);
  22958. }
  22959. }
  22960. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22961. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22962. // length MUST be 0.
  22963. // MSB set - must be rejected
  22964. {
  22965. detail::BufferStream strm;
  22966. std::string frame;
  22967. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22968. frame += static_cast<char>(127); // 64-bit extended length
  22969. frame += static_cast<char>(0x80); // MSB set (invalid)
  22970. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22971. strm.write(frame.data(), frame.size());
  22972. ws::Opcode opcode;
  22973. std::string payload;
  22974. bool fin;
  22975. EXPECT_EQ(
  22976. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22977. ws::impl::FrameRead::Fail);
  22978. }
  22979. // MSB clear - should pass length parsing (will be rejected by max_len,
  22980. // but that's a different check; use a small length to verify)
  22981. {
  22982. detail::BufferStream strm;
  22983. std::string frame;
  22984. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22985. frame += static_cast<char>(127); // 64-bit extended length
  22986. frame += std::string(7, '\0'); // high bytes = 0
  22987. frame += static_cast<char>(0x03); // length = 3
  22988. frame += "abc";
  22989. strm.write(frame.data(), frame.size());
  22990. ws::Opcode opcode;
  22991. std::string payload;
  22992. bool fin;
  22993. EXPECT_EQ(
  22994. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22995. ws::impl::FrameRead::Ok);
  22996. EXPECT_EQ(ws::Opcode::Text, opcode);
  22997. EXPECT_EQ("abc", payload);
  22998. }
  22999. }
  23000. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23001. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23002. // Valid UTF-8
  23003. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23004. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23005. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23006. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23007. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23008. // Invalid UTF-8
  23009. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23010. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23011. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23012. EXPECT_FALSE(
  23013. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23014. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23015. }
  23016. TEST(WebSocketTest, ConnectAndDisconnect) {
  23017. Server svr;
  23018. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23019. std::string msg;
  23020. while (ws.read(msg)) {}
  23021. });
  23022. auto port = svr.bind_to_any_port(HOST);
  23023. std::thread t([&]() { svr.listen_after_bind(); });
  23024. svr.wait_until_ready();
  23025. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23026. auto res = client.connect();
  23027. ASSERT_TRUE(res);
  23028. EXPECT_EQ(Error::Success, res.error());
  23029. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23030. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23031. EXPECT_TRUE(client.is_open());
  23032. client.close();
  23033. EXPECT_FALSE(client.is_open());
  23034. svr.stop();
  23035. t.join();
  23036. }
  23037. TEST(WebSocketTest, ValidURL) {
  23038. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23039. EXPECT_TRUE(ws1.is_valid());
  23040. ws::WebSocketClient ws2("ws://example.com/path");
  23041. EXPECT_TRUE(ws2.is_valid());
  23042. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23043. EXPECT_TRUE(ws3.is_valid());
  23044. #ifdef CPPHTTPLIB_SSL_ENABLED
  23045. ws::WebSocketClient wss1("wss://example.com/path");
  23046. EXPECT_TRUE(wss1.is_valid());
  23047. ws::WebSocketClient wss2("wss://example.com:443/path");
  23048. EXPECT_TRUE(wss2.is_valid());
  23049. #endif
  23050. }
  23051. TEST(WebSocketTest, InvalidURL) {
  23052. // No scheme
  23053. ws::WebSocketClient ws1("localhost:8080/path");
  23054. EXPECT_FALSE(ws1.is_valid());
  23055. // No path
  23056. ws::WebSocketClient ws2("ws://localhost:8080");
  23057. EXPECT_FALSE(ws2.is_valid());
  23058. // Empty string
  23059. ws::WebSocketClient ws3("");
  23060. EXPECT_FALSE(ws3.is_valid());
  23061. // Missing host
  23062. ws::WebSocketClient ws4("ws://:8080/path");
  23063. EXPECT_FALSE(ws4.is_valid());
  23064. // Port number overflow — should not crash
  23065. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23066. EXPECT_FALSE(ws5.is_valid());
  23067. // Port out of range
  23068. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23069. EXPECT_FALSE(ws6.is_valid());
  23070. }
  23071. TEST(WebSocketTest, UnsupportedScheme) {
  23072. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23073. ws::WebSocketClient ws1("http://localhost:8080/path");
  23074. EXPECT_FALSE(ws1.is_valid());
  23075. ws::WebSocketClient ws2("https://localhost:8080/path");
  23076. EXPECT_FALSE(ws2.is_valid());
  23077. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23078. EXPECT_FALSE(ws3.is_valid());
  23079. #else
  23080. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23081. std::invalid_argument);
  23082. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23083. std::invalid_argument);
  23084. #endif
  23085. }
  23086. TEST(WebSocketTest, ConnectWhenInvalid) {
  23087. ws::WebSocketClient ws("not a valid url");
  23088. EXPECT_FALSE(ws.is_valid());
  23089. auto res = ws.connect();
  23090. EXPECT_FALSE(res);
  23091. EXPECT_EQ(Error::Connection, res.error());
  23092. EXPECT_EQ(-1, res.status());
  23093. }
  23094. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23095. // Grab a port that is free, then close it again so nothing listens there
  23096. Server svr;
  23097. auto port = svr.bind_to_any_port(HOST);
  23098. svr.stop();
  23099. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23100. auto res = client.connect();
  23101. ASSERT_FALSE(res);
  23102. EXPECT_EQ(Error::Connection, res.error());
  23103. EXPECT_EQ(-1, res.status());
  23104. }
  23105. TEST(WebSocketTest, DefaultPort) {
  23106. ws::WebSocketClient ws1("ws://example.com/path");
  23107. EXPECT_TRUE(ws1.is_valid());
  23108. // ws:// defaults to port 80 (verified by successful parse)
  23109. #ifdef CPPHTTPLIB_SSL_ENABLED
  23110. ws::WebSocketClient ws2("wss://example.com/path");
  23111. EXPECT_TRUE(ws2.is_valid());
  23112. // wss:// defaults to port 443 (verified by successful parse)
  23113. #endif
  23114. }
  23115. TEST(WebSocketTest, IPv6LiteralAddress) {
  23116. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23117. EXPECT_TRUE(ws1.is_valid());
  23118. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23119. EXPECT_TRUE(ws2.is_valid());
  23120. }
  23121. TEST(WebSocketTest, ComplexPath) {
  23122. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23123. EXPECT_TRUE(ws1.is_valid());
  23124. ws::WebSocketClient ws2("ws://localhost:8080/");
  23125. EXPECT_TRUE(ws2.is_valid());
  23126. }
  23127. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23128. Server svr;
  23129. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23130. std::string msg;
  23131. while (ws.read(msg)) {}
  23132. });
  23133. auto port = svr.bind_to_any_port(HOST);
  23134. std::thread t([&]() { svr.listen_after_bind(); });
  23135. svr.wait_until_ready();
  23136. auto another_host = "example.com";
  23137. auto wrong_ip = "192.0.2.1";
  23138. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23139. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23140. ASSERT_TRUE(client.connect());
  23141. EXPECT_TRUE(client.is_open());
  23142. client.close();
  23143. svr.stop();
  23144. t.join();
  23145. }
  23146. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23147. Server svr;
  23148. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23149. std::string msg;
  23150. while (ws.read(msg)) {}
  23151. });
  23152. auto port = svr.bind_to_any_port(HOST);
  23153. std::thread t([&]() { svr.listen_after_bind(); });
  23154. svr.wait_until_ready();
  23155. auto wrong_ip = "192.0.2.1";
  23156. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23157. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23158. client.set_connection_timeout(1);
  23159. client.set_read_timeout(1);
  23160. client.set_write_timeout(1);
  23161. EXPECT_FALSE(client.connect());
  23162. EXPECT_FALSE(client.is_open());
  23163. svr.stop();
  23164. t.join();
  23165. }
  23166. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23167. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23168. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23169. // (RFC 6761) is only a map key and the Host header value.
  23170. auto host = "target.invalid";
  23171. Server svr;
  23172. std::string received_host;
  23173. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23174. received_host = req.get_header_value("Host");
  23175. std::string msg;
  23176. while (ws.read(msg)) {}
  23177. });
  23178. auto port = svr.bind_to_any_port(HOST);
  23179. std::thread t([&]() { svr.listen_after_bind(); });
  23180. // ASSERT_* below returns from the test body, which would leave t joinable
  23181. // and make ~thread call std::terminate.
  23182. auto se = detail::scope_exit([&] {
  23183. svr.stop();
  23184. if (t.joinable()) { t.join(); }
  23185. });
  23186. svr.wait_until_ready();
  23187. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23188. std::to_string(port) + "/ws");
  23189. client.set_hostname_addr_map({{host, HOST}});
  23190. ASSERT_TRUE(client.connect());
  23191. EXPECT_TRUE(client.is_open());
  23192. client.close();
  23193. svr.stop();
  23194. t.join();
  23195. // The mapping only redirects the connection; the identity stays host_.
  23196. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23197. }
  23198. class WebSocketIntegrationTest : public ::testing::Test {
  23199. protected:
  23200. void SetUp() override {
  23201. server_ = httplib::detail::make_unique<Server>();
  23202. setup_server();
  23203. start_server();
  23204. }
  23205. void TearDown() override {
  23206. server_->stop();
  23207. if (server_thread_.joinable()) { server_thread_.join(); }
  23208. }
  23209. void setup_server() {
  23210. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23211. std::string msg;
  23212. ws::ReadResult ret;
  23213. while ((ret = ws.read(msg))) {
  23214. if (ret == ws::Binary) {
  23215. ws.send(msg.data(), msg.size());
  23216. } else {
  23217. ws.send(msg);
  23218. }
  23219. }
  23220. });
  23221. server_->WebSocket("/ws-echo-string",
  23222. [](const Request &, ws::WebSocket &ws) {
  23223. std::string msg;
  23224. while (ws.read(msg)) {
  23225. ws.send("echo: " + msg);
  23226. }
  23227. });
  23228. server_->WebSocket(
  23229. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23230. // Echo back request metadata
  23231. ws.send("path:" + req.path);
  23232. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23233. std::string msg;
  23234. while (ws.read(msg)) {}
  23235. });
  23236. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23237. std::string msg;
  23238. ws.read(msg); // wait for a message
  23239. ws.close();
  23240. });
  23241. server_->WebSocket("/ws-close-status",
  23242. [](const Request &, ws::WebSocket &ws) {
  23243. std::string msg;
  23244. ws.read(msg); // wait for a message
  23245. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23246. });
  23247. server_->WebSocket(
  23248. "/ws-subprotocol",
  23249. [](const Request &, ws::WebSocket &ws) {
  23250. std::string msg;
  23251. while (ws.read(msg)) {
  23252. ws.send(msg);
  23253. }
  23254. },
  23255. [](const std::vector<std::string> &protocols) -> std::string {
  23256. for (const auto &p : protocols) {
  23257. if (p == "graphql-ws") { return p; }
  23258. }
  23259. return "";
  23260. });
  23261. server_->WebSocket(
  23262. "/ws-subprotocol-unoffered",
  23263. [](const Request &, ws::WebSocket &ws) {
  23264. std::string msg;
  23265. while (ws.read(msg)) {
  23266. ws.send(msg);
  23267. }
  23268. },
  23269. [](const std::vector<std::string> &) -> std::string {
  23270. return "admin";
  23271. });
  23272. }
  23273. void start_server() {
  23274. port_ = server_->bind_to_any_port(HOST);
  23275. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23276. server_->wait_until_ready();
  23277. }
  23278. std::unique_ptr<Server> server_;
  23279. std::thread server_thread_;
  23280. int port_ = 0;
  23281. };
  23282. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23283. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23284. "/ws-echo");
  23285. ASSERT_TRUE(client.connect());
  23286. ASSERT_TRUE(client.is_open());
  23287. ASSERT_TRUE(client.send("Hello WebSocket"));
  23288. std::string msg;
  23289. EXPECT_EQ(ws::Text, client.read(msg));
  23290. EXPECT_EQ("Hello WebSocket", msg);
  23291. client.close();
  23292. }
  23293. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23294. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23295. "/ws-echo");
  23296. ASSERT_TRUE(client.connect());
  23297. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23298. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23299. std::string msg;
  23300. EXPECT_EQ(ws::Binary, client.read(msg));
  23301. EXPECT_EQ(binary_data, msg);
  23302. client.close();
  23303. }
  23304. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23305. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23306. "/ws-echo");
  23307. ASSERT_TRUE(client.connect());
  23308. for (int i = 0; i < 10; i++) {
  23309. auto text = "message " + std::to_string(i);
  23310. ASSERT_TRUE(client.send(text));
  23311. std::string msg;
  23312. ASSERT_TRUE(client.read(msg));
  23313. EXPECT_EQ(text, msg);
  23314. }
  23315. client.close();
  23316. }
  23317. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23318. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23319. "/ws-close");
  23320. ASSERT_TRUE(client.connect());
  23321. // Send a message to trigger the server to close
  23322. ASSERT_TRUE(client.send("trigger close"));
  23323. // The server will close, so read should return false
  23324. std::string msg;
  23325. EXPECT_FALSE(client.read(msg));
  23326. EXPECT_FALSE(client.is_open());
  23327. }
  23328. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23329. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23330. "/ws-echo");
  23331. ASSERT_TRUE(client.connect());
  23332. // 128KB message
  23333. std::string large_data(128 * 1024, 'X');
  23334. ASSERT_TRUE(client.send(large_data));
  23335. std::string msg;
  23336. ASSERT_TRUE(client.read(msg));
  23337. EXPECT_EQ(large_data, msg);
  23338. client.close();
  23339. }
  23340. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23341. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23342. "/ws-echo");
  23343. ASSERT_TRUE(client.connect());
  23344. const int num_threads = 4;
  23345. std::vector<std::thread> threads;
  23346. std::atomic<int> send_count{0};
  23347. for (int t = 0; t < num_threads; t++) {
  23348. threads.emplace_back([&client, &send_count, t]() {
  23349. for (int i = 0; i < 5; i++) {
  23350. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23351. if (client.send(text)) { send_count++; }
  23352. }
  23353. });
  23354. }
  23355. for (auto &th : threads) {
  23356. th.join();
  23357. }
  23358. int received = 0;
  23359. std::string msg;
  23360. while (received < send_count.load()) {
  23361. if (!client.read(msg)) { break; }
  23362. received++;
  23363. }
  23364. EXPECT_EQ(send_count.load(), received);
  23365. client.close();
  23366. }
  23367. TEST_F(WebSocketIntegrationTest, ReadString) {
  23368. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23369. "/ws-echo-string");
  23370. ASSERT_TRUE(client.connect());
  23371. ASSERT_TRUE(client.send("hello"));
  23372. std::string msg;
  23373. ASSERT_TRUE(client.read(msg));
  23374. EXPECT_EQ("echo: hello", msg);
  23375. ASSERT_TRUE(client.send("world"));
  23376. ASSERT_TRUE(client.read(msg));
  23377. EXPECT_EQ("echo: world", msg);
  23378. client.close();
  23379. }
  23380. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23381. Headers headers = {{"X-Test-Header", "test-value"}};
  23382. ws::WebSocketClient client(
  23383. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23384. ASSERT_TRUE(client.connect());
  23385. std::string msg;
  23386. ASSERT_TRUE(client.read(msg));
  23387. EXPECT_EQ("path:/ws-request-info", msg);
  23388. ASSERT_TRUE(client.read(msg));
  23389. EXPECT_EQ("header:test-value", msg);
  23390. client.close();
  23391. }
  23392. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23393. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23394. "/ws-echo");
  23395. client.set_read_timeout(1, 0); // 1 second
  23396. ASSERT_TRUE(client.connect());
  23397. // Don't send anything — server echo handler waits for a message, so read()
  23398. // should time out. The connection survives it: nothing was consumed.
  23399. std::string msg;
  23400. EXPECT_EQ(client.read(msg), ws::Timeout);
  23401. EXPECT_TRUE(client.is_open());
  23402. // And it is still usable afterwards.
  23403. EXPECT_TRUE(client.send("after timeout"));
  23404. EXPECT_EQ(client.read(msg), ws::Text);
  23405. EXPECT_EQ(msg, "after timeout");
  23406. }
  23407. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23408. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23409. "/ws-echo");
  23410. client.set_read_timeout(1, 0);
  23411. ASSERT_TRUE(client.connect());
  23412. ASSERT_TRUE(client.send("first"));
  23413. std::string msg;
  23414. ASSERT_EQ(client.read(msg), ws::Text);
  23415. ASSERT_EQ(msg, "first");
  23416. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23417. // not be used with a read timeout: it would reprocess the previous message.
  23418. EXPECT_EQ(client.read(msg), ws::Timeout);
  23419. EXPECT_EQ(msg, "first");
  23420. }
  23421. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23422. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23423. "/ws-echo");
  23424. ASSERT_TRUE(client.connect());
  23425. // Setting it once the connection is open reaches the live stream, not just
  23426. // the seed for the next connect().
  23427. client.set_read_timeout(1, 0);
  23428. std::string msg;
  23429. EXPECT_EQ(client.read(msg), ws::Timeout);
  23430. EXPECT_TRUE(client.is_open());
  23431. }
  23432. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23434. "/ws-echo");
  23435. client.set_read_timeout(5, 0);
  23436. ASSERT_TRUE(client.connect());
  23437. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23438. // The server should reject it and close the connection.
  23439. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23440. client.send(oversized);
  23441. // The server's read() should have failed due to payload limit,
  23442. // so our read() should return false (connection closed).
  23443. std::string msg;
  23444. EXPECT_FALSE(client.read(msg));
  23445. }
  23446. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23447. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23448. "/ws-echo");
  23449. client.set_read_timeout(10, 0);
  23450. ASSERT_TRUE(client.connect());
  23451. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23452. // This should succeed.
  23453. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23454. ASSERT_TRUE(client.send(at_limit));
  23455. std::string msg;
  23456. ASSERT_TRUE(client.read(msg));
  23457. EXPECT_EQ(at_limit.size(), msg.size());
  23458. client.close();
  23459. }
  23460. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23461. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23462. "/nonexistent");
  23463. auto res = client.connect();
  23464. EXPECT_FALSE(res);
  23465. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23466. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23467. EXPECT_FALSE(client.is_open());
  23468. }
  23469. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23470. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23471. "/ws-echo");
  23472. ASSERT_TRUE(client.connect());
  23473. ASSERT_TRUE(client.send(""));
  23474. std::string msg;
  23475. EXPECT_EQ(ws::Text, client.read(msg));
  23476. EXPECT_EQ("", msg);
  23477. client.close();
  23478. }
  23479. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23480. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23481. "/ws-echo");
  23482. // First connection
  23483. ASSERT_TRUE(client.connect());
  23484. ASSERT_TRUE(client.send("first"));
  23485. std::string msg;
  23486. ASSERT_TRUE(client.read(msg));
  23487. EXPECT_EQ("first", msg);
  23488. client.close();
  23489. EXPECT_FALSE(client.is_open());
  23490. // Reconnect using the same client object
  23491. ASSERT_TRUE(client.connect());
  23492. ASSERT_TRUE(client.is_open());
  23493. ASSERT_TRUE(client.send("second"));
  23494. ASSERT_TRUE(client.read(msg));
  23495. EXPECT_EQ("second", msg);
  23496. client.close();
  23497. }
  23498. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23499. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23500. "/ws-close-status");
  23501. ASSERT_TRUE(client.connect());
  23502. // Trigger the server to close with GoingAway status
  23503. ASSERT_TRUE(client.send("trigger"));
  23504. // read() should return false after receiving the close frame
  23505. std::string msg;
  23506. EXPECT_FALSE(client.read(msg));
  23507. EXPECT_FALSE(client.is_open());
  23508. }
  23509. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23510. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23511. "/ws-echo");
  23512. ASSERT_TRUE(client.connect());
  23513. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23514. EXPECT_FALSE(client.is_open());
  23515. }
  23516. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23517. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23518. ws::WebSocketClient client(
  23519. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23520. ASSERT_TRUE(client.connect());
  23521. // Server should have selected graphql-ws
  23522. EXPECT_EQ("graphql-ws", client.subprotocol());
  23523. client.close();
  23524. }
  23525. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23526. Headers headers;
  23527. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23528. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23529. ws::WebSocketClient client(
  23530. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23531. ASSERT_TRUE(client.connect());
  23532. // The offer on the second field line counts too, so graphql-ws is selected
  23533. EXPECT_EQ("graphql-ws", client.subprotocol());
  23534. client.close();
  23535. }
  23536. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23537. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23538. ws::WebSocketClient client(
  23539. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23540. ASSERT_TRUE(client.connect());
  23541. // Server should not have selected any subprotocol
  23542. EXPECT_TRUE(client.subprotocol().empty());
  23543. client.close();
  23544. }
  23545. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23546. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23547. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23548. "/ws-subprotocol-unoffered",
  23549. headers);
  23550. ASSERT_TRUE(client.connect());
  23551. EXPECT_TRUE(client.subprotocol().empty());
  23552. client.close();
  23553. }
  23554. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23555. // Connect without requesting any subprotocol
  23556. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23557. "/ws-subprotocol");
  23558. ASSERT_TRUE(client.connect());
  23559. EXPECT_TRUE(client.subprotocol().empty());
  23560. client.close();
  23561. }
  23562. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23563. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23564. "/ws-echo");
  23565. client.set_tcp_nodelay(true);
  23566. client.set_connection_timeout(3, 0);
  23567. bool socket_options_called = false;
  23568. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23569. ASSERT_TRUE(client.connect());
  23570. ASSERT_TRUE(client.is_open());
  23571. EXPECT_TRUE(socket_options_called);
  23572. ASSERT_TRUE(client.send("hello"));
  23573. std::string msg;
  23574. auto result = client.read(msg);
  23575. EXPECT_EQ(result, ws::ReadResult::Text);
  23576. EXPECT_EQ(msg, "hello");
  23577. client.close();
  23578. }
  23579. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23580. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23581. "/ws-echo");
  23582. client.set_connection_timeout(std::chrono::seconds(3));
  23583. client.set_write_timeout(std::chrono::seconds(3));
  23584. // A sub-second remainder exercises the seconds/microseconds split.
  23585. client.set_read_timeout(std::chrono::milliseconds(1500));
  23586. ASSERT_TRUE(client.connect());
  23587. auto start = std::chrono::steady_clock::now();
  23588. std::string msg;
  23589. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23590. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23591. std::chrono::steady_clock::now() - start)
  23592. .count();
  23593. // Above 1s so that dropping the microseconds half of the split fails here.
  23594. // Ignoring the setter altogether would not reach this line at all: a client
  23595. // waits forever by default.
  23596. EXPECT_GE(elapsed, 1400);
  23597. EXPECT_LT(elapsed, 30000);
  23598. }
  23599. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23600. Server svr;
  23601. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23602. if (!req.has_header("Authorization")) {
  23603. res.status = StatusCode::Unauthorized_401;
  23604. res.set_content("Unauthorized", "text/plain");
  23605. return Server::HandlerResponse::Handled;
  23606. }
  23607. return Server::HandlerResponse::Unhandled;
  23608. });
  23609. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23610. std::string msg;
  23611. while (ws.read(msg)) {
  23612. ws.send(msg);
  23613. }
  23614. });
  23615. auto port = svr.bind_to_any_port("localhost");
  23616. std::thread t([&]() { svr.listen_after_bind(); });
  23617. svr.wait_until_ready();
  23618. // Without Authorization header - should be rejected before upgrade
  23619. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23620. EXPECT_FALSE(client1.connect());
  23621. // The rejection is framed like any other HTTP response
  23622. {
  23623. Client cli("localhost", port);
  23624. Headers headers = {{"Upgrade", "websocket"},
  23625. {"Connection", "Upgrade"},
  23626. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23627. {"Sec-WebSocket-Version", "13"}};
  23628. auto res = cli.Get("/ws", headers);
  23629. ASSERT_TRUE(res);
  23630. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23631. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23632. EXPECT_EQ("Unauthorized", res->body);
  23633. }
  23634. // With Authorization header - should succeed
  23635. Headers headers = {{"Authorization", "Bearer token123"}};
  23636. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23637. headers);
  23638. ASSERT_TRUE(client2.connect());
  23639. ASSERT_TRUE(client2.send("hello"));
  23640. std::string msg;
  23641. ASSERT_TRUE(client2.read(msg));
  23642. EXPECT_EQ("hello", msg);
  23643. client2.close();
  23644. svr.stop();
  23645. t.join();
  23646. }
  23647. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23648. Server svr;
  23649. std::atomic<int> pre_routing_calls{0};
  23650. std::atomic<int> pre_request_calls{0};
  23651. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23652. pre_routing_calls++;
  23653. if (req.path == "/handled") {
  23654. res.set_content("handled", "text/plain");
  23655. return Server::HandlerResponse::Handled;
  23656. }
  23657. return Server::HandlerResponse::Unhandled;
  23658. });
  23659. svr.set_pre_request_handler([&](const Request &, Response &) {
  23660. pre_request_calls++;
  23661. return Server::HandlerResponse::Unhandled;
  23662. });
  23663. svr.Get("/http", [](const Request &, Response &res) {
  23664. res.set_content("http", "text/plain");
  23665. });
  23666. svr.WebSocket("/ws",
  23667. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23668. auto port = svr.bind_to_any_port("localhost");
  23669. std::thread t([&]() { svr.listen_after_bind(); });
  23670. auto se = detail::scope_exit([&] {
  23671. svr.stop();
  23672. t.join();
  23673. });
  23674. svr.wait_until_ready();
  23675. Headers upgrade = {{"Upgrade", "websocket"},
  23676. {"Connection", "Upgrade"},
  23677. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23678. {"Sec-WebSocket-Version", "13"}};
  23679. auto get = [&](const char *path) {
  23680. pre_routing_calls = 0;
  23681. return Client("localhost", port).Get(path, upgrade);
  23682. };
  23683. // No WebSocket route, but an HTTP one
  23684. auto res = get("/http");
  23685. ASSERT_TRUE(res);
  23686. EXPECT_EQ(StatusCode::OK_200, res->status);
  23687. EXPECT_EQ("http", res->body);
  23688. EXPECT_EQ(1, pre_routing_calls);
  23689. EXPECT_EQ(1, pre_request_calls);
  23690. // No route at all
  23691. res = get("/none");
  23692. ASSERT_TRUE(res);
  23693. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23694. EXPECT_EQ(1, pre_routing_calls);
  23695. // Answered by the pre-routing handler
  23696. res = get("/handled");
  23697. ASSERT_TRUE(res);
  23698. EXPECT_EQ(StatusCode::OK_200, res->status);
  23699. EXPECT_EQ("handled", res->body);
  23700. EXPECT_EQ(1, pre_routing_calls);
  23701. // A WebSocket route
  23702. pre_routing_calls = 0;
  23703. pre_request_calls = 0;
  23704. {
  23705. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23706. "/ws");
  23707. ASSERT_TRUE(client.connect());
  23708. std::string msg;
  23709. ASSERT_TRUE(client.read(msg));
  23710. EXPECT_EQ("ws", msg);
  23711. client.close();
  23712. }
  23713. EXPECT_EQ(1, pre_routing_calls);
  23714. EXPECT_EQ(1, pre_request_calls);
  23715. }
  23716. // An upgrade request answered by a hook leaves its body unread, so that body
  23717. // must not be served as the next request on the connection.
  23718. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23719. Server svr;
  23720. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23721. if (req.path == "/pre-routing") {
  23722. res.set_content("pre-routing", "text/plain");
  23723. return Server::HandlerResponse::Handled;
  23724. }
  23725. return Server::HandlerResponse::Unhandled;
  23726. });
  23727. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23728. if (req.matched_route == "/pre-request") {
  23729. res.set_content("pre-request", "text/plain");
  23730. return Server::HandlerResponse::Handled;
  23731. }
  23732. return Server::HandlerResponse::Unhandled;
  23733. });
  23734. svr.Get("/smuggled", [](const Request &, Response &res) {
  23735. res.set_content("smuggled", "text/plain");
  23736. });
  23737. svr.WebSocket("/pre-request",
  23738. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23739. auto port = svr.bind_to_any_port(HOST);
  23740. std::thread t([&]() { svr.listen_after_bind(); });
  23741. auto se = detail::scope_exit([&] {
  23742. svr.stop();
  23743. t.join();
  23744. });
  23745. svr.wait_until_ready();
  23746. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23747. for (auto path : {"/pre-routing", "/pre-request"}) {
  23748. std::string req = std::string("GET ") + path +
  23749. " HTTP/1.1\r\n"
  23750. "Host: localhost\r\n"
  23751. "Upgrade: websocket\r\n"
  23752. "Connection: Upgrade\r\n"
  23753. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23754. "Sec-WebSocket-Version: 13\r\n"
  23755. "Content-Length: " +
  23756. std::to_string(body.size()) + "\r\n\r\n" + body;
  23757. std::string res;
  23758. ASSERT_TRUE(send_request(5, req, &res, port));
  23759. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23760. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23761. // Only one response, and the body was not served as a request
  23762. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23763. }
  23764. }
  23765. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23766. Server svr;
  23767. std::atomic<int> pre_request_calls{0};
  23768. std::atomic<bool> route_matched{false};
  23769. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23770. pre_request_calls++;
  23771. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23772. if (req.get_header_value("Authorization") != "Bearer token123") {
  23773. res.status = StatusCode::Unauthorized_401;
  23774. res.set_content("Unauthorized", "text/plain");
  23775. return Server::HandlerResponse::Handled;
  23776. }
  23777. return Server::HandlerResponse::Unhandled;
  23778. });
  23779. std::atomic<bool> handler_called{false};
  23780. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23781. handler_called = true;
  23782. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23783. });
  23784. auto port = svr.bind_to_any_port("localhost");
  23785. std::thread t([&]() { svr.listen_after_bind(); });
  23786. svr.wait_until_ready();
  23787. // Without Authorization header - should be rejected before upgrade
  23788. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23789. "/ws/1");
  23790. EXPECT_FALSE(client1.connect());
  23791. EXPECT_FALSE(handler_called);
  23792. EXPECT_EQ(1, pre_request_calls);
  23793. EXPECT_TRUE(route_matched);
  23794. // The rejection is an ordinary HTTP response, not a protocol switch
  23795. {
  23796. Client cli("localhost", port);
  23797. Headers headers = {{"Upgrade", "websocket"},
  23798. {"Connection", "Upgrade"},
  23799. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23800. {"Sec-WebSocket-Version", "13"}};
  23801. auto res = cli.Get("/ws/1", headers);
  23802. ASSERT_TRUE(res);
  23803. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23804. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23805. EXPECT_EQ("Unauthorized", res->body);
  23806. }
  23807. EXPECT_FALSE(handler_called);
  23808. // With Authorization header - should succeed
  23809. Headers headers = {{"Authorization", "Bearer token123"}};
  23810. ws::WebSocketClient client2(
  23811. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23812. ASSERT_TRUE(client2.connect());
  23813. std::string msg;
  23814. ASSERT_TRUE(client2.read(msg));
  23815. EXPECT_EQ("/ws/:id 2", msg);
  23816. EXPECT_TRUE(handler_called);
  23817. client2.close();
  23818. svr.stop();
  23819. t.join();
  23820. }
  23821. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  23822. static Headers websocket_upgrade_headers() {
  23823. return {{"Upgrade", "websocket"},
  23824. {"Connection", "Upgrade"},
  23825. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23826. {"Sec-WebSocket-Version", "13"},
  23827. {"Sec-WebSocket-Protocol", "chat"}};
  23828. }
  23829. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  23830. Server svr;
  23831. svr.set_pre_routing_handler([](const Request &req, Response &) {
  23832. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  23833. return Server::HandlerResponse::Unhandled;
  23834. });
  23835. svr.set_pre_request_handler([](const Request &req, Response &) {
  23836. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  23837. return Server::HandlerResponse::Unhandled;
  23838. });
  23839. svr.set_exception_handler(
  23840. [](const Request &, Response &res, std::exception_ptr ep) {
  23841. try {
  23842. std::rethrow_exception(ep);
  23843. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  23844. });
  23845. auto handler = [](const Request &, ws::WebSocket &) {};
  23846. svr.WebSocket("/pre-routing", handler);
  23847. svr.WebSocket("/pre-request", handler);
  23848. svr.WebSocket("/sub-protocol", handler,
  23849. [](const std::vector<std::string> &) -> std::string {
  23850. throw std::runtime_error("/sub-protocol");
  23851. });
  23852. auto port = svr.bind_to_any_port(HOST);
  23853. ASSERT_GT(port, 0);
  23854. thread t = thread([&] { svr.listen_after_bind(); });
  23855. auto se = detail::scope_exit([&] {
  23856. svr.stop();
  23857. t.join();
  23858. ASSERT_FALSE(svr.is_running());
  23859. });
  23860. svr.wait_until_ready();
  23861. Client cli(HOST, port);
  23862. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  23863. auto res = cli.Get(path, websocket_upgrade_headers());
  23864. if (!res) {
  23865. ADD_FAILURE() << path << ": " << to_string(res.error());
  23866. continue;
  23867. }
  23868. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  23869. EXPECT_EQ(path, res->body);
  23870. }
  23871. }
  23872. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  23873. Server svr;
  23874. svr.set_pre_routing_handler(
  23875. [](const Request &, Response &) -> Server::HandlerResponse {
  23876. throw std::runtime_error("pre-routing");
  23877. });
  23878. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23879. auto port = svr.bind_to_any_port(HOST);
  23880. ASSERT_GT(port, 0);
  23881. thread t = thread([&] { svr.listen_after_bind(); });
  23882. auto se = detail::scope_exit([&] {
  23883. svr.stop();
  23884. t.join();
  23885. ASSERT_FALSE(svr.is_running());
  23886. });
  23887. svr.wait_until_ready();
  23888. Client cli(HOST, port);
  23889. auto res = cli.Get("/ws", websocket_upgrade_headers());
  23890. ASSERT_TRUE(res) << to_string(res.error());
  23891. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  23892. }
  23893. #endif
  23894. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23895. Server svr;
  23896. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23897. // A read timeout is how a handler gets control back. Without it, a handler
  23898. // parked in read() can never write on the connection it is reading.
  23899. ws.set_read_timeout(std::chrono::milliseconds(100));
  23900. std::string msg;
  23901. while (ws.is_open()) {
  23902. auto r = ws.read(msg);
  23903. if (r == httplib::ws::Timeout) {
  23904. ws.send("tick");
  23905. continue;
  23906. }
  23907. if (r == httplib::ws::Fail) { break; }
  23908. ws.send(msg);
  23909. }
  23910. });
  23911. auto port = svr.bind_to_any_port("localhost");
  23912. std::thread t([&]() { svr.listen_after_bind(); });
  23913. svr.wait_until_ready();
  23914. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23915. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23916. ASSERT_TRUE(client.connect());
  23917. // The client sends nothing, so anything it receives came out of the
  23918. // handler's timeout path.
  23919. std::string msg;
  23920. ASSERT_EQ(client.read(msg), ws::Text);
  23921. EXPECT_EQ("tick", msg);
  23922. client.close();
  23923. svr.stop();
  23924. t.join();
  23925. }
  23926. // Stream::read may return fewer bytes than asked for. This is that contract at
  23927. // its worst -- one byte per call -- which is what a frame header straddling a
  23928. // read buffer's boundary looks like to the frame parser.
  23929. class WsByteAtATimeStream : public Stream {
  23930. public:
  23931. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23932. bool is_readable() const override { return true; }
  23933. bool wait_readable() const override { return true; }
  23934. bool wait_writable() const override { return true; }
  23935. ssize_t read(char *ptr, size_t size) override {
  23936. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23937. *ptr = data_[pos_++];
  23938. return 1;
  23939. }
  23940. ssize_t write(const char *, size_t size) override {
  23941. return static_cast<ssize_t>(size);
  23942. }
  23943. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23944. ip = "127.0.0.1";
  23945. port = 0;
  23946. }
  23947. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23948. ip = "127.0.0.1";
  23949. port = 0;
  23950. }
  23951. socket_t socket() const override { return INVALID_SOCKET; }
  23952. time_t duration() const override { return 0; }
  23953. private:
  23954. std::string data_;
  23955. size_t pos_ = 0;
  23956. };
  23957. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23958. // The payload uses the 16-bit extended length, so the header, the length
  23959. // and the mask key are all multi-byte fields here. Each used to be read
  23960. // with a single read() call, which fails as soon as one is split. The
  23961. // payload is also a little over one read chunk, so it is read in two.
  23962. std::string body;
  23963. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23964. body += static_cast<char>(i % 251);
  23965. }
  23966. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23967. std::string frame;
  23968. frame += static_cast<char>(0x81); // FIN + Text
  23969. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23970. frame += static_cast<char>(body.size() >> 8);
  23971. frame += static_cast<char>(body.size() & 0xff);
  23972. for (size_t i = 0; i < 4; i++) {
  23973. frame += static_cast<char>(mask[i]);
  23974. }
  23975. for (size_t i = 0; i < body.size(); i++) {
  23976. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23977. }
  23978. WsByteAtATimeStream strm(frame);
  23979. ws::Opcode opcode;
  23980. std::string payload;
  23981. bool fin = false;
  23982. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23983. /*expect_masked=*/true, body.size()),
  23984. ws::impl::FrameRead::Ok);
  23985. EXPECT_TRUE(fin);
  23986. EXPECT_EQ(opcode, ws::Opcode::Text);
  23987. EXPECT_EQ(payload, body);
  23988. }
  23989. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23990. std::string body(2000, 'x');
  23991. std::string frame;
  23992. frame += static_cast<char>(0x82); // FIN + Binary
  23993. frame += static_cast<char>(126); // 16-bit length follows
  23994. frame += static_cast<char>(body.size() >> 8);
  23995. frame += static_cast<char>(body.size() & 0xff);
  23996. frame += body;
  23997. detail::BufferStream strm;
  23998. strm.write(frame.data(), frame.size());
  23999. ws::Opcode opcode;
  24000. std::string payload;
  24001. bool fin;
  24002. EXPECT_EQ(
  24003. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24004. ws::impl::FrameRead::Ok);
  24005. EXPECT_EQ(body, payload);
  24006. }
  24007. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24008. // The header announces the largest payload allowed, and only 3 bytes of it
  24009. // ever arrive.
  24010. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24011. std::string frame;
  24012. frame += static_cast<char>(0x82); // FIN + Binary
  24013. frame += static_cast<char>(127); // 64-bit length follows
  24014. for (int shift = 56; shift >= 0; shift -= 8) {
  24015. frame += static_cast<char>((len >> shift) & 0xff);
  24016. }
  24017. frame += "abc";
  24018. detail::BufferStream strm;
  24019. strm.write(frame.data(), frame.size());
  24020. ws::Opcode opcode;
  24021. std::string payload;
  24022. bool fin;
  24023. EXPECT_EQ(
  24024. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24025. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24026. ws::impl::FrameRead::Fail);
  24027. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24028. }
  24029. TEST(WebSocketTest, QueryStringInHandshake) {
  24030. Server svr;
  24031. std::mutex mtx;
  24032. std::string received_target;
  24033. std::string received_token;
  24034. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24035. {
  24036. std::lock_guard<std::mutex> lock(mtx);
  24037. received_target = req.target;
  24038. if (req.has_param("token")) {
  24039. received_token = req.get_param_value("token");
  24040. }
  24041. }
  24042. std::string msg;
  24043. while (ws.read(msg)) {
  24044. ws.send(msg);
  24045. }
  24046. });
  24047. auto port = svr.bind_to_any_port("localhost");
  24048. std::thread t([&]() { svr.listen_after_bind(); });
  24049. svr.wait_until_ready();
  24050. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24051. "/ws?token=ABC&session=123");
  24052. ASSERT_TRUE(client.connect());
  24053. // Round-trip ensures the handler has run and captured the request.
  24054. ASSERT_TRUE(client.send("hello"));
  24055. std::string msg;
  24056. ASSERT_TRUE(client.read(msg));
  24057. EXPECT_EQ("hello", msg);
  24058. client.close();
  24059. {
  24060. std::lock_guard<std::mutex> lock(mtx);
  24061. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24062. EXPECT_EQ("ABC", received_token);
  24063. }
  24064. svr.stop();
  24065. t.join();
  24066. }
  24067. // Run a handshake against a throwaway server and hand the request the server
  24068. // received back to the caller, so tests can assert on the headers the client
  24069. // actually put on the wire.
  24070. static void capture_websocket_handshake_request(
  24071. const Headers &client_headers,
  24072. std::function<void(const Request &, int port)> verify) {
  24073. Server svr;
  24074. std::mutex mtx;
  24075. Request received;
  24076. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24077. {
  24078. std::lock_guard<std::mutex> lock(mtx);
  24079. received = req;
  24080. }
  24081. std::string msg;
  24082. while (ws.read(msg)) {
  24083. ws.send(msg);
  24084. }
  24085. });
  24086. auto port = svr.bind_to_any_port("localhost");
  24087. std::thread t([&]() { svr.listen_after_bind(); });
  24088. auto se = detail::scope_exit([&] {
  24089. svr.stop();
  24090. t.join();
  24091. });
  24092. svr.wait_until_ready();
  24093. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24094. client_headers);
  24095. ASSERT_TRUE(client.connect());
  24096. ASSERT_TRUE(client.send("hello"));
  24097. std::string msg;
  24098. ASSERT_TRUE(client.read(msg));
  24099. client.close();
  24100. {
  24101. std::lock_guard<std::mutex> lock(mtx);
  24102. verify(received, port);
  24103. }
  24104. }
  24105. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24106. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24107. // Non-default port must be present in the Host header. Default ports
  24108. // (80/443) are omitted; that logic is covered by
  24109. // MakeHostAndPortStringTest.
  24110. EXPECT_EQ("localhost:" + std::to_string(port),
  24111. req.get_header_value("Host"));
  24112. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24113. req.get_header_value("User-Agent"));
  24114. EXPECT_FALSE(req.has_header("Accept"));
  24115. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24116. EXPECT_FALSE(req.has_header("Content-Length"));
  24117. });
  24118. }
  24119. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24120. capture_websocket_handshake_request(
  24121. {{"Host", "example.com"},
  24122. {"User-Agent", "custom-agent"},
  24123. {"X-Custom", "value"}},
  24124. [](const Request &req, int) {
  24125. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24126. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24127. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24128. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24129. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24130. });
  24131. }
  24132. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24133. capture_websocket_handshake_request(
  24134. {{"Upgrade", "bogus"},
  24135. {"Connection", "close"},
  24136. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24137. {"Sec-WebSocket-Version", "8"}},
  24138. [](const Request &req, int) {
  24139. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24140. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24141. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24142. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24143. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24144. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24145. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24146. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24147. req.get_header_value("Sec-WebSocket-Key"));
  24148. });
  24149. }
  24150. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24151. // A header the client refuses to send must abort the handshake before any
  24152. // part of it reaches the wire; a lone request line would otherwise sit in
  24153. // the peer's buffer as a truncated request.
  24154. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24155. ASSERT_NE(INVALID_SOCKET, srv);
  24156. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24157. sockaddr_in addr{};
  24158. addr.sin_family = AF_INET;
  24159. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24160. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24161. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24162. ASSERT_EQ(0, ::listen(srv, 1));
  24163. sockaddr_in bound{};
  24164. socklen_t bound_len = sizeof(bound);
  24165. ASSERT_EQ(
  24166. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24167. auto port = ntohs(bound.sin_port);
  24168. ssize_t received = -1;
  24169. std::thread t([&] {
  24170. // Bound every blocking call so a regression fails the test with a bad
  24171. // value instead of hanging the suite.
  24172. fd_set rfds;
  24173. FD_ZERO(&rfds);
  24174. FD_SET(srv, &rfds);
  24175. timeval tv{5, 0};
  24176. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24177. 0) {
  24178. return;
  24179. }
  24180. sockaddr_in cli_addr{};
  24181. socklen_t cli_len = sizeof(cli_addr);
  24182. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24183. if (cli == INVALID_SOCKET) { return; }
  24184. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24185. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24186. char buf[4096];
  24187. received = ::recv(cli, buf, sizeof(buf), 0);
  24188. });
  24189. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24190. // connect() has already shut the socket down by the time it returns false,
  24191. // so the peer sees EOF without waiting for the client to be destroyed.
  24192. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24193. {{"X-Bad", "a\r\nInjected: 1"}});
  24194. EXPECT_FALSE(client.connect());
  24195. t.join();
  24196. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24197. EXPECT_EQ(0, received);
  24198. }
  24199. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24200. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24201. // contains "upgrade" as a substring is a different token and must not
  24202. // start a WebSocket handshake.
  24203. auto make_request = [](const std::vector<std::string> &connection_values) {
  24204. Request req;
  24205. req.method = "GET";
  24206. req.headers.emplace("Upgrade", "websocket");
  24207. for (const auto &value : connection_values) {
  24208. req.headers.emplace("Connection", value);
  24209. }
  24210. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24211. req.headers.emplace("Sec-WebSocket-Version", "13");
  24212. return req;
  24213. };
  24214. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24215. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24216. EXPECT_TRUE(
  24217. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24218. EXPECT_TRUE(
  24219. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24220. EXPECT_TRUE(
  24221. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24222. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24223. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24224. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24225. EXPECT_FALSE(
  24226. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24227. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24228. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24229. }
  24230. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24231. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24232. // asks recipients to match each protocol-name case-insensitively, and RFC
  24233. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24234. // client naming websocket alongside another protocol, or on a second field
  24235. // line, is offering websocket; a value that merely contains "websocket" as a
  24236. // substring is a different protocol name and is not.
  24237. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24238. Request req;
  24239. req.method = "GET";
  24240. for (const auto &value : upgrade_values) {
  24241. req.headers.emplace("Upgrade", value);
  24242. }
  24243. req.headers.emplace("Connection", "Upgrade");
  24244. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24245. req.headers.emplace("Sec-WebSocket-Version", "13");
  24246. return req;
  24247. };
  24248. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24249. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24250. EXPECT_TRUE(
  24251. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24252. EXPECT_TRUE(
  24253. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24254. EXPECT_TRUE(
  24255. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24256. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24257. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24258. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24259. EXPECT_FALSE(
  24260. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24261. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24262. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24263. }
  24264. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24265. Server svr;
  24266. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24267. auto port = svr.bind_to_any_port("localhost");
  24268. std::thread t([&]() { svr.listen_after_bind(); });
  24269. auto se = detail::scope_exit([&] {
  24270. svr.stop();
  24271. t.join();
  24272. });
  24273. svr.wait_until_ready();
  24274. Headers headers = {{"Upgrade", "websocket"},
  24275. {"Connection", "notupgrade"},
  24276. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24277. {"Sec-WebSocket-Version", "13"}};
  24278. Client cli("localhost", port);
  24279. auto res = cli.Get("/ws", headers);
  24280. // The route exists only as a WebSocket route, so a request that fails the
  24281. // handshake check falls through to ordinary routing.
  24282. ASSERT_TRUE(res);
  24283. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24284. }
  24285. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24286. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24287. // Connection value is the only thing left for the client to reject.
  24288. Server svr;
  24289. svr.Get("/ws", [](const Request &req, Response &res) {
  24290. res.status = StatusCode::SwitchingProtocol_101;
  24291. res.set_header("Upgrade", "websocket");
  24292. res.set_header("Connection", "notupgrade");
  24293. res.set_header("Sec-WebSocket-Accept",
  24294. detail::websocket_accept_key(
  24295. req.get_header_value("Sec-WebSocket-Key")));
  24296. });
  24297. auto port = svr.bind_to_any_port("localhost");
  24298. std::thread t([&]() { svr.listen_after_bind(); });
  24299. auto se = detail::scope_exit([&] {
  24300. svr.stop();
  24301. t.join();
  24302. });
  24303. svr.wait_until_ready();
  24304. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24305. auto res = client.connect();
  24306. EXPECT_FALSE(res);
  24307. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24308. EXPECT_FALSE(client.is_open());
  24309. }
  24310. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24311. Server svr;
  24312. svr.Get("/ws", [](const Request &req, Response &res) {
  24313. res.status = StatusCode::SwitchingProtocol_101;
  24314. res.set_header("Upgrade", "websocket");
  24315. res.set_header("Connection", "Upgrade");
  24316. res.set_header("Sec-WebSocket-Accept",
  24317. detail::websocket_accept_key(
  24318. req.get_header_value("Sec-WebSocket-Key")));
  24319. res.set_header("Sec-WebSocket-Protocol", "admin");
  24320. });
  24321. auto port = svr.bind_to_any_port("localhost");
  24322. std::thread t([&]() { svr.listen_after_bind(); });
  24323. auto se = detail::scope_exit([&] {
  24324. svr.stop();
  24325. t.join();
  24326. });
  24327. svr.wait_until_ready();
  24328. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24329. // Server selects a subprotocol the client never offered
  24330. {
  24331. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24332. ws::WebSocketClient client(url, headers);
  24333. auto res = client.connect();
  24334. EXPECT_FALSE(res);
  24335. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24336. EXPECT_FALSE(client.is_open());
  24337. EXPECT_TRUE(client.subprotocol().empty());
  24338. }
  24339. // Client offered none but the server named one anyway
  24340. {
  24341. ws::WebSocketClient client(url);
  24342. auto res = client.connect();
  24343. EXPECT_FALSE(res);
  24344. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24345. EXPECT_FALSE(client.is_open());
  24346. EXPECT_TRUE(client.subprotocol().empty());
  24347. }
  24348. }
  24349. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24350. // The socket path doubles as the URL host, so it must not contain '/'.
  24351. const char *shard = getenv("GTEST_SHARD_INDEX");
  24352. const std::string sock_path =
  24353. shard ? std::string("httplib-ws-") + shard + ".sock"
  24354. : std::string("httplib-ws.sock");
  24355. std::remove(sock_path.c_str());
  24356. Server svr;
  24357. std::mutex mtx;
  24358. std::string received_host;
  24359. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24360. {
  24361. std::lock_guard<std::mutex> lock(mtx);
  24362. received_host = req.get_header_value("Host");
  24363. }
  24364. std::string msg;
  24365. while (ws.read(msg)) {
  24366. ws.send(msg);
  24367. }
  24368. });
  24369. svr.set_address_family(AF_UNIX);
  24370. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24371. auto se = detail::scope_exit([&] {
  24372. svr.stop();
  24373. t.join();
  24374. std::remove(sock_path.c_str());
  24375. });
  24376. svr.wait_until_ready();
  24377. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24378. client.set_address_family(AF_UNIX);
  24379. ASSERT_TRUE(client.connect());
  24380. ASSERT_TRUE(client.send("hello"));
  24381. std::string msg;
  24382. ASSERT_TRUE(client.read(msg));
  24383. client.close();
  24384. {
  24385. std::lock_guard<std::mutex> lock(mtx);
  24386. // There is no host:port for a Unix socket, so the same "localhost"
  24387. // placeholder the HTTP client uses is expected.
  24388. EXPECT_EQ("localhost", received_host);
  24389. }
  24390. }
  24391. // Two threads must never parse WebSocket frames from the same stream.
  24392. // close() used to read the peer's Close reply with its own frame read, so it
  24393. // raced a reader thread that was in the middle of a payload: the payload loop
  24394. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24395. // so bytes taken by close() were replaced with bytes from further along the
  24396. // stream. The message kept its length and silently changed content.
  24397. //
  24398. // The raw peer below sends a frame header plus part of the payload, waits for
  24399. // the handler to call close(), and only then sends the rest. Whichever thread
  24400. // would win the race for those bytes, the message must arrive intact, because
  24401. // close() must not touch the stream while read() owns it.
  24402. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24403. #ifndef _WIN32
  24404. signal(SIGPIPE, SIG_IGN);
  24405. #endif
  24406. const size_t payload_len = 120; // fits the 7-bit length field
  24407. const size_t prefix_len = 8;
  24408. const int attempts = 8;
  24409. std::string expected(payload_len, '\0');
  24410. for (size_t i = 0; i < payload_len; i++) {
  24411. expected[i] = static_cast<char>('a' + i % 26);
  24412. }
  24413. std::atomic<bool> peer_stalled{false};
  24414. std::atomic<bool> handler_done{false};
  24415. std::mutex received_mutex;
  24416. std::vector<std::string> received;
  24417. // Bound every wait, so a regression fails the test instead of hanging the
  24418. // suite.
  24419. auto wait_for = [](const std::atomic<bool> &flag) {
  24420. for (int i = 0; i < 500 && !flag; i++) {
  24421. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24422. }
  24423. };
  24424. Server svr;
  24425. svr.set_websocket_ping_interval(0);
  24426. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24427. std::thread reader([&]() {
  24428. std::string msg;
  24429. while (ws.read(msg)) {
  24430. std::lock_guard<std::mutex> guard(received_mutex);
  24431. received.push_back(msg);
  24432. }
  24433. });
  24434. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24435. // inside read_websocket_frame() when close() runs.
  24436. wait_for(peer_stalled);
  24437. ws.close();
  24438. reader.join();
  24439. handler_done = true;
  24440. });
  24441. auto port = svr.bind_to_any_port("127.0.0.1");
  24442. std::thread t([&]() { svr.listen_after_bind(); });
  24443. auto se = detail::scope_exit([&] {
  24444. svr.stop();
  24445. t.join();
  24446. });
  24447. svr.wait_until_ready();
  24448. auto send_bytes = [](socket_t s, const std::string &data) {
  24449. #ifdef _WIN32
  24450. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24451. #else
  24452. auto n = ::send(s, data.data(), data.size(), 0);
  24453. #endif
  24454. return n == static_cast<decltype(n)>(data.size());
  24455. };
  24456. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24457. // Every length used here fits the 7-bit length field.
  24458. auto masked_header = [](uint8_t first_byte, size_t len) {
  24459. std::string h;
  24460. h += static_cast<char>(first_byte);
  24461. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24462. h.append(4, '\0'); // mask key
  24463. return h;
  24464. };
  24465. for (int attempt = 0; attempt < attempts; attempt++) {
  24466. peer_stalled = false;
  24467. handler_done = false;
  24468. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24469. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24470. auto se_sock = detail::scope_exit([&] {
  24471. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24472. });
  24473. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24474. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24475. sockaddr_in addr{};
  24476. addr.sin_family = AF_INET;
  24477. addr.sin_port = htons(static_cast<uint16_t>(port));
  24478. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24479. ASSERT_EQ(
  24480. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24481. << "attempt " << attempt;
  24482. ASSERT_TRUE(send_bytes(sock,
  24483. "GET /ws HTTP/1.1\r\n"
  24484. "Host: 127.0.0.1\r\n"
  24485. "Upgrade: websocket\r\n"
  24486. "Connection: Upgrade\r\n"
  24487. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24488. "Sec-WebSocket-Version: 13\r\n"
  24489. "\r\n"))
  24490. << "attempt " << attempt;
  24491. std::string response;
  24492. while (response.find("\r\n\r\n") == std::string::npos) {
  24493. char buf[512];
  24494. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24495. if (n <= 0) { break; }
  24496. response.append(buf, static_cast<size_t>(n));
  24497. }
  24498. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24499. << "attempt " << attempt;
  24500. // Send the header of a Binary message but only the first prefix_len bytes
  24501. // of its payload, leaving the reader thread stalled inside the payload.
  24502. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24503. expected.substr(0, prefix_len)))
  24504. << "attempt " << attempt;
  24505. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24506. peer_stalled = true;
  24507. // Let close() send its Close frame and park in its own read before the
  24508. // rest of the payload arrives, so both threads are waiting for it.
  24509. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24510. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24511. close_frame += static_cast<char>(0x03); // status 1000
  24512. close_frame += static_cast<char>(0xE8);
  24513. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24514. << "attempt " << attempt;
  24515. // Closing the peer releases the reader thread even on the buggy path,
  24516. // where it waits for bytes another thread already consumed.
  24517. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24518. detail::close_socket(sock);
  24519. sock = INVALID_SOCKET;
  24520. wait_for(handler_done);
  24521. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24522. }
  24523. std::lock_guard<std::mutex> guard(received_mutex);
  24524. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24525. << "a message in flight when close() ran was dropped";
  24526. for (size_t i = 0; i < received.size(); i++) {
  24527. EXPECT_EQ(expected, received[i]) << "message " << i;
  24528. }
  24529. }
  24530. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24531. // returning the socket, or INVALID_SOCKET.
  24532. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24533. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24534. if (sock == INVALID_SOCKET) { return sock; }
  24535. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24536. sockaddr_in addr{};
  24537. addr.sin_family = AF_INET;
  24538. addr.sin_port = htons(static_cast<uint16_t>(port));
  24539. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24540. std::string req = "GET " + path +
  24541. " HTTP/1.1\r\n"
  24542. "Host: 127.0.0.1\r\n"
  24543. "Upgrade: websocket\r\n"
  24544. "Connection: Upgrade\r\n"
  24545. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24546. "Sec-WebSocket-Version: 13\r\n"
  24547. "\r\n";
  24548. std::string res;
  24549. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24550. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24551. static_cast<ssize_t>(req.size())) {
  24552. char c;
  24553. while (res.find("\r\n\r\n") == std::string::npos &&
  24554. ::recv(sock, &c, 1, 0) == 1) {
  24555. res += c;
  24556. }
  24557. }
  24558. if (res.find(" 101 ") == std::string::npos) {
  24559. detail::close_socket(sock);
  24560. return INVALID_SOCKET;
  24561. }
  24562. return sock;
  24563. }
  24564. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24565. // The payload must fit the 7-bit length field.
  24566. static std::string masked_frame(uint8_t first_byte,
  24567. const std::string &payload) {
  24568. std::string f;
  24569. f += static_cast<char>(first_byte);
  24570. f += static_cast<char>(0x80 | payload.size());
  24571. f.append(4, '\0');
  24572. return f + payload;
  24573. }
  24574. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24575. std::atomic<bool> done{false};
  24576. std::string received;
  24577. Server svr;
  24578. svr.set_websocket_ping_interval(0);
  24579. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24580. std::string msg;
  24581. if (ws.read(msg) == ws::Binary) { received = msg; }
  24582. done = true;
  24583. });
  24584. auto port = svr.bind_to_any_port("127.0.0.1");
  24585. std::thread t([&]() { svr.listen_after_bind(); });
  24586. auto se = detail::scope_exit([&] {
  24587. svr.stop();
  24588. t.join();
  24589. });
  24590. svr.wait_until_ready();
  24591. auto sock = connect_raw_websocket(port, "/ws");
  24592. ASSERT_NE(INVALID_SOCKET, sock);
  24593. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24594. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24595. masked_frame(0x89, "p") + // FIN + Ping
  24596. masked_frame(0x80, "lo"); // FIN + Continuation
  24597. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24598. for (int i = 0; i < 500 && !done; i++) {
  24599. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24600. }
  24601. ASSERT_TRUE(done);
  24602. EXPECT_EQ("Hello", received);
  24603. // The Ping between the fragments is answered with a Pong.
  24604. char pong[3];
  24605. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24606. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24607. }
  24608. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24609. Server svr;
  24610. svr.set_websocket_ping_interval(-1);
  24611. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24612. std::string msg;
  24613. while (ws.read(msg)) {}
  24614. });
  24615. auto port = svr.bind_to_any_port("127.0.0.1");
  24616. std::thread t([&]() { svr.listen_after_bind(); });
  24617. auto se = detail::scope_exit([&] {
  24618. svr.stop();
  24619. t.join();
  24620. });
  24621. svr.wait_until_ready();
  24622. auto sock = connect_raw_websocket(port, "/ws");
  24623. ASSERT_NE(INVALID_SOCKET, sock);
  24624. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24625. // Nothing comes while the client stays quiet.
  24626. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24627. char c;
  24628. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24629. }
  24630. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24631. // and that has to end a read() already waiting on the peer, on every platform.
  24632. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24633. // The peer sends no pings, and its handler never calls read(), which is
  24634. // where pongs are written.
  24635. std::mutex mutex;
  24636. std::condition_variable cv;
  24637. auto release = false;
  24638. svr.set_websocket_ping_interval(0);
  24639. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24640. std::unique_lock<std::mutex> lock(mutex);
  24641. cv.wait(lock, [&] { return release; });
  24642. });
  24643. auto port = svr.bind_to_any_port(HOST);
  24644. std::thread t([&]() { svr.listen_after_bind(); });
  24645. auto se = detail::scope_exit([&] {
  24646. {
  24647. std::lock_guard<std::mutex> lock(mutex);
  24648. release = true;
  24649. }
  24650. cv.notify_all();
  24651. svr.stop();
  24652. t.join();
  24653. });
  24654. svr.wait_until_ready();
  24655. ws::WebSocketClient client(std::string(scheme) +
  24656. "://localhost:" + std::to_string(port) + "/ws");
  24657. #ifdef CPPHTTPLIB_SSL_ENABLED
  24658. client.enable_server_certificate_verification(false);
  24659. #endif
  24660. // A ping a second, given up on after two go unanswered: about 3s
  24661. client.set_websocket_ping_interval(1);
  24662. client.set_websocket_max_missed_pongs(2);
  24663. // Well past that, so that a read the timeout ends instead stands out
  24664. client.set_read_timeout(10);
  24665. ASSERT_TRUE(client.connect());
  24666. auto start = std::chrono::steady_clock::now();
  24667. std::string msg;
  24668. EXPECT_EQ(ws::Fail, client.read(msg));
  24669. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24670. std::chrono::steady_clock::now() - start)
  24671. .count(),
  24672. 6000);
  24673. EXPECT_FALSE(client.is_open());
  24674. }
  24675. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24676. Server svr;
  24677. check_pong_timeout_ends_read(svr, "ws");
  24678. }
  24679. #ifdef CPPHTTPLIB_SSL_ENABLED
  24680. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24682. ASSERT_TRUE(svr.is_valid());
  24683. check_pong_timeout_ends_read(svr, "wss");
  24684. }
  24685. #endif
  24686. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24687. Server svr;
  24688. svr.set_websocket_ping_interval(0);
  24689. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24690. std::string msg;
  24691. while (ws.read(msg)) {}
  24692. });
  24693. auto port = svr.bind_to_any_port("127.0.0.1");
  24694. std::thread t([&]() { svr.listen_after_bind(); });
  24695. auto se = detail::scope_exit([&] {
  24696. svr.stop();
  24697. t.join();
  24698. });
  24699. svr.wait_until_ready();
  24700. // Each Close payload and the reply it should get: an echo when valid, 1002
  24701. // otherwise.
  24702. std::vector<std::pair<std::string, std::string>> cases = {
  24703. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24704. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24705. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24706. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24707. };
  24708. // Also between the fragments of a message.
  24709. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24710. for (const auto &c : cases) {
  24711. auto sock = connect_raw_websocket(port, "/ws");
  24712. ASSERT_NE(INVALID_SOCKET, sock);
  24713. auto frames = prefix + masked_frame(0x88, c.first);
  24714. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24715. std::string reply;
  24716. char buf[256];
  24717. while (reply.size() < 2 + c.second.size()) {
  24718. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24719. if (n <= 0) { break; }
  24720. reply.append(buf, static_cast<size_t>(n));
  24721. }
  24722. detail::close_socket(sock);
  24723. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24724. c.second,
  24725. reply);
  24726. }
  24727. }
  24728. }
  24729. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24730. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24731. protected:
  24732. void SetUp() override {
  24733. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24734. SERVER_PRIVATE_KEY_FILE);
  24735. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24736. std::string msg;
  24737. ws::ReadResult ret;
  24738. while ((ret = ws.read(msg))) {
  24739. if (ret == ws::Binary) {
  24740. ws.send(msg.data(), msg.size());
  24741. } else {
  24742. ws.send(msg);
  24743. }
  24744. }
  24745. });
  24746. port_ = server_->bind_to_any_port(HOST);
  24747. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24748. server_->wait_until_ready();
  24749. }
  24750. void TearDown() override {
  24751. server_->stop();
  24752. if (server_thread_.joinable()) { server_thread_.join(); }
  24753. }
  24754. std::unique_ptr<SSLServer> server_;
  24755. std::thread server_thread_;
  24756. int port_ = 0;
  24757. };
  24758. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24759. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24760. {
  24761. ws::WebSocketClient client(url);
  24762. client.enable_server_certificate_verification(false);
  24763. auto calls = 0;
  24764. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24765. calls++;
  24766. return false;
  24767. });
  24768. EXPECT_FALSE(client.connect());
  24769. EXPECT_GT(calls, 0);
  24770. }
  24771. {
  24772. ws::WebSocketClient client(url);
  24773. client.enable_server_certificate_verification(false);
  24774. client.set_session_verifier([](tls::session_t) {
  24775. return SSLVerifierResponse::CertificateRejected;
  24776. });
  24777. EXPECT_FALSE(client.connect());
  24778. }
  24779. {
  24780. ws::WebSocketClient client(url);
  24781. client.enable_server_certificate_verification(false);
  24782. client.set_session_verifier([](tls::session_t) {
  24783. return SSLVerifierResponse::CertificateAccepted;
  24784. });
  24785. EXPECT_TRUE(client.connect());
  24786. }
  24787. }
  24788. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24789. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24790. "/ws-echo");
  24791. client.enable_server_certificate_verification(false);
  24792. ASSERT_TRUE(client.connect());
  24793. ASSERT_TRUE(client.is_open());
  24794. ASSERT_TRUE(client.send("Hello WSS"));
  24795. std::string msg;
  24796. EXPECT_EQ(ws::Text, client.read(msg));
  24797. EXPECT_EQ("Hello WSS", msg);
  24798. client.close();
  24799. }
  24800. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24801. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24802. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24803. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24804. // client (without calling close() first) is the only path that runs
  24805. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24806. // bug exactly.
  24807. //
  24808. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24809. // when linked against an instrumented libssl; run under Valgrind to catch it
  24810. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24811. // suite (the freed session otherwise stalls on the close handshake) — this test
  24812. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24813. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24814. {
  24815. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24816. "/ws-echo");
  24817. client.enable_server_certificate_verification(false);
  24818. client.set_read_timeout(2, 0);
  24819. client.set_write_timeout(2, 0);
  24820. ASSERT_TRUE(client.connect());
  24821. ASSERT_TRUE(client.is_open());
  24822. ASSERT_TRUE(client.send("still open"));
  24823. // Intentionally do NOT call client.close(): leaving scope runs
  24824. // shutdown_and_close() with the WebSocket still open, which must send the
  24825. // close frame while the TLS session is still alive.
  24826. }
  24827. }
  24828. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24829. // shutdown_and_close() at the start of connect(), reproducing the same
  24830. // use-after-free within the test body rather than at scope exit. The second
  24831. // connect must succeed and echo, proving the close handshake ran over a live
  24832. // session. See the note above about memory-tool requirements.
  24833. TEST_F(WebSocketSSLIntegrationTest,
  24834. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24835. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24836. "/ws-echo");
  24837. client.enable_server_certificate_verification(false);
  24838. client.set_read_timeout(2, 0);
  24839. client.set_write_timeout(2, 0);
  24840. ASSERT_TRUE(client.connect());
  24841. ASSERT_TRUE(client.is_open());
  24842. ASSERT_TRUE(client.send("still open"));
  24843. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24844. // the still-open connection, which must not touch a freed TLS session.
  24845. ASSERT_TRUE(client.connect());
  24846. ASSERT_TRUE(client.is_open());
  24847. ASSERT_TRUE(client.send("after reconnect"));
  24848. std::string msg;
  24849. EXPECT_EQ(ws::Text, client.read(msg));
  24850. EXPECT_EQ("after reconnect", msg);
  24851. client.close();
  24852. }
  24853. #endif
  24854. #ifdef CPPHTTPLIB_SSL_ENABLED
  24855. class WebSocketSSLCATest : public ::testing::Test {
  24856. protected:
  24857. void SetUp() override {
  24858. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24859. SERVER_PRIVATE_KEY_FILE);
  24860. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24861. std::string msg;
  24862. while (ws.read(msg)) {
  24863. ws.send(msg);
  24864. }
  24865. });
  24866. port_ = server_->bind_to_any_port("127.0.0.1");
  24867. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24868. server_->wait_until_ready();
  24869. }
  24870. void TearDown() override {
  24871. server_->stop();
  24872. if (server_thread_.joinable()) { server_thread_.join(); }
  24873. }
  24874. std::string url() const {
  24875. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24876. }
  24877. std::unique_ptr<SSLServer> server_;
  24878. std::thread server_thread_;
  24879. int port_ = 0;
  24880. };
  24881. // A custom CA loaded as PEM verifies the server with full certificate
  24882. // verification enabled
  24883. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24884. ws::WebSocketClient client(url());
  24885. std::string cert;
  24886. read_file(SERVER_CERT2_FILE, cert);
  24887. client.load_ca_cert_store(cert.c_str(), cert.size());
  24888. ASSERT_TRUE(client.connect());
  24889. ASSERT_TRUE(client.send("hello"));
  24890. std::string msg;
  24891. EXPECT_EQ(ws::Text, client.read(msg));
  24892. EXPECT_EQ("hello", msg);
  24893. client.close();
  24894. }
  24895. // A custom CA that does not cover the server must fail verification (the
  24896. // custom CA is exclusive; system certs are not loaded alongside it)
  24897. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24898. ws::WebSocketClient client(url());
  24899. std::string cert;
  24900. read_file(CLIENT_CA_CERT_FILE, cert);
  24901. client.load_ca_cert_store(cert.c_str(), cert.size());
  24902. auto res = client.connect();
  24903. ASSERT_FALSE(res);
  24904. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24905. EXPECT_EQ(-1, res.status());
  24906. EXPECT_NE(0u, res.ssl_backend_error());
  24907. }
  24908. // The same CA as a file path rather than PEM in memory
  24909. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24910. ws::WebSocketClient client(url());
  24911. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24912. ASSERT_TRUE(client.connect());
  24913. ASSERT_TRUE(client.send("hello"));
  24914. std::string msg;
  24915. EXPECT_EQ(ws::Text, client.read(msg));
  24916. EXPECT_EQ("hello", msg);
  24917. client.close();
  24918. }
  24919. // ...and a CA file that does not cover the server still fails, so it is the
  24920. // path above that decides the outcome
  24921. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24922. ws::WebSocketClient client(url());
  24923. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24924. ASSERT_FALSE(client.connect());
  24925. }
  24926. // Regression test: reconnecting with a native custom CA store used to reuse
  24927. // a store handle the previous TLS context had already freed (use-after-free
  24928. // under the OpenSSL backend). The context now lives as long as the client.
  24929. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24930. ws::WebSocketClient client(url());
  24931. std::string cert;
  24932. read_file(SERVER_CERT2_FILE, cert);
  24933. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24934. ASSERT_TRUE(client.connect());
  24935. client.close();
  24936. ASSERT_TRUE(client.connect());
  24937. ASSERT_TRUE(client.send("again"));
  24938. std::string msg;
  24939. EXPECT_EQ(ws::Text, client.read(msg));
  24940. EXPECT_EQ("again", msg);
  24941. client.close();
  24942. }
  24943. // Regression test: a certificate with a trusted chain but no identity match
  24944. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24945. // verification entirely for IP hosts, so this connection succeeded there.
  24946. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24947. // chain verification while the identity check must still fail.
  24948. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24949. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24950. ASSERT_TRUE(svr.is_valid());
  24951. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24952. std::string msg;
  24953. while (ws.read(msg)) {
  24954. ws.send(msg);
  24955. }
  24956. });
  24957. auto port = svr.bind_to_any_port("127.0.0.1");
  24958. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24959. auto se = detail::scope_exit([&] {
  24960. svr.stop();
  24961. t.join();
  24962. });
  24963. svr.wait_until_ready();
  24964. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24965. "/echo");
  24966. std::string cert;
  24967. read_file(SERVER_CERT_FILE, cert);
  24968. client.load_ca_cert_store(cert.c_str(), cert.size());
  24969. ASSERT_FALSE(client.connect());
  24970. }
  24971. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24972. // SNI, so nothing binds the host name to the TLS session. These bind the
  24973. // server to "localhost" instead, the only shape that exercises the SNI and
  24974. // hostname-verification path with certificate verification left enabled.
  24975. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24976. protected:
  24977. void Start(const char *cert_file) {
  24978. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24979. SERVER_PRIVATE_KEY_FILE);
  24980. ASSERT_TRUE(server_->is_valid());
  24981. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24982. std::string msg;
  24983. while (ws.read(msg)) {
  24984. ws.send(msg);
  24985. }
  24986. });
  24987. port_ = server_->bind_to_any_port("localhost");
  24988. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24989. server_->wait_until_ready();
  24990. }
  24991. void TearDown() override {
  24992. if (server_) { server_->stop(); }
  24993. if (server_thread_.joinable()) { server_thread_.join(); }
  24994. }
  24995. std::string url() const {
  24996. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24997. }
  24998. std::unique_ptr<SSLServer> server_;
  24999. std::thread server_thread_;
  25000. int port_ = 0;
  25001. };
  25002. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25003. // out and the connection is usable
  25004. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25005. Start(SERVER_CERT2_FILE);
  25006. ws::WebSocketClient client(url());
  25007. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25008. ASSERT_TRUE(client.connect());
  25009. ASSERT_TRUE(client.send("hello"));
  25010. std::string msg;
  25011. EXPECT_EQ(ws::Text, client.read(msg));
  25012. EXPECT_EQ("hello", msg);
  25013. client.close();
  25014. }
  25015. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25016. // while the identity check must still reject "localhost"
  25017. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25018. Start(SERVER_CERT_FILE);
  25019. ws::WebSocketClient client(url());
  25020. client.set_ca_cert_path(SERVER_CERT_FILE);
  25021. auto res = client.connect();
  25022. ASSERT_FALSE(res);
  25023. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25024. EXPECT_EQ(-1, res.status());
  25025. }
  25026. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25027. // disabled: the chain is still checked, only the identity check is skipped
  25028. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25029. Start(SERVER_CERT_FILE);
  25030. ws::WebSocketClient client(url());
  25031. client.set_ca_cert_path(SERVER_CERT_FILE);
  25032. client.enable_server_hostname_verification(false);
  25033. ASSERT_TRUE(client.connect());
  25034. ASSERT_TRUE(client.send("hello"));
  25035. std::string msg;
  25036. EXPECT_EQ(ws::Text, client.read(msg));
  25037. EXPECT_EQ("hello", msg);
  25038. client.close();
  25039. }
  25040. // A CA that did not sign the server certificate fails the chain, even though
  25041. // the name would match
  25042. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25043. Start(SERVER_CERT2_FILE);
  25044. ws::WebSocketClient client(url());
  25045. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25046. ASSERT_FALSE(client.connect());
  25047. }
  25048. // With verification disabled, neither the chain nor the name is checked
  25049. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25050. Start(SERVER_CERT_FILE);
  25051. ws::WebSocketClient client(url());
  25052. client.enable_server_certificate_verification(false);
  25053. ASSERT_TRUE(client.connect());
  25054. ASSERT_TRUE(client.send("hello"));
  25055. std::string msg;
  25056. EXPECT_EQ(ws::Text, client.read(msg));
  25057. EXPECT_EQ("hello", msg);
  25058. client.close();
  25059. }
  25060. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25061. protected:
  25062. void SetUp() override {
  25063. server_ = httplib::detail::make_unique<SSLServer>(
  25064. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25065. ASSERT_TRUE(server_->is_valid());
  25066. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25067. std::string msg;
  25068. while (ws.read(msg)) {
  25069. ws.send(msg);
  25070. }
  25071. });
  25072. port_ = server_->bind_to_any_port("localhost");
  25073. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25074. server_->wait_until_ready();
  25075. }
  25076. void TearDown() override {
  25077. server_->stop();
  25078. if (server_thread_.joinable()) { server_thread_.join(); }
  25079. }
  25080. std::string url() const {
  25081. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25082. }
  25083. void ConnectWithClientCert(const std::string &client_cert_file,
  25084. const std::string &client_private_key_file,
  25085. const char *private_key_password) {
  25086. std::string cert_pem, key_pem;
  25087. read_file(client_cert_file, cert_pem);
  25088. read_file(client_private_key_file, key_pem);
  25089. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25090. key_pem.c_str(), key_pem.size(),
  25091. private_key_password};
  25092. ConnectWithPem(pem);
  25093. }
  25094. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25095. ws::WebSocketClient client(url(), pem);
  25096. ASSERT_TRUE(client.is_valid());
  25097. client.enable_server_certificate_verification(false);
  25098. ASSERT_TRUE(client.connect());
  25099. ASSERT_TRUE(client.send("hello"));
  25100. std::string msg;
  25101. EXPECT_EQ(ws::Text, client.read(msg));
  25102. EXPECT_EQ("hello", msg);
  25103. client.close();
  25104. }
  25105. std::unique_ptr<SSLServer> server_;
  25106. std::thread server_thread_;
  25107. int port_ = 0;
  25108. };
  25109. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25110. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25111. }
  25112. // Control for the tests above: the fixture's server really does require a
  25113. // client certificate, so it is the PEM the constructor installed that decides
  25114. // the outcome.
  25115. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25116. ws::WebSocketClient client(url());
  25117. ASSERT_TRUE(client.is_valid());
  25118. client.enable_server_certificate_verification(false);
  25119. EXPECT_FALSE(client.connect());
  25120. }
  25121. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25122. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25123. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25124. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25125. }
  25126. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25127. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25128. std::string cert_pem, key_pem;
  25129. read_file(CLIENT_CERT_FILE, cert_pem);
  25130. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25131. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25132. std::vector<char> key(key_pem.begin(), key_pem.end());
  25133. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25134. key.size(), nullptr};
  25135. ConnectWithPem(pem);
  25136. }
  25137. #endif
  25138. #if !defined(_WIN32)
  25139. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25140. auto secret_dir = std::string("./symlink_test_secret");
  25141. auto served_dir = std::string("./symlink_test_served");
  25142. auto secret_file = secret_dir + "/secret.txt";
  25143. auto symlink_path = served_dir + "/escape";
  25144. // Setup: create directories and files
  25145. mkdir(secret_dir.c_str(), 0755);
  25146. mkdir(served_dir.c_str(), 0755);
  25147. {
  25148. std::ofstream ofs(secret_file);
  25149. ofs << "SECRET_DATA";
  25150. }
  25151. // Create symlink using absolute path so it resolves correctly
  25152. #ifdef PATH_MAX
  25153. char abs_secret[PATH_MAX];
  25154. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25155. #else
  25156. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25157. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25158. ASSERT_NE(nullptr, abs_secret);
  25159. #endif
  25160. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25161. auto se = detail::scope_exit([&] {
  25162. unlink(symlink_path.c_str());
  25163. unlink(secret_file.c_str());
  25164. rmdir(served_dir.c_str());
  25165. rmdir(secret_dir.c_str());
  25166. });
  25167. Server svr;
  25168. svr.set_mount_point("/", served_dir);
  25169. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25170. auto se2 = detail::scope_exit([&] {
  25171. svr.stop();
  25172. listen_thread.join();
  25173. });
  25174. svr.wait_until_ready();
  25175. Client cli("localhost", PORT);
  25176. // Symlink pointing outside base dir should be blocked
  25177. auto res = cli.Get("/escape/secret.txt");
  25178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25179. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25180. }
  25181. #endif
  25182. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25183. // "GET /smuggled" request), reads the first response, and only then sends the
  25184. // embedded request as the body. Returns how many times /smuggled ran.
  25185. //
  25186. // The body is sent AFTER receiving the first response (as in the original
  25187. // PoC) so that the stream_line_reader cannot buffer it together with the
  25188. // headers of the first request.
  25189. static int count_smuggled_requests(const std::string &outer_head,
  25190. std::string &first_response) {
  25191. Server svr;
  25192. svr.set_mount_point("/", "./www");
  25193. std::atomic<int> smuggled_count(0);
  25194. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25195. smuggled_count++;
  25196. res.set_content("oops", "text/plain");
  25197. });
  25198. svr.Post("/post", [&](const Request &req, Response &res) {
  25199. res.set_content(req.body, "text/plain");
  25200. });
  25201. auto port = svr.bind_to_any_port("localhost");
  25202. thread t = thread([&] { svr.listen_after_bind(); });
  25203. auto se = detail::scope_exit([&] {
  25204. svr.stop();
  25205. t.join();
  25206. });
  25207. svr.wait_until_ready();
  25208. auto error = Error::Success;
  25209. auto sock = detail::create_client_socket(
  25210. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25211. /*connection_timeout_sec=*/2, 0,
  25212. /*read_timeout_sec=*/2, 0,
  25213. /*write_timeout_sec=*/2, 0, std::string(), error);
  25214. EXPECT_NE(INVALID_SOCKET, sock);
  25215. if (sock == INVALID_SOCKET) { return -1; }
  25216. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25217. // The "smuggled" request will be sent as the body of the outer request
  25218. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25219. "Host: localhost\r\n"
  25220. "Connection: close\r\n"
  25221. "\r\n";
  25222. auto head = outer_head;
  25223. auto len = std::to_string(smuggled.size());
  25224. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25225. pos = head.find("{len}", pos + len.size())) {
  25226. head.replace(pos, 5, len);
  25227. }
  25228. // Step 1: Send only the outer request headers (no body yet)
  25229. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25230. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25231. // Step 2: Read the first response
  25232. char buf[4096];
  25233. for (;;) {
  25234. auto n = recv(sock, buf, sizeof(buf), 0);
  25235. if (n <= 0) break;
  25236. first_response.append(buf, static_cast<size_t>(n));
  25237. // Stop once we have a complete response (headers + body)
  25238. auto hdr_end = first_response.find("\r\n\r\n");
  25239. if (hdr_end != std::string::npos) {
  25240. // Check for Content-Length to know when the body is complete
  25241. auto cl_pos = first_response.find("Content-Length:");
  25242. if (cl_pos != std::string::npos) {
  25243. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25244. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25245. auto cl = std::stoul(
  25246. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25247. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25248. } else {
  25249. break; // No Content-Length, assume headers-only response
  25250. }
  25251. }
  25252. }
  25253. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25254. // vulnerable server the keep-alive loop reads this as a second request. The
  25255. // server may already have closed the connection, so the result is ignored.
  25256. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25257. // Half-close so that a server which drained the body sees EOF and closes,
  25258. // instead of the read below waiting for the read timeout.
  25259. #ifdef _WIN32
  25260. ::shutdown(sock, SD_SEND);
  25261. #else
  25262. ::shutdown(sock, SHUT_WR);
  25263. #endif
  25264. // Step 4: Read until the server closes the connection
  25265. for (;;) {
  25266. auto n = recv(sock, buf, sizeof(buf), 0);
  25267. if (n <= 0) break;
  25268. }
  25269. return smuggled_count.load();
  25270. }
  25271. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25272. // A GET request with Content-Length to a static file handler must have its
  25273. // body drained before the keep-alive connection is reused. Otherwise the
  25274. // unread body bytes are interpreted as the next HTTP request.
  25275. std::string first_response;
  25276. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25277. "Host: localhost\r\n"
  25278. "Content-Length: {len}\r\n"
  25279. "\r\n",
  25280. first_response));
  25281. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25282. }
  25283. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25284. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25285. // be answered with 400 and the connection closed. Treating it as "no body"
  25286. // leaves the body to be parsed as the next request.
  25287. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25288. const char *targets[] = {
  25289. "GET /file", // handler that never reads the body
  25290. "GET /not-found", // no handler matches (404)
  25291. "POST /post", // handler that reads the body
  25292. };
  25293. for (auto target : targets) {
  25294. for (auto value : values) {
  25295. std::string first_response;
  25296. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25297. " HTTP/1.1\r\n"
  25298. "Host: localhost\r\n"
  25299. "Content-Length: " +
  25300. value + "\r\n\r\n",
  25301. first_response))
  25302. << target << " with Content-Length: " << value;
  25303. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25304. << target << " with Content-Length: " << value;
  25305. }
  25306. }
  25307. }
  25308. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25309. // A 400 for an unparseable request line leaves the rest of the message
  25310. // unread, so the connection must be closed rather than reused.
  25311. std::string first_response;
  25312. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25313. "Host: localhost\r\n"
  25314. "Content-Length: {len}\r\n"
  25315. "\r\n",
  25316. first_response));
  25317. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25318. }
  25319. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25320. // Same as above for a header block that fails to parse.
  25321. std::string first_response;
  25322. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25323. "Host: localhost\r\n"
  25324. "Bad Header\r\n"
  25325. "Content-Length: {len}\r\n"
  25326. "\r\n",
  25327. first_response));
  25328. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25329. }
  25330. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25331. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25332. // server must not read another request on that connection, even when the
  25333. // request had no body to drain.
  25334. std::string first_response;
  25335. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25336. "Host: localhost\r\n"
  25337. "\r\n",
  25338. first_response));
  25339. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25340. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25341. }
  25342. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25343. // A content reader that stops early leaves the stream inside the body.
  25344. // Draining the whole Content-Length from there, or reading the body again,
  25345. // reads into the next request, and whatever follows is parsed as a request
  25346. // of its own.
  25347. Server svr;
  25348. std::atomic<int> smuggled_count(0);
  25349. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25350. svr.Post("/upload", [](const Request &req, Response &res,
  25351. const ContentReader &content_reader) {
  25352. // Stop at the last chunk, so the whole body has been read however it
  25353. // arrives.
  25354. auto length = req.get_header_value_u64("Content-Length");
  25355. size_t total = 0;
  25356. auto consumed = content_reader([&](const char *, size_t n) {
  25357. total += n;
  25358. return total < length;
  25359. });
  25360. EXPECT_FALSE(consumed);
  25361. if (req.has_param("retry")) {
  25362. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25363. }
  25364. // Replace the 400 the aborted read set, which would close the connection.
  25365. res.set_redirect("/done");
  25366. });
  25367. auto port = svr.bind_to_any_port(HOST);
  25368. thread t = thread([&] { svr.listen_after_bind(); });
  25369. auto se = detail::scope_exit([&] {
  25370. svr.stop();
  25371. t.join();
  25372. });
  25373. svr.wait_until_ready();
  25374. // A front end sees the second request as a POST whose body is the GET. The
  25375. // first body is as long as the POST's headers, so draining it again reads
  25376. // exactly those and leaves the GET to be parsed next.
  25377. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25378. "Host: localhost\r\n"
  25379. "\r\n";
  25380. std::string second_head = "POST /post HTTP/1.1\r\n"
  25381. "Host: localhost\r\n"
  25382. "Content-Length: " +
  25383. std::to_string(inner.size()) +
  25384. "\r\n"
  25385. "\r\n";
  25386. for (auto target : {"/upload", "/upload?retry"}) {
  25387. smuggled_count = 0;
  25388. std::string request = "POST " + std::string(target) +
  25389. " HTTP/1.1\r\n"
  25390. "Host: localhost\r\n"
  25391. "Content-Length: " +
  25392. std::to_string(second_head.size()) +
  25393. "\r\n"
  25394. "\r\n" +
  25395. std::string(second_head.size(), 'A') + second_head +
  25396. inner;
  25397. std::string response;
  25398. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25399. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25400. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25401. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25402. EXPECT_EQ(0, smuggled_count.load()) << target;
  25403. }
  25404. }
  25405. // An error response closes the connection anyway, so the body is left unread
  25406. // with a redirect, such as one to a login page.
  25407. static void serve_redirects(Server &svr,
  25408. const std::function<void(int)> &client) {
  25409. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25410. res.set_redirect("/login");
  25411. return Server::HandlerResponse::Handled;
  25412. });
  25413. auto port = svr.bind_to_any_port(HOST);
  25414. ASSERT_GT(port, 0);
  25415. thread t = thread([&] { svr.listen_after_bind(); });
  25416. auto se = detail::scope_exit([&] {
  25417. svr.stop();
  25418. t.join();
  25419. ASSERT_FALSE(svr.is_running());
  25420. });
  25421. svr.wait_until_ready();
  25422. client(port);
  25423. }
  25424. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25425. Server svr;
  25426. serve_redirects(svr, [](int port) {
  25427. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25428. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25429. std::to_string(body.size()) + "\r\n\r\n" + body +
  25430. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25431. std::string resp;
  25432. ASSERT_TRUE(send_request(1, req, &resp, port));
  25433. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25434. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25435. });
  25436. }
  25437. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25438. Server svr;
  25439. svr.set_read_timeout(0, 200000);
  25440. serve_redirects(svr, [](int port) {
  25441. // A byte every 100 ms keeps each read within the read timeout, but not the
  25442. // body as a whole, so the server closes and the bytes sent after that fail.
  25443. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25444. "Content-Length: 10\r\n\r\n"};
  25445. parts.resize(11, "x");
  25446. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25447. });
  25448. }
  25449. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25450. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25451. // must be rejected with 400 Bad Request.
  25452. Server svr;
  25453. svr.Post("/test", [&](const Request &, Response &res) {
  25454. res.set_content("ok", "text/plain");
  25455. });
  25456. thread t = thread([&] { svr.listen(HOST, PORT); });
  25457. auto se = detail::scope_exit([&] {
  25458. svr.stop();
  25459. t.join();
  25460. ASSERT_FALSE(svr.is_running());
  25461. });
  25462. svr.wait_until_ready();
  25463. // Exact "chunked"
  25464. {
  25465. auto req = "POST /test HTTP/1.1\r\n"
  25466. "Host: localhost\r\n"
  25467. "Content-Length: 5\r\n"
  25468. "Transfer-Encoding: chunked\r\n"
  25469. "Connection: close\r\n"
  25470. "\r\n"
  25471. "hello";
  25472. std::string response;
  25473. ASSERT_TRUE(send_request(1, req, &response));
  25474. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25475. response.substr(0, response.find("\r\n")));
  25476. }
  25477. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25478. {
  25479. auto req = "POST /test HTTP/1.1\r\n"
  25480. "Host: localhost\r\n"
  25481. "Content-Length: 5\r\n"
  25482. "Transfer-Encoding: gzip, chunked\r\n"
  25483. "Connection: close\r\n"
  25484. "\r\n"
  25485. "hello";
  25486. std::string response;
  25487. ASSERT_TRUE(send_request(1, req, &response));
  25488. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25489. response.substr(0, response.find("\r\n")));
  25490. }
  25491. }
  25492. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25493. Server svr;
  25494. svr.Post("/test", [&](const Request &, Response &res) {
  25495. res.set_content("ok", "text/plain");
  25496. });
  25497. thread t = thread([&] { svr.listen(HOST, PORT); });
  25498. auto se = detail::scope_exit([&] {
  25499. svr.stop();
  25500. t.join();
  25501. ASSERT_FALSE(svr.is_running());
  25502. });
  25503. svr.wait_until_ready();
  25504. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25505. // length cannot be determined, so the server must answer 400 and close
  25506. // rather than treat the request as bodyless and leave the body in the
  25507. // socket for the next request to pick up.
  25508. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25509. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25510. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25511. std::string response;
  25512. ASSERT_TRUE(send_request(1, req, &response));
  25513. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25514. response.substr(0, response.find("\r\n")))
  25515. << transfer_encoding;
  25516. }
  25517. // RFC 9110 5.3: the codings may also be split across several
  25518. // Transfer-Encoding lines, which combine in the order they were received.
  25519. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25520. // just like the single-line "chunked, gzip" above.
  25521. {
  25522. auto req = "POST /test HTTP/1.1\r\n"
  25523. "Host: localhost\r\n"
  25524. "Transfer-Encoding: chunked\r\n"
  25525. "Transfer-Encoding: gzip\r\n"
  25526. "\r\n"
  25527. "0\r\n\r\n";
  25528. std::string response;
  25529. ASSERT_TRUE(send_request(1, req, &response));
  25530. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25531. response.substr(0, response.find("\r\n")));
  25532. }
  25533. }
  25534. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25535. Server svr;
  25536. svr.Post("/test", [&](const Request &, Response &res) {
  25537. res.set_content("ok", "text/plain");
  25538. });
  25539. auto port = svr.bind_to_any_port(HOST);
  25540. ASSERT_GT(port, 0);
  25541. thread t = thread([&] { svr.listen_after_bind(); });
  25542. auto se = detail::scope_exit([&] {
  25543. svr.stop();
  25544. t.join();
  25545. ASSERT_FALSE(svr.is_running());
  25546. });
  25547. svr.wait_until_ready();
  25548. for (auto transfer_encoding :
  25549. {"Transfer-Encoding: gzip, chunked\r\n",
  25550. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25551. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25552. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25553. transfer_encoding + "\r\n0\r\n\r\n";
  25554. std::string response;
  25555. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25556. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25557. response.substr(0, response.find("\r\n")))
  25558. << transfer_encoding;
  25559. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25560. << transfer_encoding;
  25561. }
  25562. }
  25563. // Regression for issue #2450: a DELETE without Content-Length on a
  25564. // keep-alive connection must not let the post-response drain consume the
  25565. // next request's bytes.
  25566. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25567. Server svr;
  25568. std::atomic<int> delete_count(0);
  25569. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25570. delete_count++;
  25571. res.status = StatusCode::NoContent_204;
  25572. });
  25573. auto port = svr.bind_to_any_port(HOST);
  25574. thread t = thread([&] { svr.listen_after_bind(); });
  25575. auto se = detail::scope_exit([&] {
  25576. svr.stop();
  25577. t.join();
  25578. });
  25579. svr.wait_until_ready();
  25580. auto error = Error::Success;
  25581. auto sock = detail::create_client_socket(
  25582. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25583. /*connection_timeout_sec=*/2, 0,
  25584. /*read_timeout_sec=*/2, 0,
  25585. /*write_timeout_sec=*/2, 0, std::string(), error);
  25586. ASSERT_NE(INVALID_SOCKET, sock);
  25587. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25588. auto send_request_and_read_response = [&](const std::string &req,
  25589. std::string &out) -> bool {
  25590. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25591. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25592. char buf[4096];
  25593. for (;;) {
  25594. auto n = recv(sock, buf, sizeof(buf), 0);
  25595. if (n <= 0) { return !out.empty(); }
  25596. out.append(buf, static_cast<size_t>(n));
  25597. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25598. }
  25599. };
  25600. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25601. "Host: localhost\r\n"
  25602. "\r\n";
  25603. std::string resp1;
  25604. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25605. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25606. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25607. "Host: localhost\r\n"
  25608. "Connection: close\r\n"
  25609. "\r\n";
  25610. std::string resp2;
  25611. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25612. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25613. EXPECT_EQ(2, delete_count.load());
  25614. }
  25615. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25616. Server svr;
  25617. svr.Post("/ingest", [&](const Request &, Response &res,
  25618. const ContentReader &content_reader) {
  25619. auto consumed = content_reader([](const char *, size_t) { return false; });
  25620. EXPECT_FALSE(consumed);
  25621. res.status = StatusCode::Conflict_409;
  25622. res.set_header("Connection", "close");
  25623. });
  25624. auto port = svr.bind_to_any_port(HOST);
  25625. thread t = thread([&] { svr.listen_after_bind(); });
  25626. auto se = detail::scope_exit([&] {
  25627. svr.stop();
  25628. t.join();
  25629. });
  25630. svr.wait_until_ready();
  25631. auto error = Error::Success;
  25632. auto sock = detail::create_client_socket(
  25633. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25634. /*connection_timeout_sec=*/2, 0,
  25635. /*read_timeout_sec=*/1, 0,
  25636. /*write_timeout_sec=*/2, 0, std::string(), error);
  25637. ASSERT_NE(INVALID_SOCKET, sock);
  25638. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25639. std::string request = "POST /ingest HTTP/1.1\r\n"
  25640. "Host: localhost\r\n"
  25641. "Transfer-Encoding: chunked\r\n"
  25642. "\r\n"
  25643. "4\r\n"
  25644. "data\r\n";
  25645. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25646. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25647. std::string response;
  25648. ssize_t received = 0;
  25649. do {
  25650. char buf[4096];
  25651. received = recv(sock, buf, sizeof(buf), 0);
  25652. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25653. } while (received > 0);
  25654. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25655. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25656. EXPECT_EQ(0, received);
  25657. }
  25658. namespace no_proxy_test {
  25659. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25660. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25661. // calling listen().
  25662. class ScopedServer {
  25663. public:
  25664. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25665. ~ScopedServer() {
  25666. svr_.stop();
  25667. if (th_.joinable()) { th_.join(); }
  25668. }
  25669. Server &svr() { return svr_; }
  25670. int port() const { return port_; }
  25671. void listen() {
  25672. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25673. svr_.wait_until_ready();
  25674. }
  25675. private:
  25676. Server svr_;
  25677. std::thread th_;
  25678. int port_ = 0;
  25679. };
  25680. class ProxyAndTargetServers {
  25681. public:
  25682. ProxyAndTargetServers() {
  25683. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25684. proxy_hits_++;
  25685. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25686. res.set_content("via-proxy", "text/plain");
  25687. });
  25688. target_.Get(".*", [this](const Request &req, Response &res) {
  25689. target_hits_++;
  25690. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25691. res.set_content("direct", "text/plain");
  25692. });
  25693. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25694. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25695. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25696. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25697. proxy_mock_.wait_until_ready();
  25698. target_.wait_until_ready();
  25699. }
  25700. ~ProxyAndTargetServers() {
  25701. proxy_mock_.stop();
  25702. target_.stop();
  25703. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25704. if (target_thread_.joinable()) { target_thread_.join(); }
  25705. }
  25706. Server &proxy_mock() { return proxy_mock_; }
  25707. Server &target() { return target_; }
  25708. int proxy_port() const { return proxy_port_; }
  25709. int target_port() const { return target_port_; }
  25710. int proxy_hits() const { return proxy_hits_.load(); }
  25711. int target_hits() const { return target_hits_.load(); }
  25712. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25713. void reset_counters() {
  25714. proxy_hits_ = 0;
  25715. target_hits_ = 0;
  25716. last_had_proxy_authz_ = false;
  25717. }
  25718. private:
  25719. Server proxy_mock_;
  25720. Server target_;
  25721. std::thread proxy_thread_;
  25722. std::thread target_thread_;
  25723. int proxy_port_ = 0;
  25724. int target_port_ = 0;
  25725. std::atomic<int> proxy_hits_{0};
  25726. std::atomic<int> target_hits_{0};
  25727. std::atomic<bool> last_had_proxy_authz_{false};
  25728. };
  25729. inline std::unique_ptr<Client> make_client(const std::string &host,
  25730. ProxyAndTargetServers &s) {
  25731. auto cli = detail::make_unique<Client>(host, s.target_port());
  25732. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25733. cli->set_proxy("127.0.0.1", s.proxy_port());
  25734. return cli;
  25735. }
  25736. } // namespace no_proxy_test
  25737. using no_proxy_test::make_client;
  25738. using no_proxy_test::ProxyAndTargetServers;
  25739. // A stream request carries the credentials a buffered request does
  25740. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25741. no_proxy_test::ScopedServer origin;
  25742. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25743. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25744. });
  25745. origin.listen();
  25746. Client cli("127.0.0.1", origin.port());
  25747. cli.set_basic_auth("user", "pass");
  25748. auto handle = cli.open_stream("GET", "/x");
  25749. ASSERT_TRUE(handle.is_valid());
  25750. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25751. Client bearer("127.0.0.1", origin.port());
  25752. bearer.set_bearer_token_auth("tok");
  25753. auto handle2 = bearer.open_stream("GET", "/x");
  25754. ASSERT_TRUE(handle2.is_valid());
  25755. EXPECT_EQ("Bearer tok", read_all(handle2));
  25756. }
  25757. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25758. // takes its own credentials, as for a buffered request
  25759. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25760. std::string target, authz, proxy_authz;
  25761. no_proxy_test::ScopedServer proxy;
  25762. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25763. target = req.target;
  25764. authz = req.get_header_value("Authorization");
  25765. proxy_authz = req.get_header_value("Proxy-Authorization");
  25766. res.set_content("ok", "text/plain");
  25767. });
  25768. proxy.listen();
  25769. Client cli("origin.example", 8080);
  25770. cli.set_proxy("127.0.0.1", proxy.port());
  25771. cli.set_proxy_basic_auth("puser", "ppass");
  25772. cli.set_basic_auth("user", "pass");
  25773. auto handle = cli.open_stream("GET", "/x");
  25774. ASSERT_TRUE(handle.is_valid());
  25775. EXPECT_EQ("ok", read_all(handle));
  25776. EXPECT_EQ("http://origin.example:8080/x", target);
  25777. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25778. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25779. }
  25780. // In absolute-form the path follows the authority, so a path that does not
  25781. // begin with '/' would make the proxy connect to another host
  25782. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  25783. std::vector<std::string> targets;
  25784. no_proxy_test::ScopedServer proxy;
  25785. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25786. targets.push_back(req.target);
  25787. res.set_content("ok", "text/plain");
  25788. });
  25789. proxy.listen();
  25790. Client cli("origin.example", 8080);
  25791. cli.set_proxy("127.0.0.1", proxy.port());
  25792. cli.set_basic_auth("user", "pass");
  25793. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  25794. auto res = cli.Get(path);
  25795. EXPECT_FALSE(res) << path;
  25796. auto handle = cli.open_stream("GET", path);
  25797. EXPECT_FALSE(handle.is_valid()) << path;
  25798. }
  25799. EXPECT_TRUE(targets.empty());
  25800. auto res = cli.Get("/x");
  25801. ASSERT_TRUE(res);
  25802. ASSERT_EQ(1u, targets.size());
  25803. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  25804. }
  25805. TEST(NoProxyTest, ExactHostnameBypasses) {
  25806. ProxyAndTargetServers s;
  25807. auto cli = make_client("example.com", s);
  25808. cli->set_no_proxy({"example.com"});
  25809. auto res = cli->Get("/");
  25810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25811. EXPECT_EQ(0, s.proxy_hits());
  25812. EXPECT_EQ(1, s.target_hits());
  25813. }
  25814. TEST(NoProxyTest, SubdomainBypasses) {
  25815. ProxyAndTargetServers s;
  25816. auto cli = make_client("foo.example.com", s);
  25817. cli->set_no_proxy({"example.com"});
  25818. auto res = cli->Get("/");
  25819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25820. EXPECT_EQ(0, s.proxy_hits());
  25821. EXPECT_EQ(1, s.target_hits());
  25822. }
  25823. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25824. // Regression guard: "evilexample.com" must not be considered a subdomain
  25825. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25826. // check would let traffic bypass the proxy and leak credentials direct
  25827. // to the attacker host.
  25828. ProxyAndTargetServers s;
  25829. auto cli = make_client("evilexample.com", s);
  25830. cli->set_no_proxy({"example.com"});
  25831. auto res = cli->Get("/");
  25832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25833. EXPECT_GE(s.proxy_hits(), 1);
  25834. EXPECT_EQ(0, s.target_hits());
  25835. }
  25836. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25837. ProxyAndTargetServers s;
  25838. auto cli = make_client("example.com.evil.com", s);
  25839. cli->set_no_proxy({"example.com"});
  25840. auto res = cli->Get("/");
  25841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25842. EXPECT_GE(s.proxy_hits(), 1);
  25843. EXPECT_EQ(0, s.target_hits());
  25844. }
  25845. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25846. ProxyAndTargetServers s;
  25847. auto cli = make_client("example.com", s);
  25848. cli->set_no_proxy({".example.com"});
  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, CaseInsensitiveHostname) {
  25855. ProxyAndTargetServers s;
  25856. auto cli = make_client("Example.COM", s);
  25857. cli->set_no_proxy({"EXAMPLE.com"});
  25858. auto res = cli->Get("/");
  25859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25860. EXPECT_EQ(0, s.proxy_hits());
  25861. EXPECT_EQ(1, s.target_hits());
  25862. }
  25863. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25864. ProxyAndTargetServers s;
  25865. auto cli = make_client("example.com.", s);
  25866. cli->set_no_proxy({"example.com"});
  25867. auto res = cli->Get("/");
  25868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25869. EXPECT_EQ(0, s.proxy_hits());
  25870. EXPECT_EQ(1, s.target_hits());
  25871. }
  25872. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25873. // Trailing dots must be normalized on BOTH sides — host and entry.
  25874. // An implementation that only strips the host-side trailing dot would
  25875. // fail to match host "example.com" against entry "example.com." because
  25876. // a literal substring search would compare 11 chars against 12.
  25877. ProxyAndTargetServers s;
  25878. auto cli = make_client("example.com", s);
  25879. cli->set_no_proxy({"example.com."});
  25880. auto res = cli->Get("/");
  25881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25882. EXPECT_EQ(0, s.proxy_hits());
  25883. EXPECT_EQ(1, s.target_hits());
  25884. }
  25885. TEST(NoProxyTest, WildcardBypassesEverything) {
  25886. ProxyAndTargetServers s;
  25887. auto cli = make_client("anything.invalid.test", s);
  25888. cli->set_no_proxy({"*"});
  25889. auto res = cli->Get("/");
  25890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25891. EXPECT_EQ(0, s.proxy_hits());
  25892. EXPECT_EQ(1, s.target_hits());
  25893. }
  25894. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25895. ProxyAndTargetServers s;
  25896. Client cli("127.0.0.1", s.target_port());
  25897. cli.set_proxy("127.0.0.1", s.proxy_port());
  25898. cli.set_no_proxy({"127.0.0.1"});
  25899. auto res = cli.Get("/");
  25900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25901. EXPECT_EQ(0, s.proxy_hits());
  25902. EXPECT_EQ(1, s.target_hits());
  25903. }
  25904. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25905. ProxyAndTargetServers s;
  25906. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25907. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25908. cli.set_proxy("127.0.0.1", s.proxy_port());
  25909. cli.set_no_proxy({"::1"});
  25910. auto res = cli.Get("/");
  25911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25912. EXPECT_EQ(0, s.proxy_hits());
  25913. EXPECT_EQ(1, s.target_hits());
  25914. }
  25915. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25916. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25917. // must still be recognized as IPv6 for CIDR matching. Implementations
  25918. // that detect IPv6 only when the host begins with '[' would parse the
  25919. // host as a hostname and miss the match.
  25920. ProxyAndTargetServers s;
  25921. Client cli("fe80::1", s.target_port());
  25922. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25923. cli.set_proxy("127.0.0.1", s.proxy_port());
  25924. cli.set_no_proxy({"fe80::/10"});
  25925. auto res = cli.Get("/");
  25926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25927. EXPECT_EQ(0, s.proxy_hits());
  25928. EXPECT_EQ(1, s.target_hits());
  25929. }
  25930. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25931. ProxyAndTargetServers s;
  25932. Client cli("::1", s.target_port());
  25933. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25934. cli.set_proxy("127.0.0.1", s.proxy_port());
  25935. cli.set_no_proxy({"[::1]"});
  25936. auto res = cli.Get("/");
  25937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25938. EXPECT_EQ(0, s.proxy_hits());
  25939. EXPECT_EQ(1, s.target_hits());
  25940. }
  25941. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25942. ProxyAndTargetServers s;
  25943. Client cli("fe80::1", s.target_port());
  25944. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25945. cli.set_proxy("127.0.0.1", s.proxy_port());
  25946. cli.set_no_proxy({"[fe80::]/10"});
  25947. auto res = cli.Get("/");
  25948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25949. EXPECT_EQ(0, s.proxy_hits());
  25950. EXPECT_EQ(1, s.target_hits());
  25951. }
  25952. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25953. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25954. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25955. // tricks via address-family conversion.
  25956. ProxyAndTargetServers s;
  25957. Client cli("::ffff:127.0.0.1", s.target_port());
  25958. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25959. cli.set_proxy("127.0.0.1", s.proxy_port());
  25960. cli.set_no_proxy({"127.0.0.1"});
  25961. auto res = cli.Get("/");
  25962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25963. EXPECT_GE(s.proxy_hits(), 1);
  25964. EXPECT_EQ(0, s.target_hits());
  25965. }
  25966. TEST(NoProxyTest, IPv4CidrMatch) {
  25967. ProxyAndTargetServers s;
  25968. Client cli("127.0.0.1", s.target_port());
  25969. cli.set_proxy("127.0.0.1", s.proxy_port());
  25970. cli.set_no_proxy({"127.0.0.0/8"});
  25971. auto res = cli.Get("/");
  25972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25973. EXPECT_EQ(0, s.proxy_hits());
  25974. EXPECT_EQ(1, s.target_hits());
  25975. }
  25976. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25977. ProxyAndTargetServers s;
  25978. Client cli("127.0.0.1", s.target_port());
  25979. cli.set_proxy("127.0.0.1", s.proxy_port());
  25980. cli.set_no_proxy({"10.0.0.0/8"});
  25981. auto res = cli.Get("/");
  25982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25983. EXPECT_GE(s.proxy_hits(), 1);
  25984. EXPECT_EQ(0, s.target_hits());
  25985. }
  25986. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25987. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25988. // IPv4 target matches.
  25989. ProxyAndTargetServers s;
  25990. Client cli("127.0.0.1", s.target_port());
  25991. cli.set_proxy("127.0.0.1", s.proxy_port());
  25992. cli.set_no_proxy({"0.0.0.0/0"});
  25993. auto res = cli.Get("/");
  25994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25995. EXPECT_EQ(0, s.proxy_hits());
  25996. EXPECT_EQ(1, s.target_hits());
  25997. }
  25998. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25999. ProxyAndTargetServers s;
  26000. Client cli("127.0.0.1", s.target_port());
  26001. cli.set_proxy("127.0.0.1", s.proxy_port());
  26002. cli.set_no_proxy({"127.0.0.1"});
  26003. auto res = cli.Get("/");
  26004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26005. EXPECT_EQ(0, s.proxy_hits());
  26006. EXPECT_EQ(1, s.target_hits());
  26007. }
  26008. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26009. ProxyAndTargetServers s;
  26010. Client cli("127.0.0.1", s.target_port());
  26011. cli.set_proxy("127.0.0.1", s.proxy_port());
  26012. cli.set_no_proxy({"127.0.0.0/33"});
  26013. auto res = cli.Get("/");
  26014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26015. EXPECT_GE(s.proxy_hits(), 1);
  26016. EXPECT_EQ(0, s.target_hits());
  26017. }
  26018. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26019. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26020. ProxyAndTargetServers s;
  26021. Client cli("127.0.0.1", s.target_port());
  26022. cli.set_proxy("127.0.0.1", s.proxy_port());
  26023. cli.set_no_proxy({"127.0.0.1/"});
  26024. auto res = cli.Get("/");
  26025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26026. EXPECT_GE(s.proxy_hits(), 1);
  26027. EXPECT_EQ(0, s.target_hits());
  26028. }
  26029. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26030. ProxyAndTargetServers s;
  26031. auto cli = make_client("internal.corp", s);
  26032. cli->set_proxy_basic_auth("u", "p");
  26033. cli->set_no_proxy({"internal.corp"});
  26034. auto res = cli->Get("/");
  26035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26036. EXPECT_EQ(1, s.target_hits());
  26037. EXPECT_EQ(0, s.proxy_hits());
  26038. EXPECT_FALSE(s.last_had_proxy_authz())
  26039. << "Proxy-Authorization must not be sent direct to the target";
  26040. }
  26041. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26042. ProxyAndTargetServers s;
  26043. auto cli = make_client("public.example", s);
  26044. cli->set_proxy_basic_auth("u", "p");
  26045. cli->set_no_proxy({"internal.corp"}); // does not match
  26046. auto res = cli->Get("/");
  26047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26048. EXPECT_GE(s.proxy_hits(), 1);
  26049. EXPECT_TRUE(s.last_had_proxy_authz());
  26050. }
  26051. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26052. std::atomic<int> hits{0};
  26053. std::atomic<int> hits_with_authz{0};
  26054. no_proxy_test::ScopedServer proxy_mock;
  26055. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26056. hits++;
  26057. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26058. if (req.target.find("/redir") != std::string::npos) {
  26059. res.set_redirect("http://other.example/landed");
  26060. } else {
  26061. res.set_content("via-proxy", "text/plain");
  26062. }
  26063. });
  26064. proxy_mock.listen();
  26065. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26066. hits = 0;
  26067. hits_with_authz = 0;
  26068. Client cli("public.example", 80);
  26069. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26070. cli.set_proxy_basic_auth(c.first, c.second);
  26071. cli.set_follow_location(true);
  26072. // The redirect to another host goes through the proxy as well
  26073. auto res = cli.Get("/redir");
  26074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26075. EXPECT_EQ(2, hits.load());
  26076. EXPECT_EQ(2, hits_with_authz.load());
  26077. }
  26078. }
  26079. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26080. ProxyAndTargetServers s;
  26081. auto cli = make_client("anything.test", s);
  26082. auto res = cli->Get("/");
  26083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26084. EXPECT_GE(s.proxy_hits(), 1);
  26085. EXPECT_EQ(0, s.target_hits());
  26086. }
  26087. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26088. ProxyAndTargetServers s;
  26089. auto cli = make_client("example.com", s);
  26090. cli->set_no_proxy({"example.com:8080"});
  26091. auto res = cli->Get("/");
  26092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26093. EXPECT_GE(s.proxy_hits(), 1);
  26094. EXPECT_EQ(0, s.target_hits());
  26095. }
  26096. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26097. ProxyAndTargetServers s;
  26098. auto cli = make_client("anything.test", s);
  26099. cli->set_no_proxy({"", " ", "\t"});
  26100. auto res = cli->Get("/");
  26101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26102. EXPECT_GE(s.proxy_hits(), 1);
  26103. EXPECT_EQ(0, s.target_hits());
  26104. }
  26105. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26106. // An entry with leading/trailing whitespace must still match — env-style
  26107. // values are commonly pasted with stray spaces and an implementation
  26108. // that feeds the raw token directly to inet_pton would fail to match
  26109. // valid CIDRs because of the spaces.
  26110. ProxyAndTargetServers s;
  26111. Client cli("127.0.0.1", s.target_port());
  26112. cli.set_proxy("127.0.0.1", s.proxy_port());
  26113. cli.set_no_proxy({" 127.0.0.0/8 "});
  26114. auto res = cli.Get("/");
  26115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26116. EXPECT_EQ(0, s.proxy_hits());
  26117. EXPECT_EQ(1, s.target_hits());
  26118. }
  26119. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26120. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26121. // go direct and must NOT carry Proxy-Authorization.
  26122. std::atomic<int> proxy_hits{0};
  26123. std::atomic<int> target_hits{0};
  26124. std::atomic<bool> target_saw_authz{false};
  26125. no_proxy_test::ScopedServer proxy_mock, target;
  26126. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26127. proxy_hits++;
  26128. res.status = 302;
  26129. res.set_header("Location", "http://127.0.0.1:" +
  26130. std::to_string(target.port()) + "/landed");
  26131. });
  26132. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26133. target_hits++;
  26134. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26135. res.set_content("direct", "text/plain");
  26136. });
  26137. proxy_mock.listen();
  26138. target.listen();
  26139. Client cli("public.example", target.port());
  26140. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26141. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26142. cli.set_proxy_basic_auth("u", "p");
  26143. cli.set_no_proxy({"127.0.0.1"});
  26144. cli.set_follow_location(true);
  26145. auto res = cli.Get("/redir");
  26146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26147. EXPECT_GE(proxy_hits.load(), 1);
  26148. EXPECT_GE(target_hits.load(), 1);
  26149. EXPECT_FALSE(target_saw_authz.load());
  26150. }
  26151. #ifdef CPPHTTPLIB_SSL_ENABLED
  26152. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26153. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26154. // proxy creds would be sent to the (possibly hostile) origin.
  26155. std::atomic<int> target_hits{0};
  26156. std::atomic<bool> target_saw_proxy_authz{false};
  26157. no_proxy_test::ScopedServer target;
  26158. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26159. target_hits++;
  26160. if (req.has_header("Proxy-Authorization")) {
  26161. target_saw_proxy_authz = true;
  26162. }
  26163. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26164. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26165. "nonce=\"abc\", algorithm=MD5");
  26166. });
  26167. target.listen();
  26168. // The proxy address is set to the target's port: the bypass MUST kick in;
  26169. // if it doesn't, the test still routes "via proxy" to the same server and
  26170. // the Proxy-Authorization assertion below catches the leak.
  26171. Client cli("evil.example", target.port());
  26172. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26173. cli.set_proxy("127.0.0.1", target.port());
  26174. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26175. cli.set_no_proxy({"evil.example"});
  26176. auto res = cli.Get("/x");
  26177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26178. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26179. EXPECT_EQ(1, target_hits.load());
  26180. EXPECT_FALSE(target_saw_proxy_authz.load());
  26181. }
  26182. #endif
  26183. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26184. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26185. std::atomic<int> proxy_hits{0};
  26186. std::atomic<int> bypass_hits{0};
  26187. std::atomic<bool> proxy_saw_c_url{false};
  26188. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26189. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26190. proxy_hits++;
  26191. if (req.path.find("/start") != std::string::npos) {
  26192. res.status = 302;
  26193. res.set_header("Location", "http://127.0.0.1:" +
  26194. std::to_string(bypass_server.port()) +
  26195. "/middle");
  26196. return;
  26197. }
  26198. if (req.path.find("/end") != std::string::npos) {
  26199. proxy_saw_c_url = true;
  26200. res.set_content("c-via-proxy", "text/plain");
  26201. return;
  26202. }
  26203. res.set_content("unexpected", "text/plain");
  26204. });
  26205. // public.example's "advertised" port is arbitrary (the request never lands
  26206. // there — it goes through the proxy), but use a dynamic value to stay
  26207. // friendly with sharded parallel runs.
  26208. int public_port = bypass_server.port();
  26209. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26210. bypass_hits++;
  26211. res.status = 302;
  26212. res.set_header("Location", "http://public.example:" +
  26213. std::to_string(public_port) + "/end");
  26214. });
  26215. proxy_mock.listen();
  26216. bypass_server.listen();
  26217. Client cli("public.example", public_port);
  26218. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26219. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26220. cli.set_no_proxy({"127.0.0.1"});
  26221. cli.set_follow_location(true);
  26222. auto res = cli.Get("/start");
  26223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26224. EXPECT_EQ(StatusCode::OK_200, res->status);
  26225. EXPECT_EQ("c-via-proxy", res->body);
  26226. EXPECT_GE(proxy_hits.load(), 2);
  26227. EXPECT_GE(bypass_hits.load(), 1);
  26228. EXPECT_TRUE(proxy_saw_c_url.load());
  26229. }
  26230. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26231. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26232. // request reconnects to the correct endpoint.
  26233. std::atomic<int> proxy_hits{0};
  26234. std::atomic<int> target_hits{0};
  26235. no_proxy_test::ScopedServer proxy_mock, target;
  26236. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26237. proxy_hits++;
  26238. res.set_content("via-proxy", "text/plain");
  26239. });
  26240. target.svr().Get(".*", [&](const Request &, Response &res) {
  26241. target_hits++;
  26242. res.set_content("direct", "text/plain");
  26243. });
  26244. proxy_mock.listen();
  26245. target.listen();
  26246. Client cli("public.example", target.port());
  26247. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26248. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26249. cli.set_keep_alive(true);
  26250. auto res1 = cli.Get("/a");
  26251. ASSERT_TRUE(res1);
  26252. EXPECT_EQ("via-proxy", res1->body);
  26253. EXPECT_EQ(1, proxy_hits.load());
  26254. EXPECT_EQ(0, target_hits.load());
  26255. cli.set_no_proxy({"public.example"});
  26256. auto res2 = cli.Get("/b");
  26257. ASSERT_TRUE(res2);
  26258. EXPECT_EQ("direct", res2->body);
  26259. EXPECT_EQ(1, proxy_hits.load());
  26260. EXPECT_EQ(1, target_hits.load());
  26261. }
  26262. // Forward declarations (see the base64_encode note).
  26263. namespace httplib {
  26264. namespace detail {
  26265. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26266. int shutdown_socket(socket_t sock) noexcept;
  26267. } // namespace detail
  26268. } // namespace httplib
  26269. namespace proxy_tunnel_test {
  26270. const char *const kTunnelEstablished =
  26271. "HTTP/1.1 200 Connection established\r\n\r\n";
  26272. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26273. using ConnectReply = std::function<std::string(const std::string &head)>;
  26274. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26275. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26276. class ScopedConnectProxy {
  26277. public:
  26278. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26279. : forward_port_(forward_port), reply_(std::move(reply)) {
  26280. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26281. if (listen_sock_ == INVALID_SOCKET) { return; }
  26282. auto a = loopback(0);
  26283. auto addr = reinterpret_cast<sockaddr *>(&a);
  26284. socklen_t alen = sizeof(a);
  26285. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26286. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26287. ::listen(listen_sock_, 4) != 0) {
  26288. return;
  26289. }
  26290. port_ = ntohs(a.sin_port);
  26291. th_ = std::thread([this] { run(); });
  26292. }
  26293. ~ScopedConnectProxy() {
  26294. if (th_.joinable()) {
  26295. stop_ = true;
  26296. auto wake = connect_to(port_);
  26297. th_.join();
  26298. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26299. }
  26300. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26301. }
  26302. int port() const { return port_; }
  26303. int connect_hits() const { return connect_hits_.load(); }
  26304. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26305. std::string connect_request() const {
  26306. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26307. return connect_request_;
  26308. }
  26309. private:
  26310. static sockaddr_in loopback(int port) {
  26311. sockaddr_in a{};
  26312. a.sin_family = AF_INET;
  26313. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26314. a.sin_port = htons(static_cast<unsigned short>(port));
  26315. return a;
  26316. }
  26317. static socket_t connect_to(int port) {
  26318. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26319. if (sock == INVALID_SOCKET) { return sock; }
  26320. auto a = loopback(port);
  26321. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26322. detail::close_socket(sock);
  26323. return INVALID_SOCKET;
  26324. }
  26325. return sock;
  26326. }
  26327. static bool send_all(socket_t sock, const char *data, size_t size) {
  26328. while (size > 0) {
  26329. auto n = detail::send_socket(sock, data, size, 0);
  26330. if (n <= 0) { return false; }
  26331. data += n;
  26332. size -= static_cast<size_t>(n);
  26333. }
  26334. return true;
  26335. }
  26336. void run() {
  26337. for (;;) {
  26338. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26339. if (stop_) {
  26340. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26341. return;
  26342. }
  26343. if (client == INVALID_SOCKET) { continue; }
  26344. serve(client);
  26345. detail::close_socket(client);
  26346. }
  26347. }
  26348. void serve(socket_t client) {
  26349. std::string head;
  26350. char buf[2048];
  26351. while (head.find("\r\n\r\n") == std::string::npos) {
  26352. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26353. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26354. if (n <= 0) { return; }
  26355. head.append(buf, static_cast<size_t>(n));
  26356. }
  26357. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26358. connect_hits_++;
  26359. {
  26360. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26361. connect_request_ = head;
  26362. }
  26363. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26364. if (!send_all(client, res.data(), res.size()) ||
  26365. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26366. return;
  26367. }
  26368. auto origin = connect_to(forward_port_);
  26369. if (origin == INVALID_SOCKET) { return; }
  26370. // When either side stops, shut both down so the other pump returns too.
  26371. auto pump = [&](socket_t from, socket_t to) {
  26372. char b[8192];
  26373. for (;;) {
  26374. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26375. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26376. }
  26377. detail::shutdown_socket(client);
  26378. detail::shutdown_socket(origin);
  26379. };
  26380. std::thread up([&] { pump(client, origin); });
  26381. pump(origin, client);
  26382. up.join();
  26383. detail::close_socket(origin);
  26384. }
  26385. int forward_port_;
  26386. ConnectReply reply_;
  26387. socket_t listen_sock_ = INVALID_SOCKET;
  26388. int port_ = 0;
  26389. std::thread th_;
  26390. std::atomic<bool> stop_{false};
  26391. std::atomic<int> connect_hits_{0};
  26392. mutable std::mutex connect_request_mutex_;
  26393. std::string connect_request_;
  26394. };
  26395. } // namespace proxy_tunnel_test
  26396. #ifdef CPPHTTPLIB_SSL_ENABLED
  26397. namespace proxy_tunnel_test {
  26398. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26399. class ScopedSSLServer {
  26400. public:
  26401. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26402. port_ = svr_.bind_to_any_port("127.0.0.1");
  26403. }
  26404. ~ScopedSSLServer() {
  26405. svr_.stop();
  26406. if (th_.joinable()) { th_.join(); }
  26407. }
  26408. SSLServer &svr() { return svr_; }
  26409. int port() const { return port_; }
  26410. void listen() {
  26411. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26412. svr_.wait_until_ready();
  26413. }
  26414. private:
  26415. SSLServer svr_;
  26416. std::thread th_;
  26417. int port_ = 0;
  26418. };
  26419. // Sends one request through the CONNECT proxy to the TLS origin with a
  26420. // credential configured for each hop, and checks that each credential reaches
  26421. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26422. // origin's (every header in origin_headers) on the tunnelled request.
  26423. void CredentialsStayWithTheirHop(
  26424. const std::function<void(SSLClient &)> &set_credentials,
  26425. const std::string &scheme,
  26426. const std::vector<std::string> &origin_headers = {"Authorization"},
  26427. bool stream = false) {
  26428. std::atomic<int> origin_hits{0};
  26429. std::atomic<bool> origin_saw_proxy_authz{false};
  26430. std::atomic<bool> origin_saw_headers{false};
  26431. ScopedSSLServer origin;
  26432. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26433. origin_hits++;
  26434. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26435. origin_saw_headers =
  26436. std::all_of(origin_headers.begin(), origin_headers.end(),
  26437. [&](const std::string &h) { return req.has_header(h); });
  26438. res.set_content("ok", "text/plain");
  26439. });
  26440. origin.listen();
  26441. ScopedConnectProxy proxy(origin.port());
  26442. ASSERT_NE(0, proxy.port());
  26443. // Pinned to 127.0.0.1 for the same reason as the test below.
  26444. SSLClient cli("127.0.0.1", origin.port());
  26445. cli.enable_server_certificate_verification(false);
  26446. cli.set_proxy("127.0.0.1", proxy.port());
  26447. set_credentials(cli);
  26448. if (stream) {
  26449. auto handle = cli.open_stream("GET", "/x");
  26450. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26451. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26452. } else {
  26453. auto res = cli.Get("/x");
  26454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26455. EXPECT_EQ(StatusCode::OK_200, res->status);
  26456. }
  26457. EXPECT_EQ(1, origin_hits.load());
  26458. EXPECT_EQ(1, proxy.connect_hits());
  26459. EXPECT_TRUE(origin_saw_headers.load());
  26460. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26461. << "Proxy-Authorization must not be sent inside the tunnel";
  26462. auto connect_req = proxy.connect_request();
  26463. EXPECT_NE(std::string::npos,
  26464. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26465. for (const auto &h : origin_headers) {
  26466. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26467. << h << " must not be sent to the proxy on CONNECT";
  26468. }
  26469. }
  26470. } // namespace proxy_tunnel_test
  26471. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26472. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26473. [](SSLClient &cli) {
  26474. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26475. cli.set_basic_auth("origin-user", "origin-pass");
  26476. },
  26477. "Basic");
  26478. }
  26479. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26480. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26481. [](SSLClient &cli) {
  26482. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26483. cli.set_basic_auth("origin-user", "origin-pass");
  26484. },
  26485. "Basic", {"Authorization"}, true);
  26486. }
  26487. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26488. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26489. [](SSLClient &cli) {
  26490. cli.set_proxy_bearer_token_auth("proxy-token");
  26491. cli.set_bearer_token_auth("origin-token");
  26492. },
  26493. "Bearer");
  26494. }
  26495. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26496. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26497. [](SSLClient &cli) {
  26498. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26499. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26500. {"Cookie", "sid=origin-session"},
  26501. {"X-Api-Key", "origin-key"}});
  26502. },
  26503. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26504. }
  26505. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26506. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26507. // retry; otherwise proxy creds would be sent to the origin.
  26508. std::atomic<int> origin_hits{0};
  26509. std::atomic<bool> origin_saw_proxy_authz{false};
  26510. proxy_tunnel_test::ScopedSSLServer origin;
  26511. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26512. origin_hits++;
  26513. if (req.has_header("Proxy-Authorization")) {
  26514. origin_saw_proxy_authz = true;
  26515. }
  26516. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26517. res.set_header("Proxy-Authenticate",
  26518. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26519. "algorithm=MD5");
  26520. });
  26521. origin.listen();
  26522. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26523. ASSERT_NE(0, proxy.port());
  26524. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26525. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26526. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26527. // and answer with its own status, making this test flaky.
  26528. SSLClient cli("127.0.0.1", origin.port());
  26529. cli.enable_server_certificate_verification(false);
  26530. cli.set_proxy("127.0.0.1", proxy.port());
  26531. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26532. auto res = cli.Get("/x");
  26533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26534. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26535. EXPECT_EQ(1, origin_hits.load());
  26536. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26537. EXPECT_EQ(1, proxy.connect_hits());
  26538. }
  26539. #endif
  26540. namespace proxy_tunnel_test {
  26541. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26542. // anything else gets a 407 with `challenge`.
  26543. ConnectReply require_proxy_auth(const std::string &expected,
  26544. const std::string &challenge) {
  26545. return [=](const std::string &head) -> std::string {
  26546. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26547. std::string::npos) {
  26548. return kTunnelEstablished;
  26549. }
  26550. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26551. "Proxy-Authenticate: " +
  26552. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26553. };
  26554. }
  26555. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26556. // request, then echoes.
  26557. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26558. ws.send(
  26559. "authorization:" + req.get_header_value("Authorization") +
  26560. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26561. std::string msg;
  26562. while (ws.read(msg)) {
  26563. ws.send(msg);
  26564. }
  26565. }
  26566. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26567. class ScopedWebSocketOrigin {
  26568. public:
  26569. ScopedWebSocketOrigin() {
  26570. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26571. server_.listen();
  26572. }
  26573. int port() const { return server_.port(); }
  26574. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26575. std::string url() const {
  26576. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26577. }
  26578. private:
  26579. no_proxy_test::ScopedServer server_;
  26580. };
  26581. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26582. // passed as a constructor header, and checks that each reaches only its hop.
  26583. void WebSocketCredentialsStayWithTheirHop(
  26584. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26585. const std::string &proxy_authz, const std::string &origin_authz) {
  26586. ScopedWebSocketOrigin origin;
  26587. ScopedConnectProxy proxy(
  26588. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26589. ASSERT_NE(0, proxy.port());
  26590. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26591. client.set_proxy("127.0.0.1", proxy.port());
  26592. set_proxy_credentials(client);
  26593. auto res = client.connect();
  26594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26595. std::string msg;
  26596. ASSERT_TRUE(client.read(msg));
  26597. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26598. client.close();
  26599. EXPECT_EQ(1, proxy.connect_hits());
  26600. EXPECT_EQ(std::string::npos,
  26601. proxy.connect_request().find("\r\nAuthorization: "))
  26602. << "origin credentials must not be sent to the proxy";
  26603. }
  26604. } // namespace proxy_tunnel_test
  26605. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26606. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26607. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26608. ASSERT_NE(0, proxy.port());
  26609. ws::WebSocketClient client(origin.url());
  26610. client.set_proxy("127.0.0.1", proxy.port());
  26611. auto res = client.connect();
  26612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26613. std::string msg;
  26614. ASSERT_TRUE(client.read(msg));
  26615. ASSERT_TRUE(client.send("hello"));
  26616. ASSERT_TRUE(client.read(msg));
  26617. EXPECT_EQ("hello", msg);
  26618. client.close();
  26619. EXPECT_EQ(1, proxy.connect_hits());
  26620. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26621. auto connect_req = proxy.connect_request();
  26622. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26623. EXPECT_NE(std::string::npos,
  26624. connect_req.find("\r\nHost: " + target + "\r\n"));
  26625. }
  26626. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26627. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26628. [](ws::WebSocketClient &cli) {
  26629. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26630. },
  26631. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26632. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26633. }
  26634. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26635. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26636. [](ws::WebSocketClient &cli) {
  26637. cli.set_proxy_bearer_token_auth("proxy-token");
  26638. },
  26639. "Bearer proxy-token", "Bearer origin-token");
  26640. }
  26641. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26642. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26643. proxy_tunnel_test::ScopedConnectProxy proxy(
  26644. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26645. "Basic " + detail::base64_encode("proxy-user:"),
  26646. "Basic realm=\"proxy\""));
  26647. ASSERT_NE(0, proxy.port());
  26648. ws::WebSocketClient client(origin.url());
  26649. client.set_proxy("127.0.0.1", proxy.port());
  26650. client.set_proxy_basic_auth("proxy-user", "");
  26651. auto res = client.connect();
  26652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26653. client.close();
  26654. EXPECT_EQ(1, proxy.connect_hits());
  26655. }
  26656. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26657. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26658. proxy_tunnel_test::ScopedConnectProxy proxy(
  26659. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26660. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26661. ASSERT_NE(0, proxy.port());
  26662. ws::WebSocketClient client(origin.url());
  26663. client.set_proxy("127.0.0.1", proxy.port());
  26664. auto res = client.connect();
  26665. EXPECT_FALSE(res);
  26666. EXPECT_EQ(Error::ProxyConnection, res.error());
  26667. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26668. EXPECT_EQ("Basic realm=\"proxy\"",
  26669. res.get_header_value("Proxy-Authenticate"));
  26670. EXPECT_FALSE(client.is_open());
  26671. }
  26672. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26673. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26674. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26675. ASSERT_NE(0, proxy.port());
  26676. ws::WebSocketClient client(origin.url());
  26677. client.set_proxy("127.0.0.1", proxy.port());
  26678. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26679. client.set_no_proxy({"127.0.0.1"});
  26680. auto res = client.connect();
  26681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26682. std::string msg;
  26683. ASSERT_TRUE(client.read(msg));
  26684. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26685. << "proxy credentials must not reach a bypassed origin";
  26686. client.close();
  26687. EXPECT_EQ(0, proxy.connect_hits());
  26688. }
  26689. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26690. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26691. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26692. ASSERT_NE(0, proxy.port());
  26693. ws::WebSocketClient client(origin.url());
  26694. client.set_proxy("127.0.0.1", proxy.port());
  26695. ASSERT_TRUE(client.connect());
  26696. ASSERT_TRUE(client.connect());
  26697. client.close();
  26698. EXPECT_EQ(2, proxy.connect_hits());
  26699. }
  26700. #ifdef CPPHTTPLIB_SSL_ENABLED
  26701. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26702. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26703. proxy_tunnel_test::ScopedConnectProxy proxy(
  26704. origin.port(), [](const std::string &head) -> std::string {
  26705. if (head.find(
  26706. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26707. std::string::npos) {
  26708. return proxy_tunnel_test::kTunnelEstablished;
  26709. }
  26710. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26711. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26712. "nonce=\"abc\", algorithm=MD5\r\n"
  26713. "Content-Length: 0\r\n\r\n";
  26714. });
  26715. ASSERT_NE(0, proxy.port());
  26716. ws::WebSocketClient client(origin.url());
  26717. client.set_proxy("127.0.0.1", proxy.port());
  26718. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26719. auto res = client.connect();
  26720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26721. std::string msg;
  26722. ASSERT_TRUE(client.read(msg));
  26723. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26724. client.close();
  26725. EXPECT_EQ(2, proxy.connect_hits());
  26726. }
  26727. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26728. proxy_tunnel_test::ScopedSSLServer origin;
  26729. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26730. origin.listen();
  26731. proxy_tunnel_test::ScopedConnectProxy proxy(
  26732. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26733. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26734. ASSERT_NE(0, proxy.port());
  26735. ws::WebSocketClient client(
  26736. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26737. client.enable_server_certificate_verification(false);
  26738. client.set_proxy("127.0.0.1", proxy.port());
  26739. client.set_proxy_bearer_token_auth("proxy-token");
  26740. auto res = client.connect();
  26741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26742. std::string msg;
  26743. ASSERT_TRUE(client.read(msg));
  26744. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26745. << "Proxy-Authorization must not be sent inside the tunnel";
  26746. client.close();
  26747. EXPECT_EQ(1, proxy.connect_hits());
  26748. }
  26749. #endif