test.cc 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  71. namespace impl {
  72. SecTrustSettingsResult
  73. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  74. } // namespace impl
  75. #endif
  76. } // namespace tls
  77. } // namespace httplib
  78. #endif
  79. using namespace std;
  80. using namespace httplib;
  81. const char *HOST = "localhost";
  82. static int get_base_port() {
  83. const char *shard = getenv("GTEST_SHARD_INDEX");
  84. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  85. }
  86. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  87. // New standalone tests MUST use svr.bind_to_any_port() instead.
  88. const int PORT = get_base_port();
  89. const string LONG_QUERY_VALUE = string(25000, '@');
  90. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  91. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  92. const string TOO_LONG_QUERY_URL =
  93. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  94. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  95. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  96. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  97. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  98. return file.name == key;
  99. });
  100. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  101. return *it;
  102. #else
  103. if (it != items.end()) { return *it; }
  104. throw std::runtime_error("invalid multipart form data name error");
  105. #endif
  106. }
  107. static void read_file(const std::string &path, std::string &out) {
  108. std::ifstream fs(path, std::ios_base::binary);
  109. if (!fs) {
  110. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  111. return;
  112. #else
  113. throw std::runtime_error("File not found: " + path);
  114. #endif
  115. }
  116. fs.seekg(0, std::ios_base::end);
  117. auto size = fs.tellg();
  118. fs.seekg(0);
  119. out.resize(static_cast<size_t>(size));
  120. fs.read(&out[0], static_cast<std::streamsize>(size));
  121. }
  122. class UnixSocketTest : public ::testing::Test {
  123. protected:
  124. void TearDown() override { std::remove(pathname_.c_str()); }
  125. void client_GET(const std::string &addr) {
  126. httplib::Client cli{addr};
  127. cli.set_address_family(AF_UNIX);
  128. ASSERT_TRUE(cli.is_valid());
  129. const auto &result = cli.Get(pattern_);
  130. ASSERT_TRUE(result) << "error: " << result.error();
  131. const auto &resp = result.value();
  132. EXPECT_EQ(resp.status, StatusCode::OK_200);
  133. EXPECT_EQ(resp.body, content_);
  134. }
  135. static std::string make_sock_path() {
  136. const char *shard = getenv("GTEST_SHARD_INDEX");
  137. return shard ? std::string("./httplib-server-") + shard + ".sock"
  138. : "./httplib-server.sock";
  139. }
  140. const std::string pathname_{make_sock_path()};
  141. const std::string pattern_{"/hi"};
  142. const std::string content_{"Hello World!"};
  143. };
  144. TEST_F(UnixSocketTest, pathname) {
  145. httplib::Server svr;
  146. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  147. res.set_content(content_, "text/plain");
  148. });
  149. std::thread t{[&] {
  150. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  151. }};
  152. auto se = detail::scope_exit([&] {
  153. svr.stop();
  154. t.join();
  155. ASSERT_FALSE(svr.is_running());
  156. });
  157. svr.wait_until_ready();
  158. ASSERT_TRUE(svr.is_running());
  159. client_GET(pathname_);
  160. // ".//x.sock", which is not taken for a URL
  161. client_GET("./" + pathname_.substr(1));
  162. }
  163. #if defined(__linux__) || \
  164. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  165. TEST_F(UnixSocketTest, PeerPid) {
  166. httplib::Server svr;
  167. std::string remote_port_val;
  168. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. remote_port_val = std::to_string(req.remote_port);
  171. });
  172. std::thread t{[&] {
  173. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  174. }};
  175. auto se = detail::scope_exit([&] {
  176. svr.stop();
  177. t.join();
  178. ASSERT_FALSE(svr.is_running());
  179. });
  180. svr.wait_until_ready();
  181. ASSERT_TRUE(svr.is_running());
  182. client_GET(pathname_);
  183. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  184. }
  185. #endif
  186. #ifdef __linux__
  187. TEST_F(UnixSocketTest, abstract) {
  188. constexpr char svr_path[]{"\x00httplib-server.sock"};
  189. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  190. httplib::Server svr;
  191. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  192. res.set_content(content_, "text/plain");
  193. });
  194. std::thread t{[&] {
  195. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  196. }};
  197. auto se = detail::scope_exit([&] {
  198. svr.stop();
  199. t.join();
  200. ASSERT_FALSE(svr.is_running());
  201. });
  202. svr.wait_until_ready();
  203. ASSERT_TRUE(svr.is_running());
  204. client_GET(abstract_addr);
  205. }
  206. #endif
  207. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  208. httplib::Server svr;
  209. std::string received_host_header;
  210. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  211. // Capture the Host header sent by the client
  212. auto host_iter = req.headers.find("Host");
  213. if (host_iter != req.headers.end()) {
  214. received_host_header = host_iter->second;
  215. }
  216. res.set_content(content_, "text/plain");
  217. });
  218. std::thread t{[&] {
  219. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  220. }};
  221. auto se = detail::scope_exit([&] {
  222. svr.stop();
  223. t.join();
  224. ASSERT_FALSE(svr.is_running());
  225. });
  226. svr.wait_until_ready();
  227. ASSERT_TRUE(svr.is_running());
  228. // Test that Host header is automatically set to "localhost" for Unix socket
  229. // connections
  230. httplib::Client cli{pathname_};
  231. cli.set_address_family(AF_UNIX);
  232. ASSERT_TRUE(cli.is_valid());
  233. const auto &result = cli.Get(pattern_);
  234. ASSERT_TRUE(result) << "error: " << result.error();
  235. const auto &resp = result.value();
  236. EXPECT_EQ(resp.status, StatusCode::OK_200);
  237. EXPECT_EQ(resp.body, content_);
  238. // Verify that Host header was automatically set to "localhost"
  239. EXPECT_EQ(received_host_header, "localhost");
  240. }
  241. #ifndef _WIN32
  242. TEST(SocketStream, wait_writable_UNIX) {
  243. int fds[2];
  244. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  245. const auto asSocketStream = [&](socket_t fd,
  246. std::function<bool(Stream &)> func) {
  247. return detail::process_client_socket(
  248. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  249. };
  250. asSocketStream(fds[0], [&](Stream &s0) {
  251. EXPECT_EQ(s0.socket(), fds[0]);
  252. EXPECT_TRUE(s0.wait_writable());
  253. EXPECT_TRUE(s0.is_peer_alive());
  254. EXPECT_EQ(0, close(fds[1]));
  255. EXPECT_FALSE(s0.is_peer_alive());
  256. return true;
  257. });
  258. EXPECT_EQ(0, close(fds[0]));
  259. }
  260. TEST(SocketStream, wait_writable_INET) {
  261. sockaddr_in addr;
  262. memset(&addr, 0, sizeof(addr));
  263. addr.sin_family = AF_INET;
  264. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  265. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  266. int disconnected_svr_sock = -1;
  267. std::thread svr{[&] {
  268. const int s = socket(AF_INET, SOCK_STREAM, 0);
  269. ASSERT_LE(0, s);
  270. // PORT + 1 is shared with the SSL redirect tests and with
  271. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  272. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  273. // because that happens on a worker thread the ASSERT does not stop the
  274. // test: it runs on and fails at the disconnected_svr_sock check instead.
  275. default_socket_options(s);
  276. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  277. ASSERT_EQ(0, listen(s, 1));
  278. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  282. std::thread cli{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, close(s));
  287. }};
  288. cli.join();
  289. svr.join();
  290. ASSERT_NE(disconnected_svr_sock, -1);
  291. const auto asSocketStream = [&](socket_t fd,
  292. std::function<bool(Stream &)> func) {
  293. return detail::process_client_socket(
  294. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  295. };
  296. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  297. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  298. // wait_writable() returns true because select_write() only checks if the
  299. // send buffer has space. Peer disconnection is detected later by send().
  300. EXPECT_TRUE(ss.wait_writable());
  301. return true;
  302. });
  303. ASSERT_EQ(0, close(disconnected_svr_sock));
  304. }
  305. #endif // #ifndef _WIN32
  306. TEST(SetSocketOptTest, TcpNoDelay) {
  307. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  308. ASSERT_NE(sock, INVALID_SOCKET);
  309. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  310. int val = 0;
  311. socklen_t len = sizeof(val);
  312. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  313. reinterpret_cast<char *>(&val), &len));
  314. EXPECT_NE(val, 0);
  315. detail::close_socket(sock);
  316. }
  317. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  318. // accept() reports failures through WSAGetLastError() on Windows and through
  319. // errno everywhere else. Asking the wrong one is what made the accept loop
  320. // treat every recoverable failure as fatal on Windows.
  321. struct Classification {
  322. bool resource;
  323. bool transient;
  324. };
  325. auto classify = [](int err) {
  326. #ifdef _WIN32
  327. WSASetLastError(err);
  328. #else
  329. errno = err;
  330. #endif
  331. // Read both before asserting: an assertion may clobber the error slot.
  332. Classification c;
  333. c.resource = detail::is_accept_resource_error();
  334. c.transient = detail::is_accept_transient_error();
  335. return c;
  336. };
  337. #ifdef _WIN32
  338. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  339. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  340. WSAECONNRESET, WSAECONNABORTED};
  341. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  342. #else
  343. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  344. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  345. ECONNABORTED};
  346. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  347. #endif
  348. for (auto err : resource_errors) {
  349. const auto c = classify(err);
  350. EXPECT_TRUE(c.resource) << "error " << err;
  351. EXPECT_FALSE(c.transient) << "error " << err;
  352. }
  353. for (auto err : transient_errors) {
  354. const auto c = classify(err);
  355. EXPECT_TRUE(c.transient) << "error " << err;
  356. EXPECT_FALSE(c.resource) << "error " << err;
  357. }
  358. for (auto err : fatal_errors) {
  359. const auto c = classify(err);
  360. EXPECT_FALSE(c.resource) << "error " << err;
  361. EXPECT_FALSE(c.transient) << "error " << err;
  362. }
  363. #ifdef _WIN32
  364. WSASetLastError(0);
  365. #else
  366. errno = 0;
  367. #endif
  368. }
  369. TEST(ClientTest, MoveConstructible) {
  370. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  371. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  372. }
  373. TEST(ClientTest, MoveAssignable) {
  374. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  375. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  376. }
  377. #ifdef _WIN32
  378. TEST(StartupTest, WSAStartup) {
  379. WSADATA wsaData;
  380. int ret = WSAStartup(0x0002, &wsaData);
  381. ASSERT_EQ(0, ret);
  382. }
  383. #endif
  384. TEST(DecodePathTest, PercentCharacter) {
  385. EXPECT_EQ(
  386. decode_path_component(
  387. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  388. U8("descrip=Gastos áéíóúñÑ 6"));
  389. }
  390. TEST(DecodePathTest, PercentCharacterNUL) {
  391. string expected;
  392. expected.push_back('x');
  393. expected.push_back('\0');
  394. expected.push_back('x');
  395. EXPECT_EQ(decode_path_component("x%00x"), expected);
  396. }
  397. TEST(DecodePathTest, UnicodeEncoding) {
  398. // %u0041 = 'A' (1-byte UTF-8)
  399. EXPECT_EQ("A", decode_path_component("%u0041"));
  400. // %u00E9 = 'é' (2-byte UTF-8)
  401. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  402. // %u3042 = 'あ' (3-byte UTF-8)
  403. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  404. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  405. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  406. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  407. // neighbours)
  408. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  409. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  410. }
  411. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  412. // A sign or whitespace inside the two-character escape window must not be
  413. // accepted as a valid percent-encoding; the sequence is passed through
  414. // literally, matching decode_uri_component / decode_path_component.
  415. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  416. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  417. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  418. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  419. // Well-formed escapes still decode.
  420. EXPECT_EQ("-", decode_query_component("%2D", false));
  421. EXPECT_EQ("A", decode_query_component("%41", false));
  422. }
  423. TEST(SanitizeFilenameTest, VariousPatterns) {
  424. // Path traversal
  425. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  426. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  427. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  428. // Normal and edge cases
  429. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  430. EXPECT_EQ("filename.txt",
  431. httplib::sanitize_filename("/path/to/filename.txt"));
  432. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  433. EXPECT_EQ("", httplib::sanitize_filename(".."));
  434. EXPECT_EQ("", httplib::sanitize_filename(""));
  435. // Null bytes stripped
  436. EXPECT_EQ("safe.txt",
  437. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  438. // Whitespace-only rejected
  439. EXPECT_EQ("", httplib::sanitize_filename(" "));
  440. }
  441. // Forward declaration (see the base64_encode note below): split builds move the
  442. // definition into httplib.cc, so re-declaring it here lets the test link.
  443. namespace httplib {
  444. namespace detail {
  445. bool is_chunked_transfer_encoding(const Headers &headers);
  446. } // namespace detail
  447. } // namespace httplib
  448. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  449. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  450. auto make = [](std::initializer_list<const char *> lines) {
  451. Headers h;
  452. for (auto te : lines) {
  453. if (te) { h.emplace("Transfer-Encoding", te); }
  454. }
  455. return h;
  456. };
  457. // Sole coding, matched case-insensitively.
  458. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  460. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  461. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  462. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  464. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  465. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  466. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  470. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  471. // were received, into one list. Headers preserves that order, so the answer
  472. // is decided by the last coding of the last line and the order the lines
  473. // arrived in is significant.
  474. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  475. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  477. // The split can fall anywhere in the list.
  478. EXPECT_TRUE(
  479. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  480. EXPECT_FALSE(
  481. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  482. // A trailing line naming no coding leaves the list ending in nothing, so it
  483. // must not inherit the chunked from the line before it.
  484. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  485. }
  486. // Forward declarations (see the base64_encode note below).
  487. namespace httplib {
  488. namespace detail {
  489. bool parse_status_line(const char *line, std::string &version, int &status,
  490. std::string &reason);
  491. std::string file_extension(const std::string &path);
  492. std::string
  493. find_content_type(const std::string &path,
  494. const std::map<std::string, std::string> &user_data,
  495. const std::string &default_content_type);
  496. bool can_compress_content_type(const std::string &content_type);
  497. bool is_prohibited_header_name(const std::string &name);
  498. bool is_valid_path(const std::string &path);
  499. #ifdef CPPHTTPLIB_SSL_ENABLED
  500. bool match_hostname(const std::string &pattern, const std::string &hostname);
  501. #endif
  502. } // namespace detail
  503. } // namespace httplib
  504. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  505. struct {
  506. const char *line;
  507. const char *version;
  508. int status;
  509. const char *reason;
  510. } cases[] = {
  511. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  512. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  513. // The reason phrase may be empty, or left out along with its space.
  514. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  515. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  516. };
  517. for (const auto &c : cases) {
  518. std::string version;
  519. int status = 0;
  520. std::string reason = "unset";
  521. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  522. << c.line;
  523. EXPECT_EQ(c.version, version);
  524. EXPECT_EQ(c.status, status);
  525. EXPECT_EQ(c.reason, reason);
  526. }
  527. }
  528. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  529. const char *lines[] = {
  530. "HTTP/2 200 OK\r\n",
  531. "HTTP/1.2 200 OK\r\n",
  532. "HTTP/1.1 20 OK\r\n",
  533. "HTTP/1.1 2000 OK\r\n",
  534. "HTTP/1.1 2x0 OK\r\n",
  535. "HTTP/1.1 200 OK\r\n",
  536. "HTTP/1.1 200OK\r\n",
  537. "HTTP/1.1 200 O\rK\r\n",
  538. "HTTP/1.1 200 OK",
  539. "HTTP/1.1 200 OK\r\nX",
  540. "",
  541. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  542. "HTTP/1.1 200 OK\n",
  543. #endif
  544. };
  545. for (auto line : lines) {
  546. std::string version;
  547. int status = 0;
  548. std::string reason;
  549. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  550. << line;
  551. }
  552. }
  553. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  554. // Long enough to overflow the stack when matched with std::regex.
  555. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  556. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  557. std::string version;
  558. int status = 0;
  559. std::string reason;
  560. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  561. EXPECT_EQ(200, status);
  562. EXPECT_EQ(long_reason, reason);
  563. }
  564. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  565. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  566. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  567. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  568. EXPECT_EQ("", detail::file_extension("noext"));
  569. EXPECT_EQ("", detail::file_extension("a."));
  570. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  571. EXPECT_EQ("", detail::file_extension("a.b-c"));
  572. // Long enough to overflow the stack when matched with std::regex.
  573. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  574. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  575. }
  576. #ifdef CPPHTTPLIB_SSL_ENABLED
  577. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  578. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  579. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  580. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  581. // A wildcard needs two labels after it, in the leftmost label only
  582. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  583. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  584. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  585. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  586. EXPECT_FALSE(
  587. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  588. // No name may have an empty label
  589. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  590. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  591. }
  592. #endif
  593. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  594. detail::case_ignore::hash hash;
  595. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  596. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  597. // Long enough to overflow the stack if hashed one call per character.
  598. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  599. }
  600. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  601. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  602. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  603. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  604. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  605. // Same 26-bit hash as html, svg and js.
  606. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  607. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  608. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  609. }
  610. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  611. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  612. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  613. }
  614. }
  615. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  616. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  617. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  618. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  619. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  620. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  621. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  622. // Same 26-bit hash as application/json.
  623. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  624. }
  625. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  626. Request req;
  627. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  628. EXPECT_TRUE(req.is_multipart_form_data());
  629. std::string boundary;
  630. EXPECT_TRUE(detail::parse_multipart_boundary(
  631. req.get_header_value("Content-Type"), boundary));
  632. EXPECT_EQ("x", boundary);
  633. }
  634. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  635. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  636. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  637. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  638. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  639. // Same 26-bit hash as REMOTE_ADDR.
  640. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  641. }
  642. // Forward declaration: in split builds split.py strips `inline` and moves the
  643. // definition into httplib.cc, so detail::base64_encode is not visible from the
  644. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  645. // in both header-only and split builds.
  646. namespace httplib {
  647. namespace detail {
  648. std::string base64_encode(const std::string &in);
  649. } // namespace detail
  650. } // namespace httplib
  651. TEST(Base64EncodeTest, KnownAnswers) {
  652. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  653. // where the accumulator's top bit is already set before the next shift.
  654. EXPECT_EQ("", detail::base64_encode(""));
  655. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  656. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  657. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  658. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  659. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  660. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  661. // High bytes keep the top bit set across several rounds.
  662. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  663. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  664. }
  665. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  666. string unescapedCharacters = "-_.!~*'()";
  667. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  668. }
  669. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  670. string reservedCharacters = ";,/?:@&=+$";
  671. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  672. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  673. }
  674. TEST(ClientQueryOrder, PreserveOrder) {
  675. // This test reproduces Issue #2259: client may reorder query parameters
  676. // when sending a GET request. The expected behavior is that the client
  677. // preserves the original query string order when the caller supplied it
  678. // as part of the path.
  679. Server svr;
  680. svr.Get("/", [&](const Request &req, Response &res) {
  681. // Echo back the raw target so the test can assert ordering
  682. res.set_content(req.target, "text/plain");
  683. });
  684. std::thread t{[&] { svr.listen(HOST, PORT); }};
  685. auto se = detail::scope_exit([&] {
  686. svr.stop();
  687. t.join();
  688. ASSERT_FALSE(svr.is_running());
  689. });
  690. svr.wait_until_ready();
  691. Client cli(HOST, PORT);
  692. ASSERT_TRUE(cli.is_valid());
  693. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  694. auto res = cli.Get(original);
  695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  696. // Expect the echoed target to exactly match the original path (order
  697. // preserved)
  698. EXPECT_EQ(res->body, original);
  699. }
  700. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  701. string chineseCharacters = U8("中国語");
  702. string russianCharacters = U8("дом");
  703. string brazilianCharacters = U8("óculos");
  704. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  705. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  706. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  707. "%D0%B4%D0%BE%D0%BC");
  708. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  709. }
  710. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  711. string unescapedCharacters = "-_.!~*'()";
  712. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  713. }
  714. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  715. string reservedCharacters = ";,/?:@&=+$";
  716. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  717. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  718. }
  719. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  720. string chineseCharacters = U8("中国語");
  721. string russianCharacters = U8("дом");
  722. string brazilianCharacters = U8("óculos");
  723. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  724. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  725. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  726. "%D0%B4%D0%BE%D0%BC");
  727. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  728. }
  729. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  730. // Issue #2082 use case: encoding path component with ampersand
  731. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  732. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  733. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  734. }
  735. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  736. string unescapedCharacters = "-_.!~*'()";
  737. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  738. }
  739. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  740. string reservedCharacters = ";,/?:@&=+$#";
  741. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  742. }
  743. TEST(EncodeUriTest, TestUTF8Characters) {
  744. string chineseCharacters = U8("中国語");
  745. string russianCharacters = U8("дом");
  746. string brazilianCharacters = U8("óculos");
  747. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  748. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  749. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  750. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  751. }
  752. TEST(EncodeUriTest, TestCompleteUri) {
  753. string uri =
  754. "https://example.com/path/to/resource?query=value&param=test#fragment";
  755. EXPECT_EQ(
  756. httplib::encode_uri(uri),
  757. "https://example.com/path/to/resource?query=value&param=test#fragment");
  758. }
  759. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  760. string uri =
  761. "https://example.com/path with spaces/file name.html?q=hello world";
  762. EXPECT_EQ(httplib::encode_uri(uri),
  763. "https://example.com/path%20with%20spaces/"
  764. "file%20name.html?q=hello%20world");
  765. }
  766. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  767. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  768. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  769. }
  770. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'()";
  772. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  773. }
  774. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  775. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  776. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  777. string encodedBrazilian = "%C3%B3culos";
  778. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  779. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  780. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  781. }
  782. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  783. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  784. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  785. "Piri Tommy Villiers - on & on");
  786. }
  787. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  788. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  789. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  790. }
  791. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  792. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  793. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  794. }
  795. TEST(DecodeUriTest, TestUTF8Characters) {
  796. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  797. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  798. string encodedBrazilian = "%C3%B3culos";
  799. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  800. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  801. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  802. }
  803. TEST(DecodeUriTest, TestCompleteUri) {
  804. string encodedUri = "https://example.com/path%20with%20spaces/"
  805. "file%20name.html?q=hello%20world";
  806. EXPECT_EQ(
  807. httplib::decode_uri(encodedUri),
  808. "https://example.com/path with spaces/file name.html?q=hello world");
  809. }
  810. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  811. string original =
  812. "https://example.com/path with spaces/file name.html?q=hello world";
  813. string encoded = httplib::encode_uri(original);
  814. string decoded = httplib::decode_uri(encoded);
  815. EXPECT_EQ(decoded, original);
  816. }
  817. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  818. // decode_uri is the inverse of encode_uri: an escaped reserved character
  819. // stays encoded so it is not promoted into a real delimiter, while
  820. // non-reserved escapes still decode (like JS decodeURI).
  821. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  822. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  823. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  824. "%3F%3A%40%26%3D%2B%24%2C%3B");
  825. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  826. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  827. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  828. "http://example.com/a%2Fb");
  829. // decode_uri_component still decodes the reserved character.
  830. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  831. }
  832. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  833. string original = "Piri Tommy Villiers - on & on";
  834. string encoded = httplib::encode_uri_component(original);
  835. string decoded = httplib::decode_uri_component(encoded);
  836. EXPECT_EQ(decoded, original);
  837. }
  838. TEST(TrimTests, TrimStringTests) {
  839. EXPECT_EQ("abc", detail::trim_copy("abc"));
  840. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  841. EXPECT_TRUE(detail::trim_copy("").empty());
  842. }
  843. TEST(AsciiTest, LocaleIndependentClassification) {
  844. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  845. // which consult the global C locale: std::isalnum(0xC5) can return true
  846. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  847. // helpers must classify every byte by the ASCII grammar alone.
  848. for (int i = 0; i < 256; i++) {
  849. auto c = static_cast<char>(i);
  850. auto is_digit = i >= '0' && i <= '9';
  851. auto is_upper = i >= 'A' && i <= 'Z';
  852. auto is_lower = i >= 'a' && i <= 'z';
  853. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  854. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  855. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  856. << "byte " << i;
  857. }
  858. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  859. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  860. // Non-ASCII bytes must be percent-encoded, never passed through as
  861. // alphanumeric.
  862. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  863. }
  864. TEST(FromCharsTest, Double) {
  865. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  866. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  867. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  868. auto parse = [](const std::string &s, double &v) {
  869. return detail::from_chars(s.data(), s.data() + s.size(), v);
  870. };
  871. double v = -1.0;
  872. // Representative quality values.
  873. EXPECT_EQ(parse("0", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 0.0);
  875. EXPECT_EQ(parse("1", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 1.0);
  877. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.8);
  879. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  880. EXPECT_DOUBLE_EQ(v, 0.001);
  881. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 1.0);
  883. // A missing integer or fractional part is tolerated.
  884. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  885. EXPECT_DOUBLE_EQ(v, 0.5);
  886. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 5.0);
  888. // Values outside [0, 1] still parse; the caller range-checks them.
  889. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 123.456);
  891. // Stops at the first byte that is not part of the number and reports where.
  892. std::string trailing = "0.9, text/html";
  893. auto r = parse(trailing, v);
  894. EXPECT_EQ(r.ec, std::errc{});
  895. EXPECT_DOUBLE_EQ(v, 0.9);
  896. EXPECT_EQ(*r.ptr, ',');
  897. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  898. // outright, and an 'e'/'E' simply ends the number.
  899. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  900. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  901. std::string exp_input = "1.5e3";
  902. r = parse(exp_input, v);
  903. EXPECT_EQ(r.ec, std::errc{});
  904. EXPECT_DOUBLE_EQ(v, 1.5);
  905. EXPECT_EQ(*r.ptr, 'e');
  906. // Invalid inputs.
  907. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  908. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  909. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  910. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  911. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  912. // Pathological but well-formed inputs must stay bounded (no overflow, no
  913. // out-of-bounds table access) and stay within [0, 1] for the caller.
  914. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  915. std::errc{});
  916. EXPECT_DOUBLE_EQ(v, 0.0);
  917. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  918. std::errc{});
  919. EXPECT_GE(v, 0.0);
  920. EXPECT_LE(v, 1.0);
  921. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  922. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  923. }
  924. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  925. // Simple case without quality values
  926. std::vector<std::string> result1;
  927. EXPECT_TRUE(detail::parse_accept_header(
  928. "text/html,application/json,text/plain", result1));
  929. EXPECT_EQ(result1.size(), 3U);
  930. EXPECT_EQ(result1[0], "text/html");
  931. EXPECT_EQ(result1[1], "application/json");
  932. EXPECT_EQ(result1[2], "text/plain");
  933. // With quality values
  934. std::vector<std::string> result2;
  935. EXPECT_TRUE(detail::parse_accept_header(
  936. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  937. EXPECT_EQ(result2.size(), 3U);
  938. EXPECT_EQ(result2[0], "application/json"); // highest q value
  939. EXPECT_EQ(result2[1], "text/html");
  940. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  941. }
  942. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  943. // Mixed with and without quality values
  944. std::vector<std::string> result;
  945. EXPECT_TRUE(detail::parse_accept_header(
  946. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  947. EXPECT_EQ(result.size(), 3U);
  948. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  949. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  950. EXPECT_EQ(result[2], "application/json"); // q=0.5
  951. }
  952. TEST(ParseAcceptHeaderTest, EdgeCases) {
  953. // Empty header
  954. std::vector<std::string> empty_result;
  955. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  956. EXPECT_TRUE(empty_result.empty());
  957. // Single type
  958. std::vector<std::string> single_result;
  959. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  960. EXPECT_EQ(single_result.size(), 1U);
  961. EXPECT_EQ(single_result[0], "application/json");
  962. // Wildcard types
  963. std::vector<std::string> wildcard_result;
  964. EXPECT_TRUE(detail::parse_accept_header(
  965. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  966. EXPECT_EQ(wildcard_result.size(), 3U);
  967. EXPECT_EQ(wildcard_result[0], "application/json");
  968. EXPECT_EQ(wildcard_result[1], "text/*");
  969. EXPECT_EQ(wildcard_result[2], "*/*");
  970. }
  971. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  972. // Common browser Accept header
  973. std::vector<std::string> browser_result;
  974. EXPECT_TRUE(
  975. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  976. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  977. browser_result));
  978. EXPECT_EQ(browser_result.size(), 6U);
  979. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  980. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  981. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  982. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  983. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  984. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  985. // API client header
  986. std::vector<std::string> api_result;
  987. EXPECT_TRUE(detail::parse_accept_header(
  988. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  989. api_result));
  990. EXPECT_EQ(api_result.size(), 3U);
  991. EXPECT_EQ(api_result[0], "application/json");
  992. EXPECT_EQ(api_result[1], "application/xml");
  993. EXPECT_EQ(api_result[2], "text/plain");
  994. }
  995. TEST(ParseAcceptHeaderTest, SpecialCases) {
  996. // Quality value with 3 decimal places
  997. std::vector<std::string> decimal_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1000. EXPECT_EQ(decimal_result.size(), 2U);
  1001. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1002. EXPECT_EQ(decimal_result[1], "text/html");
  1003. // Zero quality (should still be included but with lowest priority)
  1004. std::vector<std::string> zero_q_result;
  1005. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1006. zero_q_result));
  1007. EXPECT_EQ(zero_q_result.size(), 2U);
  1008. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1009. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1010. // No spaces around commas
  1011. std::vector<std::string> no_space_result;
  1012. EXPECT_TRUE(detail::parse_accept_header(
  1013. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1014. no_space_result));
  1015. EXPECT_EQ(no_space_result.size(), 3U);
  1016. EXPECT_EQ(no_space_result[0], "text/html");
  1017. EXPECT_EQ(no_space_result[1], "application/json");
  1018. EXPECT_EQ(no_space_result[2], "text/plain");
  1019. }
  1020. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1021. // Quality values always use '.' as the decimal separator, so parsing must
  1022. // not depend on the process locale. An embedding application may have
  1023. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1024. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1025. std::string saved = cur ? cur : "C";
  1026. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1027. "fr_FR.UTF-8"};
  1028. bool switched = false;
  1029. for (const auto loc : comma_locales) {
  1030. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1031. std::localeconv()->decimal_point[0] == ',') {
  1032. switched = true;
  1033. break;
  1034. }
  1035. }
  1036. if (!switched) {
  1037. std::setlocale(LC_NUMERIC, saved.c_str());
  1038. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1039. }
  1040. // The higher-weighted type appears later in the list, so a correct parse
  1041. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1042. // sensitive parse reads both weights as 0 and leaves the original order.
  1043. std::vector<std::string> result;
  1044. EXPECT_TRUE(detail::parse_accept_header(
  1045. "application/json;q=0.1,text/html;q=0.9", result));
  1046. ASSERT_EQ(result.size(), 2U);
  1047. EXPECT_EQ(result[0], "text/html");
  1048. EXPECT_EQ(result[1], "application/json");
  1049. std::setlocale(LC_NUMERIC, saved.c_str());
  1050. }
  1051. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1052. std::vector<std::string> result;
  1053. // Invalid quality value (> 1.0)
  1054. EXPECT_FALSE(
  1055. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1056. // Invalid quality value (< 0.0)
  1057. EXPECT_FALSE(
  1058. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1059. // Invalid quality value (not a number)
  1060. EXPECT_FALSE(detail::parse_accept_header(
  1061. "text/html;q=invalid,application/json", result));
  1062. // A valid numeric prefix does not make the entire quality value valid.
  1063. EXPECT_FALSE(detail::parse_accept_header(
  1064. "text/html;q=0.5junk,application/json", result));
  1065. // Empty quality value
  1066. EXPECT_FALSE(
  1067. detail::parse_accept_header("text/html;q=,application/json", result));
  1068. // Invalid media type format (no slash and not wildcard)
  1069. EXPECT_FALSE(
  1070. detail::parse_accept_header("invalidtype,application/json", result));
  1071. // Valid cases should still work
  1072. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1073. EXPECT_EQ(result.size(), 1U);
  1074. EXPECT_EQ(result[0], "*/*");
  1075. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1076. EXPECT_EQ(result.size(), 1U);
  1077. EXPECT_EQ(result[0], "*");
  1078. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1079. EXPECT_EQ(result.size(), 1U);
  1080. EXPECT_EQ(result[0], "text/*");
  1081. }
  1082. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1083. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1084. // and must not be answered with 400 Bad Request.
  1085. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1086. struct {
  1087. const char *value;
  1088. std::vector<std::string> expected;
  1089. } cases[] = {
  1090. {",application/json", {"application/json"}},
  1091. {"text/html,", {"text/html"}},
  1092. {"text/html,,*/*", {"text/html", "*/*"}},
  1093. // An empty element may be spelled with whitespace in it
  1094. {"text/html, , application/json", {"text/html", "application/json"}},
  1095. // Nothing but empty elements is an empty list, which means the same
  1096. // thing as no Accept header at all
  1097. {",,,", {}},
  1098. // Quality values still apply across ignored empty elements
  1099. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1100. };
  1101. for (const auto &c : cases) {
  1102. std::vector<std::string> result;
  1103. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1104. << "value: " << c.value;
  1105. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1106. }
  1107. // An invalid entry is still rejected when empty elements surround it
  1108. std::vector<std::string> result;
  1109. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1110. }
  1111. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1112. // or ';' inside one does not end the list element or the parameter. Section
  1113. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1114. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1115. struct {
  1116. const char *value;
  1117. std::vector<std::string> expected;
  1118. } cases[] = {
  1119. {"text/html;profile=\"a,b\",application/json",
  1120. {"text/html", "application/json"}},
  1121. // A "q=" inside a quoted value is not the weight
  1122. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1123. {"text/html", "application/json"}},
  1124. // The weight after a quoted value still applies
  1125. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1126. {"application/json", "text/html"}},
  1127. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1128. {"application/json", "text/html"}},
  1129. {"text/html;profile=\"a\\\"b\",application/json",
  1130. {"text/html", "application/json"}},
  1131. // An escaped backslash does not escape the '"' after it
  1132. {"text/html;profile=\"a\\\\\",application/json",
  1133. {"text/html", "application/json"}},
  1134. };
  1135. for (const auto &c : cases) {
  1136. std::vector<std::string> result;
  1137. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1138. << "value: " << c.value;
  1139. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1140. }
  1141. }
  1142. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1143. Server svr;
  1144. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1145. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1146. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1147. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1148. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1149. res.set_content("ok", "text/plain");
  1150. });
  1151. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1152. EXPECT_TRUE(false);
  1153. res.set_content("bad request", "text/plain");
  1154. });
  1155. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1156. auto se = detail::scope_exit([&] {
  1157. svr.stop();
  1158. listen_thread.join();
  1159. ASSERT_FALSE(svr.is_running());
  1160. });
  1161. svr.wait_until_ready();
  1162. Client cli("localhost", PORT);
  1163. {
  1164. auto res = cli.Get(
  1165. "/accept_ok",
  1166. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1168. EXPECT_EQ(StatusCode::OK_200, res->status);
  1169. }
  1170. {
  1171. auto res = cli.Get("/accept_bad_request",
  1172. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1174. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1175. }
  1176. }
  1177. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1178. Server svr;
  1179. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1180. res.set_content("ok", "text/plain");
  1181. });
  1182. std::atomic<int> start_count{0};
  1183. std::atomic<bool> running_when_called{false};
  1184. svr.set_start_handler([&]() {
  1185. running_when_called = svr.is_running();
  1186. start_count++;
  1187. });
  1188. auto port = svr.bind_to_any_port(HOST);
  1189. std::thread t([&]() { svr.listen_after_bind(); });
  1190. auto se = detail::scope_exit([&] {
  1191. svr.stop();
  1192. t.join();
  1193. ASSERT_FALSE(svr.is_running());
  1194. });
  1195. svr.wait_until_ready();
  1196. // A successful request proves the accept loop is running, which the start
  1197. // handler precedes; so by now the handler must have run exactly once.
  1198. Client cli(HOST, port);
  1199. cli.set_connection_timeout(std::chrono::seconds(5));
  1200. auto res = cli.Get("/");
  1201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1202. EXPECT_EQ(StatusCode::OK_200, res->status);
  1203. EXPECT_EQ(1, start_count.load());
  1204. EXPECT_TRUE(running_when_called.load());
  1205. }
  1206. TEST(DivideTest, DivideStringTests) {
  1207. auto divide = [](const std::string &str, char d) {
  1208. std::string lhs;
  1209. std::string rhs;
  1210. detail::divide(str, d,
  1211. [&](const char *lhs_data, std::size_t lhs_size,
  1212. const char *rhs_data, std::size_t rhs_size) {
  1213. lhs.assign(lhs_data, lhs_size);
  1214. rhs.assign(rhs_data, rhs_size);
  1215. });
  1216. return std::make_pair(std::move(lhs), std::move(rhs));
  1217. };
  1218. {
  1219. const auto res = divide("", '=');
  1220. EXPECT_EQ(res.first, "");
  1221. EXPECT_EQ(res.second, "");
  1222. }
  1223. {
  1224. const auto res = divide("=", '=');
  1225. EXPECT_EQ(res.first, "");
  1226. EXPECT_EQ(res.second, "");
  1227. }
  1228. {
  1229. const auto res = divide(" ", '=');
  1230. EXPECT_EQ(res.first, " ");
  1231. EXPECT_EQ(res.second, "");
  1232. }
  1233. {
  1234. const auto res = divide("a", '=');
  1235. EXPECT_EQ(res.first, "a");
  1236. EXPECT_EQ(res.second, "");
  1237. }
  1238. {
  1239. const auto res = divide("a=", '=');
  1240. EXPECT_EQ(res.first, "a");
  1241. EXPECT_EQ(res.second, "");
  1242. }
  1243. {
  1244. const auto res = divide("=b", '=');
  1245. EXPECT_EQ(res.first, "");
  1246. EXPECT_EQ(res.second, "b");
  1247. }
  1248. {
  1249. const auto res = divide("a=b", '=');
  1250. EXPECT_EQ(res.first, "a");
  1251. EXPECT_EQ(res.second, "b");
  1252. }
  1253. {
  1254. const auto res = divide("a=b=", '=');
  1255. EXPECT_EQ(res.first, "a");
  1256. EXPECT_EQ(res.second, "b=");
  1257. }
  1258. {
  1259. const auto res = divide("a=b=c", '=');
  1260. EXPECT_EQ(res.first, "a");
  1261. EXPECT_EQ(res.second, "b=c");
  1262. }
  1263. }
  1264. TEST(SplitTest, ParseQueryString) {
  1265. string s = "key1=val1&key2=val2&key3=val3";
  1266. Params dic;
  1267. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1268. [&](const char *b, const char *e) {
  1269. string key, val;
  1270. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1271. if (key.empty()) {
  1272. key.assign(b2, e2);
  1273. } else {
  1274. val.assign(b2, e2);
  1275. }
  1276. });
  1277. dic.emplace(key, val);
  1278. });
  1279. EXPECT_EQ("val1", dic.find("key1")->second);
  1280. EXPECT_EQ("val2", dic.find("key2")->second);
  1281. EXPECT_EQ("val3", dic.find("key3")->second);
  1282. }
  1283. TEST(SplitTest, ParseInvalidQueryTests) {
  1284. {
  1285. string s = " ";
  1286. Params dict;
  1287. detail::parse_query_text(s, dict);
  1288. EXPECT_TRUE(dict.empty());
  1289. }
  1290. {
  1291. string s = " = =";
  1292. Params dict;
  1293. detail::parse_query_text(s, dict);
  1294. EXPECT_TRUE(dict.empty());
  1295. }
  1296. }
  1297. TEST(ParseQueryTest, ParseQueryString) {
  1298. {
  1299. std::string s = "key1=val1&key2=val2&key3=val3";
  1300. Params dic;
  1301. detail::parse_query_text(s, dic);
  1302. EXPECT_EQ("val1", dic.find("key1")->second);
  1303. EXPECT_EQ("val2", dic.find("key2")->second);
  1304. EXPECT_EQ("val3", dic.find("key3")->second);
  1305. }
  1306. {
  1307. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1308. Params dic;
  1309. detail::parse_query_text(s, dic);
  1310. EXPECT_EQ("", dic.find("key1")->second);
  1311. EXPECT_EQ("val1", dic.find("key2")->second);
  1312. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1313. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1314. }
  1315. }
  1316. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1317. Params dic;
  1318. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1319. dic.emplace("key1", "val1");
  1320. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1321. dic.emplace("key2", "val2");
  1322. dic.emplace("key3", "val3");
  1323. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1324. }
  1325. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1326. Params params;
  1327. params.emplace("a", "1");
  1328. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1329. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1330. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1331. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1332. // Long enough to overflow the stack when matched with std::regex.
  1333. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1334. EXPECT_EQ("/p?" + long_query + "&a=1",
  1335. append_query_params("/p?" + long_query, params));
  1336. }
  1337. // Joins every entry of a Headers or Params into "key=value " so a whole
  1338. // traversal can be compared in one assertion. Both are instantiations of the
  1339. // same insertion-ordered container, so one helper serves both.
  1340. template <typename Map> static std::string entries_to_string(const Map &m) {
  1341. std::string s;
  1342. for (const auto &entry : m) {
  1343. s += entry.first + "=" + entry.second + " ";
  1344. }
  1345. return s;
  1346. }
  1347. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1348. // Params used to be a std::multimap, which sorted by name and handed the
  1349. // caller's query back alphabetised. A client signing its query string could
  1350. // not reproduce the order it asked for.
  1351. Params dic;
  1352. dic.emplace("zulu", "1");
  1353. dic.emplace("alpha", "2");
  1354. dic.emplace("mike", "3");
  1355. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1356. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1357. }
  1358. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1359. Params dic;
  1360. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1361. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1362. }
  1363. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1364. Request req;
  1365. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1366. req.params);
  1367. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1368. EXPECT_EQ("first", req.get_param_value("tag"));
  1369. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1370. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1371. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1372. EXPECT_EQ("", req.get_param_value("tag", 3));
  1373. }
  1374. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1375. // Params shares its container with Headers, which matches field names
  1376. // case-insensitively. Parameter names must not pick that up.
  1377. Params dic;
  1378. dic.emplace("Key", "upper");
  1379. dic.emplace("key", "lower");
  1380. EXPECT_EQ(2U, dic.size());
  1381. EXPECT_EQ(1U, dic.count("Key"));
  1382. EXPECT_EQ(1U, dic.count("key"));
  1383. EXPECT_EQ("upper", dic.find("Key")->second);
  1384. EXPECT_EQ("lower", dic.find("key")->second);
  1385. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1386. }
  1387. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1388. Server svr;
  1389. std::string order;
  1390. svr.Get("/order", [&](const Request &req, Response &res) {
  1391. order = entries_to_string(req.params);
  1392. res.set_content("ok", "text/plain");
  1393. });
  1394. auto port = svr.bind_to_any_port(HOST);
  1395. thread t = thread([&] { svr.listen_after_bind(); });
  1396. auto se = detail::scope_exit([&] {
  1397. svr.stop();
  1398. t.join();
  1399. ASSERT_FALSE(svr.is_running());
  1400. });
  1401. svr.wait_until_ready();
  1402. Client cli(HOST, port);
  1403. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1404. ASSERT_TRUE(res);
  1405. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1406. }
  1407. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1408. Server svr;
  1409. std::string field_order, file_order;
  1410. svr.Post("/order", [&](const Request &req, Response &res) {
  1411. for (const auto &field : req.form.fields) {
  1412. field_order += field.first + "=" + field.second.content + " ";
  1413. }
  1414. for (const auto &file : req.form.files) {
  1415. file_order += file.first + "=" + file.second.filename + " ";
  1416. }
  1417. res.set_content("ok", "text/plain");
  1418. });
  1419. auto port = svr.bind_to_any_port(HOST);
  1420. thread t = thread([&] { svr.listen_after_bind(); });
  1421. auto se = detail::scope_exit([&] {
  1422. svr.stop();
  1423. t.join();
  1424. ASSERT_FALSE(svr.is_running());
  1425. });
  1426. svr.wait_until_ready();
  1427. UploadFormDataItems items = {
  1428. {"zulu", "1", "", ""},
  1429. {"alpha", "2", "", ""},
  1430. {"mike", "3", "", ""},
  1431. {"zebra", "z", "z.txt", "text/plain"},
  1432. {"apple", "a", "a.txt", "text/plain"},
  1433. };
  1434. Client cli(HOST, port);
  1435. auto res = cli.Post("/order", items);
  1436. ASSERT_TRUE(res);
  1437. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1438. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1439. }
  1440. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1441. Server svr;
  1442. std::vector<std::string> values;
  1443. std::string first, second, out_of_range, order;
  1444. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1445. values = req.form.get_fields("tag");
  1446. first = req.form.get_field("tag", 0);
  1447. second = req.form.get_field("tag", 1);
  1448. out_of_range = req.form.get_field("tag", 2);
  1449. for (const auto &field : req.form.fields) {
  1450. order += field.first + "=" + field.second.content + " ";
  1451. }
  1452. res.set_content("ok", "text/plain");
  1453. });
  1454. auto port = svr.bind_to_any_port(HOST);
  1455. thread t = thread([&] { svr.listen_after_bind(); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. t.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1463. // not adjacent in the container.
  1464. UploadFormDataItems items = {
  1465. {"tag", "first", "", ""},
  1466. {"other", "x", "", ""},
  1467. {"tag", "second", "", ""},
  1468. };
  1469. Client cli(HOST, port);
  1470. auto res = cli.Post("/repeated", items);
  1471. ASSERT_TRUE(res);
  1472. ASSERT_EQ(2U, values.size());
  1473. EXPECT_EQ("first", values[0]);
  1474. EXPECT_EQ("second", values[1]);
  1475. EXPECT_EQ("first", first);
  1476. EXPECT_EQ("second", second);
  1477. // std::multimap already kept entries sharing a name in insertion order, so
  1478. // everything above passes without this change too. The whole traversal is
  1479. // what tells the two apart: sorting by name would hoist "other" to the front
  1480. // and the two "tag" parts would end up adjacent.
  1481. EXPECT_EQ("tag=first other=x tag=second ", order);
  1482. // Advancing past the last entry of a name used to run off the container;
  1483. // the container's saturating increment makes it return the default instead.
  1484. EXPECT_EQ("", out_of_range);
  1485. }
  1486. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1487. Server svr;
  1488. std::string file_names;
  1489. svr.Post("/upload", [&](const Request &req, Response &res) {
  1490. for (const auto &file : req.form.files) {
  1491. file_names += file.first + "|" + file.second.filename + " ";
  1492. }
  1493. res.set_content("ok", "text/plain");
  1494. });
  1495. auto port = svr.bind_to_any_port(HOST);
  1496. thread t = thread([&] { svr.listen_after_bind(); });
  1497. auto se = detail::scope_exit([&] {
  1498. svr.stop();
  1499. t.join();
  1500. ASSERT_FALSE(svr.is_running());
  1501. });
  1502. svr.wait_until_ready();
  1503. // A trailing backslash would otherwise escape the closing quote.
  1504. UploadFormDataItems items = {
  1505. {"dir\\", "x", "a.txt", "text/plain"},
  1506. {"b", "y", "a\\\\b.txt", "text/plain"},
  1507. };
  1508. Client cli(HOST, port);
  1509. auto res = cli.Post("/upload", items);
  1510. ASSERT_TRUE(res);
  1511. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1512. }
  1513. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1514. // Server::read_content() keeps a FormFields::iterator alive across the
  1515. // content callbacks that fill the part it points at. The container is
  1516. // vector-backed, so a later emplace can reallocate and invalidate an older
  1517. // iterator; 64 parts grow the vector through seven reallocations, which
  1518. // checks that every part's content still lands in its own entry.
  1519. const size_t part_count = 64;
  1520. // One formula for both the parts sent and the values expected back, so the
  1521. // two cannot drift apart.
  1522. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1523. auto content_of = [](size_t i) {
  1524. return std::string(64, static_cast<char>('a' + (i % 26)));
  1525. };
  1526. Server svr;
  1527. std::vector<std::pair<std::string, std::string>> received;
  1528. svr.Post("/many", [&](const Request &req, Response &res) {
  1529. for (const auto &field : req.form.fields) {
  1530. received.emplace_back(field.first, field.second.content);
  1531. }
  1532. res.set_content("ok", "text/plain");
  1533. });
  1534. auto port = svr.bind_to_any_port(HOST);
  1535. thread t = thread([&] { svr.listen_after_bind(); });
  1536. auto se = detail::scope_exit([&] {
  1537. svr.stop();
  1538. t.join();
  1539. ASSERT_FALSE(svr.is_running());
  1540. });
  1541. svr.wait_until_ready();
  1542. UploadFormDataItems items;
  1543. for (size_t i = 0; i < part_count; i++) {
  1544. items.push_back({name_of(i), content_of(i), "", ""});
  1545. }
  1546. Client cli(HOST, port);
  1547. auto res = cli.Post("/many", items);
  1548. ASSERT_TRUE(res);
  1549. ASSERT_EQ(part_count, received.size());
  1550. for (size_t i = 0; i < part_count; i++) {
  1551. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1552. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1553. }
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1556. string content_type = "multipart/form-data; boundary=something";
  1557. string boundary;
  1558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1559. EXPECT_TRUE(ret);
  1560. EXPECT_EQ(boundary, "something");
  1561. }
  1562. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1563. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1564. string boundary;
  1565. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1566. EXPECT_TRUE(ret);
  1567. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1568. }
  1569. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1570. string content_type =
  1571. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1572. string boundary;
  1573. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1574. EXPECT_TRUE(ret);
  1575. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1576. }
  1577. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1578. string content_type =
  1579. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1580. string boundary;
  1581. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1582. EXPECT_TRUE(ret);
  1583. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1584. }
  1585. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1586. const string boundary(70, 'a');
  1587. string content_type = "multipart/form-data; boundary=" + boundary;
  1588. string parsed;
  1589. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1590. EXPECT_TRUE(ret);
  1591. EXPECT_EQ(parsed, boundary);
  1592. }
  1593. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1594. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1595. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1596. string parsed;
  1597. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1598. EXPECT_FALSE(ret);
  1599. }
  1600. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1601. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1602. // is 72 characters on the wire and still valid.
  1603. const string boundary(70, 'a');
  1604. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, boundary);
  1608. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1609. parsed.clear();
  1610. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1611. }
  1612. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1613. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1614. // The parameter parser must not treat that '=' as the key/value separator.
  1615. string content_type =
  1616. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1617. "charset=UTF-8";
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1620. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1621. }
  1622. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1623. // A ';' inside the quoted-string is part of the value, not a parameter
  1624. // separator, so it must not truncate the boundary.
  1625. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1626. string parsed;
  1627. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1628. EXPECT_EQ(parsed, "a;b");
  1629. }
  1630. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1631. string parsed;
  1632. EXPECT_TRUE(detail::parse_multipart_boundary(
  1633. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1634. EXPECT_EQ("a\\b", parsed);
  1635. EXPECT_TRUE(detail::parse_multipart_boundary(
  1636. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1637. EXPECT_EQ("a\"b", parsed);
  1638. }
  1639. TEST(ParseDispositionParamsTest, QuotedValues) {
  1640. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1641. // ';' and '=' are ordinary characters inside one.
  1642. struct {
  1643. const char *value;
  1644. std::vector<std::pair<const char *, const char *>> expected;
  1645. } cases[] = {
  1646. {"name=\"file1\"; filename=\"a.txt\"",
  1647. {{"name", "file1"}, {"filename", "a.txt"}}},
  1648. // Whitespace around '=' and ';' is still trimmed
  1649. {"name=\"file2\" ;filename = \"a.html\"",
  1650. {{"name", "file2"}, {"filename", "a.html"}}},
  1651. // '=' inside the value used to leave only the text after the last one
  1652. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1653. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1654. {"name=\"x=y\"", {{"name", "x=y"}}},
  1655. // ';' inside the value used to truncate the pair and leave a bogus one
  1656. {"name=\"file3\"; filename=\"a;b.txt\"",
  1657. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1658. // An unquoted value keeps working, and so does filename*
  1659. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1660. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1661. // A parameter with no key is dropped rather than turned into one whose
  1662. // key is the value
  1663. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1664. // An escaped quote does not end the value
  1665. {"name=\"a\\\"; filename=evil.php\"",
  1666. {{"name", "a\"; filename=evil.php"}}},
  1667. // Other backslashes, as in a Windows path, are kept
  1668. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1669. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1670. };
  1671. for (const auto &c : cases) {
  1672. Params params;
  1673. detail::parse_disposition_params(c.value, params);
  1674. for (const auto &kv : c.expected) {
  1675. auto it = params.find(kv.first);
  1676. ASSERT_NE(it, params.end())
  1677. << "value: " << c.value << ", key: " << kv.first;
  1678. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1679. }
  1680. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1681. }
  1682. }
  1683. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1684. Server svr;
  1685. std::string filename;
  1686. std::string content;
  1687. svr.Post("/upload", [&](const Request &req, Response &) {
  1688. const auto &file = req.form.get_file("file");
  1689. filename = file.filename;
  1690. content = file.content;
  1691. });
  1692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1693. auto se = detail::scope_exit([&] {
  1694. svr.stop();
  1695. thread.join();
  1696. ASSERT_FALSE(svr.is_running());
  1697. });
  1698. svr.wait_until_ready();
  1699. std::string body = "--B\r\n"
  1700. "Content-Disposition: form-data; name=\"file\"; "
  1701. "filename=\"a.txt\"\r\n"
  1702. "Content-Type: text/plain\r\n"
  1703. "\r\n"
  1704. "hello\r\n"
  1705. "--B--\r\n";
  1706. Client cli(HOST, PORT);
  1707. auto res = cli.Post(
  1708. "/upload",
  1709. [&](size_t offset, DataSink &sink) {
  1710. if (offset < body.size()) {
  1711. sink.write(&body[offset], 1);
  1712. } else {
  1713. sink.done();
  1714. }
  1715. return true;
  1716. },
  1717. "multipart/form-data; boundary=B");
  1718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1719. EXPECT_EQ(StatusCode::OK_200, res->status);
  1720. EXPECT_EQ("a.txt", filename);
  1721. EXPECT_EQ("hello", content);
  1722. }
  1723. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1724. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1725. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1726. Server svr;
  1727. std::string field_value, file_name, file_filename;
  1728. bool has_field = false, has_file = false;
  1729. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1730. has_field = req.form.has_field("x=y");
  1731. field_value = req.form.get_field("x=y");
  1732. has_file = req.form.has_file("file1");
  1733. const auto &file = req.form.get_file("file1");
  1734. file_name = file.name;
  1735. file_filename = file.filename;
  1736. res.set_content("ok", "text/plain");
  1737. });
  1738. auto port = svr.bind_to_any_port(HOST);
  1739. thread t = thread([&] { svr.listen_after_bind(); });
  1740. auto se = detail::scope_exit([&] {
  1741. svr.stop();
  1742. t.join();
  1743. ASSERT_FALSE(svr.is_running());
  1744. });
  1745. svr.wait_until_ready();
  1746. UploadFormDataItems items = {
  1747. {"x=y", "field-value", "", ""},
  1748. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1749. };
  1750. Client cli(HOST, port);
  1751. auto res = cli.Post("/quoted", items);
  1752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1753. ASSERT_EQ(StatusCode::OK_200, res->status);
  1754. EXPECT_TRUE(has_field);
  1755. EXPECT_EQ("field-value", field_value);
  1756. EXPECT_TRUE(has_file);
  1757. EXPECT_EQ("file1", file_name);
  1758. EXPECT_EQ("a;b=report.pdf", file_filename);
  1759. }
  1760. TEST(GetHeaderValueTest, DefaultValue) {
  1761. Headers headers = {{"Dummy", "Dummy"}};
  1762. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1763. EXPECT_STREQ("text/plain", val);
  1764. }
  1765. TEST(GetHeaderValueTest, DefaultValueInt) {
  1766. Headers headers = {{"Dummy", "Dummy"}};
  1767. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1768. EXPECT_EQ(100ull, val);
  1769. }
  1770. TEST(GetHeaderValueTest, RegularValue) {
  1771. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1772. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1773. EXPECT_STREQ("text/html", val);
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1776. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1778. EXPECT_STREQ("text/html", val);
  1779. }
  1780. TEST(GetHeaderValueTest, SetContent) {
  1781. Response res;
  1782. res.set_content("html", "text/html");
  1783. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1784. res.set_content("text", "text/plain");
  1785. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1786. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1787. }
  1788. TEST(GetHeaderValueTest, RegularValueInt) {
  1789. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1790. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1791. EXPECT_EQ(100ull, val);
  1792. }
  1793. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1794. Headers headers = {{"Content-Length", "x"}};
  1795. auto is_invalid_value = false;
  1796. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1797. is_invalid_value);
  1798. EXPECT_EQ(0ull, val);
  1799. EXPECT_TRUE(is_invalid_value);
  1800. }
  1801. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1802. // An all-digit value that overflows size_t must be reported as invalid, not
  1803. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1804. // a large length to a small one on 32-bit builds, leaving the framing length
  1805. // wrong while is_invalid_value stayed false.
  1806. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1807. auto is_invalid_value = false;
  1808. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1809. is_invalid_value);
  1810. EXPECT_TRUE(is_invalid_value);
  1811. // A well-formed length is unaffected.
  1812. Headers ok = {{"Content-Length", "1234"}};
  1813. is_invalid_value = false;
  1814. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1815. is_invalid_value);
  1816. EXPECT_EQ(1234ull, val);
  1817. EXPECT_FALSE(is_invalid_value);
  1818. }
  1819. TEST(GetHeaderValueTest, Range) {
  1820. {
  1821. Headers headers = {make_range_header({{1, -1}})};
  1822. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1823. EXPECT_STREQ("bytes=1-", val);
  1824. }
  1825. {
  1826. Headers headers = {make_range_header({{-1, 1}})};
  1827. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1828. EXPECT_STREQ("bytes=-1", val);
  1829. }
  1830. {
  1831. Headers headers = {make_range_header({{1, 10}})};
  1832. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1833. EXPECT_STREQ("bytes=1-10", val);
  1834. }
  1835. {
  1836. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1837. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1838. EXPECT_STREQ("bytes=1-10, 100-", val);
  1839. }
  1840. {
  1841. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1842. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1843. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1844. }
  1845. {
  1846. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1847. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1848. EXPECT_STREQ("bytes=0-0, -1", val);
  1849. }
  1850. }
  1851. TEST(BearerTokenAuthTest, SchemeValidation) {
  1852. // A value shorter than "Bearer " must not throw from the fixed-length
  1853. // substr, and a non-Bearer scheme must not be reported as a token.
  1854. struct {
  1855. const char *value;
  1856. const char *expected;
  1857. } cases[] = {
  1858. {"x", ""},
  1859. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1860. {"Bearer abc123", "abc123"},
  1861. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1862. };
  1863. for (const auto &c : cases) {
  1864. Request req;
  1865. req.set_header("Authorization", c.value);
  1866. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1867. }
  1868. }
  1869. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1870. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1871. // to depend on the standard library (libstdc++ handed back duplicates in
  1872. // reverse insertion order, libc++ in insertion order).
  1873. Request req;
  1874. req.set_header("Accept-Encoding", "gzip");
  1875. req.set_header("Accept-Encoding", "deflate");
  1876. req.set_header("Accept-Encoding", "br");
  1877. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1878. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1879. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1880. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1881. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1882. }
  1883. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1884. Request req;
  1885. req.set_header("X-Test", "only");
  1886. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1887. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1888. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1889. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1890. }
  1891. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1892. Request req;
  1893. req.set_header("X-First", "1");
  1894. req.set_header("X-Test", "2");
  1895. req.params.emplace("first", "1");
  1896. req.params.emplace("test", "2");
  1897. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1898. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1899. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1900. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1901. // The second one is negative when read as a signed value
  1902. const auto max_id = (std::numeric_limits<size_t>::max)();
  1903. for (auto id : {max_id / 2, max_id}) {
  1904. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1905. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1906. EXPECT_EQ("", req.get_param_value("test", id));
  1907. EXPECT_EQ("", req.form.get_field("test", id));
  1908. EXPECT_EQ("", req.form.get_file("test", id).content);
  1909. }
  1910. }
  1911. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1912. Headers headers;
  1913. headers.emplace("Host", "example.com");
  1914. headers.emplace("Accept-Encoding", "gzip");
  1915. headers.emplace("User-Agent", "test");
  1916. headers.emplace("Accept-Encoding", "deflate");
  1917. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1918. "Accept-Encoding=deflate ",
  1919. entries_to_string(headers));
  1920. }
  1921. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1922. Headers headers = {{"Content-Type", "text/html"},
  1923. {"CONTENT-TYPE", "text/xml"}};
  1924. EXPECT_EQ(2U, headers.count("content-type"));
  1925. auto it = headers.find("content-type");
  1926. ASSERT_TRUE(it != headers.end());
  1927. EXPECT_EQ("text/html", it->second);
  1928. }
  1929. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1930. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1931. // drop only those fields and leave everything positioned between them.
  1932. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1933. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1934. auto rng = headers.equal_range("a");
  1935. headers.erase(rng.first, rng.second);
  1936. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1937. }
  1938. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1939. Headers headers = {
  1940. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1941. EXPECT_EQ(3U, headers.erase("A"));
  1942. EXPECT_EQ(0U, headers.count("A"));
  1943. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1944. }
  1945. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1946. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1947. headers.emplace_front("Host", "example.com");
  1948. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1949. entries_to_string(headers));
  1950. }
  1951. TEST(ParseHeaderValueTest, Range) {
  1952. {
  1953. Ranges ranges;
  1954. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1955. EXPECT_TRUE(ret);
  1956. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1957. }
  1958. {
  1959. Ranges ranges;
  1960. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1961. EXPECT_TRUE(ret);
  1962. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1963. }
  1964. {
  1965. Ranges ranges;
  1966. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1967. EXPECT_TRUE(ret);
  1968. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1969. }
  1970. {
  1971. Ranges ranges;
  1972. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1973. EXPECT_FALSE(ret);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1980. }
  1981. {
  1982. Ranges ranges;
  1983. auto ret =
  1984. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1985. EXPECT_TRUE(ret);
  1986. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1987. }
  1988. {
  1989. Ranges ranges;
  1990. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2003. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2004. EXPECT_FALSE(
  2005. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2006. EXPECT_TRUE(ranges.empty());
  2007. }
  2008. {
  2009. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2010. // remainder of the representation, so it stays accepted.
  2011. Ranges ranges;
  2012. auto ret =
  2013. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2014. EXPECT_TRUE(ret);
  2015. ASSERT_EQ(1u, ranges.size());
  2016. EXPECT_EQ(0, ranges[0].first);
  2017. EXPECT_EQ(-1, ranges[0].second);
  2018. }
  2019. // RFC 9110 14.1: range unit names are case-insensitive.
  2020. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2021. Ranges ranges;
  2022. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2023. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2024. }
  2025. }
  2026. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2027. Request req;
  2028. req.set_header("Accept-Encoding", "gzip");
  2029. Response res;
  2030. res.set_header("Content-Type", "text/plain");
  2031. auto ret = detail::encoding_type(req, res);
  2032. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2033. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2034. #else
  2035. EXPECT_TRUE(ret == detail::EncodingType::None);
  2036. #endif
  2037. }
  2038. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2039. Request req;
  2040. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2041. Response res;
  2042. res.set_header("Content-Type", "text/plain");
  2043. auto ret = detail::encoding_type(req, res);
  2044. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2046. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2048. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2050. #else
  2051. EXPECT_TRUE(ret == detail::EncodingType::None);
  2052. #endif
  2053. }
  2054. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2055. Request req;
  2056. req.set_header("Accept-Encoding",
  2057. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2058. Response res;
  2059. res.set_header("Content-Type", "text/plain");
  2060. auto ret = detail::encoding_type(req, res);
  2061. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2063. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2065. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2067. #else
  2068. EXPECT_TRUE(ret == detail::EncodingType::None);
  2069. #endif
  2070. }
  2071. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2072. // All supported encodings rejected with q=0 should return None
  2073. Request req;
  2074. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2075. Response res;
  2076. res.set_header("Content-Type", "text/plain");
  2077. auto ret = detail::encoding_type(req, res);
  2078. EXPECT_TRUE(ret == detail::EncodingType::None);
  2079. }
  2080. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2081. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2082. Request req;
  2083. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2084. Response res;
  2085. res.set_header("Content-Type", "text/plain");
  2086. auto ret = detail::encoding_type(req, res);
  2087. EXPECT_TRUE(ret == detail::EncodingType::None);
  2088. }
  2089. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2092. Response res;
  2093. res.set_header("Content-Type", "text/plain");
  2094. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2095. }
  2096. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2097. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2098. Request req;
  2099. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2100. Response res;
  2101. res.set_header("Content-Type", "text/plain");
  2102. auto ret = detail::encoding_type(req, res);
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. }
  2105. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2106. // RFC 7231: Accept-Encoding values are case-insensitive
  2107. Request req;
  2108. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2109. Response res;
  2110. res.set_header("Content-Type", "text/plain");
  2111. auto ret = detail::encoding_type(req, res);
  2112. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2113. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2114. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2116. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2118. #else
  2119. EXPECT_TRUE(ret == detail::EncodingType::None);
  2120. #endif
  2121. }
  2122. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2123. // q value should determine priority, not hardcoded order
  2124. Request req;
  2125. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2126. Response res;
  2127. res.set_header("Content-Type", "text/plain");
  2128. auto ret = detail::encoding_type(req, res);
  2129. // gzip has highest q=1.0, so it should be selected even though
  2130. // br and zstd are also supported
  2131. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2132. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2133. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2135. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2137. #else
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. #endif
  2140. }
  2141. TEST(BufferStreamTest, read) {
  2142. detail::BufferStream strm1;
  2143. Stream &strm = strm1;
  2144. EXPECT_EQ(5, strm.write("hello"));
  2145. char buf[512];
  2146. EXPECT_EQ(2, strm.read(buf, 2));
  2147. EXPECT_EQ('h', buf[0]);
  2148. EXPECT_EQ('e', buf[1]);
  2149. EXPECT_EQ(2, strm.read(buf, 2));
  2150. EXPECT_EQ('l', buf[0]);
  2151. EXPECT_EQ('l', buf[1]);
  2152. EXPECT_EQ(1, strm.read(buf, 1));
  2153. EXPECT_EQ('o', buf[0]);
  2154. EXPECT_EQ(0, strm.read(buf, 1));
  2155. }
  2156. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2157. auto host = "www.httpwatch.com";
  2158. auto ip = hosted_at(host);
  2159. EXPECT_EQ("23.96.13.243", ip);
  2160. std::vector<std::string> addrs;
  2161. hosted_at(host, addrs);
  2162. EXPECT_EQ(1u, addrs.size());
  2163. }
  2164. #if 0 // It depends on each test environment...
  2165. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2166. auto host = "www.youtube.com";
  2167. std::vector<std::string> addrs;
  2168. hosted_at(host, addrs);
  2169. EXPECT_EQ(20u, addrs.size());
  2170. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2171. EXPECT_TRUE(it != addrs.end());
  2172. }
  2173. #endif
  2174. class ChunkedEncodingTest : public ::testing::Test {
  2175. protected:
  2176. ChunkedEncodingTest()
  2177. : cli_(HOST, PORT)
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. ,
  2180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2181. #endif
  2182. {
  2183. cli_.set_connection_timeout(2);
  2184. #ifdef CPPHTTPLIB_SSL_ENABLED
  2185. cli_.enable_server_certificate_verification(false);
  2186. #endif
  2187. }
  2188. virtual void SetUp() {
  2189. read_file("./image.jpg", image_data_);
  2190. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2191. res.set_content("Hello World!", "text/plain");
  2192. });
  2193. svr_.Get(
  2194. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2195. res.set_chunked_content_provider(
  2196. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2197. size_t remaining = image_data_.size() - offset;
  2198. if (remaining == 0) {
  2199. sink.done();
  2200. } else {
  2201. constexpr size_t CHUNK_SIZE = 1024;
  2202. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2203. sink.write(&image_data_[offset], send_size);
  2204. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2205. }
  2206. return true;
  2207. });
  2208. });
  2209. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2210. svr_.wait_until_ready();
  2211. }
  2212. virtual void TearDown() {
  2213. svr_.stop();
  2214. if (!request_threads_.empty()) {
  2215. std::this_thread::sleep_for(std::chrono::seconds(1));
  2216. for (auto &t : request_threads_) {
  2217. t.join();
  2218. }
  2219. }
  2220. t_.join();
  2221. }
  2222. #ifdef CPPHTTPLIB_SSL_ENABLED
  2223. SSLClient cli_;
  2224. SSLServer svr_;
  2225. #else
  2226. Client cli_;
  2227. Server svr_;
  2228. #endif
  2229. thread t_;
  2230. std::vector<thread> request_threads_;
  2231. std::string image_data_;
  2232. };
  2233. TEST_F(ChunkedEncodingTest, NormalGet) {
  2234. auto res = cli_.Get("/chunked");
  2235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2236. std::string out;
  2237. read_file("./image.jpg", out);
  2238. EXPECT_EQ(StatusCode::OK_200, res->status);
  2239. EXPECT_EQ(out, res->body);
  2240. }
  2241. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2242. std::string body;
  2243. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2244. body.append(data, data_length);
  2245. return true;
  2246. });
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. std::string out;
  2249. read_file("./image.jpg", out);
  2250. EXPECT_EQ(StatusCode::OK_200, res->status);
  2251. EXPECT_EQ(out, body);
  2252. }
  2253. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2254. std::string body;
  2255. auto res = cli_.Get(
  2256. "/chunked",
  2257. [&](const Response &response) {
  2258. EXPECT_EQ(StatusCode::OK_200, response.status);
  2259. return true;
  2260. },
  2261. [&](const char *data, size_t data_length) {
  2262. body.append(data, data_length);
  2263. return true;
  2264. });
  2265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2266. std::string out;
  2267. read_file("./image.jpg", out);
  2268. EXPECT_EQ(StatusCode::OK_200, res->status);
  2269. EXPECT_EQ(out, body);
  2270. }
  2271. TEST(RangeTest, FromHTTPBin_Online) {
  2272. auto host = "httpbingo.org";
  2273. auto path = std::string{"/range/32"};
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. auto port = 443;
  2276. SSLClient cli(host, port);
  2277. #else
  2278. auto port = 80;
  2279. Client cli(host, port);
  2280. #endif
  2281. cli.set_connection_timeout(5);
  2282. {
  2283. auto res = cli.Get(path);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2286. EXPECT_EQ(StatusCode::OK_200, res->status);
  2287. }
  2288. {
  2289. Headers headers = {make_range_header({{1, -1}})};
  2290. auto res = cli.Get(path, headers);
  2291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2292. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2294. }
  2295. {
  2296. Headers headers = {make_range_header({{1, 10}})};
  2297. auto res = cli.Get(path, headers);
  2298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2299. EXPECT_EQ("bcdefghijk", res->body);
  2300. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2301. }
  2302. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2303. // entire resource, while the original httpbin returned 200. Both are
  2304. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2305. {
  2306. Headers headers = {make_range_header({{0, 31}})};
  2307. auto res = cli.Get(path, headers);
  2308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2309. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2310. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2311. res->status == StatusCode::PartialContent_206);
  2312. }
  2313. {
  2314. Headers headers = {make_range_header({{0, -1}})};
  2315. auto res = cli.Get(path, headers);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2318. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2319. res->status == StatusCode::PartialContent_206);
  2320. }
  2321. // go-httpbin returns 206 with clamped range for over-range requests,
  2322. // while the original httpbin returned 416. Both behaviors are observed
  2323. // in real servers, so we only verify the request succeeds.
  2324. {
  2325. Headers headers = {make_range_header({{0, 32}})};
  2326. auto res = cli.Get(path, headers);
  2327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2328. }
  2329. }
  2330. TEST(RangeTest, IgnoredForPost) {
  2331. Server svr;
  2332. svr.Post("/", [](const Request &, Response &res) {
  2333. res.set_content("abcdefg", "text/plain");
  2334. });
  2335. auto port = svr.bind_to_any_port(HOST);
  2336. ASSERT_GT(port, 0);
  2337. thread t = thread([&] { svr.listen_after_bind(); });
  2338. auto se = detail::scope_exit([&] {
  2339. svr.stop();
  2340. t.join();
  2341. ASSERT_FALSE(svr.is_running());
  2342. });
  2343. svr.wait_until_ready();
  2344. Client cli(HOST, port);
  2345. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2346. auto res = cli.Post("/", Headers{{"Range", range}});
  2347. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2348. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2349. EXPECT_EQ("abcdefg", res->body) << range;
  2350. }
  2351. }
  2352. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2353. auto host = "unresolvableaddress.local";
  2354. auto path = std::string{"/"};
  2355. #ifdef CPPHTTPLIB_SSL_ENABLED
  2356. auto port = 443;
  2357. SSLClient cli(host, port);
  2358. #else
  2359. auto port = 80;
  2360. Client cli(host, port);
  2361. #endif
  2362. cli.set_connection_timeout(1);
  2363. {
  2364. auto res = cli.Get(path);
  2365. ASSERT_FALSE(res);
  2366. }
  2367. std::this_thread::sleep_for(std::chrono::seconds(8));
  2368. }
  2369. #if defined(__linux__) && defined(__GLIBC__) && \
  2370. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2371. // Forward declaration: in split builds split.py strips `inline` and moves the
  2372. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2373. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2374. // against the symbol in both header-only and split builds.
  2375. namespace httplib {
  2376. namespace detail {
  2377. int getaddrinfo_with_timeout(const char *node, const char *service,
  2378. const struct addrinfo *hints,
  2379. struct addrinfo **res, time_t timeout_sec);
  2380. } // namespace detail
  2381. } // namespace httplib
  2382. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2383. //
  2384. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2385. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2386. // gai_suspend() call hits the connection timeout the function calls
  2387. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2388. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2389. // still alive and still references the now-destroyed stack frame.
  2390. //
  2391. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2392. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2393. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2394. // and runs them in a container.
  2395. namespace {
  2396. bool should_run_issue_2431_tests() {
  2397. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2398. return v && *v && std::string(v) != "0";
  2399. }
  2400. std::string unique_unresolvable_host(int n) {
  2401. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2402. // glibc still asks the configured nameserver — which is exactly the path
  2403. // we want to exercise. A unique label per call avoids the resolver cache.
  2404. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2405. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2406. std::to_string(n) + ".invalid";
  2407. }
  2408. } // namespace
  2409. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2410. if (!should_run_issue_2431_tests()) {
  2411. GTEST_SKIP()
  2412. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2413. }
  2414. for (int i = 0; i < 8; ++i) {
  2415. struct addrinfo hints;
  2416. memset(&hints, 0, sizeof(hints));
  2417. hints.ai_family = AF_UNSPEC;
  2418. hints.ai_socktype = SOCK_STREAM;
  2419. auto host = unique_unresolvable_host(i);
  2420. struct addrinfo *result = nullptr;
  2421. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2422. &result, /*timeout_sec=*/1);
  2423. if (rc == 0 && result) { freeaddrinfo(result); }
  2424. }
  2425. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2426. // stack region they still believe holds their gaicb.
  2427. std::this_thread::sleep_for(std::chrono::seconds(3));
  2428. }
  2429. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2430. if (!should_run_issue_2431_tests()) {
  2431. GTEST_SKIP()
  2432. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2433. }
  2434. std::atomic<bool> stop{false};
  2435. std::vector<std::thread> threads;
  2436. for (int t = 0; t < 8; ++t) {
  2437. threads.emplace_back([t, &stop] {
  2438. int i = 0;
  2439. while (!stop.load(std::memory_order_relaxed)) {
  2440. struct addrinfo hints;
  2441. memset(&hints, 0, sizeof(hints));
  2442. hints.ai_family = AF_UNSPEC;
  2443. hints.ai_socktype = SOCK_STREAM;
  2444. auto host = unique_unresolvable_host(t * 100000 + i++);
  2445. struct addrinfo *result = nullptr;
  2446. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2447. &result, /*timeout_sec=*/1);
  2448. if (rc == 0 && result) { freeaddrinfo(result); }
  2449. }
  2450. });
  2451. }
  2452. std::this_thread::sleep_for(std::chrono::seconds(8));
  2453. stop.store(true, std::memory_order_relaxed);
  2454. for (auto &th : threads) {
  2455. th.join();
  2456. }
  2457. std::this_thread::sleep_for(std::chrono::seconds(3));
  2458. }
  2459. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2460. if (!should_run_issue_2431_tests()) {
  2461. GTEST_SKIP()
  2462. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2463. }
  2464. std::atomic<bool> stop{false};
  2465. std::vector<std::thread> threads;
  2466. for (int t = 0; t < 8; ++t) {
  2467. threads.emplace_back([t, &stop] {
  2468. int i = 0;
  2469. while (!stop.load(std::memory_order_relaxed)) {
  2470. auto host = unique_unresolvable_host(t * 100000 + i++);
  2471. Client cli(host, 80);
  2472. cli.set_connection_timeout(1, 0);
  2473. cli.set_read_timeout(1, 0);
  2474. cli.set_write_timeout(1, 0);
  2475. (void)cli.Get("/");
  2476. }
  2477. });
  2478. }
  2479. std::this_thread::sleep_for(std::chrono::seconds(8));
  2480. stop.store(true, std::memory_order_relaxed);
  2481. for (auto &th : threads) {
  2482. th.join();
  2483. }
  2484. std::this_thread::sleep_for(std::chrono::seconds(3));
  2485. }
  2486. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2487. TEST(ConnectionErrorTest, InvalidHost) {
  2488. auto host = "-abcde.com";
  2489. #ifdef CPPHTTPLIB_SSL_ENABLED
  2490. auto port = 443;
  2491. SSLClient cli(host, port);
  2492. #else
  2493. auto port = 80;
  2494. Client cli(host, port);
  2495. #endif
  2496. cli.set_connection_timeout(std::chrono::seconds(2));
  2497. auto res = cli.Get("/");
  2498. ASSERT_TRUE(!res);
  2499. EXPECT_EQ(Error::Connection, res.error());
  2500. }
  2501. TEST(ConnectionErrorTest, InvalidHost2) {
  2502. auto host = "httpcan.org/";
  2503. #ifdef CPPHTTPLIB_SSL_ENABLED
  2504. SSLClient cli(host);
  2505. #else
  2506. Client cli(host);
  2507. #endif
  2508. cli.set_connection_timeout(std::chrono::seconds(2));
  2509. auto res = cli.Get("/");
  2510. ASSERT_TRUE(!res);
  2511. EXPECT_EQ(Error::Connection, res.error());
  2512. }
  2513. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2514. auto host = "httpcan.org/";
  2515. #ifdef CPPHTTPLIB_SSL_ENABLED
  2516. SSLClient cli(host);
  2517. #else
  2518. Client cli(host);
  2519. #endif
  2520. cli.set_connection_timeout(std::chrono::seconds(2));
  2521. auto res = cli.Get("/");
  2522. ASSERT_TRUE(!res);
  2523. stringstream s;
  2524. s << "error code: " << res.error();
  2525. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2526. }
  2527. TEST(ConnectionErrorTest, InvalidPort) {
  2528. auto host = "localhost";
  2529. auto port = 44380;
  2530. #ifdef CPPHTTPLIB_SSL_ENABLED
  2531. SSLClient cli(host, port);
  2532. #else
  2533. Client cli(host, port);
  2534. #endif
  2535. cli.set_connection_timeout(std::chrono::seconds(2));
  2536. auto res = cli.Get("/");
  2537. ASSERT_TRUE(!res);
  2538. EXPECT_TRUE(Error::Connection == res.error() ||
  2539. Error::ConnectionTimeout == res.error());
  2540. }
  2541. TEST(ConnectionErrorTest, Timeout_Online) {
  2542. auto host = "google.com";
  2543. #ifdef CPPHTTPLIB_SSL_ENABLED
  2544. auto port = 44380;
  2545. SSLClient cli(host, port);
  2546. #else
  2547. auto port = 8080;
  2548. Client cli(host, port);
  2549. #endif
  2550. cli.set_connection_timeout(std::chrono::seconds(2));
  2551. // only probe one address type so that the error reason
  2552. // correlates to the timed-out IPv4, not the unsupported
  2553. // IPv6 connection attempt
  2554. cli.set_address_family(AF_INET);
  2555. auto res = cli.Get("/");
  2556. ASSERT_TRUE(!res);
  2557. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2558. }
  2559. TEST(CancelTest, NoCancel_Online) {
  2560. auto host = "httpbingo.org";
  2561. auto path = std::string{"/range/32"};
  2562. #ifdef CPPHTTPLIB_SSL_ENABLED
  2563. auto port = 443;
  2564. SSLClient cli(host, port);
  2565. #else
  2566. auto port = 80;
  2567. Client cli(host, port);
  2568. #endif
  2569. cli.set_connection_timeout(std::chrono::seconds(5));
  2570. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2572. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2573. EXPECT_EQ(StatusCode::OK_200, res->status);
  2574. }
  2575. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2576. // Use /bytes with a large payload so that the DownloadProgress callback
  2577. // (which only fires for Content-Length responses) is invoked before the
  2578. // entire body is received, giving cancellation a chance to fire.
  2579. auto host = "httpbingo.org";
  2580. auto path = std::string{"/bytes/524288"};
  2581. #ifdef CPPHTTPLIB_SSL_ENABLED
  2582. auto port = 443;
  2583. SSLClient cli(host, port);
  2584. #else
  2585. auto port = 80;
  2586. Client cli(host, port);
  2587. #endif
  2588. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2589. cli.set_connection_timeout(std::chrono::seconds(5));
  2590. ASSERT_TRUE(!res);
  2591. EXPECT_EQ(Error::Canceled, res.error());
  2592. }
  2593. TEST(CancelTest, WithCancelLargePayload_Online) {
  2594. auto host = "httpbingo.org";
  2595. auto path = std::string{"/bytes/524288"};
  2596. #ifdef CPPHTTPLIB_SSL_ENABLED
  2597. auto port = 443;
  2598. SSLClient cli(host, port);
  2599. #else
  2600. auto port = 80;
  2601. Client cli(host, port);
  2602. #endif
  2603. cli.set_connection_timeout(std::chrono::seconds(5));
  2604. uint32_t count = 0;
  2605. auto res =
  2606. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2607. ASSERT_TRUE(!res);
  2608. EXPECT_EQ(Error::Canceled, res.error());
  2609. }
  2610. TEST(CancelTest, NoCancelPost) {
  2611. Server svr;
  2612. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2613. res.set_content("Hello World!", "text/plain");
  2614. });
  2615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2616. auto se = detail::scope_exit([&] {
  2617. svr.stop();
  2618. thread.join();
  2619. ASSERT_FALSE(svr.is_running());
  2620. });
  2621. svr.wait_until_ready();
  2622. Client cli(HOST, PORT);
  2623. cli.set_connection_timeout(std::chrono::seconds(5));
  2624. auto res =
  2625. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2626. "application/json", [](uint64_t, uint64_t) { return true; });
  2627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2628. EXPECT_EQ("Hello World!", res->body);
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. }
  2631. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2632. Server svr;
  2633. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2634. res.set_content("Hello World!", "text/plain");
  2635. });
  2636. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2637. auto se = detail::scope_exit([&] {
  2638. svr.stop();
  2639. thread.join();
  2640. ASSERT_FALSE(svr.is_running());
  2641. });
  2642. svr.wait_until_ready();
  2643. Client cli(HOST, PORT);
  2644. cli.set_connection_timeout(std::chrono::seconds(5));
  2645. auto res =
  2646. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2647. "application/json", [](uint64_t, uint64_t) { return false; });
  2648. ASSERT_TRUE(!res);
  2649. EXPECT_EQ(Error::Canceled, res.error());
  2650. }
  2651. TEST(CancelTest, WithCancelLargePayloadPost) {
  2652. Server svr;
  2653. svr.set_payload_max_length(200 * 1024 * 1024);
  2654. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2655. res.set_content(LARGE_DATA, "text/plain");
  2656. });
  2657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2658. auto se = detail::scope_exit([&] {
  2659. svr.stop();
  2660. thread.join();
  2661. ASSERT_FALSE(svr.is_running());
  2662. });
  2663. svr.wait_until_ready();
  2664. Client cli(HOST, PORT);
  2665. cli.set_payload_max_length(200 * 1024 * 1024);
  2666. cli.set_connection_timeout(std::chrono::seconds(5));
  2667. auto res =
  2668. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2669. "application/json", [](uint64_t, uint64_t) { return false; });
  2670. ASSERT_TRUE(!res);
  2671. EXPECT_EQ(Error::Canceled, res.error());
  2672. }
  2673. TEST(CancelTest, NoCancelPut) {
  2674. Server svr;
  2675. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2676. res.set_content("Hello World!", "text/plain");
  2677. });
  2678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2679. auto se = detail::scope_exit([&] {
  2680. svr.stop();
  2681. thread.join();
  2682. ASSERT_FALSE(svr.is_running());
  2683. });
  2684. svr.wait_until_ready();
  2685. Client cli(HOST, PORT);
  2686. cli.set_connection_timeout(std::chrono::seconds(5));
  2687. auto res =
  2688. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2689. "application/json", [](uint64_t, uint64_t) { return true; });
  2690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2691. EXPECT_EQ("Hello World!", res->body);
  2692. EXPECT_EQ(StatusCode::OK_200, res->status);
  2693. }
  2694. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2695. Server svr;
  2696. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2697. res.set_content("Hello World!", "text/plain");
  2698. });
  2699. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2700. auto se = detail::scope_exit([&] {
  2701. svr.stop();
  2702. thread.join();
  2703. ASSERT_FALSE(svr.is_running());
  2704. });
  2705. svr.wait_until_ready();
  2706. Client cli(HOST, PORT);
  2707. cli.set_connection_timeout(std::chrono::seconds(5));
  2708. auto res =
  2709. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2710. "application/json", [](uint64_t, uint64_t) { return false; });
  2711. ASSERT_TRUE(!res);
  2712. EXPECT_EQ(Error::Canceled, res.error());
  2713. }
  2714. TEST(CancelTest, WithCancelLargePayloadPut) {
  2715. Server svr;
  2716. svr.set_payload_max_length(200 * 1024 * 1024);
  2717. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2718. res.set_content(LARGE_DATA, "text/plain");
  2719. });
  2720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2721. auto se = detail::scope_exit([&] {
  2722. svr.stop();
  2723. thread.join();
  2724. ASSERT_FALSE(svr.is_running());
  2725. });
  2726. svr.wait_until_ready();
  2727. Client cli(HOST, PORT);
  2728. cli.set_payload_max_length(200 * 1024 * 1024);
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. auto res =
  2731. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2732. "application/json", [](uint64_t, uint64_t) { return false; });
  2733. ASSERT_TRUE(!res);
  2734. EXPECT_EQ(Error::Canceled, res.error());
  2735. }
  2736. TEST(CancelTest, NoCancelPatch) {
  2737. Server svr;
  2738. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2739. res.set_content("Hello World!", "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. cli.set_connection_timeout(std::chrono::seconds(5));
  2750. auto res =
  2751. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2752. "application/json", [](uint64_t, uint64_t) { return true; });
  2753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2754. EXPECT_EQ("Hello World!", res->body);
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. }
  2757. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2758. Server svr;
  2759. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2760. res.set_content("Hello World!", "text/plain");
  2761. });
  2762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2763. auto se = detail::scope_exit([&] {
  2764. svr.stop();
  2765. thread.join();
  2766. ASSERT_FALSE(svr.is_running());
  2767. });
  2768. svr.wait_until_ready();
  2769. Client cli(HOST, PORT);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2778. Server svr;
  2779. svr.set_payload_max_length(200 * 1024 * 1024);
  2780. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2781. res.set_content(LARGE_DATA, "text/plain");
  2782. });
  2783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2784. auto se = detail::scope_exit([&] {
  2785. svr.stop();
  2786. thread.join();
  2787. ASSERT_FALSE(svr.is_running());
  2788. });
  2789. svr.wait_until_ready();
  2790. Client cli(HOST, PORT);
  2791. cli.set_payload_max_length(200 * 1024 * 1024);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return false; });
  2796. ASSERT_TRUE(!res);
  2797. EXPECT_EQ(Error::Canceled, res.error());
  2798. }
  2799. TEST(CancelTest, NoCancelDelete) {
  2800. Server svr;
  2801. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2802. res.set_content("Hello World!", "text/plain");
  2803. });
  2804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2805. auto se = detail::scope_exit([&] {
  2806. svr.stop();
  2807. thread.join();
  2808. ASSERT_FALSE(svr.is_running());
  2809. });
  2810. svr.wait_until_ready();
  2811. Client cli(HOST, PORT);
  2812. cli.set_connection_timeout(std::chrono::seconds(5));
  2813. auto res =
  2814. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2815. "application/json", [](uint64_t, uint64_t) { return true; });
  2816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2817. EXPECT_EQ("Hello World!", res->body);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. }
  2820. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2821. Server svr;
  2822. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2823. res.set_content("Hello World!", "text/plain");
  2824. });
  2825. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2826. auto se = detail::scope_exit([&] {
  2827. svr.stop();
  2828. thread.join();
  2829. ASSERT_FALSE(svr.is_running());
  2830. });
  2831. svr.wait_until_ready();
  2832. Client cli(HOST, PORT);
  2833. cli.set_connection_timeout(std::chrono::seconds(5));
  2834. auto res =
  2835. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2836. "application/json", [](uint64_t, uint64_t) { return false; });
  2837. ASSERT_TRUE(!res);
  2838. EXPECT_EQ(Error::Canceled, res.error());
  2839. }
  2840. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2841. Server svr;
  2842. svr.set_payload_max_length(200 * 1024 * 1024);
  2843. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2844. res.set_content(LARGE_DATA, "text/plain");
  2845. });
  2846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2847. auto se = detail::scope_exit([&] {
  2848. svr.stop();
  2849. thread.join();
  2850. ASSERT_FALSE(svr.is_running());
  2851. });
  2852. svr.wait_until_ready();
  2853. Client cli(HOST, PORT);
  2854. cli.set_payload_max_length(200 * 1024 * 1024);
  2855. cli.set_connection_timeout(std::chrono::seconds(5));
  2856. auto res =
  2857. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2858. "application/json", [](uint64_t, uint64_t) { return false; });
  2859. ASSERT_TRUE(!res);
  2860. EXPECT_EQ(Error::Canceled, res.error());
  2861. }
  2862. static std::string remove_whitespace(const std::string &input) {
  2863. std::string output;
  2864. output.reserve(input.size());
  2865. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2866. [](unsigned char c) { return !std::isspace(c); });
  2867. return output;
  2868. }
  2869. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2870. auto host = "httpbingo.org";
  2871. auto path = std::string{"/basic-auth/hello/world"};
  2872. #ifdef CPPHTTPLIB_SSL_ENABLED
  2873. auto port = 443;
  2874. SSLClient cli(host, port);
  2875. #else
  2876. auto port = 80;
  2877. Client cli(host, port);
  2878. #endif
  2879. {
  2880. auto res = cli.Get(path);
  2881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2882. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2883. }
  2884. {
  2885. auto res = cli.Get(
  2886. path, Headers{make_basic_authentication_header("hello", "world")});
  2887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2888. auto body = remove_whitespace(res->body);
  2889. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2890. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2891. EXPECT_EQ(StatusCode::OK_200, res->status);
  2892. }
  2893. {
  2894. cli.set_basic_auth("hello", "world");
  2895. auto res = cli.Get(path);
  2896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2897. auto body = remove_whitespace(res->body);
  2898. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2899. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2900. EXPECT_EQ(StatusCode::OK_200, res->status);
  2901. }
  2902. {
  2903. cli.set_basic_auth("hello", "bad");
  2904. auto res = cli.Get(path);
  2905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2906. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2907. }
  2908. {
  2909. cli.set_basic_auth("bad", "world");
  2910. auto res = cli.Get(path);
  2911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2912. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2913. }
  2914. }
  2915. #ifdef CPPHTTPLIB_SSL_ENABLED
  2916. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2917. auto host = "httpbingo.org";
  2918. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2919. auto paths = std::vector<std::string>{
  2920. "/digest-auth/auth/hello/world/MD5",
  2921. "/digest-auth/auth/hello/world/SHA-256",
  2922. };
  2923. auto port = 443;
  2924. SSLClient cli(host, port);
  2925. {
  2926. auto res = cli.Get(unauth_path);
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2929. }
  2930. {
  2931. cli.set_digest_auth("hello", "world");
  2932. for (const auto &path : paths) {
  2933. auto res = cli.Get(path.c_str());
  2934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2935. auto body = remove_whitespace(res->body);
  2936. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2937. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2938. EXPECT_EQ(StatusCode::OK_200, res->status);
  2939. }
  2940. cli.set_digest_auth("hello", "bad");
  2941. for (const auto &path : paths) {
  2942. auto res = cli.Get(path.c_str());
  2943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2944. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2945. }
  2946. }
  2947. }
  2948. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2949. // comma-separated list of challenges, and each challenge may itself carry a
  2950. // comma-separated auth-param list, so a server can legally offer Basic
  2951. // before Digest, either as two field lines or packed into one. Runs one 401
  2952. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2953. // value() joins them in receipt order) and checks that the retry carries a
  2954. // well-formed Digest Authorization header naming expected_realm.
  2955. static void
  2956. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2957. const std::string &expected_realm) {
  2958. std::atomic<int> hits{0};
  2959. Server svr;
  2960. svr.Get("/x", [&](const Request &req, Response &res) {
  2961. if (++hits == 1) {
  2962. res.status = StatusCode::Unauthorized_401;
  2963. for (const auto &challenge : challenges) {
  2964. res.set_header("WWW-Authenticate", challenge);
  2965. }
  2966. } else {
  2967. auto authorization = req.get_header_value("Authorization");
  2968. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2969. EXPECT_NE(std::string::npos,
  2970. authorization.find("realm=\"" + expected_realm + "\""));
  2971. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2972. res.set_content("ok", "text/plain");
  2973. }
  2974. });
  2975. auto port = svr.bind_to_any_port(HOST);
  2976. std::thread t([&]() { svr.listen_after_bind(); });
  2977. auto se = detail::scope_exit([&] {
  2978. svr.stop();
  2979. t.join();
  2980. });
  2981. svr.wait_until_ready();
  2982. Client cli(HOST, port);
  2983. cli.set_digest_auth("hello", "world");
  2984. auto res = cli.Get("/x");
  2985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2986. EXPECT_EQ(2, hits.load());
  2987. }
  2988. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2989. static const char *kDigestChallenge =
  2990. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2991. "algorithm=MD5";
  2992. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2993. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2994. "testrealm");
  2995. }
  2996. // Same challenge list with the schemes in the opposite order, to make sure
  2997. // the fix above didn't just special-case "Basic first".
  2998. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2999. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3000. "testrealm");
  3001. }
  3002. // A comma inside a quoted auth-param value must not be mistaken for the
  3003. // separator between two challenges (or two auth-params).
  3004. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3005. run_digest_challenge_list_test(
  3006. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3007. "algorithm=MD5"},
  3008. "test,realm");
  3009. }
  3010. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3011. // the params and leaves out the fragment.
  3012. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3013. Server svr;
  3014. std::string uri, target;
  3015. svr.Get("/a b", [&](const Request &req, Response &res) {
  3016. auto auth = req.get_header_value("Authorization");
  3017. if (auth.empty()) {
  3018. res.status = StatusCode::Unauthorized_401;
  3019. res.set_header("WWW-Authenticate",
  3020. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3021. return;
  3022. }
  3023. auto b = auth.find("uri=\"") + 5;
  3024. uri = auth.substr(b, auth.find('"', b) - b);
  3025. target = req.target;
  3026. });
  3027. auto port = svr.bind_to_any_port(HOST);
  3028. std::thread t([&]() { svr.listen_after_bind(); });
  3029. auto se = detail::scope_exit([&] {
  3030. svr.stop();
  3031. t.join();
  3032. });
  3033. svr.wait_until_ready();
  3034. Client cli(HOST, port);
  3035. cli.set_digest_auth("hello", "world");
  3036. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3038. EXPECT_EQ("/a%20b?x=1", target);
  3039. EXPECT_EQ(target, uri);
  3040. }
  3041. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3042. // make_digest_authentication_header() dereferences both unconditionally, so
  3043. // a server sending a challenge missing either one must not be treated as
  3044. // usable -- doing so used to crash the client with std::out_of_range.
  3045. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3046. Server svr;
  3047. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3048. res.status = StatusCode::Unauthorized_401;
  3049. res.set_header("WWW-Authenticate", challenge);
  3050. });
  3051. auto port = svr.bind_to_any_port(HOST);
  3052. std::thread t([&]() { svr.listen_after_bind(); });
  3053. auto se = detail::scope_exit([&] {
  3054. svr.stop();
  3055. t.join();
  3056. });
  3057. svr.wait_until_ready();
  3058. Client cli(HOST, port);
  3059. cli.set_digest_auth("hello", "world");
  3060. auto res = cli.Get("/x");
  3061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3062. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3063. }
  3064. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3065. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3066. }
  3067. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3068. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3069. }
  3070. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3071. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3072. }
  3073. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3074. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3075. // when storing the values, so the header builder has to re-escape them (and
  3076. // keep algorithm a bare token); otherwise the value breaks out of its
  3077. // quoted-string and injects extra auth-params into the client's Authorization.
  3078. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3079. std::atomic<int> hits{0};
  3080. std::string authorization;
  3081. Server svr;
  3082. svr.Get("/x", [&](const Request &req, Response &res) {
  3083. if (++hits == 1) {
  3084. res.status = StatusCode::Unauthorized_401;
  3085. // On the wire the quotes embedded in the values are backslash-escaped.
  3086. res.set_header("WWW-Authenticate",
  3087. "Digest realm=\"testrealm\", "
  3088. "nonce=\"n\\\"; injected=\\\"x\", "
  3089. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3090. } else {
  3091. authorization = req.get_header_value("Authorization");
  3092. res.set_content("ok", "text/plain");
  3093. }
  3094. });
  3095. auto port = svr.bind_to_any_port(HOST);
  3096. std::thread t([&]() { svr.listen_after_bind(); });
  3097. auto se = detail::scope_exit([&] {
  3098. svr.stop();
  3099. t.join();
  3100. });
  3101. svr.wait_until_ready();
  3102. Client cli(HOST, port);
  3103. cli.set_digest_auth("hello", "world");
  3104. auto res = cli.Get("/x");
  3105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3106. EXPECT_EQ(2, hits.load());
  3107. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3108. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3109. // inside its quoted-string rather than starting an "injected" auth-param.
  3110. EXPECT_NE(std::string::npos,
  3111. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3112. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3113. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3114. }
  3115. #endif
  3116. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3117. auto host = "google.com";
  3118. auto another_host = "example.com";
  3119. auto wrong_ip = "0.0.0.0";
  3120. #ifdef CPPHTTPLIB_SSL_ENABLED
  3121. SSLClient cli(host);
  3122. #else
  3123. Client cli(host);
  3124. #endif
  3125. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3126. auto res = cli.Get("/");
  3127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3128. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3129. }
  3130. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3131. auto host = "google.com";
  3132. auto wrong_ip = "0.0.0.0";
  3133. #ifdef CPPHTTPLIB_SSL_ENABLED
  3134. SSLClient cli(host);
  3135. #else
  3136. Client cli(host);
  3137. #endif
  3138. cli.set_hostname_addr_map({{host, wrong_ip}});
  3139. auto res = cli.Get("/");
  3140. ASSERT_TRUE(!res);
  3141. EXPECT_EQ(Error::Connection, res.error());
  3142. }
  3143. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3144. // A mapped value that is not an IP literal must be resolved. "localhost"
  3145. // resolves from the hosts file, so this test needs no external DNS.
  3146. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3147. auto host = "target.invalid";
  3148. Server svr;
  3149. std::string received_host;
  3150. svr.Get("/hi", [&](const Request &req, Response &res) {
  3151. received_host = req.get_header_value("Host");
  3152. res.set_content("Hello World!", "text/plain");
  3153. });
  3154. auto port = svr.bind_to_any_port(HOST);
  3155. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3156. auto se = detail::scope_exit([&] {
  3157. svr.stop();
  3158. thread.join();
  3159. ASSERT_FALSE(svr.is_running());
  3160. });
  3161. svr.wait_until_ready();
  3162. Client cli(host, port);
  3163. cli.set_hostname_addr_map({{host, HOST}});
  3164. auto res = cli.Get("/hi");
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. // The mapping only redirects the connection; the identity stays host_.
  3168. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3169. }
  3170. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3171. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3172. auto host = "target.invalid";
  3173. Server svr;
  3174. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3175. res.set_content("Hello World!", "text/plain");
  3176. });
  3177. auto port = svr.bind_to_any_port("127.0.0.1");
  3178. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3179. auto se = detail::scope_exit([&] {
  3180. svr.stop();
  3181. thread.join();
  3182. ASSERT_FALSE(svr.is_running());
  3183. });
  3184. svr.wait_until_ready();
  3185. Client cli(host, port);
  3186. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3187. auto res = cli.Get("/hi");
  3188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3189. EXPECT_EQ(StatusCode::OK_200, res->status);
  3190. }
  3191. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3192. // An empty mapped value must leave host_ as the connection target. Without
  3193. // that guard the empty value would become the host argument, getaddrinfo
  3194. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3195. // loopback - silently connecting somewhere the caller never asked for.
  3196. // The server listens on loopback, so such a fallback would succeed and is
  3197. // therefore observable as a failure of this test.
  3198. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3199. Server svr;
  3200. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3201. res.set_content("Hello World!", "text/plain");
  3202. });
  3203. auto port = svr.bind_to_any_port(HOST);
  3204. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3205. auto se = detail::scope_exit([&] {
  3206. svr.stop();
  3207. thread.join();
  3208. ASSERT_FALSE(svr.is_running());
  3209. });
  3210. svr.wait_until_ready();
  3211. Client cli(blackhole, port);
  3212. cli.set_hostname_addr_map({{blackhole, ""}});
  3213. cli.set_connection_timeout(1);
  3214. auto res = cli.Get("/hi");
  3215. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3216. }
  3217. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3218. auto host = "httpbingo.org";
  3219. auto path = std::string{"/absolute-redirect/3"};
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(host);
  3222. #else
  3223. Client cli(host);
  3224. #endif
  3225. cli.set_follow_location(true);
  3226. auto res = cli.Get(path);
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. }
  3230. TEST(RedirectTest, Redirect_Online) {
  3231. auto host = "httpbingo.org";
  3232. auto path = std::string{"/redirect/3"};
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. SSLClient cli(host);
  3235. #else
  3236. Client cli(host);
  3237. #endif
  3238. cli.set_follow_location(true);
  3239. auto res = cli.Get(path);
  3240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. }
  3243. TEST(RelativeRedirectTest, Redirect_Online) {
  3244. auto host = "httpbingo.org";
  3245. auto path = std::string{"/relative-redirect/3"};
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. SSLClient cli(host);
  3248. #else
  3249. Client cli(host);
  3250. #endif
  3251. cli.set_follow_location(true);
  3252. auto res = cli.Get(path);
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. }
  3256. TEST(TooManyRedirectTest, Redirect_Online) {
  3257. auto host = "httpbingo.org";
  3258. auto path = std::string{"/redirect/21"};
  3259. #ifdef CPPHTTPLIB_SSL_ENABLED
  3260. SSLClient cli(host);
  3261. #else
  3262. Client cli(host);
  3263. #endif
  3264. cli.set_follow_location(true);
  3265. auto res = cli.Get(path);
  3266. ASSERT_TRUE(!res);
  3267. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3268. }
  3269. #ifdef CPPHTTPLIB_SSL_ENABLED
  3270. TEST(YahooRedirectTest, Redirect_Online) {
  3271. Client cli("yahoo.com");
  3272. auto res = cli.Get("/");
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3275. cli.set_follow_location(true);
  3276. res = cli.Get("/");
  3277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3278. EXPECT_EQ(StatusCode::OK_200, res->status);
  3279. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3280. }
  3281. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3282. #define REDIR_HOST "httpbingo.org"
  3283. #define REDIR_PATH "/redirect-to"
  3284. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3285. SSLClient cli(REDIR_HOST);
  3286. cli.set_follow_location(true);
  3287. auto res =
  3288. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. EXPECT_EQ(StatusCode::OK_200, res->status);
  3291. }
  3292. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3293. SSLClient cli(REDIR_HOST);
  3294. cli.set_follow_location(true);
  3295. Params params;
  3296. params.emplace("url", "http://example.com");
  3297. params.emplace("status_code", "302");
  3298. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3300. EXPECT_EQ(StatusCode::OK_200, res->status);
  3301. }
  3302. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3303. SSLClient cli(REDIR_HOST);
  3304. cli.set_follow_location(true);
  3305. Params params;
  3306. params.emplace("url", "http://example.com");
  3307. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3309. EXPECT_EQ(StatusCode::OK_200, res->status);
  3310. }
  3311. TEST(UrlWithSpace, Redirect_Online) {
  3312. SSLClient cli("edge.forgecdn.net");
  3313. cli.set_follow_location(true);
  3314. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3316. EXPECT_EQ(StatusCode::OK_200, res->status);
  3317. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3318. }
  3319. #endif
  3320. #if !defined(_WIN32) && !defined(_WIN64)
  3321. TEST(ReceiveSignals, Signal) {
  3322. auto setupSignalHandlers = []() {
  3323. struct sigaction act;
  3324. sigemptyset(&act.sa_mask);
  3325. act.sa_flags = SA_SIGINFO;
  3326. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3327. switch (sig) {
  3328. case SIGINT:
  3329. default: break;
  3330. }
  3331. };
  3332. ::sigaction(SIGINT, &act, nullptr);
  3333. };
  3334. Server svr;
  3335. int port = 0;
  3336. auto thread = std::thread([&]() {
  3337. setupSignalHandlers();
  3338. port = svr.bind_to_any_port(HOST);
  3339. svr.listen_after_bind();
  3340. });
  3341. auto se = detail::scope_exit([&] {
  3342. svr.stop();
  3343. thread.join();
  3344. ASSERT_FALSE(svr.is_running());
  3345. });
  3346. svr.wait_until_ready();
  3347. ASSERT_TRUE(svr.is_running());
  3348. pthread_kill(thread.native_handle(), SIGINT);
  3349. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3350. ASSERT_TRUE(svr.is_running());
  3351. }
  3352. #endif
  3353. TEST(RedirectToDifferentPort, Redirect) {
  3354. Server svr1;
  3355. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3356. res.set_content("Hello World!", "text/plain");
  3357. });
  3358. int svr1_port = 0;
  3359. auto thread1 = std::thread([&]() {
  3360. svr1_port = svr1.bind_to_any_port(HOST);
  3361. svr1.listen_after_bind();
  3362. });
  3363. Server svr2;
  3364. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3365. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3366. });
  3367. int svr2_port = 0;
  3368. auto thread2 = std::thread([&]() {
  3369. svr2_port = svr2.bind_to_any_port(HOST);
  3370. svr2.listen_after_bind();
  3371. });
  3372. auto se = detail::scope_exit([&] {
  3373. svr2.stop();
  3374. thread2.join();
  3375. svr1.stop();
  3376. thread1.join();
  3377. ASSERT_FALSE(svr2.is_running());
  3378. ASSERT_FALSE(svr1.is_running());
  3379. });
  3380. svr1.wait_until_ready();
  3381. svr2.wait_until_ready();
  3382. Client cli("localhost", svr2_port);
  3383. cli.set_follow_location(true);
  3384. auto res = cli.Get("/2");
  3385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3386. EXPECT_EQ(StatusCode::OK_200, res->status);
  3387. EXPECT_EQ("Hello World!", res->body);
  3388. }
  3389. // GET /redir on one server redirects to /target on another port, so the
  3390. // client follows it with a new client.
  3391. static Result
  3392. GetThroughRedirectToDifferentPort(Server::Handler target,
  3393. const std::function<void(Client &)> &setup,
  3394. const Headers &headers = Headers()) {
  3395. Server target_svr;
  3396. target_svr.Get("/target", target);
  3397. int target_port = 0;
  3398. auto target_thread = std::thread([&]() {
  3399. target_port = target_svr.bind_to_any_port(HOST);
  3400. target_svr.listen_after_bind();
  3401. });
  3402. Server origin_svr;
  3403. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3404. res.set_redirect(
  3405. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3406. });
  3407. int origin_port = 0;
  3408. auto origin_thread = std::thread([&]() {
  3409. origin_port = origin_svr.bind_to_any_port(HOST);
  3410. origin_svr.listen_after_bind();
  3411. });
  3412. auto se = detail::scope_exit([&] {
  3413. origin_svr.stop();
  3414. origin_thread.join();
  3415. target_svr.stop();
  3416. target_thread.join();
  3417. });
  3418. target_svr.wait_until_ready();
  3419. origin_svr.wait_until_ready();
  3420. Client cli("localhost", origin_port);
  3421. cli.set_follow_location(true);
  3422. setup(cli);
  3423. return cli.Get("/redir", headers);
  3424. }
  3425. static void
  3426. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3427. std::string captured_authorization;
  3428. auto result = GetThroughRedirectToDifferentPort(
  3429. [&](const Request &req, Response &res) {
  3430. captured_authorization = req.get_header_value("Authorization");
  3431. res.set_content("OK", "text/plain");
  3432. },
  3433. set_auth);
  3434. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3435. EXPECT_EQ(StatusCode::OK_200, result->status);
  3436. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3437. EXPECT_TRUE(captured_authorization.empty());
  3438. }
  3439. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3440. TestDoNotForwardCredentialsOnRedirect(
  3441. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3442. }
  3443. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3444. TestDoNotForwardCredentialsOnRedirect(
  3445. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3446. }
  3447. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3448. std::string captured_cookie;
  3449. auto result = GetThroughRedirectToDifferentPort(
  3450. [&](const Request &req, Response &res) {
  3451. captured_cookie = req.get_header_value("Cookie");
  3452. res.set_content("OK", "text/plain");
  3453. },
  3454. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3455. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3456. EXPECT_EQ(StatusCode::OK_200, result->status);
  3457. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3458. EXPECT_TRUE(captured_cookie.empty());
  3459. }
  3460. TEST(RedirectToSamePort, ForwardCookie) {
  3461. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3462. // header so that ordinary session flows keep working.
  3463. Server svr;
  3464. std::string captured_cookie;
  3465. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3466. res.set_redirect("/target", 302);
  3467. });
  3468. svr.Get("/target", [&](const Request &req, Response &res) {
  3469. captured_cookie = req.get_header_value("Cookie");
  3470. res.set_content("OK", "text/plain");
  3471. });
  3472. auto port = svr.bind_to_any_port(HOST);
  3473. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3474. auto se = detail::scope_exit([&] {
  3475. svr.stop();
  3476. thread.join();
  3477. ASSERT_FALSE(svr.is_running());
  3478. });
  3479. svr.wait_until_ready();
  3480. Client cli(HOST, port);
  3481. cli.set_follow_location(true);
  3482. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3483. auto res = cli.Get("/redir", headers);
  3484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3485. EXPECT_EQ(StatusCode::OK_200, res->status);
  3486. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3487. }
  3488. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3489. std::string authorization;
  3490. std::string trace_id;
  3491. auto result = GetThroughRedirectToDifferentPort(
  3492. [&](const Request &req, Response &res) {
  3493. authorization = req.get_header_value("Authorization");
  3494. trace_id = req.get_header_value("X-Trace-Id");
  3495. res.set_content("OK", "text/plain");
  3496. },
  3497. [](Client &cli) {
  3498. cli.set_default_headers(
  3499. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3500. });
  3501. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3502. EXPECT_EQ(StatusCode::OK_200, result->status);
  3503. // Like a header given with the request, a default one goes along unless it
  3504. // carries credentials (RFC 9110 15.4).
  3505. EXPECT_TRUE(authorization.empty());
  3506. EXPECT_EQ("42", trace_id);
  3507. }
  3508. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3509. auto result = GetThroughRedirectToDifferentPort(
  3510. [](const Request &, Response &res) {
  3511. res.set_content(std::string(2048, 'x'), "text/plain");
  3512. },
  3513. [](Client &cli) { cli.set_payload_max_length(1024); });
  3514. EXPECT_FALSE(result);
  3515. }
  3516. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3517. auto result = GetThroughRedirectToDifferentPort(
  3518. [](const Request &req, Response &res) {
  3519. // Answer after a second, or once the client gives up.
  3520. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3521. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3522. }
  3523. res.set_content("late", "text/plain");
  3524. },
  3525. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3526. ASSERT_FALSE(result);
  3527. EXPECT_EQ(Error::Read, result.error());
  3528. }
  3529. #ifdef CPPHTTPLIB_SSL_ENABLED
  3530. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3531. auto result = GetThroughRedirectToDifferentPort(
  3532. [](const Request &, Response &res) {
  3533. res.status = StatusCode::Unauthorized_401;
  3534. res.set_header("WWW-Authenticate",
  3535. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3536. },
  3537. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3538. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3539. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3540. }
  3541. #endif
  3542. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3543. Server svr;
  3544. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3545. // Port number that overflows int — should not crash
  3546. res.set_redirect("http://localhost:99999999999999999999/target");
  3547. });
  3548. auto port = svr.bind_to_any_port(HOST);
  3549. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3550. auto se = detail::scope_exit([&] {
  3551. svr.stop();
  3552. thread.join();
  3553. ASSERT_FALSE(svr.is_running());
  3554. });
  3555. svr.wait_until_ready();
  3556. Client cli(HOST, port);
  3557. cli.set_follow_location(true);
  3558. auto res = cli.Get("/redir");
  3559. // Should fail gracefully, not crash (no valid response due to bad port)
  3560. EXPECT_FALSE(res);
  3561. }
  3562. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3563. Server svr;
  3564. auto port = svr.bind_to_any_port(HOST);
  3565. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3566. // The server's own port followed by junk must not be followed
  3567. res.set_redirect("http://" + std::string(HOST) + ":" +
  3568. std::to_string(port) + "junk/target");
  3569. });
  3570. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3571. res.set_content("target", "text/plain");
  3572. });
  3573. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3574. auto se = detail::scope_exit([&] {
  3575. svr.stop();
  3576. thread.join();
  3577. ASSERT_FALSE(svr.is_running());
  3578. });
  3579. svr.wait_until_ready();
  3580. Client cli(HOST, port);
  3581. cli.set_follow_location(true);
  3582. auto res = cli.Get("/redir");
  3583. EXPECT_FALSE(res);
  3584. }
  3585. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3586. Server svr;
  3587. std::atomic<bool> followed{false};
  3588. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3589. res.status = StatusCode::NotModified_304;
  3590. res.set_header("Location", "/target");
  3591. });
  3592. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3593. res.status = StatusCode::UseProxy_305;
  3594. res.set_header("Location", "/target");
  3595. });
  3596. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3597. followed = true;
  3598. res.set_content("target", "text/plain");
  3599. });
  3600. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3601. auto se = detail::scope_exit([&] {
  3602. svr.stop();
  3603. th.join();
  3604. ASSERT_FALSE(svr.is_running());
  3605. });
  3606. svr.wait_until_ready();
  3607. Client cli("localhost", PORT);
  3608. cli.set_follow_location(true);
  3609. auto res = cli.Get("/304");
  3610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3611. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3612. res = cli.Get("/305");
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3615. EXPECT_FALSE(followed);
  3616. }
  3617. TEST(RedirectFromPageWithContent, Redirect) {
  3618. Server svr;
  3619. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3620. res.set_content("___", "text/plain");
  3621. res.set_redirect("/2");
  3622. });
  3623. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3624. res.set_content("Hello World!", "text/plain");
  3625. });
  3626. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3627. auto se = detail::scope_exit([&] {
  3628. svr.stop();
  3629. th.join();
  3630. ASSERT_FALSE(svr.is_running());
  3631. });
  3632. svr.wait_until_ready();
  3633. {
  3634. Client cli("localhost", PORT);
  3635. cli.set_follow_location(true);
  3636. std::string body;
  3637. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3638. body.append(data, data_length);
  3639. return true;
  3640. });
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::OK_200, res->status);
  3643. EXPECT_EQ("Hello World!", body);
  3644. }
  3645. {
  3646. Client cli("localhost", PORT);
  3647. std::string body;
  3648. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3649. body.append(data, data_length);
  3650. return true;
  3651. });
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::Found_302, res->status);
  3654. EXPECT_EQ("___", body);
  3655. }
  3656. }
  3657. // A server can close the connection after a request with "Connection: close"
  3658. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3659. // redirected request must go out on a new connection.
  3660. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3661. #ifndef _WIN32
  3662. signal(SIGPIPE, SIG_IGN);
  3663. #endif
  3664. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3665. default_socket_options(srv);
  3666. sockaddr_in addr{};
  3667. addr.sin_family = AF_INET;
  3668. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3669. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3670. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3671. ASSERT_EQ(0, ::listen(srv, 2));
  3672. auto send_text = [](socket_t sock, const std::string &text) {
  3673. ::send(sock,
  3674. #ifdef _WIN32
  3675. static_cast<const char *>(text.c_str()),
  3676. static_cast<int>(text.size()),
  3677. #else
  3678. text.c_str(), text.size(),
  3679. #endif
  3680. 0);
  3681. };
  3682. auto reused = false;
  3683. auto server_thread = std::thread([&] {
  3684. char buf[4096];
  3685. auto first = ::accept(srv, nullptr, nullptr);
  3686. if (first == INVALID_SOCKET) { return; }
  3687. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3688. ::recv(first, buf, sizeof(buf), 0);
  3689. send_text(
  3690. first,
  3691. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3692. auto next = first;
  3693. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3694. reused = true;
  3695. } else {
  3696. detail::close_socket(first);
  3697. next = ::accept(srv, nullptr, nullptr);
  3698. if (next == INVALID_SOCKET) { return; }
  3699. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3700. ::recv(next, buf, sizeof(buf), 0);
  3701. }
  3702. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3703. "Connection: close\r\n\r\nok");
  3704. detail::close_socket(next);
  3705. });
  3706. Client cli("127.0.0.1", PORT + 2);
  3707. cli.set_follow_location(true);
  3708. cli.set_read_timeout(5, 0);
  3709. auto res = cli.Get("/1");
  3710. server_thread.join();
  3711. detail::close_socket(srv);
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. EXPECT_EQ("ok", res->body);
  3715. EXPECT_FALSE(reused);
  3716. }
  3717. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3718. Server svr;
  3719. auto port_str = std::to_string(PORT);
  3720. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3721. auto expected_host = "[::1]:" + port_str;
  3722. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3723. res.set_content("___", "text/plain");
  3724. // res.set_redirect("/2");
  3725. res.set_redirect(redirect_url);
  3726. });
  3727. svr.Get("/2", [&](const Request &req, Response &res) {
  3728. auto host_header = req.headers.find("Host");
  3729. ASSERT_TRUE(host_header != req.headers.end());
  3730. EXPECT_EQ(expected_host, host_header->second);
  3731. res.set_content("Hello World!", "text/plain");
  3732. });
  3733. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3734. auto se = detail::scope_exit([&] {
  3735. svr.stop();
  3736. th.join();
  3737. ASSERT_FALSE(svr.is_running());
  3738. });
  3739. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3740. // actually starts anything, so the condition !svr.is_running() will
  3741. // always remain true, and the loop never stops.
  3742. // This basically counts how many milliseconds have passed since the
  3743. // call to svr.listen(), and if after 5 seconds nothing started yet
  3744. // aborts the test.
  3745. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3746. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3747. ASSERT_LT(milliseconds, 5000U);
  3748. }
  3749. {
  3750. Client cli("::1", PORT);
  3751. cli.set_follow_location(true);
  3752. std::string body;
  3753. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3754. body.append(data, data_length);
  3755. return true;
  3756. });
  3757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. EXPECT_EQ("Hello World!", body);
  3760. }
  3761. {
  3762. Client cli("::1", PORT);
  3763. std::string body;
  3764. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3765. body.append(data, data_length);
  3766. return true;
  3767. });
  3768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3769. EXPECT_EQ(StatusCode::Found_302, res->status);
  3770. EXPECT_EQ("___", body);
  3771. }
  3772. }
  3773. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3774. Server svr;
  3775. svr.Get("/foo", [](const Request &req, Response &res) {
  3776. auto a = req.params.find("a");
  3777. if (a != req.params.end()) {
  3778. res.set_content((*a).second, "text/plain");
  3779. res.status = StatusCode::OK_200;
  3780. } else {
  3781. res.status = StatusCode::BadRequest_400;
  3782. }
  3783. });
  3784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3785. auto se = detail::scope_exit([&] {
  3786. svr.stop();
  3787. thread.join();
  3788. ASSERT_FALSE(svr.is_running());
  3789. });
  3790. svr.wait_until_ready();
  3791. {
  3792. Client cli(HOST, PORT);
  3793. cli.set_path_encode(false);
  3794. auto res = cli.Get("/foo?a=explicitly+encoded");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. // This expects it back with a space, as the `+` won't have been
  3798. // url-encoded, and server-side the params get decoded turning `+`
  3799. // into spaces.
  3800. EXPECT_EQ("explicitly encoded", res->body);
  3801. }
  3802. }
  3803. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3804. // When path encoding is disabled the client must transmit the supplied
  3805. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3806. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3807. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3808. // than a space (0x20). Assert on the raw wire target to catch this.
  3809. Server svr;
  3810. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3811. svr.Get("/foo", [&](const Request &req, Response &res) {
  3812. EXPECT_EQ(expected_target, req.target);
  3813. res.status = StatusCode::OK_200;
  3814. });
  3815. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3816. auto se = detail::scope_exit([&] {
  3817. svr.stop();
  3818. thread.join();
  3819. ASSERT_FALSE(svr.is_running());
  3820. });
  3821. svr.wait_until_ready();
  3822. {
  3823. Client cli(HOST, PORT);
  3824. cli.set_path_encode(false);
  3825. auto res = cli.Get(expected_target.c_str());
  3826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3827. EXPECT_EQ(StatusCode::OK_200, res->status);
  3828. }
  3829. }
  3830. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3831. // `open_stream()` used to skip the path encoding that the buffered send
  3832. // path applies, so the same `path` produced different bytes in the request
  3833. // line depending on which API was used. Assert the two agree.
  3834. Server svr;
  3835. std::string target;
  3836. svr.Get(".*", [&](const Request &req, Response &res) {
  3837. target = req.target;
  3838. res.status = StatusCode::OK_200;
  3839. });
  3840. auto port = svr.bind_to_any_port(HOST);
  3841. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3842. auto se = detail::scope_exit([&] {
  3843. svr.stop();
  3844. thread.join();
  3845. ASSERT_FALSE(svr.is_running());
  3846. });
  3847. svr.wait_until_ready();
  3848. struct {
  3849. const char *path;
  3850. const char *expected;
  3851. } cases[] = {
  3852. {"/a b?x=1", "/a%20b?x=1"},
  3853. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3854. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3855. };
  3856. for (const auto &c : cases) {
  3857. Client cli(HOST, port);
  3858. target.clear();
  3859. auto res = cli.Get(c.path);
  3860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3861. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3862. auto buffered_target = target;
  3863. target.clear();
  3864. auto handle = cli.open_stream("GET", c.path);
  3865. EXPECT_TRUE(handle.is_valid())
  3866. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3867. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3868. }
  3869. }
  3870. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3871. // The `set_path_encode(false)` contract — transmit the supplied target
  3872. // verbatim — must hold for the streaming API too.
  3873. Server svr;
  3874. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3875. std::string target;
  3876. svr.Get("/foo", [&](const Request &req, Response &res) {
  3877. target = req.target;
  3878. res.status = StatusCode::OK_200;
  3879. });
  3880. auto port = svr.bind_to_any_port(HOST);
  3881. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3882. auto se = detail::scope_exit([&] {
  3883. svr.stop();
  3884. thread.join();
  3885. ASSERT_FALSE(svr.is_running());
  3886. });
  3887. svr.wait_until_ready();
  3888. {
  3889. Client cli(HOST, port);
  3890. cli.set_path_encode(false);
  3891. auto handle = cli.open_stream("GET", expected_target);
  3892. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3893. EXPECT_EQ(expected_target, target);
  3894. }
  3895. }
  3896. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3897. // With path encoding enabled a CR/LF in the target is percent-encoded
  3898. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3899. // write_request_line still backstops `set_path_encode(false)`, which is
  3900. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3901. Server svr;
  3902. // Captured before routing: the decoded path contains a newline, which a
  3903. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3904. std::string target;
  3905. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3906. target = req.target;
  3907. res.status = StatusCode::OK_200;
  3908. return Server::HandlerResponse::Handled;
  3909. });
  3910. auto port = svr.bind_to_any_port(HOST);
  3911. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3912. auto se = detail::scope_exit([&] {
  3913. svr.stop();
  3914. thread.join();
  3915. ASSERT_FALSE(svr.is_running());
  3916. });
  3917. svr.wait_until_ready();
  3918. {
  3919. Client cli(HOST, port);
  3920. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3921. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3922. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3923. }
  3924. }
  3925. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3926. // Every control character is percent-encoded, not just CR/LF, so the target
  3927. // passes the request-target check in write_request_line.
  3928. Server svr;
  3929. std::string target;
  3930. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3931. target = req.target;
  3932. res.status = StatusCode::OK_200;
  3933. return Server::HandlerResponse::Handled;
  3934. });
  3935. auto port = svr.bind_to_any_port(HOST);
  3936. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3937. auto se = detail::scope_exit([&] {
  3938. svr.stop();
  3939. thread.join();
  3940. ASSERT_FALSE(svr.is_running());
  3941. });
  3942. svr.wait_until_ready();
  3943. {
  3944. Client cli(HOST, port);
  3945. auto res = cli.Get("/a\tb\x1b\x7f");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ("/a%09b%1B%7F", target);
  3948. }
  3949. }
  3950. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3951. // Nothing may reach the wire: a raw CR/LF target would split the request
  3952. // line and inject headers.
  3953. Server svr;
  3954. // Pre-routing so that "not called" means nothing reached the server at all,
  3955. // rather than merely failing to match a handler pattern.
  3956. auto handler_called = false;
  3957. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3958. handler_called = true;
  3959. res.status = StatusCode::OK_200;
  3960. return Server::HandlerResponse::Handled;
  3961. });
  3962. auto port = svr.bind_to_any_port(HOST);
  3963. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3964. auto se = detail::scope_exit([&] {
  3965. svr.stop();
  3966. thread.join();
  3967. ASSERT_FALSE(svr.is_running());
  3968. });
  3969. svr.wait_until_ready();
  3970. {
  3971. Client cli(HOST, port);
  3972. cli.set_path_encode(false);
  3973. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3974. EXPECT_FALSE(handle.is_valid());
  3975. EXPECT_EQ(Error::Write, handle.error);
  3976. EXPECT_FALSE(handler_called);
  3977. }
  3978. }
  3979. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3980. // Which of the two branches runs is decided by whether the query component
  3981. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3982. // an empty query and must still fall back to building one from
  3983. // `req.params`, while a non-empty query must win over `req.params`.
  3984. Server svr;
  3985. std::string target;
  3986. svr.Get("/foo", [&](const Request &req, Response &res) {
  3987. target = req.target;
  3988. res.status = StatusCode::OK_200;
  3989. });
  3990. auto port = svr.bind_to_any_port(HOST);
  3991. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3992. auto se = detail::scope_exit([&] {
  3993. svr.stop();
  3994. thread.join();
  3995. ASSERT_FALSE(svr.is_running());
  3996. });
  3997. svr.wait_until_ready();
  3998. {
  3999. // Trailing `?` -> empty query component -> `req.params` is used.
  4000. Client cli(HOST, port);
  4001. Request req;
  4002. req.method = "GET";
  4003. req.path = "/foo?";
  4004. req.params.emplace("a", "1");
  4005. target.clear();
  4006. auto res = cli.send(req);
  4007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4008. EXPECT_EQ("/foo?a=1", target);
  4009. }
  4010. {
  4011. // Non-empty query in `req.path` -> `req.params` is not appended.
  4012. Client cli(HOST, port);
  4013. Request req;
  4014. req.method = "GET";
  4015. req.path = "/foo?b=2";
  4016. req.params.emplace("a", "1");
  4017. target.clear();
  4018. auto res = cli.send(req);
  4019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4020. EXPECT_EQ("/foo?b=2", target);
  4021. }
  4022. }
  4023. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4024. Server svr;
  4025. svr.Get("/", [](const Request &req, Response &) {
  4026. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4027. });
  4028. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4029. auto se = detail::scope_exit([&] {
  4030. svr.stop();
  4031. thread.join();
  4032. ASSERT_FALSE(svr.is_running());
  4033. });
  4034. svr.wait_until_ready();
  4035. {
  4036. Client cli(HOST, PORT);
  4037. cli.set_path_encode(false);
  4038. auto res = cli.Get("/?something=%0A");
  4039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4040. EXPECT_EQ(StatusCode::OK_200, res->status);
  4041. }
  4042. }
  4043. TEST(BindServerTest, BindDualStack) {
  4044. Server svr;
  4045. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4046. res.set_content("Hello World!", "text/plain");
  4047. });
  4048. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4049. auto se = detail::scope_exit([&] {
  4050. svr.stop();
  4051. thread.join();
  4052. ASSERT_FALSE(svr.is_running());
  4053. });
  4054. svr.wait_until_ready();
  4055. {
  4056. Client cli("127.0.0.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. Client cli("::1", PORT);
  4064. auto res = cli.Get("/1");
  4065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4066. EXPECT_EQ(StatusCode::OK_200, res->status);
  4067. EXPECT_EQ("Hello World!", res->body);
  4068. }
  4069. }
  4070. TEST(BindServerTest, BindAndListenSeparately) {
  4071. Server svr;
  4072. int port = svr.bind_to_any_port("0.0.0.0");
  4073. ASSERT_TRUE(svr.is_valid());
  4074. ASSERT_TRUE(port > 0);
  4075. svr.stop();
  4076. }
  4077. // Reports whether anything is still listening on a loopback port. A plain
  4078. // connect() is used instead of a Client request because a socket left bound by
  4079. // mistake accepts the connection into its backlog and never answers, which
  4080. // would hang the test instead of failing it.
  4081. static bool is_loopback_port_accepting(int port) {
  4082. sockaddr_in addr{};
  4083. addr.sin_family = AF_INET;
  4084. addr.sin_port = htons(static_cast<uint16_t>(port));
  4085. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4086. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4087. EXPECT_NE(sock, INVALID_SOCKET);
  4088. if (sock == INVALID_SOCKET) { return false; }
  4089. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4090. static_cast<socklen_t>(sizeof(addr)));
  4091. detail::close_socket(sock);
  4092. return ret == 0;
  4093. }
  4094. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4095. Server svr;
  4096. auto port = svr.bind_to_any_port("127.0.0.1");
  4097. ASSERT_TRUE(port > 0);
  4098. svr.stop();
  4099. // bind_to_any_port() already called listen(2), so until stop() closed the
  4100. // descriptor the port kept accepting connections into the backlog. ASSERT
  4101. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4102. // below blocks forever in the accept loop.
  4103. ASSERT_FALSE(is_loopback_port_accepting(port));
  4104. // Nothing is left to accept on, so listen_after_bind() must report failure
  4105. // instead of returning success without ever serving.
  4106. EXPECT_FALSE(svr.listen_after_bind());
  4107. // The failed listen marks the server decommissioned, so a waiter returns
  4108. // instead of spinning forever.
  4109. svr.wait_until_ready();
  4110. }
  4111. #ifdef CPPHTTPLIB_SSL_ENABLED
  4112. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4114. CLIENT_CA_CERT_DIR);
  4115. int port = svr.bind_to_any_port("0.0.0.0");
  4116. ASSERT_TRUE(svr.is_valid());
  4117. ASSERT_TRUE(port > 0);
  4118. svr.stop();
  4119. }
  4120. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4121. // or a rejected CustomRoute() registration would not stop the server binding.
  4122. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4123. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4124. CLIENT_CA_CERT_DIR);
  4125. ASSERT_TRUE(svr.is_valid());
  4126. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4127. EXPECT_FALSE(svr.is_valid());
  4128. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4129. }
  4130. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4131. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4132. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4133. int port = svr.bind_to_any_port("0.0.0.0");
  4134. ASSERT_TRUE(svr.is_valid());
  4135. ASSERT_TRUE(port > 0);
  4136. svr.stop();
  4137. }
  4138. TEST(BindServerTest, UpdateCertsPem) {
  4139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4140. int port = svr.bind_to_any_port("0.0.0.0");
  4141. ASSERT_TRUE(svr.is_valid());
  4142. ASSERT_TRUE(port > 0);
  4143. // Read PEM files
  4144. std::string cert_pem, key_pem, ca_pem;
  4145. read_file(SERVER_CERT_FILE, cert_pem);
  4146. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4147. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4148. // Update server certificates using PEM API
  4149. ASSERT_TRUE(
  4150. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4151. ASSERT_TRUE(svr.is_valid());
  4152. svr.stop();
  4153. }
  4154. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4155. // Start server with client CA (enables client auth)
  4156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4157. ASSERT_TRUE(svr.is_valid());
  4158. bool handler_called = false;
  4159. svr.Get("/test", [&](const Request &req, Response &res) {
  4160. handler_called = true;
  4161. // Verify client certificate is present
  4162. auto cert = req.peer_cert();
  4163. EXPECT_TRUE(static_cast<bool>(cert));
  4164. res.set_content("ok", "text/plain");
  4165. });
  4166. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4167. auto se = detail::scope_exit([&] {
  4168. svr.stop();
  4169. t.join();
  4170. ASSERT_FALSE(svr.is_running());
  4171. });
  4172. svr.wait_until_ready();
  4173. // Read PEM files
  4174. std::string cert_pem, key_pem, ca_pem;
  4175. read_file(SERVER_CERT_FILE, cert_pem);
  4176. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4177. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4178. // Update server certificates and client CA using PEM API while server running
  4179. ASSERT_TRUE(
  4180. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4181. // Connect with client certificate
  4182. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4183. cli.enable_server_certificate_verification(false);
  4184. cli.set_connection_timeout(30);
  4185. auto res = cli.Get("/test");
  4186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4187. ASSERT_EQ(StatusCode::OK_200, res->status);
  4188. ASSERT_TRUE(handler_called);
  4189. EXPECT_EQ("ok", res->body);
  4190. }
  4191. // Puts a CA that did not sign the client's certificate in the old one's place.
  4192. static bool replace_client_ca(SSLServer &svr) {
  4193. std::string cert_pem, key_pem, ca_pem;
  4194. read_file(SERVER_CERT_FILE, cert_pem);
  4195. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4196. read_file(SERVER_CERT2_FILE, ca_pem);
  4197. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4198. ca_pem.c_str());
  4199. }
  4200. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4202. ASSERT_TRUE(svr.is_valid());
  4203. svr.Get("/test", [](const Request &, Response &res) {
  4204. res.set_content("ok", "text/plain");
  4205. });
  4206. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4207. auto se = detail::scope_exit([&] {
  4208. svr.stop();
  4209. t.join();
  4210. ASSERT_FALSE(svr.is_running());
  4211. });
  4212. svr.wait_until_ready();
  4213. auto get = [] {
  4214. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4215. cli.enable_server_certificate_verification(false);
  4216. return cli.Get("/test");
  4217. };
  4218. ASSERT_TRUE(get());
  4219. ASSERT_TRUE(replace_client_ca(svr));
  4220. EXPECT_FALSE(get());
  4221. }
  4222. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4223. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4225. ASSERT_TRUE(svr.is_valid());
  4226. tls::set_verify_callback(svr.tls_context(),
  4227. [](const tls::VerifyContext &) -> bool {
  4228. throw std::runtime_error("verify");
  4229. });
  4230. svr.Get("/test", [](const Request &, Response &res) {
  4231. res.set_content("ok", "text/plain");
  4232. });
  4233. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4234. auto se = detail::scope_exit([&] {
  4235. svr.stop();
  4236. t.join();
  4237. ASSERT_FALSE(svr.is_running());
  4238. });
  4239. svr.wait_until_ready();
  4240. auto get = [] {
  4241. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4242. cli.enable_server_certificate_verification(false);
  4243. return cli.Get("/test");
  4244. };
  4245. EXPECT_FALSE(get());
  4246. // The handshake is over, so an update does not wait for it.
  4247. std::string cert_pem, key_pem;
  4248. read_file(SERVER_CERT_FILE, cert_pem);
  4249. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4250. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4251. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4252. return v.preverify_ok;
  4253. });
  4254. auto res = get();
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. EXPECT_EQ("ok", res->body);
  4257. }
  4258. #endif
  4259. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4260. // Sends each request over a new connection with a client certificate,
  4261. // resuming the session of the one before when there is one.
  4262. class ResumingClient {
  4263. public:
  4264. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4265. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4266. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4267. SSL_FILETYPE_PEM);
  4268. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4269. // callback, not through SSL_get1_session().
  4270. SSL_CTX_set_app_data(ctx_, this);
  4271. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4272. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4273. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4274. auto self = static_cast<ResumingClient *>(
  4275. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4276. SSL_SESSION_free(self->session_);
  4277. self->session_ = session;
  4278. return 1; // Keeps the reference
  4279. });
  4280. }
  4281. ~ResumingClient() {
  4282. SSL_SESSION_free(session_);
  4283. SSL_CTX_free(ctx_);
  4284. }
  4285. // Tells whether the request was answered.
  4286. bool get() {
  4287. auto error = Error::Success;
  4288. auto sock = detail::create_client_socket(
  4289. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4290. /*connection_timeout_sec=*/5, 0,
  4291. /*read_timeout_sec=*/5, 0,
  4292. /*write_timeout_sec=*/5, 0, std::string(), error);
  4293. if (sock == INVALID_SOCKET) { return false; }
  4294. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4295. auto ssl = SSL_new(ctx_);
  4296. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4297. SSL_set_fd(ssl, static_cast<int>(sock));
  4298. if (session_) { SSL_set_session(ssl, session_); }
  4299. if (SSL_connect(ssl) != 1) { return false; }
  4300. reused_ = SSL_session_reused(ssl) == 1;
  4301. // Reading the response also takes in a TLS 1.3 session ticket.
  4302. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4303. "Connection: close\r\n\r\n";
  4304. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4305. std::string res;
  4306. char buf[256];
  4307. int n;
  4308. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4309. res.append(buf, static_cast<size_t>(n));
  4310. }
  4311. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4312. SSL_shutdown(ssl);
  4313. return res.find("200 OK") != std::string::npos;
  4314. }
  4315. // Whether the last connection resumed a session
  4316. bool reused() const { return reused_; }
  4317. private:
  4318. SSL_CTX *ctx_;
  4319. SSL_SESSION *session_ = nullptr;
  4320. bool reused_ = false;
  4321. };
  4322. // A client that resumes its session gets through, but not once the client CA
  4323. // has changed, as a resumed session does not show the certificate again.
  4324. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4326. ASSERT_TRUE(svr.is_valid());
  4327. svr.Get("/test", [](const Request &, Response &res) {
  4328. res.set_content("ok", "text/plain");
  4329. });
  4330. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4331. auto se = detail::scope_exit([&] {
  4332. svr.stop();
  4333. t.join();
  4334. ASSERT_FALSE(svr.is_running());
  4335. });
  4336. svr.wait_until_ready();
  4337. ResumingClient cli;
  4338. ASSERT_TRUE(cli.get());
  4339. ASSERT_TRUE(cli.get());
  4340. EXPECT_TRUE(cli.reused());
  4341. ASSERT_TRUE(replace_client_ca(svr));
  4342. EXPECT_FALSE(cli.get());
  4343. }
  4344. // A resumed session does not show the certificate again, so the server does
  4345. // not resume one with a verify callback to run on it.
  4346. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4348. ASSERT_TRUE(svr.is_valid());
  4349. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4350. return v.preverify_ok;
  4351. });
  4352. svr.Get("/test", [](const Request &, Response &res) {
  4353. res.set_content("ok", "text/plain");
  4354. });
  4355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4356. auto se = detail::scope_exit([&] {
  4357. svr.stop();
  4358. t.join();
  4359. ASSERT_FALSE(svr.is_running());
  4360. });
  4361. svr.wait_until_ready();
  4362. ResumingClient cli;
  4363. ASSERT_TRUE(cli.get());
  4364. ASSERT_TRUE(cli.get());
  4365. EXPECT_FALSE(cli.reused());
  4366. }
  4367. #endif
  4368. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4369. // wolfSSL shares its session cache between contexts, so a resumed session
  4370. // could carry a client certificate checked against another server's CA, or
  4371. // against a client CA since replaced.
  4372. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4374. ASSERT_TRUE(svr.is_valid());
  4375. // Trusts a CA that did not sign the client's certificate.
  4376. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4377. ASSERT_TRUE(other.is_valid());
  4378. for (auto s : {&svr, &other}) {
  4379. s->Get("/test", [](const Request &, Response &res) {
  4380. res.set_content("ok", "text/plain");
  4381. });
  4382. }
  4383. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4384. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4385. auto se = detail::scope_exit([&] {
  4386. other.stop();
  4387. svr.stop();
  4388. t2.join();
  4389. t.join();
  4390. });
  4391. svr.wait_until_ready();
  4392. other.wait_until_ready();
  4393. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4394. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4395. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4396. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4397. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4398. ASSERT_EQ(WOLFSSL_SUCCESS,
  4399. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4400. WOLFSSL_FILETYPE_PEM));
  4401. WOLFSSL_SESSION *session = nullptr;
  4402. auto session_se = detail::scope_exit([&] {
  4403. if (session) { wolfSSL_SESSION_free(session); }
  4404. });
  4405. // A request over a new connection, resuming `session` when there is one and
  4406. // keeping the connection's own in its place. Tells whether it was answered.
  4407. auto get = [&](int port) {
  4408. auto error = Error::Success;
  4409. auto sock = detail::create_client_socket(
  4410. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4411. /*connection_timeout_sec=*/5, 0,
  4412. /*read_timeout_sec=*/5, 0,
  4413. /*write_timeout_sec=*/5, 0, std::string(), error);
  4414. if (sock == INVALID_SOCKET) { return false; }
  4415. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4416. auto ssl = wolfSSL_new(ctx);
  4417. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4418. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4419. if (session) { wolfSSL_set_session(ssl, session); }
  4420. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4421. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4422. "Connection: close\r\n\r\n";
  4423. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4424. std::string res;
  4425. char buf[256];
  4426. int n;
  4427. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4428. res.append(buf, static_cast<size_t>(n));
  4429. }
  4430. wolfSSL_shutdown(ssl);
  4431. if (session) { wolfSSL_SESSION_free(session); }
  4432. session = wolfSSL_get1_session(ssl);
  4433. return res.find("200 OK") != std::string::npos;
  4434. };
  4435. ASSERT_TRUE(get(PORT));
  4436. EXPECT_FALSE(get(PORT + 1));
  4437. ASSERT_TRUE(get(PORT));
  4438. ASSERT_TRUE(replace_client_ca(svr));
  4439. EXPECT_FALSE(get(PORT));
  4440. }
  4441. #endif
  4442. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4444. ASSERT_TRUE(svr.is_valid());
  4445. svr.Get("/test", [](const Request &, Response &res) {
  4446. res.set_content("ok", "text/plain");
  4447. });
  4448. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4449. auto se = detail::scope_exit([&] {
  4450. svr.stop();
  4451. t.join();
  4452. ASSERT_FALSE(svr.is_running());
  4453. });
  4454. svr.wait_until_ready();
  4455. // A connection that sends no ClientHello keeps its handshake in progress,
  4456. // once the server has had a moment to start it.
  4457. auto error = Error::Success;
  4458. auto sock = detail::create_client_socket(
  4459. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4460. /*connection_timeout_sec=*/5, 0,
  4461. /*read_timeout_sec=*/5, 0,
  4462. /*write_timeout_sec=*/5, 0, std::string(), error);
  4463. ASSERT_NE(INVALID_SOCKET, sock);
  4464. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4465. std::string cert_pem, key_pem;
  4466. read_file(SERVER_CERT_FILE, cert_pem);
  4467. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4468. auto update = std::async(std::launch::async, [&]() {
  4469. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4470. });
  4471. EXPECT_EQ(std::future_status::timeout,
  4472. update.wait_for(std::chrono::milliseconds(200)));
  4473. detail::close_socket(sock);
  4474. EXPECT_TRUE(update.get());
  4475. SSLClient cli(HOST, PORT);
  4476. cli.enable_server_certificate_verification(false);
  4477. auto res = cli.Get("/test");
  4478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4479. EXPECT_EQ(StatusCode::OK_200, res->status);
  4480. }
  4481. #endif
  4482. TEST(ErrorHandlerTest, ContentLength) {
  4483. Server svr;
  4484. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4485. res.status = StatusCode::OK_200;
  4486. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4487. "text/html"); // <= Content-Length still 13
  4488. });
  4489. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4490. res.set_content("Hello World!\n", "text/plain");
  4491. res.status = 524;
  4492. });
  4493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4494. auto se = detail::scope_exit([&] {
  4495. svr.stop();
  4496. thread.join();
  4497. ASSERT_FALSE(svr.is_running());
  4498. });
  4499. svr.wait_until_ready();
  4500. {
  4501. Client cli(HOST, PORT);
  4502. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4504. EXPECT_EQ(StatusCode::OK_200, res->status);
  4505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4506. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4507. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4508. }
  4509. }
  4510. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4511. TEST(ExceptionTest, WithoutExceptionHandler) {
  4512. Server svr;
  4513. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4514. throw std::runtime_error("exception...");
  4515. });
  4516. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4517. throw std::runtime_error("exception\r\n...");
  4518. });
  4519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4520. auto se = detail::scope_exit([&] {
  4521. svr.stop();
  4522. listen_thread.join();
  4523. ASSERT_FALSE(svr.is_running());
  4524. });
  4525. svr.wait_until_ready();
  4526. Client cli("localhost", PORT);
  4527. {
  4528. auto res = cli.Get("/exception");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4531. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4532. }
  4533. {
  4534. auto res = cli.Get("/unknown");
  4535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4536. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4537. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4538. }
  4539. }
  4540. TEST(ExceptionTest, WithExceptionHandler) {
  4541. Server svr;
  4542. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4543. std::exception_ptr ep) {
  4544. EXPECT_FALSE(ep == nullptr);
  4545. try {
  4546. std::rethrow_exception(ep);
  4547. } catch (std::exception &e) {
  4548. EXPECT_EQ("abc", std::string(e.what()));
  4549. } catch (...) {}
  4550. res.status = StatusCode::InternalServerError_500;
  4551. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4552. "text/html"); // <= Content-Length still 13 at this point
  4553. });
  4554. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4555. res.set_content("Hello World!\n", "text/plain");
  4556. throw std::runtime_error("abc");
  4557. });
  4558. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4559. auto se = detail::scope_exit([&] {
  4560. svr.stop();
  4561. thread.join();
  4562. ASSERT_FALSE(svr.is_running());
  4563. });
  4564. svr.wait_until_ready();
  4565. for (size_t i = 0; i < 10; i++) {
  4566. Client cli(HOST, PORT);
  4567. for (size_t j = 0; j < 100; j++) {
  4568. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4570. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4571. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4572. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4573. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4574. }
  4575. cli.set_keep_alive(true);
  4576. for (size_t j = 0; j < 100; j++) {
  4577. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4579. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4580. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4581. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4582. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4583. }
  4584. }
  4585. }
  4586. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4587. Server svr;
  4588. svr.set_exception_handler(
  4589. [](const Request &, Response &res, std::exception_ptr) {
  4590. res.set_content("oops", "text/plain");
  4591. });
  4592. svr.Get("/throw", [](const Request &, Response &) {
  4593. throw std::runtime_error("throw");
  4594. });
  4595. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4596. res.status = StatusCode::Created_201;
  4597. throw std::runtime_error("created-then-throw");
  4598. });
  4599. auto port = svr.bind_to_any_port(HOST);
  4600. ASSERT_GT(port, 0);
  4601. thread t = thread([&] { svr.listen_after_bind(); });
  4602. auto se = detail::scope_exit([&] {
  4603. svr.stop();
  4604. t.join();
  4605. ASSERT_FALSE(svr.is_running());
  4606. });
  4607. svr.wait_until_ready();
  4608. Client cli(HOST, port);
  4609. for (auto path : {"/throw", "/created-then-throw"}) {
  4610. auto res = cli.Get(path);
  4611. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4612. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4613. }
  4614. }
  4615. TEST(ExceptionTest, AndErrorHandler) {
  4616. Server svr;
  4617. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4618. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4619. });
  4620. svr.set_exception_handler(
  4621. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4622. EXPECT_FALSE(ep == nullptr);
  4623. try {
  4624. std::rethrow_exception(ep);
  4625. } catch (std::exception &e) {
  4626. res.set_content(e.what(), "text/html");
  4627. } catch (...) {}
  4628. res.status = StatusCode::InternalServerError_500;
  4629. });
  4630. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4631. throw std::runtime_error("EXCEPTION");
  4632. });
  4633. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4634. res.set_content("ERROR", "text/html");
  4635. res.status = StatusCode::InternalServerError_500;
  4636. });
  4637. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4638. auto se = detail::scope_exit([&] {
  4639. svr.stop();
  4640. thread.join();
  4641. ASSERT_FALSE(svr.is_running());
  4642. });
  4643. svr.wait_until_ready();
  4644. Client cli(HOST, PORT);
  4645. {
  4646. auto res = cli.Get("/exception");
  4647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4648. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4649. EXPECT_EQ("EXCEPTION", res->body);
  4650. }
  4651. {
  4652. auto res = cli.Get("/error");
  4653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4654. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4655. EXPECT_EQ("ERROR", res->body);
  4656. }
  4657. {
  4658. auto res = cli.Get("/invalid");
  4659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4660. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4661. EXPECT_EQ("NOT_FOUND", res->body);
  4662. }
  4663. }
  4664. #endif
  4665. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4666. // An exception from a user callback outside process_request()'s try/catch
  4667. // used to unwind into the task queue - which does not catch - and terminate
  4668. // the process. Each test below runs the server on a single worker thread: a
  4669. // guard that catches the exception but still loses the thread would otherwise
  4670. // be hidden by a spare worker serving the follow-up request. Note that a
  4671. // regression here aborts the whole test binary rather than failing one test.
  4672. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4673. Server svr;
  4674. svr.new_task_queue = [] { return new ThreadPool(1); };
  4675. std::atomic<int> reported{0};
  4676. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4677. if (err == Error::UserCallbackException) { reported++; }
  4678. });
  4679. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4680. res.set_content_provider(
  4681. 1024, "text/plain",
  4682. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4683. sink.write("hello", 5);
  4684. throw std::runtime_error("from the content provider");
  4685. });
  4686. });
  4687. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4688. res.set_content("ok", "text/plain");
  4689. });
  4690. auto port = svr.bind_to_any_port(HOST);
  4691. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4692. auto se = detail::scope_exit([&] {
  4693. svr.stop();
  4694. listen_thread.join();
  4695. ASSERT_FALSE(svr.is_running());
  4696. });
  4697. svr.wait_until_ready();
  4698. {
  4699. Client cli(HOST, port);
  4700. cli.set_read_timeout(5, 0);
  4701. EXPECT_FALSE(cli.Get("/throw"));
  4702. }
  4703. EXPECT_TRUE(svr.is_running());
  4704. EXPECT_EQ(1, reported.load());
  4705. // A request on a fresh connection is still served.
  4706. {
  4707. Client cli(HOST, port);
  4708. auto res = cli.Get("/ok");
  4709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. EXPECT_EQ("ok", res->body);
  4712. }
  4713. }
  4714. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4715. Server svr;
  4716. svr.new_task_queue = [] { return new ThreadPool(1); };
  4717. std::atomic<bool> should_throw{true};
  4718. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4719. res.set_content("hi", "text/plain");
  4720. });
  4721. svr.set_post_routing_handler(
  4722. [&](const Request & /*req*/, Response & /*res*/) {
  4723. if (should_throw) {
  4724. throw std::runtime_error("from the post-routing handler");
  4725. }
  4726. });
  4727. auto port = svr.bind_to_any_port(HOST);
  4728. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4729. auto se = detail::scope_exit([&] {
  4730. svr.stop();
  4731. listen_thread.join();
  4732. ASSERT_FALSE(svr.is_running());
  4733. });
  4734. svr.wait_until_ready();
  4735. {
  4736. Client cli(HOST, port);
  4737. cli.set_read_timeout(5, 0);
  4738. EXPECT_FALSE(cli.Get("/hi"));
  4739. }
  4740. EXPECT_TRUE(svr.is_running());
  4741. should_throw = false;
  4742. {
  4743. Client cli(HOST, port);
  4744. auto res = cli.Get("/hi");
  4745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4746. EXPECT_EQ(StatusCode::OK_200, res->status);
  4747. EXPECT_EQ("hi", res->body);
  4748. }
  4749. }
  4750. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4751. // The guard reports the caught exception through the error logger, which is
  4752. // a user callback too. A logger that throws has to be contained as well, or
  4753. // the process would terminate from inside the catch.
  4754. Server svr;
  4755. svr.new_task_queue = [] { return new ThreadPool(1); };
  4756. std::atomic<int> reported{0};
  4757. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4758. if (err == Error::UserCallbackException) {
  4759. reported++;
  4760. throw std::runtime_error("from the error logger");
  4761. }
  4762. });
  4763. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4764. res.set_content_provider(
  4765. 1024, "text/plain",
  4766. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4767. sink.write("hello", 5);
  4768. throw std::runtime_error("from the content provider");
  4769. });
  4770. });
  4771. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4772. res.set_content("ok", "text/plain");
  4773. });
  4774. auto port = svr.bind_to_any_port(HOST);
  4775. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4776. auto se = detail::scope_exit([&] {
  4777. svr.stop();
  4778. listen_thread.join();
  4779. ASSERT_FALSE(svr.is_running());
  4780. });
  4781. svr.wait_until_ready();
  4782. {
  4783. Client cli(HOST, port);
  4784. cli.set_read_timeout(5, 0);
  4785. EXPECT_FALSE(cli.Get("/throw"));
  4786. }
  4787. EXPECT_TRUE(svr.is_running());
  4788. EXPECT_EQ(1, reported.load());
  4789. {
  4790. Client cli(HOST, port);
  4791. auto res = cli.Get("/ok");
  4792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4793. EXPECT_EQ(StatusCode::OK_200, res->status);
  4794. EXPECT_EQ("ok", res->body);
  4795. }
  4796. }
  4797. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4798. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4799. // so the exception unwinds through the ws::WebSocket object on its way to
  4800. // the guard. None of the HTTP cases above cross that.
  4801. Server svr;
  4802. svr.new_task_queue = [] { return new ThreadPool(1); };
  4803. std::atomic<int> reported{0};
  4804. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4805. if (err == Error::UserCallbackException) { reported++; }
  4806. });
  4807. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4808. throw std::runtime_error("from the WebSocket handler");
  4809. });
  4810. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4811. res.set_content("ok", "text/plain");
  4812. });
  4813. auto port = svr.bind_to_any_port(HOST);
  4814. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4815. auto se = detail::scope_exit([&] {
  4816. svr.stop();
  4817. listen_thread.join();
  4818. ASSERT_FALSE(svr.is_running());
  4819. });
  4820. svr.wait_until_ready();
  4821. {
  4822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4823. "/ws");
  4824. auto res = client.connect();
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. // The server dropped the connection instead of dying.
  4827. std::string msg;
  4828. EXPECT_FALSE(client.read(msg));
  4829. client.close();
  4830. }
  4831. EXPECT_TRUE(svr.is_running());
  4832. EXPECT_EQ(1, reported.load());
  4833. {
  4834. Client cli(HOST, port);
  4835. auto res = cli.Get("/ok");
  4836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4837. EXPECT_EQ(StatusCode::OK_200, res->status);
  4838. EXPECT_EQ("ok", res->body);
  4839. }
  4840. }
  4841. #ifdef CPPHTTPLIB_SSL_ENABLED
  4842. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4843. // SSLServer::process_and_close_socket() is a separate overload with its own
  4844. // guard, so it is exercised on its own.
  4845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4846. ASSERT_TRUE(svr.is_valid());
  4847. svr.new_task_queue = [] { return new ThreadPool(1); };
  4848. std::atomic<int> reported{0};
  4849. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4850. if (err == Error::UserCallbackException) { reported++; }
  4851. });
  4852. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4853. res.set_content_provider(
  4854. 1024, "text/plain",
  4855. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4856. sink.write("hello", 5);
  4857. throw std::runtime_error("from the content provider");
  4858. });
  4859. });
  4860. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4861. res.set_content("ok", "text/plain");
  4862. });
  4863. auto port = svr.bind_to_any_port(HOST);
  4864. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4865. auto se = detail::scope_exit([&] {
  4866. svr.stop();
  4867. listen_thread.join();
  4868. ASSERT_FALSE(svr.is_running());
  4869. });
  4870. svr.wait_until_ready();
  4871. {
  4872. SSLClient cli(HOST, port);
  4873. cli.enable_server_certificate_verification(false);
  4874. cli.set_read_timeout(5, 0);
  4875. EXPECT_FALSE(cli.Get("/throw"));
  4876. }
  4877. EXPECT_TRUE(svr.is_running());
  4878. EXPECT_EQ(1, reported.load());
  4879. {
  4880. SSLClient cli(HOST, port);
  4881. cli.enable_server_certificate_verification(false);
  4882. auto res = cli.Get("/ok");
  4883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4884. EXPECT_EQ(StatusCode::OK_200, res->status);
  4885. EXPECT_EQ("ok", res->body);
  4886. }
  4887. }
  4888. #endif
  4889. #endif
  4890. TEST(NoContentTest, ContentLength) {
  4891. Server svr;
  4892. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4893. res.status = StatusCode::NoContent_204;
  4894. });
  4895. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4896. auto se = detail::scope_exit([&] {
  4897. svr.stop();
  4898. thread.join();
  4899. ASSERT_FALSE(svr.is_running());
  4900. });
  4901. svr.wait_until_ready();
  4902. {
  4903. Client cli(HOST, PORT);
  4904. auto res = cli.Get("/hi");
  4905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4906. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4907. // RFC 9110 8.6: none in a 204 response
  4908. EXPECT_FALSE(res->has_header("Content-Length"));
  4909. }
  4910. }
  4911. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4912. Server svr;
  4913. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4914. res.set_header("Content-Length", "5");
  4915. res.set_content("hello world", "text/plain");
  4916. });
  4917. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4918. // A body that reads as the last chunk, were it taken as chunked
  4919. res.set_header("Transfer-Encoding", "chunked");
  4920. res.set_content("0\r\n\r\n", "text/plain");
  4921. });
  4922. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4923. res.set_header("Content-Length", "2");
  4924. res.set_content_provider(5, "text/plain",
  4925. [](size_t offset, size_t length, DataSink &sink) {
  4926. sink.write(&"hello"[offset], length);
  4927. return true;
  4928. });
  4929. });
  4930. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4931. res.set_header("Content-Length", "1234");
  4932. });
  4933. thread t = thread([&] { svr.listen(HOST, PORT); });
  4934. auto se = detail::scope_exit([&] {
  4935. svr.stop();
  4936. t.join();
  4937. ASSERT_FALSE(svr.is_running());
  4938. });
  4939. svr.wait_until_ready();
  4940. Client cli(HOST, PORT);
  4941. cli.set_read_timeout(1, 0);
  4942. auto expect_body = [&](const Result &res, const std::string &body) {
  4943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4944. EXPECT_EQ(body, res->body);
  4945. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4946. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4947. };
  4948. Headers identity{{"Accept-Encoding", ""}};
  4949. expect_body(cli.Get("/body", identity), "hello world");
  4950. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4951. expect_body(cli.Get("/body",
  4952. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4953. "he");
  4954. expect_body(cli.Get("/provider", identity), "hello");
  4955. expect_body(cli.Get("/empty", identity), "");
  4956. // A HEAD response may give the length of the body a GET would get.
  4957. auto res = cli.Head("/empty");
  4958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4959. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4960. }
  4961. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4962. Server svr;
  4963. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4964. res.set_content("short", "text/plain");
  4965. });
  4966. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4967. res.body += " with a footer";
  4968. res.set_header("Transfer-Encoding", "chunked");
  4969. });
  4970. thread t = thread([&] { svr.listen(HOST, PORT); });
  4971. auto se = detail::scope_exit([&] {
  4972. svr.stop();
  4973. t.join();
  4974. ASSERT_FALSE(svr.is_running());
  4975. });
  4976. svr.wait_until_ready();
  4977. Client cli(HOST, PORT);
  4978. cli.set_read_timeout(1, 0);
  4979. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ("short with a footer", res->body);
  4982. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4983. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4984. }
  4985. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4986. Server svr;
  4987. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4988. res.set_header("Content-Length", "3");
  4989. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4990. sink.write("abc", 3);
  4991. sink.done();
  4992. return true;
  4993. });
  4994. });
  4995. thread t = thread([&] { svr.listen(HOST, PORT); });
  4996. auto se = detail::scope_exit([&] {
  4997. svr.stop();
  4998. t.join();
  4999. ASSERT_FALSE(svr.is_running());
  5000. });
  5001. svr.wait_until_ready();
  5002. Client cli(HOST, PORT);
  5003. cli.set_keep_alive(true);
  5004. auto res = cli.Get("/");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ("abc", res->body);
  5007. EXPECT_FALSE(res->has_header("Content-Length"));
  5008. EXPECT_EQ("close", res->get_header_value("Connection"));
  5009. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5010. // No body to delimit
  5011. auto head = cli.Head("/");
  5012. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5013. EXPECT_FALSE(head->has_header("Connection"));
  5014. }
  5015. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5016. #ifdef CPPHTTPLIB_SSL_ENABLED
  5017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5018. ASSERT_TRUE(svr.is_valid());
  5019. #else
  5020. Server svr;
  5021. #endif
  5022. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5023. if (req.path == "/routing_handler") {
  5024. res.set_header("PRE_ROUTING", "on");
  5025. res.set_content("Routing Handler", "text/plain");
  5026. return httplib::Server::HandlerResponse::Handled;
  5027. }
  5028. return httplib::Server::HandlerResponse::Unhandled;
  5029. });
  5030. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5031. res.set_content("Error", "text/html");
  5032. });
  5033. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5034. if (req.path == "/routing_handler") {
  5035. res.set_header("POST_ROUTING", "on");
  5036. }
  5037. });
  5038. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5039. res.set_content("Hello World!\n", "text/plain");
  5040. });
  5041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5042. auto se = detail::scope_exit([&] {
  5043. svr.stop();
  5044. thread.join();
  5045. ASSERT_FALSE(svr.is_running());
  5046. });
  5047. svr.wait_until_ready();
  5048. {
  5049. #ifdef CPPHTTPLIB_SSL_ENABLED
  5050. SSLClient cli(HOST, PORT);
  5051. cli.enable_server_certificate_verification(false);
  5052. #else
  5053. Client cli(HOST, PORT);
  5054. #endif
  5055. auto res = cli.Get("/routing_handler");
  5056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. EXPECT_EQ("Routing Handler", res->body);
  5059. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5060. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5061. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5062. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5063. }
  5064. {
  5065. #ifdef CPPHTTPLIB_SSL_ENABLED
  5066. SSLClient cli(HOST, PORT);
  5067. cli.enable_server_certificate_verification(false);
  5068. #else
  5069. Client cli(HOST, PORT);
  5070. #endif
  5071. auto res = cli.Get("/hi");
  5072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5073. EXPECT_EQ(StatusCode::OK_200, res->status);
  5074. EXPECT_EQ("Hello World!\n", res->body);
  5075. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5076. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5077. }
  5078. {
  5079. #ifdef CPPHTTPLIB_SSL_ENABLED
  5080. SSLClient cli(HOST, PORT);
  5081. cli.enable_server_certificate_verification(false);
  5082. #else
  5083. Client cli(HOST, PORT);
  5084. #endif
  5085. auto res = cli.Get("/aaa");
  5086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5087. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5088. EXPECT_EQ("Error", res->body);
  5089. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5090. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5091. }
  5092. }
  5093. TEST(RequestHandlerTest, PreRequestHandler) {
  5094. auto route_path = "/user/:user";
  5095. Server svr;
  5096. svr.Get("/hi", [](const Request &, Response &res) {
  5097. res.set_content("hi", "text/plain");
  5098. });
  5099. svr.Get(route_path, [](const Request &req, Response &res) {
  5100. res.set_content(req.path_params.at("user"), "text/plain");
  5101. });
  5102. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5103. if (req.matched_route == route_path) {
  5104. auto user = req.path_params.at("user");
  5105. if (user != "john") {
  5106. res.status = StatusCode::Forbidden_403;
  5107. res.set_content("error", "text/html");
  5108. return Server::HandlerResponse::Handled;
  5109. }
  5110. }
  5111. return Server::HandlerResponse::Unhandled;
  5112. });
  5113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5114. auto se = detail::scope_exit([&] {
  5115. svr.stop();
  5116. thread.join();
  5117. ASSERT_FALSE(svr.is_running());
  5118. });
  5119. svr.wait_until_ready();
  5120. Client cli(HOST, PORT);
  5121. {
  5122. auto res = cli.Get("/hi");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::OK_200, res->status);
  5125. EXPECT_EQ("hi", res->body);
  5126. }
  5127. {
  5128. auto res = cli.Get("/user/john");
  5129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. EXPECT_EQ("john", res->body);
  5132. }
  5133. {
  5134. auto res = cli.Get("/user/invalid-user");
  5135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5136. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5137. EXPECT_EQ("error", res->body);
  5138. }
  5139. }
  5140. // The pre-request handler must run before the request body is read, so a
  5141. // rejected request never forces the server to buffer a (potentially large)
  5142. // body. Here the posted body is larger than the payload limit: if the body
  5143. // were read first the server would answer 413, but because the pre-request
  5144. // handler runs first it answers 403 and the body is never read.
  5145. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5146. Server svr;
  5147. svr.set_payload_max_length(8);
  5148. auto handler_ran = false;
  5149. svr.Post("/reject", [&](const Request &req, Response &res) {
  5150. handler_ran = true;
  5151. res.set_content(req.body, "text/plain");
  5152. });
  5153. svr.Post("/accept", [](const Request &req, Response &res) {
  5154. res.set_content(req.body, "text/plain");
  5155. });
  5156. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5157. if (req.matched_route == "/reject") {
  5158. res.status = StatusCode::Forbidden_403;
  5159. res.set_content("denied", "text/plain");
  5160. return Server::HandlerResponse::Handled;
  5161. }
  5162. return Server::HandlerResponse::Unhandled;
  5163. });
  5164. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5165. auto se = detail::scope_exit([&] {
  5166. svr.stop();
  5167. thread.join();
  5168. ASSERT_FALSE(svr.is_running());
  5169. });
  5170. svr.wait_until_ready();
  5171. Client cli(HOST, PORT);
  5172. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5173. // rejects with 403 before the body is read, so 413 is never reached.
  5174. {
  5175. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5177. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5178. EXPECT_EQ("denied", res->body);
  5179. EXPECT_FALSE(handler_ran);
  5180. }
  5181. // An approved route still reads the body and enforces the payload limit.
  5182. {
  5183. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5185. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5186. }
  5187. }
  5188. TEST(UserDataTest, BasicOperations) {
  5189. httplib::UserData ud;
  5190. // Initially empty
  5191. EXPECT_FALSE(ud.has("key"));
  5192. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5193. // set and get
  5194. ud.set("key", 42);
  5195. EXPECT_TRUE(ud.has("key"));
  5196. auto *p = ud.get<int>("key");
  5197. ASSERT_NE(nullptr, p);
  5198. EXPECT_EQ(42, *p);
  5199. // Type mismatch → nullptr
  5200. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5201. // Overwrite with different type
  5202. ud.set("key", std::string("hello"));
  5203. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5204. auto *s = ud.get<std::string>("key");
  5205. ASSERT_NE(nullptr, s);
  5206. EXPECT_EQ("hello", *s);
  5207. // erase
  5208. ud.erase("key");
  5209. EXPECT_FALSE(ud.has("key"));
  5210. // clear
  5211. ud.set("a", 1);
  5212. ud.set("b", 2);
  5213. ud.clear();
  5214. EXPECT_FALSE(ud.has("a"));
  5215. EXPECT_FALSE(ud.has("b"));
  5216. }
  5217. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5218. struct AuthCtx {
  5219. std::string user_id;
  5220. };
  5221. Server svr;
  5222. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5223. res.user_data.set("auth", AuthCtx{"alice"});
  5224. return Server::HandlerResponse::Unhandled;
  5225. });
  5226. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5227. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5228. ASSERT_NE(nullptr, ctx);
  5229. res.set_content("Hello " + ctx->user_id, "text/plain");
  5230. });
  5231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5232. auto se = detail::scope_exit([&] {
  5233. svr.stop();
  5234. thread.join();
  5235. ASSERT_FALSE(svr.is_running());
  5236. });
  5237. svr.wait_until_ready();
  5238. Client cli(HOST, PORT);
  5239. auto res = cli.Get("/me");
  5240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5241. EXPECT_EQ(StatusCode::OK_200, res->status);
  5242. EXPECT_EQ("Hello alice", res->body);
  5243. }
  5244. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5245. struct RoleCtx {
  5246. std::string role;
  5247. };
  5248. Server svr;
  5249. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5250. res.user_data.set("role", RoleCtx{"admin"});
  5251. return Server::HandlerResponse::Unhandled;
  5252. });
  5253. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5254. auto *ctx = res.user_data.get<RoleCtx>("role");
  5255. ASSERT_NE(nullptr, ctx);
  5256. res.set_content(ctx->role, "text/plain");
  5257. });
  5258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5259. auto se = detail::scope_exit([&] {
  5260. svr.stop();
  5261. thread.join();
  5262. ASSERT_FALSE(svr.is_running());
  5263. });
  5264. svr.wait_until_ready();
  5265. Client cli(HOST, PORT);
  5266. auto res = cli.Get("/role");
  5267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5268. EXPECT_EQ(StatusCode::OK_200, res->status);
  5269. EXPECT_EQ("admin", res->body);
  5270. }
  5271. TEST(InvalidFormatTest, StatusCode) {
  5272. Server svr;
  5273. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5274. res.set_content("Hello World!\n", "text/plain");
  5275. res.status = 9999; // Status should be a three-digit code...
  5276. });
  5277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5278. auto se = detail::scope_exit([&] {
  5279. svr.stop();
  5280. thread.join();
  5281. ASSERT_FALSE(svr.is_running());
  5282. });
  5283. svr.wait_until_ready();
  5284. {
  5285. Client cli(HOST, PORT);
  5286. auto res = cli.Get("/hi");
  5287. ASSERT_FALSE(res);
  5288. }
  5289. }
  5290. TEST(URLFragmentTest, WithFragment) {
  5291. Server svr;
  5292. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5293. EXPECT_TRUE(req.target == "/hi");
  5294. });
  5295. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5296. auto se = detail::scope_exit([&] {
  5297. svr.stop();
  5298. thread.join();
  5299. ASSERT_FALSE(svr.is_running());
  5300. });
  5301. svr.wait_until_ready();
  5302. {
  5303. Client cli(HOST, PORT);
  5304. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5305. EXPECT_TRUE(res);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. res = cli.Get("/hi%23key1=val1=key2=val2");
  5308. EXPECT_TRUE(res);
  5309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5310. }
  5311. }
  5312. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5313. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5314. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5315. Server svr;
  5316. std::vector<std::string> targets;
  5317. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5318. targets.push_back(req.target);
  5319. });
  5320. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5321. auto se = detail::scope_exit([&] {
  5322. svr.stop();
  5323. thread.join();
  5324. ASSERT_FALSE(svr.is_running());
  5325. });
  5326. svr.wait_until_ready();
  5327. Client cli(HOST, PORT);
  5328. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5329. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5330. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5331. // A '?' after the '#' belongs to the fragment, not to the query.
  5332. Request req;
  5333. req.method = "GET";
  5334. req.path = "/hi#f?x=1";
  5335. req.params.emplace("a", "1");
  5336. Response res;
  5337. auto error = Error::Success;
  5338. EXPECT_TRUE(cli.send(req, res, error));
  5339. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5340. "/hi?a=1"}),
  5341. targets);
  5342. }
  5343. TEST(HeaderWriter, SetHeaderWriter) {
  5344. Server svr;
  5345. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5346. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5347. return detail::write_headers(strm, hdrs);
  5348. });
  5349. svr.Get("/hi", [](const Request &req, Response &res) {
  5350. auto it = req.headers.find("CustomClientHeader");
  5351. EXPECT_TRUE(it != req.headers.end());
  5352. EXPECT_EQ(it->second, "CustomClientValue");
  5353. res.set_content("Hello World!\n", "text/plain");
  5354. });
  5355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5356. auto se = detail::scope_exit([&] {
  5357. svr.stop();
  5358. thread.join();
  5359. ASSERT_FALSE(svr.is_running());
  5360. });
  5361. svr.wait_until_ready();
  5362. {
  5363. Client cli(HOST, PORT);
  5364. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5365. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5366. return detail::write_headers(strm, hdrs);
  5367. });
  5368. auto res = cli.Get("/hi");
  5369. EXPECT_TRUE(res);
  5370. EXPECT_EQ(StatusCode::OK_200, res->status);
  5371. auto it = res->headers.find("CustomServerHeader");
  5372. EXPECT_TRUE(it != res->headers.end());
  5373. EXPECT_EQ(it->second, "CustomServerValue");
  5374. }
  5375. }
  5376. class ServerTest : public ::testing::Test {
  5377. protected:
  5378. ServerTest()
  5379. : cli_(HOST, PORT)
  5380. #ifdef CPPHTTPLIB_SSL_ENABLED
  5381. ,
  5382. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5383. #endif
  5384. {
  5385. #ifdef CPPHTTPLIB_SSL_ENABLED
  5386. cli_.enable_server_certificate_verification(false);
  5387. #endif
  5388. // Allow LARGE_DATA (100MB) responses
  5389. cli_.set_payload_max_length(200 * 1024 * 1024);
  5390. }
  5391. virtual void SetUp() {
  5392. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5393. svr_.set_payload_max_length(200 * 1024 * 1024);
  5394. svr_.set_mount_point("/", "./www");
  5395. svr_.set_mount_point("/mount", "./www2");
  5396. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5397. svr_.Get("/hi",
  5398. [&](const Request & /*req*/, Response &res) {
  5399. res.set_content("Hello World!", "text/plain");
  5400. })
  5401. .Get("/file_content",
  5402. [&](const Request & /*req*/, Response &res) {
  5403. res.set_file_content("./www/dir/test.html");
  5404. })
  5405. .Get("/file_content_with_content_type",
  5406. [&](const Request & /*req*/, Response &res) {
  5407. res.set_file_content("./www/file", "text/plain");
  5408. })
  5409. .Get("/invalid_file_content",
  5410. [&](const Request & /*req*/, Response &res) {
  5411. res.set_file_content("./www/dir/invalid_file_path");
  5412. })
  5413. .Get("/http_response_splitting",
  5414. [&](const Request & /*req*/, Response &res) {
  5415. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5416. EXPECT_EQ(0U, res.headers.size());
  5417. EXPECT_FALSE(res.has_header("a"));
  5418. res.set_header("a", "1\nSet-Cookie: a=1");
  5419. EXPECT_EQ(0U, res.headers.size());
  5420. EXPECT_FALSE(res.has_header("a"));
  5421. res.set_header("a", "1\rSet-Cookie: a=1");
  5422. EXPECT_EQ(0U, res.headers.size());
  5423. EXPECT_FALSE(res.has_header("a"));
  5424. res.set_header("a\r\nb", "0");
  5425. EXPECT_EQ(0U, res.headers.size());
  5426. EXPECT_FALSE(res.has_header("a"));
  5427. res.set_header("a\rb", "0");
  5428. EXPECT_EQ(0U, res.headers.size());
  5429. EXPECT_FALSE(res.has_header("a"));
  5430. res.set_header("a\nb", "0");
  5431. EXPECT_EQ(0U, res.headers.size());
  5432. EXPECT_FALSE(res.has_header("a"));
  5433. res.set_redirect("1\r\nSet-Cookie: a=1");
  5434. EXPECT_EQ(0U, res.headers.size());
  5435. EXPECT_FALSE(res.has_header("Location"));
  5436. })
  5437. .Get("/slow",
  5438. [&](const Request & /*req*/, Response &res) {
  5439. std::this_thread::sleep_for(std::chrono::seconds(4));
  5440. res.set_content("slow", "text/plain");
  5441. })
  5442. #if 0
  5443. .Post("/slowpost",
  5444. [&](const Request & /*req*/, Response &res) {
  5445. std::this_thread::sleep_for(std::chrono::seconds(2));
  5446. res.set_content("slow", "text/plain");
  5447. })
  5448. #endif
  5449. .Get("/remote_addr",
  5450. [&](const Request &req, Response &res) {
  5451. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5452. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5453. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5454. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5455. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5456. #endif
  5457. res.set_content(req.remote_addr, "text/plain");
  5458. })
  5459. .Get("/local_addr",
  5460. [&](const Request &req, Response &res) {
  5461. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5462. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5463. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5464. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5465. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5466. #endif
  5467. auto local_addr = req.local_addr;
  5468. auto local_port = std::to_string(req.local_port);
  5469. res.set_content(local_addr.append(":").append(local_port),
  5470. "text/plain");
  5471. })
  5472. .Get("/endwith%",
  5473. [&](const Request & /*req*/, Response &res) {
  5474. res.set_content("Hello World!", "text/plain");
  5475. })
  5476. .Get("/a\\+\\+b",
  5477. [&](const Request &req, Response &res) {
  5478. ASSERT_TRUE(req.has_param("a +b"));
  5479. auto val = req.get_param_value("a +b");
  5480. res.set_content(val, "text/plain");
  5481. })
  5482. .Get("/", [&](const Request & /*req*/,
  5483. Response &res) { res.set_redirect("/hi"); })
  5484. .Post("/1",
  5485. [](const Request & /*req*/, Response &res) {
  5486. res.set_redirect("/2", StatusCode::SeeOther_303);
  5487. })
  5488. .Get("/2",
  5489. [](const Request & /*req*/, Response &res) {
  5490. res.set_content("redirected.", "text/plain");
  5491. res.status = StatusCode::OK_200;
  5492. })
  5493. .Post("/person",
  5494. [&](const Request &req, Response &res) {
  5495. if (req.has_param("name") && req.has_param("note")) {
  5496. persons_[req.get_param_value("name")] =
  5497. req.get_param_value("note");
  5498. } else {
  5499. res.status = StatusCode::BadRequest_400;
  5500. }
  5501. })
  5502. .Put("/person",
  5503. [&](const Request &req, Response &res) {
  5504. if (req.has_param("name") && req.has_param("note")) {
  5505. persons_[req.get_param_value("name")] =
  5506. req.get_param_value("note");
  5507. } else {
  5508. res.status = StatusCode::BadRequest_400;
  5509. }
  5510. })
  5511. .Get("/person/(.*)",
  5512. [&](const Request &req, Response &res) {
  5513. string name = req.matches[1];
  5514. if (persons_.find(name) != persons_.end()) {
  5515. auto note = persons_[name];
  5516. res.set_content(note, "text/plain");
  5517. } else {
  5518. res.status = StatusCode::NotFound_404;
  5519. }
  5520. })
  5521. .Delete("/person",
  5522. [&](const Request &req, Response &res) {
  5523. if (req.has_param("name")) {
  5524. string name = req.get_param_value("name");
  5525. if (persons_.find(name) != persons_.end()) {
  5526. persons_.erase(name);
  5527. res.set_content("DELETED", "text/plain");
  5528. } else {
  5529. res.status = StatusCode::NotFound_404;
  5530. }
  5531. } else {
  5532. res.status = StatusCode::BadRequest_400;
  5533. }
  5534. })
  5535. .Post("/x-www-form-urlencoded-json",
  5536. [&](const Request &req, Response &res) {
  5537. auto json = req.get_param_value("json");
  5538. ASSERT_EQ(JSON_DATA, json);
  5539. res.set_content(json, "appliation/json");
  5540. res.status = StatusCode::OK_200;
  5541. })
  5542. .Get("/streamed-chunked",
  5543. [&](const Request & /*req*/, Response &res) {
  5544. res.set_chunked_content_provider(
  5545. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5546. sink.os << "123";
  5547. sink.os << "456";
  5548. sink.os << "789";
  5549. sink.done();
  5550. return true;
  5551. });
  5552. })
  5553. .Get("/streamed-chunked-with-prohibited-trailer",
  5554. [&](const Request & /*req*/, Response &res) {
  5555. auto i = new int(0);
  5556. // Declare both a prohibited trailer (Content-Length) and an
  5557. // allowed one
  5558. res.set_header("Trailer", "Content-Length, X-Allowed");
  5559. res.set_chunked_content_provider(
  5560. "text/plain",
  5561. [i](size_t /*offset*/, DataSink &sink) {
  5562. switch (*i) {
  5563. case 0: sink.os << "123"; break;
  5564. case 1: sink.os << "456"; break;
  5565. case 2: sink.os << "789"; break;
  5566. case 3: {
  5567. sink.done_with_trailer(
  5568. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5569. } break;
  5570. }
  5571. (*i)++;
  5572. return true;
  5573. },
  5574. [i](bool success) {
  5575. EXPECT_TRUE(success);
  5576. delete i;
  5577. });
  5578. })
  5579. .Get("/streamed-chunked2",
  5580. [&](const Request & /*req*/, Response &res) {
  5581. auto i = new int(0);
  5582. res.set_chunked_content_provider(
  5583. "text/plain",
  5584. [i](size_t /*offset*/, DataSink &sink) {
  5585. switch (*i) {
  5586. case 0: sink.os << "123"; break;
  5587. case 1: sink.os << "456"; break;
  5588. case 2: sink.os << "789"; break;
  5589. case 3: sink.done(); break;
  5590. }
  5591. (*i)++;
  5592. return true;
  5593. },
  5594. [i](bool success) {
  5595. EXPECT_TRUE(success);
  5596. delete i;
  5597. });
  5598. })
  5599. .Get("/streamed-chunked-with-trailer",
  5600. [&](const Request & /*req*/, Response &res) {
  5601. auto i = new int(0);
  5602. res.set_header("Trailer", "Dummy1, Dummy2");
  5603. res.set_chunked_content_provider(
  5604. "text/plain",
  5605. [i](size_t /*offset*/, DataSink &sink) {
  5606. switch (*i) {
  5607. case 0: sink.os << "123"; break;
  5608. case 1: sink.os << "456"; break;
  5609. case 2: sink.os << "789"; break;
  5610. case 3: {
  5611. sink.done_with_trailer(
  5612. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5613. } break;
  5614. }
  5615. (*i)++;
  5616. return true;
  5617. },
  5618. [i](bool success) {
  5619. EXPECT_TRUE(success);
  5620. delete i;
  5621. });
  5622. })
  5623. .Get("/streamed",
  5624. [&](const Request & /*req*/, Response &res) {
  5625. res.set_content_provider(
  5626. 6, "text/plain",
  5627. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5628. sink.os << (offset < 3 ? "a" : "b");
  5629. return true;
  5630. });
  5631. })
  5632. .Get("/streamed-without-length",
  5633. [&](const Request & /*req*/, Response &res) {
  5634. auto data = new std::string("abcdefg");
  5635. res.set_content_provider(
  5636. "text/plain",
  5637. [data](size_t offset, DataSink &sink) {
  5638. if (offset < data->size()) {
  5639. sink.os << data->substr(offset);
  5640. }
  5641. sink.done();
  5642. return true;
  5643. },
  5644. [data](bool success) {
  5645. EXPECT_TRUE(success);
  5646. delete data;
  5647. });
  5648. })
  5649. .Get("/streamed-with-range",
  5650. [&](const Request &req, Response &res) {
  5651. auto data = new std::string("abcdefg");
  5652. // An explicit status keeps the server from picking the 206 it
  5653. // would otherwise choose for a ranged request, so the response
  5654. // is not a partial representation.
  5655. auto status = req.get_param_value("status");
  5656. if (status == "200") {
  5657. res.status = StatusCode::OK_200;
  5658. } else if (status == "403") {
  5659. res.status = StatusCode::Forbidden_403;
  5660. }
  5661. res.set_content_provider(
  5662. data->size(), "text/plain",
  5663. [data](size_t offset, size_t length, DataSink &sink) {
  5664. size_t DATA_CHUNK_SIZE = 4;
  5665. const auto &d = *data;
  5666. auto out_len =
  5667. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5668. auto ret =
  5669. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5670. EXPECT_TRUE(ret);
  5671. return true;
  5672. },
  5673. [data, &req](bool success) {
  5674. EXPECT_EQ(success, !req.has_param("error"));
  5675. delete data;
  5676. });
  5677. })
  5678. .Get("/streamed-cancel",
  5679. [&](const Request & /*req*/, Response &res) {
  5680. res.set_content_provider(
  5681. size_t(-1), "text/plain",
  5682. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5683. sink.os << "data_chunk";
  5684. return true;
  5685. });
  5686. })
  5687. .Get("/regex-with-delimiter",
  5688. [&](const Request &req, Response & /*res*/) {
  5689. ASSERT_TRUE(req.has_param("key"));
  5690. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5691. })
  5692. .Get("/with-range",
  5693. [&](const Request & /*req*/, Response &res) {
  5694. res.set_content("abcdefg", "text/plain");
  5695. })
  5696. .Get("/test-start-time",
  5697. [&](const Request &req, Response & /*res*/) {
  5698. EXPECT_NE(req.start_time_,
  5699. std::chrono::steady_clock::time_point::min());
  5700. })
  5701. .Get("/with-range-customized-response",
  5702. [&](const Request & /*req*/, Response &res) {
  5703. res.status = StatusCode::BadRequest_400;
  5704. res.set_content(JSON_DATA, "application/json");
  5705. })
  5706. .Post("/chunked",
  5707. [&](const Request &req, Response & /*res*/) {
  5708. EXPECT_EQ(req.body, "dechunked post body");
  5709. })
  5710. .Post("/large-chunked",
  5711. [&](const Request &req, Response & /*res*/) {
  5712. std::string expected(6 * 30 * 1024u, 'a');
  5713. EXPECT_EQ(req.body, expected);
  5714. })
  5715. .Post("/multipart",
  5716. [&](const Request &req, Response & /*res*/) {
  5717. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5718. req.form.get_field_count("text2") +
  5719. req.form.get_field_count("file3") +
  5720. req.form.get_field_count("file4"));
  5721. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5722. req.form.get_file_count("file2"));
  5723. ASSERT_TRUE(!req.form.has_file("???"));
  5724. ASSERT_TRUE(!req.form.has_field("???"));
  5725. ASSERT_TRUE(req.body.empty());
  5726. {
  5727. const auto &text = req.form.get_field("text1");
  5728. EXPECT_EQ("text default", text);
  5729. }
  5730. {
  5731. const auto &text = req.form.get_field("text2");
  5732. EXPECT_EQ("aωb", text);
  5733. }
  5734. {
  5735. const auto &file = req.form.get_file("file1");
  5736. EXPECT_EQ("hello.txt", file.filename);
  5737. EXPECT_EQ("text/plain", file.content_type);
  5738. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5739. }
  5740. {
  5741. const auto &file = req.form.get_file("file2");
  5742. EXPECT_EQ("world.json", file.filename);
  5743. EXPECT_EQ("application/json", file.content_type);
  5744. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5745. }
  5746. {
  5747. const auto &text = req.form.get_field("file3");
  5748. EXPECT_EQ(0u, text.size());
  5749. }
  5750. {
  5751. const auto &text = req.form.get_field("file4");
  5752. EXPECT_EQ(0u, text.size());
  5753. }
  5754. })
  5755. .Post("/multipart/multi_file_values",
  5756. [&](const Request &req, Response & /*res*/) {
  5757. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5758. req.form.get_field_count("multi_text1"));
  5759. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5760. ASSERT_TRUE(!req.form.has_file("???"));
  5761. ASSERT_TRUE(!req.form.has_field("???"));
  5762. ASSERT_TRUE(req.body.empty());
  5763. {
  5764. const auto &text = req.form.get_field("text");
  5765. EXPECT_EQ("default text", text);
  5766. }
  5767. {
  5768. const auto &text1_values = req.form.get_fields("multi_text1");
  5769. EXPECT_EQ(2u, text1_values.size());
  5770. EXPECT_EQ("aaaaa", text1_values[0]);
  5771. EXPECT_EQ("bbbbb", text1_values[1]);
  5772. }
  5773. {
  5774. const auto &file1_values = req.form.get_files("multi_file1");
  5775. EXPECT_EQ(2u, file1_values.size());
  5776. auto file1 = file1_values[0];
  5777. EXPECT_EQ(file1.filename, "hello.txt");
  5778. EXPECT_EQ(file1.content_type, "text/plain");
  5779. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5780. auto file2 = file1_values[1];
  5781. EXPECT_EQ(file2.filename, "world.json");
  5782. EXPECT_EQ(file2.content_type, "application/json");
  5783. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5784. }
  5785. })
  5786. .Post("/empty",
  5787. [&](const Request &req, Response &res) {
  5788. EXPECT_EQ(req.body, "");
  5789. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5790. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5791. res.set_content("empty", "text/plain");
  5792. })
  5793. .Post("/empty-no-content-type",
  5794. [&](const Request &req, Response &res) {
  5795. EXPECT_EQ(req.body, "");
  5796. EXPECT_FALSE(req.has_header("Content-Type"));
  5797. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5798. res.set_content("empty-no-content-type", "text/plain");
  5799. })
  5800. .Post("/path-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. res.set_content("path-only", "text/plain");
  5806. })
  5807. .Post("/path-headers-only",
  5808. [&](const Request &req, Response &res) {
  5809. EXPECT_EQ(req.body, "");
  5810. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5811. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5812. EXPECT_EQ("world", req.get_header_value("hello"));
  5813. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5814. res.set_content("path-headers-only", "text/plain");
  5815. })
  5816. .Post("/post-large",
  5817. [&](const Request &req, Response &res) {
  5818. EXPECT_EQ(req.body, LARGE_DATA);
  5819. res.set_content(req.body, "text/plain");
  5820. })
  5821. .Post("/post-loopback",
  5822. [&](const Request &, Response &res,
  5823. ContentReader const &content_reader) {
  5824. std::string body;
  5825. content_reader([&](const char *data, size_t data_length) {
  5826. body.append(data, data_length);
  5827. return true;
  5828. });
  5829. res.set_content(body, "text/plain");
  5830. })
  5831. .Put("/put-loopback",
  5832. [&](const Request &, Response &res,
  5833. ContentReader const &content_reader) {
  5834. std::string body;
  5835. content_reader([&](const char *data, size_t data_length) {
  5836. body.append(data, data_length);
  5837. return true;
  5838. });
  5839. res.set_content(body, "text/plain");
  5840. })
  5841. .Patch("/patch-loopback",
  5842. [&](const Request &, Response &res,
  5843. ContentReader const &content_reader) {
  5844. std::string body;
  5845. content_reader([&](const char *data, size_t data_length) {
  5846. body.append(data, data_length);
  5847. return true;
  5848. });
  5849. res.set_content(body, "text/plain");
  5850. })
  5851. .Put("/empty-no-content-type",
  5852. [&](const Request &req, Response &res) {
  5853. EXPECT_EQ(req.body, "");
  5854. EXPECT_FALSE(req.has_header("Content-Type"));
  5855. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5856. res.set_content("empty-no-content-type", "text/plain");
  5857. })
  5858. .Put("/put",
  5859. [&](const Request &req, Response &res) {
  5860. EXPECT_EQ(req.body, "PUT");
  5861. res.set_content(req.body, "text/plain");
  5862. })
  5863. .Put("/put-large",
  5864. [&](const Request &req, Response &res) {
  5865. EXPECT_EQ(req.body, LARGE_DATA);
  5866. res.set_content(req.body, "text/plain");
  5867. })
  5868. .Patch("/patch",
  5869. [&](const Request &req, Response &res) {
  5870. EXPECT_EQ(req.body, "PATCH");
  5871. res.set_content(req.body, "text/plain");
  5872. })
  5873. .Delete("/delete",
  5874. [&](const Request & /*req*/, Response &res) {
  5875. res.set_content("DELETE", "text/plain");
  5876. })
  5877. .Delete("/delete-body",
  5878. [&](const Request &req, Response &res) {
  5879. EXPECT_EQ(req.body, "content");
  5880. res.set_content(req.body, "text/plain");
  5881. })
  5882. .Options(R"(\*)",
  5883. [&](const Request & /*req*/, Response &res) {
  5884. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5885. })
  5886. .CustomRoute("PROPFIND", "/dav/:id",
  5887. [&](const Request &req, Response &res) {
  5888. res.set_header("x-body-size",
  5889. std::to_string(req.body.size()));
  5890. res.set_header("x-matched-route", req.matched_route);
  5891. res.set_header("x-dav-id", req.path_params.at("id"));
  5892. res.status = StatusCode::MultiStatus_207;
  5893. res.set_content(req.body, "application/xml");
  5894. })
  5895. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5896. [&](const Request &req, Response &res) {
  5897. res.set_header("x-dav-match", req.matches[1]);
  5898. res.status = StatusCode::MultiStatus_207;
  5899. })
  5900. .CustomRoute("MKCOL", "/dav-mkcol",
  5901. [&](const Request &req, Response &res) {
  5902. EXPECT_TRUE(req.body.empty());
  5903. res.status = StatusCode::Created_201;
  5904. })
  5905. .CustomRoute(
  5906. "REPORT", "/dav-report",
  5907. [&](const Request & /*req*/, Response &res,
  5908. const ContentReader &content_reader) {
  5909. std::string body;
  5910. content_reader([&](const char *data, size_t data_length) {
  5911. body.append(data, data_length);
  5912. return true;
  5913. });
  5914. res.set_header("x-body-size", std::to_string(body.size()));
  5915. res.status = StatusCode::MultiStatus_207;
  5916. res.set_content(body, "application/xml");
  5917. })
  5918. .Get("/request-target",
  5919. [&](const Request &req, Response & /*res*/) {
  5920. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5921. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5922. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5923. })
  5924. .Get("/long-query-value",
  5925. [&](const Request &req, Response & /*res*/) {
  5926. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5927. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5928. })
  5929. .Get("/too-long-query-value",
  5930. [&](const Request &req, Response & /*res*/) {
  5931. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5932. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5933. })
  5934. .Get("/array-param",
  5935. [&](const Request &req, Response & /*res*/) {
  5936. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5937. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5938. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5939. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5940. })
  5941. .Get("/array-param-values",
  5942. [&](const Request &req, Response & /*res*/) {
  5943. auto values = req.get_param_values("array");
  5944. EXPECT_EQ(3u, values.size());
  5945. EXPECT_EQ("value1", values[0]);
  5946. EXPECT_EQ("value2", values[1]);
  5947. EXPECT_EQ("value3", values[2]);
  5948. auto empty = req.get_param_values("nonexistent");
  5949. EXPECT_TRUE(empty.empty());
  5950. })
  5951. .Post("/validate-no-multiple-headers",
  5952. [&](const Request &req, Response & /*res*/) {
  5953. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5954. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5955. })
  5956. .Post("/content_receiver",
  5957. [&](const Request &req, Response &res,
  5958. const ContentReader &content_reader) {
  5959. if (req.is_multipart_form_data()) {
  5960. std::vector<FormData> items;
  5961. content_reader(
  5962. [&](const FormData &file) {
  5963. items.push_back(file);
  5964. return true;
  5965. },
  5966. [&](const char *data, size_t data_length) {
  5967. items.back().content.append(data, data_length);
  5968. return true;
  5969. });
  5970. EXPECT_EQ(5u, items.size());
  5971. {
  5972. const auto &file = get_file_value(items, "text1");
  5973. EXPECT_TRUE(file.filename.empty());
  5974. EXPECT_EQ("text default", file.content);
  5975. }
  5976. {
  5977. const auto &file = get_file_value(items, "text2");
  5978. EXPECT_TRUE(file.filename.empty());
  5979. EXPECT_EQ("aωb", file.content);
  5980. }
  5981. {
  5982. const auto &file = get_file_value(items, "file1");
  5983. EXPECT_EQ("hello.txt", file.filename);
  5984. EXPECT_EQ("text/plain", file.content_type);
  5985. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5986. }
  5987. {
  5988. const auto &file = get_file_value(items, "file2");
  5989. EXPECT_EQ("world.json", file.filename);
  5990. EXPECT_EQ("application/json", file.content_type);
  5991. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5992. }
  5993. {
  5994. const auto &file = get_file_value(items, "file3");
  5995. EXPECT_TRUE(file.filename.empty());
  5996. EXPECT_EQ("application/octet-stream", file.content_type);
  5997. EXPECT_EQ(0u, file.content.size());
  5998. }
  5999. } else {
  6000. std::string body;
  6001. content_reader([&](const char *data, size_t data_length) {
  6002. EXPECT_EQ(7U, data_length);
  6003. body.append(data, data_length);
  6004. return true;
  6005. });
  6006. EXPECT_EQ(body, "content");
  6007. res.set_content(body, "text/plain");
  6008. }
  6009. })
  6010. .Put("/content_receiver",
  6011. [&](const Request & /*req*/, Response &res,
  6012. const ContentReader &content_reader) {
  6013. std::string body;
  6014. content_reader([&](const char *data, size_t data_length) {
  6015. body.append(data, data_length);
  6016. return true;
  6017. });
  6018. EXPECT_EQ(body, "content");
  6019. res.set_content(body, "text/plain");
  6020. })
  6021. .Patch("/content_receiver",
  6022. [&](const Request & /*req*/, Response &res,
  6023. const ContentReader &content_reader) {
  6024. std::string body;
  6025. content_reader([&](const char *data, size_t data_length) {
  6026. body.append(data, data_length);
  6027. return true;
  6028. });
  6029. EXPECT_EQ(body, "content");
  6030. res.set_content(body, "text/plain");
  6031. })
  6032. .Post("/query-string-and-body",
  6033. [&](const Request &req, Response & /*res*/) {
  6034. ASSERT_TRUE(req.has_param("key"));
  6035. EXPECT_EQ(req.get_param_value("key"), "value");
  6036. EXPECT_EQ(req.body, "content");
  6037. })
  6038. .Get("/last-request",
  6039. [&](const Request &req, Response & /*res*/) {
  6040. EXPECT_EQ("close", req.get_header_value("Connection"));
  6041. })
  6042. .Get(R"(/redirect/(\d+))",
  6043. [&](const Request &req, Response &res) {
  6044. auto num = std::stoi(req.matches[1]) + 1;
  6045. std::string url = "/redirect/" + std::to_string(num);
  6046. res.set_redirect(url);
  6047. })
  6048. .Post("/binary",
  6049. [&](const Request &req, Response &res) {
  6050. EXPECT_EQ(4U, req.body.size());
  6051. EXPECT_EQ("application/octet-stream",
  6052. req.get_header_value("Content-Type"));
  6053. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6054. res.set_content(req.body, "application/octet-stream");
  6055. })
  6056. .Put("/binary",
  6057. [&](const Request &req, Response &res) {
  6058. EXPECT_EQ(4U, req.body.size());
  6059. EXPECT_EQ("application/octet-stream",
  6060. req.get_header_value("Content-Type"));
  6061. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6062. res.set_content(req.body, "application/octet-stream");
  6063. })
  6064. .Patch("/binary",
  6065. [&](const Request &req, Response &res) {
  6066. EXPECT_EQ(4U, req.body.size());
  6067. EXPECT_EQ("application/octet-stream",
  6068. req.get_header_value("Content-Type"));
  6069. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6070. res.set_content(req.body, "application/octet-stream");
  6071. })
  6072. .Delete("/binary",
  6073. [&](const Request &req, Response &res) {
  6074. EXPECT_EQ(4U, req.body.size());
  6075. EXPECT_EQ("application/octet-stream",
  6076. req.get_header_value("Content-Type"));
  6077. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6078. res.set_content(req.body, "application/octet-stream");
  6079. })
  6080. .Get("/issue1772",
  6081. [&](const Request & /*req*/, Response &res) {
  6082. res.status = 401;
  6083. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6084. })
  6085. .Delete("/issue609",
  6086. [](const httplib::Request &, httplib::Response &res,
  6087. const httplib::ContentReader &) {
  6088. res.set_content("ok", "text/plain");
  6089. })
  6090. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6091. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6092. .Get("/compress",
  6093. [&](const Request & /*req*/, Response &res) {
  6094. res.set_content(
  6095. "12345678901234567890123456789012345678901234567890123456789"
  6096. "01234567890123456789012345678901234567890",
  6097. "text/plain");
  6098. })
  6099. .Get("/compress-with-charset",
  6100. [&](const Request & /*req*/, Response &res) {
  6101. res.set_content(
  6102. "12345678901234567890123456789012345678901234567890123456789"
  6103. "01234567890123456789012345678901234567890",
  6104. "application/json; charset=utf-8");
  6105. })
  6106. .Get("/nocompress",
  6107. [&](const Request & /*req*/, Response &res) {
  6108. res.set_content(
  6109. "12345678901234567890123456789012345678901234567890123456789"
  6110. "01234567890123456789012345678901234567890",
  6111. "application/octet-stream");
  6112. })
  6113. .Post("/compress-multipart",
  6114. [&](const Request &req, Response & /*res*/) {
  6115. EXPECT_EQ(2u, req.form.fields.size());
  6116. ASSERT_TRUE(!req.form.has_field("???"));
  6117. {
  6118. const auto &text = req.form.get_field("key1");
  6119. EXPECT_EQ("test", text);
  6120. }
  6121. {
  6122. const auto &text = req.form.get_field("key2");
  6123. EXPECT_EQ("--abcdefg123", text);
  6124. }
  6125. })
  6126. #endif
  6127. ;
  6128. persons_["john"] = "programmer";
  6129. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6130. svr_.wait_until_ready();
  6131. }
  6132. virtual void TearDown() {
  6133. svr_.stop();
  6134. if (!request_threads_.empty()) {
  6135. std::this_thread::sleep_for(std::chrono::seconds(1));
  6136. for (auto &t : request_threads_) {
  6137. t.join();
  6138. }
  6139. }
  6140. t_.join();
  6141. }
  6142. map<string, string> persons_;
  6143. #ifdef CPPHTTPLIB_SSL_ENABLED
  6144. SSLClient cli_;
  6145. SSLServer svr_;
  6146. #else
  6147. Client cli_;
  6148. Server svr_;
  6149. #endif
  6150. thread t_;
  6151. std::vector<thread> request_threads_;
  6152. };
  6153. TEST_F(ServerTest, GetMethod200) {
  6154. auto res = cli_.Get("/hi");
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. EXPECT_EQ("HTTP/1.1", res->version);
  6157. EXPECT_EQ(StatusCode::OK_200, res->status);
  6158. EXPECT_EQ("OK", res->reason);
  6159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6160. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6161. EXPECT_EQ("Hello World!", res->body);
  6162. }
  6163. TEST_F(ServerTest, GetEmptyFile) {
  6164. auto res = cli_.Get("/empty_file");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6168. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6169. EXPECT_EQ("", res->body);
  6170. }
  6171. TEST_F(ServerTest, GetFileContent) {
  6172. auto res = cli_.Get("/file_content");
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::OK_200, res->status);
  6175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6176. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6177. EXPECT_EQ("test.html", res->body);
  6178. }
  6179. TEST_F(ServerTest, GetFileContentWithRange) {
  6180. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6183. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6184. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6185. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6186. EXPECT_EQ("est", res->body);
  6187. }
  6188. TEST_F(ServerTest, GetFileContentWithContentType) {
  6189. auto res = cli_.Get("/file_content_with_content_type");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6193. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6194. EXPECT_EQ("file\n", res->body);
  6195. }
  6196. TEST_F(ServerTest, GetInvalidFileContent) {
  6197. auto res = cli_.Get("/invalid_file_content");
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6200. }
  6201. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6202. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. EXPECT_EQ("HTTP/1.1", res->version);
  6205. EXPECT_EQ(StatusCode::OK_200, res->status);
  6206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6207. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6208. EXPECT_EQ("Hello World!", res->body);
  6209. }
  6210. TEST_F(ServerTest, GetMethod302) {
  6211. auto res = cli_.Get("/");
  6212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6213. EXPECT_EQ(StatusCode::Found_302, res->status);
  6214. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6215. }
  6216. TEST_F(ServerTest, GetMethod302Redirect) {
  6217. cli_.set_follow_location(true);
  6218. auto res = cli_.Get("/");
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. EXPECT_EQ(StatusCode::OK_200, res->status);
  6221. EXPECT_EQ("Hello World!", res->body);
  6222. EXPECT_EQ("/hi", res->location);
  6223. }
  6224. TEST_F(ServerTest, GetMethod404) {
  6225. auto res = cli_.Get("/invalid");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6228. }
  6229. TEST_F(ServerTest, HeadMethod200) {
  6230. auto res = cli_.Head("/hi");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::OK_200, res->status);
  6233. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6234. EXPECT_TRUE(res->body.empty());
  6235. }
  6236. TEST_F(ServerTest, HeadMethod200Static) {
  6237. auto res = cli_.Head("/mount/dir/index.html");
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6241. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6242. EXPECT_TRUE(res->body.empty());
  6243. }
  6244. TEST_F(ServerTest, HeadMethod404) {
  6245. auto res = cli_.Head("/invalid");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6248. EXPECT_TRUE(res->body.empty());
  6249. }
  6250. TEST_F(ServerTest, GetMethodPersonJohn) {
  6251. auto res = cli_.Get("/person/john");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. EXPECT_EQ(StatusCode::OK_200, res->status);
  6254. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6255. EXPECT_EQ("programmer", res->body);
  6256. }
  6257. TEST_F(ServerTest, PostMethod1) {
  6258. auto res = cli_.Get("/person/john1");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6261. res = cli_.Post("/person", "name=john1&note=coder",
  6262. "application/x-www-form-urlencoded");
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. ASSERT_EQ(StatusCode::OK_200, res->status);
  6265. res = cli_.Get("/person/john1");
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. ASSERT_EQ(StatusCode::OK_200, res->status);
  6268. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6269. ASSERT_EQ("coder", res->body);
  6270. }
  6271. TEST_F(ServerTest, PostMethod2) {
  6272. auto res = cli_.Get("/person/john2");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6275. Params params;
  6276. params.emplace("name", "john2");
  6277. params.emplace("note", "coder");
  6278. res = cli_.Post("/person", params);
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. ASSERT_EQ(StatusCode::OK_200, res->status);
  6281. res = cli_.Get("/person/john2");
  6282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6283. ASSERT_EQ(StatusCode::OK_200, res->status);
  6284. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6285. ASSERT_EQ("coder", res->body);
  6286. }
  6287. TEST_F(ServerTest, PutMethod3) {
  6288. auto res = cli_.Get("/person/john3");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6291. Params params;
  6292. params.emplace("name", "john3");
  6293. params.emplace("note", "coder");
  6294. res = cli_.Put("/person", params);
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. ASSERT_EQ(StatusCode::OK_200, res->status);
  6297. res = cli_.Get("/person/john3");
  6298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6299. ASSERT_EQ(StatusCode::OK_200, res->status);
  6300. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6301. ASSERT_EQ("coder", res->body);
  6302. }
  6303. TEST_F(ServerTest, DeleteMethod1) {
  6304. auto res = cli_.Get("/person/john4");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6307. Params params;
  6308. params.emplace("name", "john4");
  6309. params.emplace("note", "coder");
  6310. res = cli_.Post("/person", params);
  6311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6312. ASSERT_EQ(StatusCode::OK_200, res->status);
  6313. res = cli_.Get("/person/john4");
  6314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6315. ASSERT_EQ(StatusCode::OK_200, res->status);
  6316. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6317. ASSERT_EQ("coder", res->body);
  6318. Params delete_params;
  6319. delete_params.emplace("name", "john4");
  6320. res = cli_.Delete("/person", delete_params);
  6321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6322. ASSERT_EQ(StatusCode::OK_200, res->status);
  6323. ASSERT_EQ("DELETED", res->body);
  6324. res = cli_.Get("/person/john4");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6327. }
  6328. TEST_F(ServerTest, DeleteMethod2) {
  6329. auto res = cli_.Get("/person/john5");
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6332. Params params;
  6333. params.emplace("name", "john5");
  6334. params.emplace("note", "developer");
  6335. res = cli_.Post("/person", params);
  6336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6337. ASSERT_EQ(StatusCode::OK_200, res->status);
  6338. res = cli_.Get("/person/john5");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. ASSERT_EQ(StatusCode::OK_200, res->status);
  6341. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6342. ASSERT_EQ("developer", res->body);
  6343. Params delete_params;
  6344. delete_params.emplace("name", "john5");
  6345. Headers headers;
  6346. headers.emplace("Custom-Header", "test-value");
  6347. res = cli_.Delete("/person", headers, delete_params);
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. ASSERT_EQ(StatusCode::OK_200, res->status);
  6350. ASSERT_EQ("DELETED", res->body);
  6351. res = cli_.Get("/person/john5");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6354. }
  6355. TEST_F(ServerTest, DeleteMethod3) {
  6356. auto res = cli_.Get("/person/john6");
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6359. Params params;
  6360. params.emplace("name", "john6");
  6361. params.emplace("note", "tester");
  6362. res = cli_.Post("/person", params);
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. ASSERT_EQ(StatusCode::OK_200, res->status);
  6365. res = cli_.Get("/person/john6");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. ASSERT_EQ(StatusCode::OK_200, res->status);
  6368. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6369. ASSERT_EQ("tester", res->body);
  6370. Params delete_params;
  6371. delete_params.emplace("name", "john6");
  6372. Headers headers;
  6373. headers.emplace("Custom-Header", "test-value");
  6374. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6376. ASSERT_EQ(StatusCode::OK_200, res->status);
  6377. ASSERT_EQ("DELETED", res->body);
  6378. res = cli_.Get("/person/john6");
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6381. }
  6382. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6383. Params params;
  6384. params.emplace("json", JSON_DATA);
  6385. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6387. ASSERT_EQ(StatusCode::OK_200, res->status);
  6388. ASSERT_EQ(JSON_DATA, res->body);
  6389. }
  6390. TEST_F(ServerTest, PostEmptyContent) {
  6391. auto res = cli_.Post("/empty", "", "text/plain");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. ASSERT_EQ(StatusCode::OK_200, res->status);
  6394. ASSERT_EQ("empty", res->body);
  6395. }
  6396. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6397. auto res = cli_.Post("/empty-no-content-type");
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. ASSERT_EQ(StatusCode::OK_200, res->status);
  6400. ASSERT_EQ("empty-no-content-type", res->body);
  6401. }
  6402. TEST_F(ServerTest, PostPathOnly) {
  6403. auto res = cli_.Post("/path-only");
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. ASSERT_EQ(StatusCode::OK_200, res->status);
  6406. ASSERT_EQ("path-only", res->body);
  6407. }
  6408. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6409. auto res = cli_.Post("/path-headers-only",
  6410. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. ASSERT_EQ(StatusCode::OK_200, res->status);
  6413. ASSERT_EQ("path-headers-only", res->body);
  6414. }
  6415. TEST_F(ServerTest, PostLarge) {
  6416. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. ASSERT_EQ(StatusCode::OK_200, res->status);
  6419. EXPECT_EQ(LARGE_DATA, res->body);
  6420. }
  6421. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6422. auto res = cli_.Put("/empty-no-content-type");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. ASSERT_EQ(StatusCode::OK_200, res->status);
  6425. ASSERT_EQ("empty-no-content-type", res->body);
  6426. }
  6427. TEST_F(ServerTest, GetMethodDir) {
  6428. auto res = cli_.Get("/dir/");
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::OK_200, res->status);
  6431. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6432. auto body = R"(<html>
  6433. <head>
  6434. </head>
  6435. <body>
  6436. <a href="/dir/test.html">Test</a>
  6437. <a href="/hi">hi</a>
  6438. </body>
  6439. </html>
  6440. )";
  6441. EXPECT_EQ(body, res->body);
  6442. }
  6443. TEST_F(ServerTest, GetMethodDirTest) {
  6444. auto res = cli_.Get("/dir/test.html");
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. EXPECT_EQ(StatusCode::OK_200, res->status);
  6447. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6448. EXPECT_EQ("test.html", res->body);
  6449. }
  6450. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6451. auto res = cli_.Get("/dir/../dir/test.html");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6454. }
  6455. TEST_F(ServerTest, GetMethodInvalidPath) {
  6456. auto res = cli_.Get("/dir/../test.html");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6459. }
  6460. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6461. auto res = cli_.Get("/../www/dir/test.html");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6464. }
  6465. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6466. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6469. }
  6470. TEST_F(ServerTest, GetMethodDirMountTest) {
  6471. auto res = cli_.Get("/mount/dir/test.html");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6475. EXPECT_EQ("test.html", res->body);
  6476. }
  6477. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6478. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6481. }
  6482. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6483. auto res = cli_.Get("/mount/dir/../test.html");
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6486. }
  6487. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6488. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6491. }
  6492. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6493. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6495. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6496. }
  6497. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6498. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6501. }
  6502. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6503. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6506. }
  6507. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6508. auto res = cli_.Get("/mount/dir");
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6511. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6512. }
  6513. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6514. auto res = cli_.Get("//dir");
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6517. EXPECT_FALSE(res->has_header("Location"));
  6518. }
  6519. TEST_F(ServerTest, PostMethod303) {
  6520. auto res = cli_.Post("/1", "body", "text/plain");
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6523. EXPECT_EQ("/2", res->get_header_value("Location"));
  6524. }
  6525. TEST_F(ServerTest, PostMethod303Redirect) {
  6526. cli_.set_follow_location(true);
  6527. auto res = cli_.Post("/1", "body", "text/plain");
  6528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6529. EXPECT_EQ(StatusCode::OK_200, res->status);
  6530. EXPECT_EQ("redirected.", res->body);
  6531. EXPECT_EQ("/2", res->location);
  6532. }
  6533. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6534. auto res = cli_.Get("/dir/test.abcde");
  6535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6536. EXPECT_EQ(StatusCode::OK_200, res->status);
  6537. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6538. EXPECT_EQ("abcde", res->body);
  6539. }
  6540. TEST_F(ServerTest, StaticFileRange) {
  6541. auto res =
  6542. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6544. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6545. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6546. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6547. EXPECT_EQ(true, res->has_header("Content-Range"));
  6548. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6549. EXPECT_EQ(std::string("cd"), res->body);
  6550. }
  6551. TEST_F(ServerTest, StaticFileRanges) {
  6552. auto res = cli_.Get("/dir/test.abcde",
  6553. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6555. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6556. EXPECT_TRUE(
  6557. res->get_header_value("Content-Type")
  6558. .find(
  6559. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6560. 0);
  6561. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6562. }
  6563. TEST_F(ServerTest, StaticFileRangeHead) {
  6564. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6567. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6568. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6569. EXPECT_EQ(true, res->has_header("Content-Range"));
  6570. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6571. }
  6572. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6573. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6577. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6578. EXPECT_EQ(true, res->has_header("Content-Range"));
  6579. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6580. res->get_header_value("Content-Range"));
  6581. EXPECT_EQ("LAST\n", res->body);
  6582. }
  6583. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6584. auto res =
  6585. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6589. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6590. EXPECT_EQ(true, res->has_header("Content-Range"));
  6591. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6592. }
  6593. TEST_F(ServerTest, StaticFileBigFile) {
  6594. auto res = cli_.Get("/dir/1MB.txt");
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6598. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6599. }
  6600. TEST_F(ServerTest, InvalidBaseDirMount) {
  6601. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6602. }
  6603. TEST_F(ServerTest, Binary) {
  6604. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6605. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6606. "application/octet-stream");
  6607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6608. ASSERT_EQ(StatusCode::OK_200, res->status);
  6609. ASSERT_EQ(4U, res->body.size());
  6610. res = cli_.Put("/binary", binary.data(), binary.size(),
  6611. "application/octet-stream");
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. ASSERT_EQ(StatusCode::OK_200, res->status);
  6614. ASSERT_EQ(4U, res->body.size());
  6615. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6616. "application/octet-stream");
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. ASSERT_EQ(StatusCode::OK_200, res->status);
  6619. ASSERT_EQ(4U, res->body.size());
  6620. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6621. "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. }
  6626. TEST_F(ServerTest, BinaryString) {
  6627. auto binary = std::string("\x00\x01\x02\x03", 4);
  6628. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6630. ASSERT_EQ(StatusCode::OK_200, res->status);
  6631. ASSERT_EQ(4U, res->body.size());
  6632. res = cli_.Put("/binary", binary, "application/octet-stream");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. ASSERT_EQ(StatusCode::OK_200, res->status);
  6635. ASSERT_EQ(4U, res->body.size());
  6636. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6638. ASSERT_EQ(StatusCode::OK_200, res->status);
  6639. ASSERT_EQ(4U, res->body.size());
  6640. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6642. ASSERT_EQ(StatusCode::OK_200, res->status);
  6643. ASSERT_EQ(4U, res->body.size());
  6644. }
  6645. TEST_F(ServerTest, EmptyRequest) {
  6646. auto res = cli_.Get("");
  6647. ASSERT_TRUE(!res);
  6648. EXPECT_EQ(Error::Connection, res.error());
  6649. }
  6650. TEST_F(ServerTest, LongRequest) {
  6651. std::string request;
  6652. for (size_t i = 0; i < 545; i++) {
  6653. request += "/TooLongRequest";
  6654. }
  6655. request += "OK";
  6656. auto res = cli_.Get(request.c_str());
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6659. }
  6660. TEST_F(ServerTest, TooLongRequest) {
  6661. std::string request;
  6662. for (size_t i = 0; i < 546; i++) {
  6663. request += "/TooLongRequest";
  6664. }
  6665. request += "_NG";
  6666. auto start = std::chrono::high_resolution_clock::now();
  6667. cli_.set_keep_alive(true);
  6668. auto res = cli_.Get(request.c_str());
  6669. auto end = std::chrono::high_resolution_clock::now();
  6670. auto elapsed =
  6671. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6672. .count();
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6675. EXPECT_LE(elapsed, 1000);
  6676. EXPECT_EQ("close", res->get_header_value("Connection"));
  6677. EXPECT_FALSE(cli_.is_socket_open());
  6678. }
  6679. TEST_F(ServerTest, AlmostTooLongRequest) {
  6680. // test for #2046 - URI length check shouldn't include other content on req
  6681. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6682. // leading /, space, HTTP/1.1)
  6683. std::string request =
  6684. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6685. auto res = cli_.Get(request.c_str());
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6688. }
  6689. TEST_F(ServerTest, LongHeader) {
  6690. Request req;
  6691. req.method = "GET";
  6692. req.path = "/hi";
  6693. std::string host_and_port;
  6694. host_and_port += HOST;
  6695. host_and_port += ":";
  6696. host_and_port += std::to_string(PORT);
  6697. req.headers.emplace("Host", host_and_port.c_str());
  6698. req.headers.emplace("Accept", "*/*");
  6699. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6700. req.headers.emplace(
  6701. "Header-Name",
  6702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6730. "@@@@@@@@@@@@@@@@");
  6731. auto res = std::make_shared<Response>();
  6732. auto error = Error::Success;
  6733. auto ret = cli_.send(req, *res, error);
  6734. ASSERT_TRUE(ret);
  6735. EXPECT_EQ(StatusCode::OK_200, res->status);
  6736. }
  6737. TEST_F(ServerTest, LongQueryValue) {
  6738. auto start = std::chrono::high_resolution_clock::now();
  6739. cli_.set_keep_alive(true);
  6740. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6741. auto end = std::chrono::high_resolution_clock::now();
  6742. auto elapsed =
  6743. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6744. .count();
  6745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6746. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6747. EXPECT_LE(elapsed, 1000);
  6748. EXPECT_EQ("close", res->get_header_value("Connection"));
  6749. EXPECT_FALSE(cli_.is_socket_open());
  6750. }
  6751. TEST_F(ServerTest, TooLongQueryValue) {
  6752. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6753. ASSERT_FALSE(res);
  6754. EXPECT_EQ(Error::Read, res.error());
  6755. }
  6756. TEST_F(ServerTest, TooLongHeader) {
  6757. Request req;
  6758. req.method = "GET";
  6759. req.path = "/hi";
  6760. std::string host_and_port;
  6761. host_and_port += HOST;
  6762. host_and_port += ":";
  6763. host_and_port += std::to_string(PORT);
  6764. req.headers.emplace("Host", host_and_port.c_str());
  6765. req.headers.emplace("Accept", "*/*");
  6766. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6767. req.headers.emplace(
  6768. "Header-Name",
  6769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6797. "@@@@@@@@@@@@@@@@@");
  6798. auto res = std::make_shared<Response>();
  6799. auto error = Error::Success;
  6800. auto ret = cli_.send(req, *res, error);
  6801. ASSERT_TRUE(ret);
  6802. EXPECT_EQ(StatusCode::OK_200, res->status);
  6803. }
  6804. TEST_F(ServerTest, HeaderCountAtLimit) {
  6805. // Test with headers just under the 100 limit
  6806. httplib::Headers headers;
  6807. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6808. // This should keep us just under the 100 header limit
  6809. for (int i = 0; i < 95; i++) {
  6810. std::string name = "X-Test-Header-" + std::to_string(i);
  6811. std::string value = "value" + std::to_string(i);
  6812. headers.emplace(name, value);
  6813. }
  6814. // This should work fine as we're under the limit
  6815. auto res = cli_.Get("/hi", headers);
  6816. EXPECT_TRUE(res);
  6817. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6818. }
  6819. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6820. // Test with many headers to exceed the 100 limit
  6821. httplib::Headers headers;
  6822. // Add 150 headers to definitely exceed the 100 limit
  6823. for (int i = 0; i < 150; i++) {
  6824. std::string name = "X-Test-Header-" + std::to_string(i);
  6825. std::string value = "value" + std::to_string(i);
  6826. headers.emplace(name, value);
  6827. }
  6828. // This should fail due to exceeding header count limit
  6829. cli_.set_keep_alive(true);
  6830. auto res = cli_.Get("/hi", headers);
  6831. // The server should respond with 400 Bad Request
  6832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6833. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6834. EXPECT_EQ("close", res->get_header_value("Connection"));
  6835. EXPECT_FALSE(cli_.is_socket_open());
  6836. }
  6837. TEST_F(ServerTest, PercentEncoding) {
  6838. auto res = cli_.Get("/e%6edwith%");
  6839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6840. EXPECT_EQ(StatusCode::OK_200, res->status);
  6841. }
  6842. TEST_F(ServerTest, PercentEncodingUnicode) {
  6843. auto res = cli_.Get("/e%u006edwith%");
  6844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6845. EXPECT_EQ(StatusCode::OK_200, res->status);
  6846. }
  6847. TEST_F(ServerTest, InvalidPercentEncoding) {
  6848. auto res = cli_.Get("/%endwith%");
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6851. }
  6852. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6853. auto res = cli_.Get("/%uendwith%");
  6854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6855. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6856. }
  6857. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6858. auto res = cli_.Get("/hello?aaa=bbb%");
  6859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6860. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6861. }
  6862. TEST_F(ServerTest, PlusSignEncoding) {
  6863. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. EXPECT_EQ("a +b", res->body);
  6867. }
  6868. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6869. // This test simulates a potential DoS attack using many headers
  6870. // to verify our security fix prevents memory exhaustion
  6871. httplib::Headers attack_headers;
  6872. // Attempt to add many headers like an attacker would (200 headers to far
  6873. // exceed limit)
  6874. for (int i = 0; i < 200; i++) {
  6875. std::string name = "X-Attack-Header-" + std::to_string(i);
  6876. std::string value = "attack_payload_" + std::to_string(i);
  6877. attack_headers.emplace(name, value);
  6878. }
  6879. // Try to POST with excessive headers
  6880. cli_.set_keep_alive(true);
  6881. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6882. // Should either fail or return 400 Bad Request due to security limit
  6883. if (res) {
  6884. // If we get a response, it should be 400 Bad Request
  6885. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6886. EXPECT_EQ("close", res->get_header_value("Connection"));
  6887. }
  6888. EXPECT_FALSE(cli_.is_socket_open());
  6889. }
  6890. TEST_F(ServerTest, MultipartFormData) {
  6891. UploadFormDataItems items = {
  6892. {"text1", "text default", "", ""},
  6893. {"text2", "aωb", "", ""},
  6894. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6895. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6896. {"file3", "", "", "application/octet-stream"},
  6897. {"file4", "", "", " application/json tmp-string "}};
  6898. auto res = cli_.Post("/multipart", items);
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. }
  6902. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6903. UploadFormDataItems items = {
  6904. {"text", "default text", "", ""},
  6905. {"multi_text1", "aaaaa", "", ""},
  6906. {"multi_text1", "bbbbb", "", ""},
  6907. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6908. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6909. "application/json"},
  6910. };
  6911. auto res = cli_.Post("/multipart/multi_file_values", items);
  6912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6913. EXPECT_EQ(StatusCode::OK_200, res->status);
  6914. }
  6915. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6916. auto res = cli_.Get("/hi");
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::OK_200, res->status);
  6919. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6920. EXPECT_EQ("Hello World!", res->body);
  6921. }
  6922. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6923. Request req;
  6924. req.method = "POST";
  6925. req.path = "/chunked";
  6926. std::string host_and_port;
  6927. host_and_port += HOST;
  6928. host_and_port += ":";
  6929. host_and_port += std::to_string(PORT);
  6930. req.headers.emplace("Host", host_and_port.c_str());
  6931. req.headers.emplace("Accept", "*/*");
  6932. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6933. req.headers.emplace("Content-Type", "text/plain");
  6934. req.headers.emplace("Content-Length", "0");
  6935. req.headers.emplace(
  6936. "Transfer-Encoding",
  6937. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6938. // Client does not chunk, so make a chunked body manually.
  6939. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6940. auto res = std::make_shared<Response>();
  6941. auto error = Error::Success;
  6942. auto ret = cli_.send(req, *res, error);
  6943. ASSERT_TRUE(ret);
  6944. EXPECT_EQ(StatusCode::OK_200, res->status);
  6945. }
  6946. template <typename ClientT>
  6947. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6948. int expected_status) {
  6949. Request req;
  6950. req.method = "POST";
  6951. req.path = "/chunked";
  6952. std::string host_and_port;
  6953. host_and_port += HOST;
  6954. host_and_port += ":";
  6955. host_and_port += std::to_string(PORT);
  6956. req.headers.emplace("Host", host_and_port.c_str());
  6957. req.headers.emplace("Content-Length", "0");
  6958. req.headers.emplace("Transfer-Encoding", "chunked");
  6959. req.body = body;
  6960. auto res = std::make_shared<Response>();
  6961. auto error = Error::Success;
  6962. ASSERT_TRUE(cli.send(req, *res, error));
  6963. EXPECT_EQ(expected_status, res->status);
  6964. }
  6965. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6966. // rather than treat them as valid lengths.
  6967. template <typename ClientT>
  6968. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6969. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6970. }
  6971. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6972. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6973. }
  6974. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6975. expect_chunked_body_rejected(
  6976. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6977. }
  6978. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6979. // chunk-size line carries no CR, LF or other control character ahead of its
  6980. // terminator. Such a line must be refused rather than read as extension text.
  6981. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6982. expect_chunked_body_rejected(
  6983. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6984. }
  6985. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6986. expect_chunked_body_rejected(
  6987. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6988. }
  6989. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6990. expect_chunked_body_rejected(
  6991. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6992. }
  6993. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6994. // The literal stays split: a hex escape consumes every hex digit that
  6995. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6996. expect_chunked_body_rejected(
  6997. cli_, "4;a\x01"
  6998. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6999. }
  7000. // The bytes around chunk data are no payload, so they cannot ride on the
  7001. // payload limit
  7002. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7003. // Small enough that the whole request is sent before the server turns it
  7004. // down, yet past the limit by the last chunks
  7005. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7006. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7007. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7008. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7009. SCOPED_TRACE(size_line.substr(0, 2));
  7010. std::string body;
  7011. for (auto c : std::string("dechunked post body")) {
  7012. body += size_line + "\r\n" + c + "\r\n";
  7013. }
  7014. body += "0\r\n\r\n";
  7015. expect_chunked_body_rejected(cli_, body.c_str());
  7016. }
  7017. }
  7018. TEST_F(ServerTest, AcceptsChunkExtension) {
  7019. expect_chunked_body_status(cli_,
  7020. "4;name=value\r\ndech\r\n"
  7021. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7022. "0;last\r\n\r\n",
  7023. StatusCode::OK_200);
  7024. }
  7025. TEST_F(ServerTest, GetStreamed2) {
  7026. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7029. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7030. EXPECT_EQ(true, res->has_header("Content-Range"));
  7031. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7032. EXPECT_EQ(std::string("ab"), res->body);
  7033. }
  7034. TEST_F(ServerTest, GetStreamed) {
  7035. auto res = cli_.Get("/streamed");
  7036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7039. EXPECT_EQ(std::string("aaabbb"), res->body);
  7040. }
  7041. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7042. auto res = cli_.Get("/streamed-without-length",
  7043. Headers{make_range_header({{0, -1}})});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::OK_200, res->status);
  7046. EXPECT_EQ(false, res->has_header("Content-Length"));
  7047. EXPECT_EQ(false, res->has_header("Content-Range"));
  7048. EXPECT_EQ(std::string("abcdefg"), res->body);
  7049. }
  7050. TEST_F(ServerTest, GetStreamedWithRange1) {
  7051. auto res =
  7052. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7055. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7056. EXPECT_EQ(true, res->has_header("Content-Range"));
  7057. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7058. EXPECT_EQ(std::string("def"), res->body);
  7059. }
  7060. TEST_F(ServerTest, GetStreamedWithRange2) {
  7061. auto res =
  7062. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7065. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7066. EXPECT_EQ(true, res->has_header("Content-Range"));
  7067. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7068. EXPECT_EQ(std::string("bcdefg"), res->body);
  7069. }
  7070. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7071. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7074. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7075. EXPECT_EQ(true, res->has_header("Content-Range"));
  7076. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7077. EXPECT_EQ(std::string("efg"), res->body);
  7078. }
  7079. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7080. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7081. // the entire representation.
  7082. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7083. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7086. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7087. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7088. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7089. }
  7090. }
  7091. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7092. auto res =
  7093. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7096. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7097. EXPECT_EQ(false, res->has_header("Content-Range"));
  7098. EXPECT_EQ(0U, res->body.size());
  7099. }
  7100. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7101. // Only a 206 is served as a partial representation. Under any other status
  7102. // `apply_ranges()` reported the full content length, so the body must match
  7103. // that header, and the content provider must never be asked for an offset
  7104. // outside the representation.
  7105. auto check = [&](int status, const char *range) {
  7106. auto path =
  7107. std::string("/streamed-with-range?status=") + std::to_string(status);
  7108. auto ctx = path + " Range: " + range;
  7109. auto res = cli_.Get(path, Headers{{"Range", range}});
  7110. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7111. EXPECT_EQ(status, res->status) << ctx;
  7112. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7113. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7114. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7115. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7116. };
  7117. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7118. check(403, "bytes=3-5");
  7119. // The offset is far past the representation.
  7120. check(403, "bytes=100000-100200");
  7121. // `first_pos` is still -1 here, and the bounds asserts in
  7122. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7123. check(403, "bytes=-3");
  7124. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7125. // multipart branch would have written one that is empty.
  7126. check(403, "bytes=1-2, 4-5");
  7127. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7128. // covers the whole representation.
  7129. check(200, "bytes=3-5");
  7130. check(200, "bytes=1-2, 4-5");
  7131. }
  7132. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7133. auto res =
  7134. cli_.Get("/streamed-with-range",
  7135. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7136. "92233720368547758079223372036854775807"}});
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7139. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7140. EXPECT_EQ(false, res->has_header("Content-Range"));
  7141. EXPECT_EQ(0U, res->body.size());
  7142. }
  7143. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7144. auto res = cli_.Get(
  7145. "/with-range",
  7146. Headers{{"Range",
  7147. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7148. {"Accept-Encoding", ""}});
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7151. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7152. EXPECT_EQ(true, res->has_header("Content-Range"));
  7153. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7154. EXPECT_EQ(std::string("abcdefg"), res->body);
  7155. }
  7156. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7157. auto res = cli_.Get("/with-range", Headers{
  7158. {"Range", "bytes=0-"},
  7159. {"Accept-Encoding", ""},
  7160. });
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7164. EXPECT_EQ(true, res->has_header("Content-Range"));
  7165. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7166. EXPECT_EQ(std::string("abcdefg"), res->body);
  7167. }
  7168. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7169. auto res = cli_.Get("/streamed-with-range",
  7170. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7173. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7174. EXPECT_EQ(false, res->has_header("Content-Range"));
  7175. EXPECT_EQ(267U, res->body.size());
  7176. // Check that both range contents are present
  7177. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7178. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7179. // Check that Content-Range headers are present for both ranges
  7180. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7181. std::string::npos);
  7182. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7183. std::string::npos);
  7184. }
  7185. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7186. Ranges ranges;
  7187. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7188. ranges.emplace_back(0, -1);
  7189. }
  7190. auto res = cli_.Get("/streamed-with-range?error",
  7191. Headers{{make_range_header(ranges)}});
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7194. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7195. EXPECT_EQ(false, res->has_header("Content-Range"));
  7196. EXPECT_EQ(0U, res->body.size());
  7197. }
  7198. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7199. auto res = cli_.Get("/streamed-with-range",
  7200. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7203. EXPECT_EQ(5U, res->body.size());
  7204. // Check that overlapping ranges are coalesced into a single range
  7205. EXPECT_EQ("bcdef", res->body);
  7206. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7207. // Should be single range, not multipart
  7208. EXPECT_TRUE(res->has_header("Content-Range"));
  7209. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7210. }
  7211. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7212. auto res = cli_.Get("/streamed-with-range",
  7213. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7215. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7216. EXPECT_EQ(268U, res->body.size());
  7217. // Check that both range contents are present
  7218. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7219. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7220. // Check that Content-Range headers are present for both ranges
  7221. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7222. std::string::npos);
  7223. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7224. std::string::npos);
  7225. }
  7226. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7227. auto res = cli_.Get("/streamed-with-range",
  7228. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7230. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7231. EXPECT_EQ(269U, res->body.size());
  7232. // Check that both duplicate range contents are present
  7233. size_t first_abc = res->body.find("abc\r\n");
  7234. EXPECT_TRUE(first_abc != std::string::npos);
  7235. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7236. EXPECT_TRUE(second_abc != std::string::npos);
  7237. // Check that Content-Range headers are present for both ranges
  7238. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7239. EXPECT_TRUE(first_range != std::string::npos);
  7240. size_t second_range =
  7241. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7242. EXPECT_TRUE(second_range != std::string::npos);
  7243. }
  7244. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7245. auto res =
  7246. cli_.Get("/streamed-with-range?error",
  7247. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7249. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7250. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7251. EXPECT_EQ(false, res->has_header("Content-Range"));
  7252. EXPECT_EQ(0U, res->body.size());
  7253. }
  7254. TEST_F(ServerTest, GetStreamedEndless) {
  7255. uint64_t offset = 0;
  7256. auto res = cli_.Get("/streamed-cancel",
  7257. [&](const char * /*data*/, uint64_t data_length) {
  7258. if (offset < 100) {
  7259. offset += data_length;
  7260. return true;
  7261. }
  7262. return false;
  7263. });
  7264. ASSERT_TRUE(!res);
  7265. EXPECT_EQ(Error::Canceled, res.error());
  7266. }
  7267. TEST_F(ServerTest, ClientStop) {
  7268. std::atomic_size_t count{4};
  7269. std::vector<std::thread> threads;
  7270. for (auto i = count.load(); i != 0; --i) {
  7271. threads.emplace_back([&]() {
  7272. auto res = cli_.Get("/streamed-cancel",
  7273. [&](const char *, uint64_t) { return true; });
  7274. --count;
  7275. ASSERT_TRUE(!res);
  7276. EXPECT_TRUE(res.error() == Error::Canceled ||
  7277. res.error() == Error::Read || res.error() == Error::Write);
  7278. });
  7279. }
  7280. std::this_thread::sleep_for(std::chrono::seconds(2));
  7281. while (count != 0) {
  7282. cli_.stop();
  7283. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7284. }
  7285. for (auto &t : threads) {
  7286. t.join();
  7287. }
  7288. }
  7289. TEST_F(ServerTest, GetWithRange1) {
  7290. auto res = cli_.Get("/with-range", Headers{
  7291. make_range_header({{3, 5}}),
  7292. {"Accept-Encoding", ""},
  7293. });
  7294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7296. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7297. EXPECT_EQ(true, res->has_header("Content-Range"));
  7298. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7299. EXPECT_EQ(std::string("def"), res->body);
  7300. }
  7301. TEST_F(ServerTest, GetWithRange2) {
  7302. auto res = cli_.Get("/with-range", Headers{
  7303. make_range_header({{1, -1}}),
  7304. {"Accept-Encoding", ""},
  7305. });
  7306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7307. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7308. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7309. EXPECT_EQ(true, res->has_header("Content-Range"));
  7310. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7311. EXPECT_EQ(std::string("bcdefg"), res->body);
  7312. }
  7313. TEST_F(ServerTest, GetWithRange3) {
  7314. auto res = cli_.Get("/with-range", Headers{
  7315. make_range_header({{0, 0}}),
  7316. {"Accept-Encoding", ""},
  7317. });
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7320. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7321. EXPECT_EQ(true, res->has_header("Content-Range"));
  7322. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7323. EXPECT_EQ(std::string("a"), res->body);
  7324. }
  7325. TEST_F(ServerTest, GetWithRange4) {
  7326. auto res = cli_.Get("/with-range", Headers{
  7327. make_range_header({{-1, 2}}),
  7328. {"Accept-Encoding", ""},
  7329. });
  7330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7331. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7332. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7333. EXPECT_EQ(true, res->has_header("Content-Range"));
  7334. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7335. EXPECT_EQ(std::string("fg"), res->body);
  7336. }
  7337. TEST_F(ServerTest, GetWithRange5) {
  7338. auto res = cli_.Get("/with-range", Headers{
  7339. make_range_header({{0, 5}}),
  7340. {"Accept-Encoding", ""},
  7341. });
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7344. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7345. EXPECT_EQ(true, res->has_header("Content-Range"));
  7346. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7347. EXPECT_EQ(std::string("abcdef"), res->body);
  7348. }
  7349. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7350. auto res =
  7351. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7353. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7354. }
  7355. TEST_F(ServerTest, GetWithRangeMultipart) {
  7356. auto res =
  7357. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7360. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7361. EXPECT_EQ(false, res->has_header("Content-Range"));
  7362. EXPECT_EQ(267U, res->body.size());
  7363. }
  7364. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7365. auto res = cli_.Get("/with-range",
  7366. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7369. }
  7370. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7371. auto res = cli_.Get("/with-range-customized-response",
  7372. Headers{{make_range_header({{1, 2}})}});
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7375. EXPECT_EQ(true, res->has_header("Content-Length"));
  7376. EXPECT_EQ(false, res->has_header("Content-Range"));
  7377. EXPECT_EQ(JSON_DATA, res->body);
  7378. }
  7379. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7380. auto res = cli_.Get("/with-range-customized-response",
  7381. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7383. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7384. EXPECT_EQ(true, res->has_header("Content-Length"));
  7385. EXPECT_EQ(false, res->has_header("Content-Range"));
  7386. EXPECT_EQ(JSON_DATA, res->body);
  7387. }
  7388. TEST_F(ServerTest, Issue1772) {
  7389. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7391. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7392. }
  7393. TEST_F(ServerTest, Issue609) {
  7394. auto res = cli_.Delete("/issue609");
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::OK_200, res->status);
  7397. EXPECT_EQ(std::string("ok"), res->body);
  7398. }
  7399. TEST_F(ServerTest, GetStreamedChunked) {
  7400. auto res = cli_.Get("/streamed-chunked");
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::OK_200, res->status);
  7403. EXPECT_EQ(std::string("123456789"), res->body);
  7404. }
  7405. TEST_F(ServerTest, GetStreamedChunked2) {
  7406. auto res = cli_.Get("/streamed-chunked2");
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::OK_200, res->status);
  7409. EXPECT_EQ(std::string("123456789"), res->body);
  7410. }
  7411. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7412. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ(StatusCode::OK_200, res->status);
  7415. EXPECT_EQ(std::string("123456789"), res->body);
  7416. EXPECT_TRUE(res->has_header("Trailer"));
  7417. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7418. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7419. // Trailers are now stored separately from headers (security fix)
  7420. EXPECT_EQ(2U, res->trailers.size());
  7421. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7422. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7423. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7424. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7425. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7426. // Verify trailers are NOT in headers (security verification)
  7427. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7428. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7429. }
  7430. TEST_F(ServerTest, LargeChunkedPost) {
  7431. Request req;
  7432. req.method = "POST";
  7433. req.path = "/large-chunked";
  7434. std::string host_and_port;
  7435. host_and_port += HOST;
  7436. host_and_port += ":";
  7437. host_and_port += std::to_string(PORT);
  7438. req.headers.emplace("Host", host_and_port.c_str());
  7439. req.headers.emplace("Accept", "*/*");
  7440. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7441. req.headers.emplace("Content-Type", "text/plain");
  7442. req.headers.emplace("Content-Length", "0");
  7443. req.headers.emplace("Transfer-Encoding", "chunked");
  7444. std::string long_string(30 * 1024u, 'a');
  7445. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7446. // Attempt to make a large enough post to exceed OS buffers, to test that
  7447. // the server handles short reads if the full chunk data isn't available.
  7448. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7449. auto res = std::make_shared<Response>();
  7450. auto error = Error::Success;
  7451. auto ret = cli_.send(req, *res, error);
  7452. ASSERT_TRUE(ret);
  7453. EXPECT_EQ(StatusCode::OK_200, res->status);
  7454. }
  7455. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7456. auto res = cli_.Get("/remote_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 == "::1" || res->body == "127.0.0.1");
  7461. }
  7462. TEST_F(ServerTest, GetMethodLocalAddr) {
  7463. auto res = cli_.Get("/local_addr");
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::OK_200, res->status);
  7466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7467. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7468. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7469. }
  7470. TEST_F(ServerTest, HTTPResponseSplitting) {
  7471. auto res = cli_.Get("/http_response_splitting");
  7472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7473. EXPECT_EQ(StatusCode::OK_200, res->status);
  7474. }
  7475. TEST_F(ServerTest, SlowRequest) {
  7476. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7477. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7478. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7479. }
  7480. #if 0
  7481. TEST_F(ServerTest, SlowPost) {
  7482. char buffer[64 * 1024];
  7483. memset(buffer, 0x42, sizeof(buffer));
  7484. auto res = cli_.Post(
  7485. "/slowpost", 64 * 1024 * 1024,
  7486. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7487. auto ret = sink.write(buffer, sizeof(buffer));
  7488. EXPECT_TRUE(ret);
  7489. return true;
  7490. },
  7491. "text/plain");
  7492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. }
  7495. TEST_F(ServerTest, SlowPostFail) {
  7496. char buffer[64 * 1024];
  7497. memset(buffer, 0x42, sizeof(buffer));
  7498. cli_.set_write_timeout(std::chrono::seconds(0));
  7499. auto res = cli_.Post(
  7500. "/slowpost", 64 * 1024 * 1024,
  7501. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7502. sink.write(buffer, sizeof(buffer));
  7503. return true;
  7504. },
  7505. "text/plain");
  7506. ASSERT_TRUE(!res);
  7507. EXPECT_EQ(Error::Write, res.error());
  7508. }
  7509. #endif
  7510. TEST_F(ServerTest, Put) {
  7511. auto res = cli_.Put("/put", "PUT", "text/plain");
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ(StatusCode::OK_200, res->status);
  7514. EXPECT_EQ("PUT", res->body);
  7515. }
  7516. TEST_F(ServerTest, PutWithContentProvider) {
  7517. auto res = cli_.Put(
  7518. "/put", 3,
  7519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7520. sink.os << "PUT";
  7521. return true;
  7522. },
  7523. "text/plain");
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. EXPECT_EQ(StatusCode::OK_200, res->status);
  7526. EXPECT_EQ("PUT", res->body);
  7527. }
  7528. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7529. auto res = cli_.Post(
  7530. "/post", 42,
  7531. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7532. return false;
  7533. },
  7534. "text/plain");
  7535. ASSERT_TRUE(!res);
  7536. EXPECT_EQ(Error::Canceled, res.error());
  7537. }
  7538. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7539. auto res = cli_.Put(
  7540. "/put",
  7541. [](size_t /*offset*/, DataSink &sink) {
  7542. sink.os << "PUT";
  7543. sink.done();
  7544. return true;
  7545. },
  7546. "text/plain");
  7547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7548. EXPECT_EQ(StatusCode::OK_200, res->status);
  7549. EXPECT_EQ("PUT", res->body);
  7550. }
  7551. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7552. auto res = cli_.Post(
  7553. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7554. "text/plain");
  7555. ASSERT_TRUE(!res);
  7556. EXPECT_EQ(Error::Canceled, res.error());
  7557. }
  7558. TEST_F(ServerTest, PostLoopBack) {
  7559. std::string body;
  7560. auto res = cli_.Post(
  7561. "/post-loopback", 9,
  7562. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7563. EXPECT_EQ(9u, length);
  7564. sink.write("123", 3);
  7565. sink.write("456", 3);
  7566. sink.write("789", 3);
  7567. return true;
  7568. },
  7569. "text/plain",
  7570. [&body](const char *data, size_t data_length) {
  7571. body.append(data, data_length);
  7572. return true;
  7573. });
  7574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7575. EXPECT_EQ(StatusCode::OK_200, res->status);
  7576. EXPECT_EQ("123456789", body);
  7577. }
  7578. TEST_F(ServerTest, PutLoopBack) {
  7579. std::string body;
  7580. auto res = cli_.Put(
  7581. "/put-loopback", 9,
  7582. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7583. EXPECT_EQ(9u, length);
  7584. sink.write("123", 3);
  7585. sink.write("456", 3);
  7586. sink.write("789", 3);
  7587. return true;
  7588. },
  7589. "text/plain",
  7590. [&body](const char *data, size_t data_length) {
  7591. body.append(data, data_length);
  7592. return true;
  7593. });
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. EXPECT_EQ(StatusCode::OK_200, res->status);
  7596. EXPECT_EQ("123456789", body);
  7597. }
  7598. TEST_F(ServerTest, PatchLoopBack) {
  7599. std::string body;
  7600. auto res = cli_.Patch(
  7601. "/patch-loopback", 9,
  7602. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7603. EXPECT_EQ(9u, length);
  7604. sink.write("123", 3);
  7605. sink.write("456", 3);
  7606. sink.write("789", 3);
  7607. return true;
  7608. },
  7609. "text/plain",
  7610. [&body](const char *data, size_t data_length) {
  7611. body.append(data, data_length);
  7612. return true;
  7613. });
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. EXPECT_EQ("123456789", body);
  7617. }
  7618. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7619. std::string body;
  7620. auto res = cli_.Post(
  7621. "/post-loopback",
  7622. [](size_t /*offset*/, DataSink &sink) {
  7623. sink.write("123", 3);
  7624. sink.write("456", 3);
  7625. sink.write("789", 3);
  7626. sink.done();
  7627. return true;
  7628. },
  7629. "text/plain",
  7630. [&body](const char *data, size_t data_length) {
  7631. body.append(data, data_length);
  7632. return true;
  7633. });
  7634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. EXPECT_EQ("123456789", body);
  7637. }
  7638. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7639. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7640. cli_.set_compress(true);
  7641. auto res = cli_.Put(
  7642. "/put", 3,
  7643. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7644. sink.os << "PUT";
  7645. return true;
  7646. },
  7647. "text/plain");
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. EXPECT_EQ("PUT", res->body);
  7651. }
  7652. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7653. cli_.set_compress(true);
  7654. auto res = cli_.Post(
  7655. "/post", 42,
  7656. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7657. return false;
  7658. },
  7659. "text/plain");
  7660. ASSERT_TRUE(!res);
  7661. EXPECT_EQ(Error::Canceled, res.error());
  7662. }
  7663. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7664. cli_.set_compress(true);
  7665. auto res = cli_.Put(
  7666. "/put",
  7667. [](size_t /*offset*/, DataSink &sink) {
  7668. sink.os << "PUT";
  7669. sink.done();
  7670. return true;
  7671. },
  7672. "text/plain");
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ("PUT", res->body);
  7676. }
  7677. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7678. cli_.set_compress(true);
  7679. auto res = cli_.Post(
  7680. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7681. "text/plain");
  7682. ASSERT_TRUE(!res);
  7683. EXPECT_EQ(Error::Canceled, res.error());
  7684. }
  7685. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7686. cli_.set_compress(true);
  7687. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ(LARGE_DATA, res->body);
  7691. }
  7692. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7693. #ifdef CPPHTTPLIB_SSL_ENABLED
  7694. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7695. Client cli(s.c_str());
  7696. cli.enable_server_certificate_verification(false);
  7697. #else
  7698. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7699. Client cli(s.c_str());
  7700. #endif
  7701. cli.set_compress(true);
  7702. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::OK_200, res->status);
  7705. EXPECT_EQ(LARGE_DATA, res->body);
  7706. // The compressed size should be less than a 10th of the original. May vary
  7707. // depending on the zlib library.
  7708. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7709. static_cast<uint64_t>(10 * 1024 * 1024));
  7710. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7711. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7712. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7713. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7714. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7715. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7716. #endif
  7717. }
  7718. TEST_F(ServerTest, PutContentWithDeflate) {
  7719. cli_.set_compress(false);
  7720. Headers headers;
  7721. headers.emplace("Content-Encoding", "deflate");
  7722. // PUT in deflate format:
  7723. auto res = cli_.Put("/put", headers,
  7724. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("PUT", res->body);
  7728. }
  7729. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7730. Headers headers;
  7731. headers.emplace("Accept-Encoding", "gzip, deflate");
  7732. auto res = cli_.Get("/streamed-chunked", headers);
  7733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7734. EXPECT_EQ(StatusCode::OK_200, res->status);
  7735. EXPECT_EQ(std::string("123456789"), res->body);
  7736. }
  7737. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7738. Headers headers;
  7739. headers.emplace("Accept-Encoding", "gzip, deflate");
  7740. auto res = cli_.Get("/streamed-chunked2", headers);
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. EXPECT_EQ(std::string("123456789"), res->body);
  7744. }
  7745. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7746. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. }
  7750. TEST(GzipDecompressor, ChunkedDecompression) {
  7751. std::string data;
  7752. for (size_t i = 0; i < 32 * 1024; ++i) {
  7753. data.push_back(static_cast<char>('a' + i % 26));
  7754. }
  7755. std::string compressed_data;
  7756. {
  7757. httplib::detail::gzip_compressor compressor;
  7758. bool result = compressor.compress(
  7759. data.data(), data.size(),
  7760. /*last=*/true,
  7761. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7762. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7763. compressed_data_size);
  7764. return true;
  7765. });
  7766. ASSERT_TRUE(result);
  7767. }
  7768. std::string decompressed_data;
  7769. {
  7770. httplib::detail::gzip_decompressor decompressor;
  7771. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7772. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7773. size_t chunk_size = 130;
  7774. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7775. chunk_begin += chunk_size) {
  7776. size_t current_chunk_size =
  7777. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7778. bool result = decompressor.decompress(
  7779. compressed_data.data() + chunk_begin, current_chunk_size,
  7780. [&](const char *decompressed_data_chunk,
  7781. size_t decompressed_data_chunk_size) {
  7782. decompressed_data.insert(decompressed_data.size(),
  7783. decompressed_data_chunk,
  7784. decompressed_data_chunk_size);
  7785. return true;
  7786. });
  7787. ASSERT_TRUE(result);
  7788. }
  7789. }
  7790. ASSERT_EQ(data, decompressed_data);
  7791. }
  7792. TEST(GzipDecompressor, DeflateDecompression) {
  7793. std::string original_text = "Raw deflate without gzip";
  7794. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7795. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7796. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7797. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7798. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7799. std::string decompressed_data;
  7800. {
  7801. httplib::detail::gzip_decompressor decompressor;
  7802. bool result = decompressor.decompress(
  7803. compressed_data.data(), compressed_data.size(),
  7804. [&](const char *decompressed_data_chunk,
  7805. size_t decompressed_data_chunk_size) {
  7806. decompressed_data.insert(decompressed_data.size(),
  7807. decompressed_data_chunk,
  7808. decompressed_data_chunk_size);
  7809. return true;
  7810. });
  7811. ASSERT_TRUE(result);
  7812. }
  7813. ASSERT_EQ(original_text, decompressed_data);
  7814. }
  7815. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7816. std::string original_text = "Raw deflate without gzip";
  7817. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7818. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7819. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7820. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7821. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7822. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7823. std::string decompressed_data;
  7824. {
  7825. httplib::detail::gzip_decompressor decompressor;
  7826. bool result = decompressor.decompress(
  7827. compressed_data.data(), compressed_data.size(),
  7828. [&](const char *decompressed_data_chunk,
  7829. size_t decompressed_data_chunk_size) {
  7830. decompressed_data.insert(decompressed_data.size(),
  7831. decompressed_data_chunk,
  7832. decompressed_data_chunk_size);
  7833. return true;
  7834. });
  7835. ASSERT_TRUE(result);
  7836. }
  7837. ASSERT_EQ(original_text, decompressed_data);
  7838. }
  7839. #endif
  7840. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7841. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7842. Headers headers;
  7843. headers.emplace("Accept-Encoding", "br");
  7844. auto res = cli_.Get("/streamed-chunked", headers);
  7845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7846. EXPECT_EQ(StatusCode::OK_200, res->status);
  7847. EXPECT_EQ(std::string("123456789"), res->body);
  7848. }
  7849. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7850. Headers headers;
  7851. headers.emplace("Accept-Encoding", "br");
  7852. auto res = cli_.Get("/streamed-chunked2", headers);
  7853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7854. EXPECT_EQ(StatusCode::OK_200, res->status);
  7855. EXPECT_EQ(std::string("123456789"), res->body);
  7856. }
  7857. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7858. cli_.set_compress(true);
  7859. auto res = cli_.Put(
  7860. "/put", 3,
  7861. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7862. sink.os << "PUT";
  7863. return true;
  7864. },
  7865. "text/plain");
  7866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7867. EXPECT_EQ(StatusCode::OK_200, res->status);
  7868. EXPECT_EQ("PUT", res->body);
  7869. }
  7870. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7871. cli_.set_compress(true);
  7872. auto res = cli_.Put(
  7873. "/put",
  7874. [](size_t /*offset*/, DataSink &sink) {
  7875. sink.os << "PUT";
  7876. sink.done();
  7877. return true;
  7878. },
  7879. "text/plain");
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. EXPECT_EQ("PUT", res->body);
  7883. }
  7884. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7885. cli_.set_compress(true);
  7886. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. EXPECT_EQ(LARGE_DATA, res->body);
  7890. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7891. }
  7892. #endif
  7893. TEST_F(ServerTest, Patch) {
  7894. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7896. EXPECT_EQ(StatusCode::OK_200, res->status);
  7897. EXPECT_EQ("PATCH", res->body);
  7898. }
  7899. TEST_F(ServerTest, Delete) {
  7900. auto res = cli_.Delete("/delete");
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ(StatusCode::OK_200, res->status);
  7903. EXPECT_EQ("DELETE", res->body);
  7904. }
  7905. TEST_F(ServerTest, DeleteContentReceiver) {
  7906. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7908. EXPECT_EQ(StatusCode::OK_200, res->status);
  7909. EXPECT_EQ("content", res->body);
  7910. }
  7911. TEST_F(ServerTest, Options) {
  7912. auto res = cli_.Options("*");
  7913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7914. EXPECT_EQ(StatusCode::OK_200, res->status);
  7915. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7916. EXPECT_TRUE(res->body.empty());
  7917. }
  7918. TEST_F(ServerTest, URL) {
  7919. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. }
  7923. TEST_F(ServerTest, ArrayParam) {
  7924. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7926. EXPECT_EQ(StatusCode::OK_200, res->status);
  7927. }
  7928. TEST_F(ServerTest, ArrayParamValues) {
  7929. auto res =
  7930. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7932. EXPECT_EQ(StatusCode::OK_200, res->status);
  7933. }
  7934. TEST_F(ServerTest, NoMultipleHeaders) {
  7935. Headers headers = {{"Content-Length", "5"}};
  7936. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7937. "text/plain");
  7938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7939. EXPECT_EQ(StatusCode::OK_200, res->status);
  7940. }
  7941. TEST_F(ServerTest, PostContentReceiver) {
  7942. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. ASSERT_EQ(StatusCode::OK_200, res->status);
  7945. ASSERT_EQ("content", res->body);
  7946. }
  7947. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7948. UploadFormDataItems items = {
  7949. {"text1", "text default", "", ""},
  7950. {"text2", "aωb", "", ""},
  7951. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7952. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7953. {"file3", "", "", "application/octet-stream"},
  7954. };
  7955. auto res = cli_.Post("/content_receiver", items);
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. }
  7959. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7960. UploadFormDataItems items = {
  7961. {"text1", "text default", "", ""},
  7962. {"text2", "aωb", "", ""},
  7963. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7964. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7965. {"file3", "", "", "application/octet-stream"},
  7966. };
  7967. auto boundary = std::string("+++++");
  7968. std::string body;
  7969. for (const auto &item : items) {
  7970. body += "--" + boundary + "\r\n";
  7971. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7972. if (!item.filename.empty()) {
  7973. body += "; filename=\"" + item.filename + "\"";
  7974. }
  7975. body += "\r\n";
  7976. if (!item.content_type.empty()) {
  7977. body += "Content-Type: " + item.content_type + "\r\n";
  7978. }
  7979. body += "\r\n";
  7980. body += item.content + "\r\n";
  7981. }
  7982. body += "--" + boundary + "--\r\n";
  7983. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7984. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(StatusCode::OK_200, res->status);
  7987. }
  7988. TEST(MultipartFormDataTest, FieldEscaping) {
  7989. Server svr;
  7990. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7991. const ContentReader &content_reader) {
  7992. ASSERT_TRUE(req.is_multipart_form_data());
  7993. std::vector<FormData> received;
  7994. content_reader(
  7995. [&](const FormData &file) {
  7996. received.push_back(file);
  7997. return true;
  7998. },
  7999. [&](const char *data, size_t data_length) {
  8000. received.back().content.append(data, data_length);
  8001. return true;
  8002. });
  8003. // '"', CR and LF in names and filenames are escaped following the
  8004. // WHATWG HTML standard, so each part still parses as a single part
  8005. // with no injected headers. Content types get CR/LF escaped too,
  8006. // while '"' (legal there, e.g. quoted charset) is preserved.
  8007. ASSERT_EQ(4U, received.size());
  8008. EXPECT_EQ("na%22me", received[0].name);
  8009. EXPECT_EQ("quoted name", received[0].content);
  8010. EXPECT_EQ("file", received[1].name);
  8011. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8012. received[1].filename);
  8013. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8014. EXPECT_EQ("injected", received[1].content);
  8015. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8016. EXPECT_EQ("my%22file.txt", received[2].filename);
  8017. EXPECT_EQ("cr lf name", received[2].content);
  8018. EXPECT_EQ("typed", received[3].name);
  8019. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8020. received[3].content_type);
  8021. EXPECT_EQ("typed content", received[3].content);
  8022. });
  8023. auto port = svr.bind_to_any_port("localhost");
  8024. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8025. auto se = detail::scope_exit([&] {
  8026. svr.stop();
  8027. t.join();
  8028. ASSERT_FALSE(svr.is_running());
  8029. });
  8030. svr.wait_until_ready();
  8031. Client cli("localhost", port);
  8032. UploadFormDataItems items = {
  8033. {"na\"me", "quoted name", "", ""},
  8034. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8035. "application/octet-stream"},
  8036. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8037. {"typed", "typed content", "",
  8038. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8039. };
  8040. auto res = cli.Post("/post", items);
  8041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8042. EXPECT_EQ(StatusCode::OK_200, res->status);
  8043. }
  8044. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8045. const UploadFormDataItems items = {
  8046. {"name1", "Content 1", "", ""},
  8047. {"name2", "Content 2", "file2.txt", "text/plain"},
  8048. };
  8049. Server svr;
  8050. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8051. const ContentReader &content_reader) {
  8052. ASSERT_TRUE(req.is_multipart_form_data());
  8053. std::vector<FormData> received;
  8054. content_reader(
  8055. [&](const FormData &file) {
  8056. received.push_back(file);
  8057. return true;
  8058. },
  8059. [&](const char *data, size_t data_length) {
  8060. received.back().content.append(data, data_length);
  8061. return true;
  8062. });
  8063. ASSERT_EQ(2U, received.size());
  8064. EXPECT_EQ("name1", received[0].name);
  8065. EXPECT_EQ("Content 1", received[0].content);
  8066. EXPECT_EQ("name2", received[1].name);
  8067. EXPECT_EQ("Content 2", received[1].content);
  8068. EXPECT_EQ("file2.txt", received[1].filename);
  8069. EXPECT_EQ("text/plain", received[1].content_type);
  8070. });
  8071. auto port = svr.bind_to_any_port("localhost");
  8072. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8073. auto se = detail::scope_exit([&] {
  8074. svr.stop();
  8075. t.join();
  8076. ASSERT_FALSE(svr.is_running());
  8077. });
  8078. svr.wait_until_ready();
  8079. Client cli("localhost", port);
  8080. // Whole-body serialization with a generated boundary
  8081. {
  8082. MultipartFormDataWriter writer;
  8083. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8084. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8085. writer.content_type());
  8086. auto body = writer.serialize(items);
  8087. EXPECT_EQ(body.size(), writer.content_length(items));
  8088. auto res = cli.Post("/post", body, writer.content_type());
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ(StatusCode::OK_200, res->status);
  8091. }
  8092. // Per-part framing with a custom boundary via a content provider
  8093. {
  8094. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8095. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8096. MultipartFormDataWriter writer("custom-boundary_123");
  8097. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8098. std::string body;
  8099. for (const auto &item : items) {
  8100. body += writer.item_begin(item);
  8101. body += item.content;
  8102. body += MultipartFormDataWriter::item_end();
  8103. }
  8104. body += writer.finish();
  8105. EXPECT_EQ(body.size(), writer.content_length(items));
  8106. auto res = cli.Post(
  8107. "/post", body.size(),
  8108. [&](size_t offset, size_t length, DataSink &sink) {
  8109. sink.write(body.data() + offset, length);
  8110. return true;
  8111. },
  8112. writer.content_type());
  8113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. }
  8116. }
  8117. TEST_F(ServerTest, PostContentReceiverGzip) {
  8118. cli_.set_compress(true);
  8119. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8121. ASSERT_EQ(StatusCode::OK_200, res->status);
  8122. ASSERT_EQ("content", res->body);
  8123. }
  8124. TEST_F(ServerTest, PutContentReceiver) {
  8125. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. ASSERT_EQ(StatusCode::OK_200, res->status);
  8128. ASSERT_EQ("content", res->body);
  8129. }
  8130. TEST_F(ServerTest, PatchContentReceiver) {
  8131. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. ASSERT_EQ(StatusCode::OK_200, res->status);
  8134. ASSERT_EQ("content", res->body);
  8135. }
  8136. template <typename ClientType>
  8137. void TestWithHeadersAndContentReceiver(
  8138. ClientType &cli,
  8139. std::function<Result(ClientType &, const std::string &, const Headers &,
  8140. const std::string &, const std::string &,
  8141. ContentReceiver, DownloadProgress)>
  8142. request_func) {
  8143. Headers headers;
  8144. headers.emplace("X-Custom-Header", "test-value");
  8145. std::string received_body;
  8146. auto res = request_func(
  8147. cli, "/content_receiver", headers, "content", "application/json",
  8148. [&](const char *data, size_t data_length) {
  8149. received_body.append(data, data_length);
  8150. return true;
  8151. },
  8152. nullptr);
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. EXPECT_EQ(StatusCode::OK_200, res->status);
  8155. EXPECT_EQ("content", received_body);
  8156. }
  8157. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8158. #ifdef CPPHTTPLIB_SSL_ENABLED
  8159. using ClientT = SSLClient;
  8160. #else
  8161. using ClientT = Client;
  8162. #endif
  8163. TestWithHeadersAndContentReceiver<ClientT>(
  8164. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8165. const std::string &body, const std::string &content_type,
  8166. ContentReceiver receiver, DownloadProgress progress) {
  8167. return cli.Post(path, headers, body, content_type, receiver, progress);
  8168. });
  8169. }
  8170. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8171. #ifdef CPPHTTPLIB_SSL_ENABLED
  8172. using ClientT = SSLClient;
  8173. #else
  8174. using ClientT = Client;
  8175. #endif
  8176. TestWithHeadersAndContentReceiver<ClientT>(
  8177. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8178. const std::string &body, const std::string &content_type,
  8179. ContentReceiver receiver, DownloadProgress progress) {
  8180. return cli.Put(path, headers, body, content_type, receiver, progress);
  8181. });
  8182. }
  8183. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8184. #ifdef CPPHTTPLIB_SSL_ENABLED
  8185. using ClientT = SSLClient;
  8186. #else
  8187. using ClientT = Client;
  8188. #endif
  8189. TestWithHeadersAndContentReceiver<ClientT>(
  8190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8191. const std::string &body, const std::string &content_type,
  8192. ContentReceiver receiver, DownloadProgress progress) {
  8193. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8194. });
  8195. }
  8196. template <typename ClientType>
  8197. void TestWithHeadersAndContentReceiverWithProgress(
  8198. ClientType &cli,
  8199. std::function<Result(ClientType &, const std::string &, const Headers &,
  8200. const std::string &, const std::string &,
  8201. ContentReceiver, DownloadProgress)>
  8202. request_func) {
  8203. Headers headers;
  8204. headers.emplace("X-Test-Header", "progress-test");
  8205. std::string received_body;
  8206. auto progress_called = false;
  8207. auto res = request_func(
  8208. cli, "/content_receiver", headers, "content", "text/plain",
  8209. [&](const char *data, size_t data_length) {
  8210. received_body.append(data, data_length);
  8211. return true;
  8212. },
  8213. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8214. progress_called = true;
  8215. return true;
  8216. });
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::OK_200, res->status);
  8219. EXPECT_EQ("content", received_body);
  8220. EXPECT_TRUE(progress_called);
  8221. }
  8222. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8223. #ifdef CPPHTTPLIB_SSL_ENABLED
  8224. using ClientT = SSLClient;
  8225. #else
  8226. using ClientT = Client;
  8227. #endif
  8228. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8229. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8230. const std::string &body, const std::string &content_type,
  8231. ContentReceiver receiver, DownloadProgress progress) {
  8232. return cli.Post(path, headers, body, content_type, receiver, progress);
  8233. });
  8234. }
  8235. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8236. #ifdef CPPHTTPLIB_SSL_ENABLED
  8237. using ClientT = SSLClient;
  8238. #else
  8239. using ClientT = Client;
  8240. #endif
  8241. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8242. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8243. const std::string &body, const std::string &content_type,
  8244. ContentReceiver receiver, DownloadProgress progress) {
  8245. return cli.Put(path, headers, body, content_type, receiver, progress);
  8246. });
  8247. }
  8248. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8249. #ifdef CPPHTTPLIB_SSL_ENABLED
  8250. using ClientT = SSLClient;
  8251. #else
  8252. using ClientT = Client;
  8253. #endif
  8254. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8255. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8256. const std::string &body, const std::string &content_type,
  8257. ContentReceiver receiver, DownloadProgress progress) {
  8258. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8259. });
  8260. }
  8261. template <typename ClientType>
  8262. void TestWithHeadersAndContentReceiverError(
  8263. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8264. const Headers &, const std::string &,
  8265. const std::string &, ContentReceiver)>
  8266. request_func) {
  8267. Headers headers;
  8268. headers.emplace("X-Error-Test", "true");
  8269. std::string received_body;
  8270. auto receiver_failed = false;
  8271. auto res =
  8272. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8273. [&](const char *data, size_t data_length) {
  8274. received_body.append(data, data_length);
  8275. receiver_failed = true;
  8276. return false;
  8277. });
  8278. ASSERT_FALSE(res);
  8279. EXPECT_TRUE(receiver_failed);
  8280. }
  8281. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8282. #ifdef CPPHTTPLIB_SSL_ENABLED
  8283. using ClientT = SSLClient;
  8284. #else
  8285. using ClientT = Client;
  8286. #endif
  8287. TestWithHeadersAndContentReceiverError<ClientT>(
  8288. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8289. const std::string &body, const std::string &content_type,
  8290. ContentReceiver receiver) {
  8291. return cli.Post(path, headers, body, content_type, receiver);
  8292. });
  8293. }
  8294. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8295. #ifdef CPPHTTPLIB_SSL_ENABLED
  8296. using ClientT = SSLClient;
  8297. #else
  8298. using ClientT = Client;
  8299. #endif
  8300. TestWithHeadersAndContentReceiverError<ClientT>(
  8301. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8302. const std::string &body, const std::string &content_type,
  8303. ContentReceiver receiver) {
  8304. return cli.Put(path, headers, body, content_type, receiver);
  8305. });
  8306. }
  8307. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8308. #ifdef CPPHTTPLIB_SSL_ENABLED
  8309. using ClientT = SSLClient;
  8310. #else
  8311. using ClientT = Client;
  8312. #endif
  8313. TestWithHeadersAndContentReceiverError<ClientT>(
  8314. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8315. const std::string &body, const std::string &content_type,
  8316. ContentReceiver receiver) {
  8317. return cli.Patch(path, headers, body, content_type, receiver);
  8318. });
  8319. }
  8320. TEST_F(ServerTest, PostQueryStringAndBody) {
  8321. auto res =
  8322. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8324. ASSERT_EQ(StatusCode::OK_200, res->status);
  8325. }
  8326. TEST_F(ServerTest, HTTP2Magic) {
  8327. Request req;
  8328. req.method = "PRI";
  8329. req.path = "*";
  8330. req.body = "SM";
  8331. auto res = std::make_shared<Response>();
  8332. auto error = Error::Success;
  8333. auto ret = cli_.send(req, *res, error);
  8334. ASSERT_TRUE(ret);
  8335. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8336. }
  8337. TEST_F(ServerTest, KeepAlive) {
  8338. auto res = cli_.Get("/hi");
  8339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8340. EXPECT_EQ(StatusCode::OK_200, res->status);
  8341. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8342. EXPECT_EQ("Hello World!", res->body);
  8343. res = cli_.Get("/hi");
  8344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8345. EXPECT_EQ(StatusCode::OK_200, res->status);
  8346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8347. EXPECT_EQ("Hello World!", res->body);
  8348. res = cli_.Get("/hi");
  8349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8350. EXPECT_EQ(StatusCode::OK_200, res->status);
  8351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8352. EXPECT_EQ("Hello World!", res->body);
  8353. res = cli_.Get("/not-exist");
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8356. res = cli_.Post("/empty", "", "text/plain");
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ(StatusCode::OK_200, res->status);
  8359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8360. EXPECT_EQ("empty", res->body);
  8361. EXPECT_EQ("close", res->get_header_value("Connection"));
  8362. res = cli_.Post(
  8363. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8364. "text/plain");
  8365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8366. EXPECT_EQ(StatusCode::OK_200, res->status);
  8367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8368. EXPECT_EQ("empty", res->body);
  8369. cli_.set_keep_alive(false);
  8370. res = cli_.Get("/last-request");
  8371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8372. EXPECT_EQ(StatusCode::OK_200, res->status);
  8373. EXPECT_EQ("close", res->get_header_value("Connection"));
  8374. }
  8375. TEST_F(ServerTest, TooManyRedirect) {
  8376. cli_.set_follow_location(true);
  8377. auto res = cli_.Get("/redirect/0");
  8378. ASSERT_TRUE(!res);
  8379. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8380. }
  8381. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8382. Request req;
  8383. req.method = "FOOBAR";
  8384. req.path = "/hi";
  8385. cli_.set_keep_alive(true);
  8386. auto res = cli_.send(req);
  8387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8388. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8389. EXPECT_EQ("close", res->get_header_value("Connection"));
  8390. EXPECT_FALSE(cli_.is_socket_open());
  8391. }
  8392. TEST_F(ServerTest, CustomRouteReadsBody) {
  8393. const std::string xml =
  8394. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8395. Request req;
  8396. req.method = "PROPFIND";
  8397. req.path = "/dav/dir";
  8398. req.set_header("Depth", "1");
  8399. req.body = xml;
  8400. auto res = cli_.send(req);
  8401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8402. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8403. EXPECT_EQ(xml, res->body);
  8404. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8405. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8406. }
  8407. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8408. Request req;
  8409. req.method = "PROPFIND";
  8410. req.path = "/dav/42";
  8411. auto res = cli_.send(req);
  8412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8413. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8414. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8415. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8416. }
  8417. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8418. Request req;
  8419. req.method = "PROPFIND";
  8420. req.path = "/dav-re/123";
  8421. auto res = cli_.send(req);
  8422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8423. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8424. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8425. }
  8426. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8427. Request req;
  8428. req.method = "MKCOL";
  8429. req.path = "/dav-mkcol";
  8430. auto res = cli_.send(req);
  8431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8432. EXPECT_EQ(StatusCode::Created_201, res->status);
  8433. }
  8434. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8435. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8436. Request req;
  8437. req.method = "REPORT";
  8438. req.path = "/dav-report";
  8439. req.body = xml;
  8440. auto res = cli_.send(req);
  8441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8442. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8443. EXPECT_EQ(xml, res->body);
  8444. }
  8445. // A content reader route must fire even when the request carries no body,
  8446. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8447. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8448. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8449. Request req;
  8450. req.method = "REPORT";
  8451. req.path = "/dav-report";
  8452. auto res = cli_.send(req);
  8453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8454. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8455. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8456. }
  8457. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8458. Request req;
  8459. req.method = "PROPFIND";
  8460. req.path = "/not-dav";
  8461. auto res = cli_.send(req);
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8464. }
  8465. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8466. Request req;
  8467. req.method = "UNLOCK";
  8468. req.path = "/dav/dir";
  8469. cli_.set_keep_alive(true);
  8470. auto res = cli_.send(req);
  8471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8472. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8473. EXPECT_EQ("close", res->get_header_value("Connection"));
  8474. EXPECT_FALSE(cli_.is_socket_open());
  8475. }
  8476. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8477. // The mount point serves this path, but only for GET and HEAD.
  8478. auto get_res = cli_.Get("/dir/index.html");
  8479. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8480. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8481. Request req;
  8482. req.method = "PROPFIND";
  8483. req.path = "/dir/index.html";
  8484. auto res = cli_.send(req);
  8485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8487. }
  8488. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8489. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8490. cli_.set_keep_alive(true);
  8491. for (auto i = 0; i < 2; i++) {
  8492. Request req;
  8493. req.method = "PROPFIND";
  8494. req.path = "/dav/dir";
  8495. req.body = xml;
  8496. auto res = cli_.send(req);
  8497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8498. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8499. EXPECT_EQ(xml, res->body);
  8500. EXPECT_TRUE(cli_.is_socket_open());
  8501. }
  8502. // A built-in method must still be served on the same connection.
  8503. cli_.set_keep_alive(false);
  8504. auto res = cli_.Get("/hi");
  8505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8506. EXPECT_EQ(StatusCode::OK_200, res->status);
  8507. EXPECT_EQ("close", res->get_header_value("Connection"));
  8508. }
  8509. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8510. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8511. Request req;
  8512. req.method = "PROPFIND";
  8513. req.path = "/dav/dir";
  8514. req.set_header("Expect", "100-continue");
  8515. req.body = xml;
  8516. auto res = cli_.send(req);
  8517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8518. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8519. EXPECT_EQ(xml, res->body);
  8520. }
  8521. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8522. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8523. TEST_F(ServerTest, Gzip) {
  8524. Headers headers;
  8525. headers.emplace("Accept-Encoding", "gzip, deflate");
  8526. auto res = cli_.Get("/compress", headers);
  8527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8528. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8529. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8530. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8531. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8532. "7890123456789012345678901234567890",
  8533. res->body);
  8534. EXPECT_EQ(StatusCode::OK_200, res->status);
  8535. }
  8536. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8537. Headers headers;
  8538. headers.emplace("Accept-Encoding", "gzip, deflate");
  8539. auto res = cli_.Get("/compress-with-charset", headers);
  8540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8541. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8542. EXPECT_EQ("application/json; charset=utf-8",
  8543. res->get_header_value("Content-Type"));
  8544. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8545. "7890123456789012345678901234567890",
  8546. res->body);
  8547. EXPECT_EQ(StatusCode::OK_200, res->status);
  8548. }
  8549. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8550. Headers headers;
  8551. headers.emplace("Accept-Encoding", "");
  8552. auto res = cli_.Get("/compress", headers);
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8556. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8558. "7890123456789012345678901234567890",
  8559. res->body);
  8560. EXPECT_EQ(StatusCode::OK_200, res->status);
  8561. }
  8562. TEST_F(ServerTest, GzipWithContentReceiver) {
  8563. Headers headers;
  8564. headers.emplace("Accept-Encoding", "gzip, deflate");
  8565. std::string body;
  8566. auto res =
  8567. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8568. EXPECT_EQ(100U, data_length);
  8569. body.append(data, data_length);
  8570. return true;
  8571. });
  8572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8573. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8575. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8576. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8577. "7890123456789012345678901234567890",
  8578. body);
  8579. EXPECT_EQ(StatusCode::OK_200, res->status);
  8580. }
  8581. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8582. Headers headers;
  8583. headers.emplace("Accept-Encoding", "gzip, deflate");
  8584. cli_.set_decompress(false);
  8585. auto res = cli_.Get("/compress", headers);
  8586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8587. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8589. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8590. EXPECT_EQ(33U, res->body.size());
  8591. EXPECT_EQ(StatusCode::OK_200, res->status);
  8592. }
  8593. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8594. Headers headers;
  8595. headers.emplace("Accept-Encoding", "");
  8596. std::string body;
  8597. auto res =
  8598. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8599. EXPECT_EQ(100U, data_length);
  8600. body.append(data, data_length);
  8601. return true;
  8602. });
  8603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8604. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8605. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8606. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8607. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8608. "7890123456789012345678901234567890",
  8609. body);
  8610. EXPECT_EQ(StatusCode::OK_200, res->status);
  8611. }
  8612. TEST_F(ServerTest, NoGzip) {
  8613. Headers headers;
  8614. headers.emplace("Accept-Encoding", "gzip, deflate");
  8615. auto res = cli_.Get("/nocompress", headers);
  8616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8617. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8618. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8619. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8620. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8621. "7890123456789012345678901234567890",
  8622. res->body);
  8623. EXPECT_EQ(StatusCode::OK_200, res->status);
  8624. }
  8625. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8626. Headers headers;
  8627. headers.emplace("Accept-Encoding", "gzip, deflate");
  8628. std::string body;
  8629. auto res = cli_.Get("/nocompress", headers,
  8630. [&](const char *data, size_t data_length) {
  8631. EXPECT_EQ(100U, data_length);
  8632. body.append(data, data_length);
  8633. return true;
  8634. });
  8635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8636. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8637. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8638. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8639. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8640. "7890123456789012345678901234567890",
  8641. body);
  8642. EXPECT_EQ(StatusCode::OK_200, res->status);
  8643. }
  8644. TEST_F(ServerTest, MultipartFormDataGzip) {
  8645. UploadFormDataItems items = {
  8646. {"key1", "test", "", ""},
  8647. {"key2", "--abcdefg123", "", ""},
  8648. };
  8649. cli_.set_compress(true);
  8650. auto res = cli_.Post("/compress-multipart", items);
  8651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8652. EXPECT_EQ(StatusCode::OK_200, res->status);
  8653. }
  8654. #endif
  8655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8656. // Static file compression is opt-in, so these run their own server rather than
  8657. // flipping it on for the shared ServerTest fixture, which would silently
  8658. // rewrite what every other static file test is asserting.
  8659. class StaticFileCompressionTest : public ::testing::Test {
  8660. protected:
  8661. void TearDown() override {
  8662. if (t_.joinable()) {
  8663. svr_.stop();
  8664. t_.join();
  8665. }
  8666. }
  8667. int start(const std::function<void(Server &)> &configure = nullptr) {
  8668. // Serves the same tree as a directory of build-time compressed assets
  8669. // would be served: the mount point names the coding the files are already
  8670. // stored in. Registered before "/" so it is the one that matches.
  8671. svr_.set_mount_point("/pre-encoded", "./www",
  8672. {{"Content-Encoding", "gzip"}});
  8673. svr_.set_mount_point("/", "./www");
  8674. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8675. res.set_file_content("./www/dir/index.html", "text/html");
  8676. });
  8677. svr_.Get("/pre-encoded-file-content",
  8678. [](const Request & /*req*/, Response &res) {
  8679. res.set_header("Content-Encoding", "gzip");
  8680. res.set_file_content("./www/dir/index.html", "text/html");
  8681. });
  8682. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8683. res.set_content_provider(
  8684. 6, "text/plain",
  8685. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8686. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8687. return true;
  8688. });
  8689. });
  8690. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8691. res.set_content_provider(
  8692. 1000, "text/plain",
  8693. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8694. if (offset < 100) {
  8695. std::string data(100, 'A');
  8696. sink.write(data.data(), data.size());
  8697. return true;
  8698. }
  8699. std::this_thread::sleep_for(std::chrono::seconds(2));
  8700. std::string data(900, 'B');
  8701. sink.write(data.data(), data.size());
  8702. return true;
  8703. });
  8704. });
  8705. if (configure) { configure(svr_); }
  8706. auto port = svr_.bind_to_any_port(HOST);
  8707. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8708. svr_.wait_until_ready();
  8709. return port;
  8710. }
  8711. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8712. // Every file under ./www except 1MB.txt is smaller than the default
  8713. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8714. // it out of the way.
  8715. static void enable_without_floor(Server &svr) {
  8716. svr.set_static_file_compression(true);
  8717. svr.set_static_file_compression_min_length(0);
  8718. }
  8719. Server svr_;
  8720. std::thread t_;
  8721. };
  8722. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8723. auto port = start();
  8724. Client cli(HOST, port);
  8725. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8727. EXPECT_EQ(StatusCode::OK_200, res->status);
  8728. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8729. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8730. EXPECT_EQ(1048576U, res->body.size());
  8731. }
  8732. TEST_F(StaticFileCompressionTest, MountPoint) {
  8733. auto port = start(enable);
  8734. Client cli(HOST, port);
  8735. cli.set_decompress(false);
  8736. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8738. EXPECT_EQ(StatusCode::OK_200, res->status);
  8739. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8740. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8741. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8742. // The response stays self-delimiting: a length, not a chunked body.
  8743. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8744. EXPECT_EQ(std::to_string(res->body.size()),
  8745. res->get_header_value("Content-Length"));
  8746. EXPECT_LT(res->body.size(), 1048576U);
  8747. EXPECT_FALSE(res->body.empty());
  8748. }
  8749. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8750. auto port = start(enable);
  8751. Client cli(HOST, port);
  8752. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8754. EXPECT_EQ(StatusCode::OK_200, res->status);
  8755. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8756. EXPECT_EQ(1048576U, res->body.size());
  8757. }
  8758. TEST_F(StaticFileCompressionTest, FileContent) {
  8759. auto port = start(enable_without_floor);
  8760. Client cli(HOST, port);
  8761. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8763. EXPECT_EQ(StatusCode::OK_200, res->status);
  8764. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8765. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8766. EXPECT_EQ(104U, res->body.size());
  8767. }
  8768. // A handler that serves an already-encoded file names the coding itself. The
  8769. // file-backed path decided its coding from Accept-Encoding and the content
  8770. // type alone, so it compressed the stored bytes a second time and appended a
  8771. // second Content-Encoding field line.
  8772. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8773. auto port = start(enable_without_floor);
  8774. Client cli(HOST, port);
  8775. cli.set_decompress(false);
  8776. auto res = cli.Get("/pre-encoded-file-content",
  8777. Headers{{"Accept-Encoding", "gzip"}});
  8778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8779. EXPECT_EQ(StatusCode::OK_200, res->status);
  8780. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8782. // Vary belongs to a coding the server chose, and it chose none here.
  8783. EXPECT_FALSE(res->has_header("Vary"));
  8784. // The file travels exactly as it is stored on disk.
  8785. EXPECT_EQ(104U, res->body.size());
  8786. }
  8787. // The 1MB file clears the default floor, so this one runs the configuration a
  8788. // deployment would actually have.
  8789. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8790. auto port = start(enable);
  8791. Client cli(HOST, port);
  8792. cli.set_decompress(false);
  8793. auto res =
  8794. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8796. EXPECT_EQ(StatusCode::OK_200, res->status);
  8797. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8798. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8799. EXPECT_FALSE(res->has_header("Vary"));
  8800. EXPECT_EQ(1048576U, res->body.size());
  8801. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8802. }
  8803. TEST_F(StaticFileCompressionTest, Head) {
  8804. auto port = start(enable);
  8805. Client cli(HOST, port);
  8806. cli.set_decompress(false);
  8807. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8808. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8809. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ(StatusCode::OK_200, res->status);
  8812. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8813. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8814. // HEAD still reports the size a GET would return.
  8815. EXPECT_EQ(get->get_header_value("Content-Length"),
  8816. res->get_header_value("Content-Length"));
  8817. EXPECT_TRUE(res->body.empty());
  8818. }
  8819. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8820. auto port = start(enable);
  8821. Client cli(HOST, port);
  8822. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8823. {"Accept-Encoding", "gzip"}});
  8824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8825. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8826. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8827. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8828. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8829. EXPECT_EQ("cd", res->body);
  8830. }
  8831. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8832. auto port = start(enable);
  8833. Client cli(HOST, port);
  8834. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8836. EXPECT_EQ(StatusCode::OK_200, res->status);
  8837. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8838. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8839. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8840. }
  8841. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8842. auto port = start(enable);
  8843. Client cli(HOST, port);
  8844. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8848. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8849. EXPECT_TRUE(res->body.empty());
  8850. }
  8851. TEST_F(StaticFileCompressionTest, MinLength) {
  8852. auto port = start(enable);
  8853. Client cli(HOST, port);
  8854. // 104 bytes, well under the default floor. Compressing it would add the
  8855. // gzip header and trailer to a body that already fits in one packet.
  8856. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8858. EXPECT_EQ(StatusCode::OK_200, res->status);
  8859. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8860. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8861. }
  8862. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8863. auto port = start([](Server &svr) {
  8864. svr.set_static_file_compression(true);
  8865. svr.set_static_file_compression_min_length(1);
  8866. });
  8867. Client cli(HOST, port);
  8868. cli.set_decompress(false);
  8869. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8871. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8872. // A 9-byte file comes back larger than it went in, because gzip's header and
  8873. // trailer outweigh anything deflate can save. That is the end of the range
  8874. // the floor exists to keep out.
  8875. EXPECT_GT(res->body.size(), 9U);
  8876. }
  8877. TEST_F(StaticFileCompressionTest, MaxLength) {
  8878. auto port = start([](Server &svr) {
  8879. svr.set_static_file_compression(true);
  8880. svr.set_static_file_compression_min_length(0);
  8881. svr.set_static_file_compression_max_length(1024);
  8882. });
  8883. Client cli(HOST, port);
  8884. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8885. // defines `small` as a macro on Windows.
  8886. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8887. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8888. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8889. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8890. // Under it: compressed.
  8891. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8892. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8893. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8894. }
  8895. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8896. auto port = start(enable_without_floor);
  8897. Client cli(HOST, port);
  8898. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8899. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8900. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8901. auto identity_etag = identity->get_header_value("ETag");
  8902. ASSERT_FALSE(identity_etag.empty());
  8903. auto gzipped =
  8904. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8905. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8906. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8907. auto gzip_etag = gzipped->get_header_value("ETag");
  8908. ASSERT_FALSE(gzip_etag.empty());
  8909. // Two representations, two validators.
  8910. EXPECT_NE(identity_etag, gzip_etag);
  8911. // Each one revalidates against the request that would produce it...
  8912. auto fresh =
  8913. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8914. {"If-None-Match", gzip_etag}});
  8915. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8916. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8917. auto fresh_identity =
  8918. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8919. {"If-None-Match", identity_etag}});
  8920. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8921. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8922. // ...and not against the other representation.
  8923. auto crossed =
  8924. cli.Get("/dir/index.html",
  8925. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8926. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8927. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8928. }
  8929. // The opt-in covers responses the server reads off disk itself. A caller's own
  8930. // known-length provider keeps its Content-Length and, more importantly, keeps
  8931. // delivering incrementally: routing it through a compressor would hold every
  8932. // write back until zlib's window filled.
  8933. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8934. auto port = start(enable);
  8935. Client cli(HOST, port);
  8936. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8938. EXPECT_EQ(StatusCode::OK_200, res->status);
  8939. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8940. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8941. EXPECT_EQ("aaabbb", res->body);
  8942. }
  8943. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8944. auto port = start(enable);
  8945. Client cli(HOST, port);
  8946. cli.set_read_timeout(1, 0);
  8947. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8948. Headers{{"Accept-Encoding", "gzip"}});
  8949. ASSERT_TRUE(handle.is_valid());
  8950. // The provider writes 100 bytes and then stalls for longer than the read
  8951. // timeout. Those first bytes have to arrive anyway: run the response through
  8952. // a compressor and zlib holds them until its window fills, so the read would
  8953. // come back empty instead.
  8954. char buf[256];
  8955. auto n = handle.read(buf, sizeof(buf));
  8956. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8957. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8958. }
  8959. #endif
  8960. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8961. TEST_F(ServerTest, Brotli) {
  8962. Headers headers;
  8963. headers.emplace("Accept-Encoding", "br");
  8964. auto res = cli_.Get("/compress", headers);
  8965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8966. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8968. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8969. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8970. "7890123456789012345678901234567890",
  8971. res->body);
  8972. EXPECT_EQ(StatusCode::OK_200, res->status);
  8973. }
  8974. #endif
  8975. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8976. TEST_F(ServerTest, Zstd) {
  8977. Headers headers;
  8978. headers.emplace("Accept-Encoding", "zstd");
  8979. auto res = cli_.Get("/compress", headers);
  8980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8981. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8982. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8983. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8984. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8985. "7890123456789012345678901234567890",
  8986. res->body);
  8987. EXPECT_EQ(StatusCode::OK_200, res->status);
  8988. }
  8989. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8990. Headers headers;
  8991. headers.emplace("Accept-Encoding", "");
  8992. auto res = cli_.Get("/compress", headers);
  8993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8994. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8995. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8996. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8997. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8998. "7890123456789012345678901234567890",
  8999. res->body);
  9000. EXPECT_EQ(StatusCode::OK_200, res->status);
  9001. }
  9002. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9003. Headers headers;
  9004. headers.emplace("Accept-Encoding", "zstd");
  9005. std::string body;
  9006. auto res =
  9007. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9008. EXPECT_EQ(100U, data_length);
  9009. body.append(data, data_length);
  9010. return true;
  9011. });
  9012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9013. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9015. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9016. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9017. "7890123456789012345678901234567890",
  9018. body);
  9019. EXPECT_EQ(StatusCode::OK_200, res->status);
  9020. }
  9021. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9022. Headers headers;
  9023. headers.emplace("Accept-Encoding", "zstd");
  9024. cli_.set_decompress(false);
  9025. auto res = cli_.Get("/compress", headers);
  9026. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9027. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9028. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9029. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9031. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9033. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9034. EXPECT_EQ(StatusCode::OK_200, res->status);
  9035. ASSERT_EQ(26U, res->body.size());
  9036. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9037. 0);
  9038. }
  9039. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9040. Headers headers;
  9041. headers.emplace("Accept-Encoding", "");
  9042. std::string body;
  9043. auto res =
  9044. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9045. EXPECT_EQ(100U, data_length);
  9046. body.append(data, data_length);
  9047. return true;
  9048. });
  9049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9050. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9052. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9053. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9054. "7890123456789012345678901234567890",
  9055. body);
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. }
  9058. TEST_F(ServerTest, NoZstd) {
  9059. Headers headers;
  9060. headers.emplace("Accept-Encoding", "zstd");
  9061. auto res = cli_.Get("/nocompress", headers);
  9062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9063. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9064. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9065. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9066. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9067. "7890123456789012345678901234567890",
  9068. res->body);
  9069. EXPECT_EQ(StatusCode::OK_200, res->status);
  9070. }
  9071. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9072. Headers headers;
  9073. headers.emplace("Accept-Encoding", "zstd");
  9074. std::string body;
  9075. auto res = cli_.Get("/nocompress", headers,
  9076. [&](const char *data, size_t data_length) {
  9077. EXPECT_EQ(100U, data_length);
  9078. body.append(data, data_length);
  9079. return true;
  9080. });
  9081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9082. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9083. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9084. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9085. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9086. "7890123456789012345678901234567890",
  9087. body);
  9088. EXPECT_EQ(StatusCode::OK_200, res->status);
  9089. }
  9090. // TODO: How to enable zstd ??
  9091. TEST_F(ServerTest, MultipartFormDataZstd) {
  9092. UploadFormDataItems items = {
  9093. {"key1", "test", "", ""},
  9094. {"key2", "--abcdefg123", "", ""},
  9095. };
  9096. Headers headers;
  9097. headers.emplace("Accept-Encoding", "zstd");
  9098. cli_.set_compress(true);
  9099. auto res = cli_.Post("/compress-multipart", headers, items);
  9100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9101. EXPECT_EQ(StatusCode::OK_200, res->status);
  9102. }
  9103. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9104. Headers headers;
  9105. headers.emplace("Accept-Encoding", "zstd");
  9106. cli_.set_compress(true);
  9107. auto res = cli_.Put(
  9108. "/put", headers, 3,
  9109. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9110. sink.os << "PUT";
  9111. return true;
  9112. },
  9113. "text/plain");
  9114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9115. EXPECT_EQ(StatusCode::OK_200, res->status);
  9116. EXPECT_EQ("PUT", res->body);
  9117. }
  9118. // Pre-compression logging tests
  9119. TEST_F(ServerTest, PreCompressionLogging) {
  9120. // Test data for compression (matches the actual /compress endpoint content)
  9121. const std::string test_content =
  9122. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9123. "3456789012345678901234567890";
  9124. // Variables to capture logging data
  9125. std::string pre_compression_body;
  9126. std::string pre_compression_content_type;
  9127. std::string pre_compression_content_encoding;
  9128. std::string post_compression_body;
  9129. std::string post_compression_content_type;
  9130. std::string post_compression_content_encoding;
  9131. // Set up pre-compression logger
  9132. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9133. const Response &res) {
  9134. pre_compression_body = res.body;
  9135. pre_compression_content_type = res.get_header_value("Content-Type");
  9136. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9137. });
  9138. // Set up post-compression logger
  9139. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9140. post_compression_body = res.body;
  9141. post_compression_content_type = res.get_header_value("Content-Type");
  9142. post_compression_content_encoding =
  9143. res.get_header_value("Content-Encoding");
  9144. });
  9145. // Test with gzip compression
  9146. Headers headers;
  9147. headers.emplace("Accept-Encoding", "gzip");
  9148. auto res = cli_.Get("/compress", headers);
  9149. // Verify response was compressed
  9150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9151. EXPECT_EQ(StatusCode::OK_200, res->status);
  9152. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9153. // Verify pre-compression logger captured uncompressed content
  9154. EXPECT_EQ(test_content, pre_compression_body);
  9155. EXPECT_EQ("text/plain", pre_compression_content_type);
  9156. EXPECT_TRUE(pre_compression_content_encoding
  9157. .empty()); // No encoding header before compression
  9158. // Verify post-compression logger captured compressed content
  9159. EXPECT_NE(test_content,
  9160. post_compression_body); // Should be different after compression
  9161. EXPECT_EQ("text/plain", post_compression_content_type);
  9162. EXPECT_EQ("gzip", post_compression_content_encoding);
  9163. // Verify compressed content is smaller
  9164. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9165. }
  9166. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9167. const std::string test_content =
  9168. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9169. "3456789012345678901234567890";
  9170. std::string pre_compression_body;
  9171. std::string post_compression_body;
  9172. svr_.set_pre_compression_logger(
  9173. [&](const Request & /*req*/, const Response &res) {
  9174. pre_compression_body = res.body;
  9175. });
  9176. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9177. post_compression_body = res.body;
  9178. });
  9179. Headers headers;
  9180. headers.emplace("Accept-Encoding", "br");
  9181. auto res = cli_.Get("/compress", headers);
  9182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9183. EXPECT_EQ(StatusCode::OK_200, res->status);
  9184. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9185. // Verify pre-compression content is uncompressed
  9186. EXPECT_EQ(test_content, pre_compression_body);
  9187. // Verify post-compression content is compressed
  9188. EXPECT_NE(test_content, post_compression_body);
  9189. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9190. }
  9191. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9192. const std::string test_content =
  9193. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9194. "3456789012345678901234567890";
  9195. std::string pre_compression_body;
  9196. std::string post_compression_body;
  9197. svr_.set_pre_compression_logger(
  9198. [&](const Request & /*req*/, const Response &res) {
  9199. pre_compression_body = res.body;
  9200. });
  9201. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9202. post_compression_body = res.body;
  9203. });
  9204. // Request without compression (use /nocompress endpoint)
  9205. Headers headers;
  9206. auto res = cli_.Get("/nocompress", headers);
  9207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9208. EXPECT_EQ(StatusCode::OK_200, res->status);
  9209. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9210. // Pre-compression logger should not be called when no compression is applied
  9211. EXPECT_TRUE(
  9212. pre_compression_body.empty()); // Pre-compression logger not called
  9213. EXPECT_EQ(
  9214. test_content,
  9215. post_compression_body); // Post-compression logger captures final content
  9216. }
  9217. TEST_F(ServerTest, LoggerSeesContentLength) {
  9218. size_t logged_content_length = 0;
  9219. std::string logged_content_length_header;
  9220. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9221. logged_content_length = res.content_length_;
  9222. logged_content_length_header = res.get_header_value("Content-Length");
  9223. });
  9224. auto res = cli_.Get("/nocompress");
  9225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9226. EXPECT_EQ(StatusCode::OK_200, res->status);
  9227. EXPECT_EQ(res->body.size(), logged_content_length);
  9228. EXPECT_EQ(std::to_string(logged_content_length),
  9229. logged_content_length_header);
  9230. }
  9231. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9232. const std::string test_content =
  9233. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9234. "3456789012345678901234567890";
  9235. std::string pre_compression_body;
  9236. bool pre_logger_called = false;
  9237. // Set only pre-compression logger
  9238. svr_.set_pre_compression_logger(
  9239. [&](const Request & /*req*/, const Response &res) {
  9240. pre_compression_body = res.body;
  9241. pre_logger_called = true;
  9242. });
  9243. Headers headers;
  9244. headers.emplace("Accept-Encoding", "gzip");
  9245. auto res = cli_.Get("/compress", headers);
  9246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9247. EXPECT_EQ(StatusCode::OK_200, res->status);
  9248. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9249. // Verify pre-compression logger was called
  9250. EXPECT_TRUE(pre_logger_called);
  9251. EXPECT_EQ(test_content, pre_compression_body);
  9252. }
  9253. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9254. {
  9255. // Test with Expect: 100-continue header - success case
  9256. // Server returns 100 Continue, client sends body, server returns 200 OK
  9257. Request req;
  9258. req.method = "POST";
  9259. req.path = "/post-large";
  9260. req.set_header("Expect", "100-continue");
  9261. req.body = LARGE_DATA;
  9262. Response res;
  9263. auto error = Error::Success;
  9264. cli_.set_keep_alive(true);
  9265. auto ret = cli_.send(req, res, error);
  9266. EXPECT_TRUE(ret);
  9267. EXPECT_EQ(StatusCode::OK_200, res.status);
  9268. EXPECT_EQ(LARGE_DATA, res.body);
  9269. }
  9270. {
  9271. // Test with Expect: 100-continue header - error case
  9272. // Client should not send the body when server returns an error
  9273. Request req;
  9274. req.method = "POST";
  9275. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9276. req.set_header("Expect", "100-continue");
  9277. req.body = LARGE_DATA;
  9278. Response res;
  9279. auto error = Error::Success;
  9280. auto start = std::chrono::high_resolution_clock::now();
  9281. cli_.set_keep_alive(true);
  9282. auto ret = cli_.send(req, res, error);
  9283. auto end = std::chrono::high_resolution_clock::now();
  9284. auto elapsed =
  9285. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9286. .count();
  9287. // With Expect: 100-continue, request completes successfully but with error
  9288. EXPECT_TRUE(ret);
  9289. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9290. EXPECT_EQ("close", res.get_header_value("Connection"));
  9291. EXPECT_FALSE(cli_.is_socket_open());
  9292. EXPECT_LE(elapsed, 2000);
  9293. }
  9294. {
  9295. // Send an extra GET request to ensure error recovery without hanging
  9296. Request req;
  9297. req.method = "GET";
  9298. req.path = "/hi";
  9299. auto start = std::chrono::high_resolution_clock::now();
  9300. auto res = cli_.send(req);
  9301. auto end = std::chrono::high_resolution_clock::now();
  9302. auto elapsed =
  9303. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9304. .count();
  9305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9306. EXPECT_EQ(StatusCode::OK_200, res->status);
  9307. EXPECT_EQ("Hello World!", res->body);
  9308. EXPECT_LE(elapsed, 500);
  9309. }
  9310. }
  9311. TEST(ZstdDecompressor, ChunkedDecompression) {
  9312. std::string data;
  9313. for (size_t i = 0; i < 32 * 1024; ++i) {
  9314. data.push_back(static_cast<char>('a' + i % 26));
  9315. }
  9316. std::string compressed_data;
  9317. {
  9318. httplib::detail::zstd_compressor compressor;
  9319. bool result = compressor.compress(
  9320. data.data(), data.size(),
  9321. /*last=*/true,
  9322. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9323. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9324. compressed_data_size);
  9325. return true;
  9326. });
  9327. ASSERT_TRUE(result);
  9328. }
  9329. std::string decompressed_data;
  9330. {
  9331. httplib::detail::zstd_decompressor decompressor;
  9332. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9333. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9334. size_t chunk_size = 130;
  9335. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9336. chunk_begin += chunk_size) {
  9337. size_t current_chunk_size =
  9338. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9339. bool result = decompressor.decompress(
  9340. compressed_data.data() + chunk_begin, current_chunk_size,
  9341. [&](const char *decompressed_data_chunk,
  9342. size_t decompressed_data_chunk_size) {
  9343. decompressed_data.insert(decompressed_data.size(),
  9344. decompressed_data_chunk,
  9345. decompressed_data_chunk_size);
  9346. return true;
  9347. });
  9348. ASSERT_TRUE(result);
  9349. }
  9350. }
  9351. ASSERT_EQ(data, decompressed_data);
  9352. }
  9353. TEST(ZstdDecompressor, Decompress) {
  9354. std::string original_text = "Compressed with ZSTD";
  9355. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9356. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9357. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9358. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9359. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9360. std::string decompressed_data;
  9361. {
  9362. httplib::detail::zstd_decompressor decompressor;
  9363. bool result = decompressor.decompress(
  9364. compressed_data.data(), compressed_data.size(),
  9365. [&](const char *decompressed_data_chunk,
  9366. size_t decompressed_data_chunk_size) {
  9367. decompressed_data.insert(decompressed_data.size(),
  9368. decompressed_data_chunk,
  9369. decompressed_data_chunk_size);
  9370. return true;
  9371. });
  9372. ASSERT_TRUE(result);
  9373. }
  9374. ASSERT_EQ(original_text, decompressed_data);
  9375. }
  9376. #endif
  9377. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9378. // separate chunks so that the server sees each part in its own read(). Used to
  9379. // place a read boundary at a specific offset of a request body.
  9380. static bool send_request_in_parts(time_t read_timeout_sec,
  9381. const std::vector<std::string> &parts,
  9382. std::string *resp = nullptr,
  9383. int port = PORT) {
  9384. auto error = Error::Success;
  9385. auto client_sock = detail::create_client_socket(
  9386. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9387. /*connection_timeout_sec=*/5, 0,
  9388. /*read_timeout_sec=*/5, 0,
  9389. /*write_timeout_sec=*/5, 0, std::string(), error);
  9390. if (client_sock == INVALID_SOCKET) { return false; }
  9391. auto ret = detail::process_client_socket(
  9392. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9393. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9394. for (size_t i = 0; i < parts.size(); i++) {
  9395. const auto &part = parts[i];
  9396. if (part.size() !=
  9397. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9398. return false;
  9399. }
  9400. if (i + 1 < parts.size()) {
  9401. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9402. }
  9403. }
  9404. char buf[512];
  9405. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9406. while (line_reader.getline()) {
  9407. if (resp) { *resp += line_reader.ptr(); }
  9408. }
  9409. return true;
  9410. });
  9411. detail::close_socket(client_sock);
  9412. return ret;
  9413. }
  9414. // Sends a raw request to a server listening at HOST:PORT.
  9415. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9416. std::string *resp = nullptr, int port = PORT) {
  9417. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9418. }
  9419. #ifdef CPPHTTPLIB_SSL_ENABLED
  9420. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9422. ASSERT_TRUE(svr.is_valid());
  9423. svr.set_read_timeout(1, 0);
  9424. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9425. auto se = detail::scope_exit([&] {
  9426. svr.stop();
  9427. t.join();
  9428. ASSERT_FALSE(svr.is_running());
  9429. });
  9430. svr.wait_until_ready();
  9431. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9432. // keeps each wait well within the read timeout. The server gives up a
  9433. // second in, so the bytes sent after that fail.
  9434. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9435. parts.resize(26, std::string(1, '\0'));
  9436. EXPECT_FALSE(send_request_in_parts(5, parts));
  9437. }
  9438. #endif
  9439. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9440. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9441. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9442. const std::vector<std::string> &parts,
  9443. std::string *resp = nullptr,
  9444. int port = PORT) {
  9445. auto error = Error::Success;
  9446. auto sock = detail::create_client_socket(
  9447. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9448. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9449. /*write_timeout_sec=*/5, 0, std::string(), error);
  9450. if (sock == INVALID_SOCKET) { return false; }
  9451. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9452. auto ctx = SSL_CTX_new(TLS_client_method());
  9453. auto ssl = SSL_new(ctx);
  9454. auto ssl_se = detail::scope_exit([&] {
  9455. SSL_free(ssl);
  9456. SSL_CTX_free(ctx);
  9457. });
  9458. SSL_set_fd(ssl, static_cast<int>(sock));
  9459. if (SSL_connect(ssl) != 1) { return false; }
  9460. for (size_t i = 0; i < parts.size(); i++) {
  9461. const auto &part = parts[i];
  9462. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9463. static_cast<int>(part.size())) {
  9464. return false;
  9465. }
  9466. if (i + 1 < parts.size()) {
  9467. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9468. }
  9469. }
  9470. char buf[512];
  9471. int n;
  9472. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9473. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9474. }
  9475. return true;
  9476. }
  9477. #endif
  9478. // The request line, then a header value a byte at a time.
  9479. static std::vector<std::string> slow_request_head_parts() {
  9480. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9481. parts.resize(26, "a");
  9482. parts.emplace_back("\r\n\r\n");
  9483. return parts;
  9484. }
  9485. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9486. // within the one-second read timeout. The server gives up a second in, before
  9487. // the head is complete.
  9488. static void
  9489. expect_slow_request_head_dropped(Server &svr,
  9490. const std::function<std::string()> &send) {
  9491. std::atomic<bool> handled(false);
  9492. svr.Get("/", [&](const Request &, Response &res) {
  9493. handled = true;
  9494. res.set_content("ok", "text/plain");
  9495. });
  9496. svr.set_read_timeout(1, 0);
  9497. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9498. auto se = detail::scope_exit([&] {
  9499. svr.stop();
  9500. t.join();
  9501. ASSERT_FALSE(svr.is_running());
  9502. });
  9503. svr.wait_until_ready();
  9504. auto resp = send();
  9505. EXPECT_FALSE(handled);
  9506. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9507. }
  9508. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9509. Server svr;
  9510. expect_slow_request_head_dropped(svr, [] {
  9511. std::string resp;
  9512. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9513. return resp;
  9514. });
  9515. }
  9516. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9517. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9518. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9519. ASSERT_TRUE(svr.is_valid());
  9520. expect_slow_request_head_dropped(svr, [] {
  9521. std::string resp;
  9522. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9523. return resp;
  9524. });
  9525. }
  9526. #endif
  9527. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9528. Server svr;
  9529. std::string header_value;
  9530. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9531. header_value = req.get_header_value("foo");
  9532. res.set_content("ok", "text/plain");
  9533. });
  9534. thread t = thread([&] { svr.listen(HOST, PORT); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. t.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9542. // like characters are not treated the same - use vertical tab and escape.
  9543. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9544. "foo: \t \v bar \x1B\t \r\n"
  9545. "Connection: close\r\n"
  9546. "\r\n";
  9547. std::string res;
  9548. ASSERT_TRUE(send_request(5, req, &res));
  9549. EXPECT_EQ(header_value, "");
  9550. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9551. }
  9552. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9553. Server svr;
  9554. std::string received;
  9555. svr.Get("/order", [&](const Request &req, Response &res) {
  9556. received = entries_to_string(req.headers);
  9557. res.set_content("ok", "text/plain");
  9558. });
  9559. auto port = svr.bind_to_any_port(HOST);
  9560. thread t = thread([&] { svr.listen_after_bind(); });
  9561. auto se = detail::scope_exit([&] {
  9562. svr.stop();
  9563. t.join();
  9564. ASSERT_FALSE(svr.is_running());
  9565. });
  9566. svr.wait_until_ready();
  9567. const std::string req = "GET /order HTTP/1.1\r\n"
  9568. "Host: localhost\r\n"
  9569. "X-First: 1\r\n"
  9570. "X-Dup: a\r\n"
  9571. "X-Second: 2\r\n"
  9572. "X-Dup: b\r\n"
  9573. "Connection: close\r\n"
  9574. "\r\n";
  9575. std::string res;
  9576. ASSERT_TRUE(send_request(5, req, &res, port));
  9577. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9578. EXPECT_EQ(
  9579. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9580. received);
  9581. }
  9582. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9583. Server svr;
  9584. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9585. res.set_header("Set-Cookie", "first=1");
  9586. res.set_header("X-Between", "y");
  9587. res.set_header("Set-Cookie", "second=2");
  9588. res.set_content("ok", "text/plain");
  9589. });
  9590. auto port = svr.bind_to_any_port(HOST);
  9591. thread t = thread([&] { svr.listen_after_bind(); });
  9592. auto se = detail::scope_exit([&] {
  9593. svr.stop();
  9594. t.join();
  9595. ASSERT_FALSE(svr.is_running());
  9596. });
  9597. svr.wait_until_ready();
  9598. Client cli(HOST, port);
  9599. auto res = cli.Get("/cookies");
  9600. ASSERT_TRUE(res);
  9601. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9602. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9603. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9604. }
  9605. // A stream may send a byte at a time with a small extension on each chunk,
  9606. // however long it runs
  9607. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9608. Server svr;
  9609. svr.Post("/count", [](const Request &req, Response &res) {
  9610. res.set_content(std::to_string(req.body.size()), "text/plain");
  9611. });
  9612. auto port = svr.bind_to_any_port(HOST);
  9613. ASSERT_LT(0, port);
  9614. thread t = thread([&] { svr.listen_after_bind(); });
  9615. auto se = detail::scope_exit([&] {
  9616. svr.stop();
  9617. t.join();
  9618. ASSERT_FALSE(svr.is_running());
  9619. });
  9620. svr.wait_until_ready();
  9621. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9622. "\r\nTransfer-Encoding: chunked\r\n"
  9623. "Connection: close\r\n\r\n";
  9624. for (auto i = 0; i < 4096; i++) {
  9625. req += "1;a=b\r\nx\r\n";
  9626. }
  9627. req += "0\r\n\r\n";
  9628. std::string res;
  9629. ASSERT_TRUE(send_request(5, req, &res, port));
  9630. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9631. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9632. }
  9633. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9634. Server svr;
  9635. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9636. auto i = new int(0);
  9637. res.set_header("Trailer", "X-Safe, X-Reflected");
  9638. res.set_chunked_content_provider(
  9639. "text/plain",
  9640. [i](size_t /*offset*/, DataSink &sink) {
  9641. if (*i == 0) {
  9642. sink.os << "body";
  9643. } else {
  9644. Headers trailer;
  9645. // A valid trailer that must survive.
  9646. trailer.emplace("X-Safe", "safe");
  9647. // Attacker-controlled value carrying CR/LF (response splitting).
  9648. trailer.emplace("X-Reflected",
  9649. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9650. // Attacker-controlled name carrying CR/LF.
  9651. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9652. sink.done_with_trailer(trailer);
  9653. }
  9654. (*i)++;
  9655. return true;
  9656. },
  9657. [i](bool /*success*/) { delete i; });
  9658. });
  9659. thread t = thread([&] { svr.listen(HOST, PORT); });
  9660. auto se = detail::scope_exit([&] {
  9661. svr.stop();
  9662. t.join();
  9663. ASSERT_FALSE(svr.is_running());
  9664. });
  9665. svr.wait_until_ready();
  9666. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9667. "Host: " + HOST +
  9668. "\r\n"
  9669. "Connection: close\r\n"
  9670. "\r\n";
  9671. std::string res;
  9672. ASSERT_TRUE(send_request(5, req, &res));
  9673. // The injected fields must not appear anywhere in the raw response.
  9674. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9675. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9676. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9677. // Invalid trailers are dropped entirely, matching set_header().
  9678. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9679. // The valid trailer still passes through.
  9680. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9681. }
  9682. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9683. // A custom header writer gets only the fields the default one writes
  9684. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9685. std::string s;
  9686. for (const auto &h : hdrs) {
  9687. s += h.first + ": " + h.second + "\r\n";
  9688. }
  9689. s += "\r\n";
  9690. return strm.write(s.data(), s.size());
  9691. };
  9692. for (auto custom_writer : {false, true}) {
  9693. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9694. Server svr;
  9695. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9696. svr.set_post_routing_handler([](const Request &, Response &res) {
  9697. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9698. });
  9699. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9700. // res.headers is a public field an application can populate directly,
  9701. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9702. // A valid header that must survive.
  9703. res.headers.emplace("X-Safe", "safe");
  9704. // Attacker-controlled value carrying CR/LF (response splitting).
  9705. res.headers.emplace("X-Reflected",
  9706. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9707. // Attacker-controlled name carrying CR/LF.
  9708. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9709. res.set_content("body", "text/plain");
  9710. });
  9711. thread t = thread([&] { svr.listen(HOST, PORT); });
  9712. auto se = detail::scope_exit([&] {
  9713. svr.stop();
  9714. t.join();
  9715. ASSERT_FALSE(svr.is_running());
  9716. });
  9717. svr.wait_until_ready();
  9718. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9719. "Host: " + HOST +
  9720. "\r\n"
  9721. "Connection: close\r\n"
  9722. "\r\n";
  9723. std::string res;
  9724. ASSERT_TRUE(send_request(5, req, &res));
  9725. // The injected fields must not appear anywhere in the raw response.
  9726. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9727. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9728. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9729. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9730. // Invalid headers are dropped entirely, matching set_header().
  9731. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9732. // The valid header still passes through.
  9733. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9734. }
  9735. }
  9736. // Forward declaration: in split builds split.py strips `inline` and moves the
  9737. // definition into httplib.cc, so detail::write_request_line is not visible from
  9738. // the public httplib.h. Re-declaring it here lets the tests link against the
  9739. // symbol in both header-only and split builds.
  9740. namespace httplib {
  9741. namespace detail {
  9742. ssize_t write_request_line(Stream &strm, const std::string &method,
  9743. const std::string &path);
  9744. } // namespace detail
  9745. } // namespace httplib
  9746. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9747. // A well-formed target is written verbatim.
  9748. {
  9749. detail::BufferStream strm;
  9750. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9751. EXPECT_GT(n, 0);
  9752. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9753. }
  9754. // A target carrying CR/LF, SP or other control octets must be rejected
  9755. // before anything reaches the wire, otherwise it splits the request line and
  9756. // injects a header or a whole request.
  9757. const std::string evil_targets[] = {
  9758. "/a\r\nInjected: pwned",
  9759. "/a\rInjected",
  9760. "/a\nInjected",
  9761. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9762. "/a b",
  9763. "/a\tb",
  9764. "/a\x7f",
  9765. };
  9766. for (const auto &evil : evil_targets) {
  9767. detail::BufferStream strm;
  9768. auto n = detail::write_request_line(strm, "GET", evil);
  9769. EXPECT_LT(n, 0);
  9770. EXPECT_TRUE(strm.get_buffer().empty());
  9771. }
  9772. }
  9773. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9774. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9775. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9776. // target reaches write_request. The client must fail cleanly with
  9777. // Error::Write instead of putting a request-line-less, header-injecting
  9778. // request on the wire.
  9779. Server svr;
  9780. svr.Get("/a", [](const Request &, Response &res) {
  9781. res.set_content("ok", "text/plain");
  9782. });
  9783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9784. auto se = detail::scope_exit([&] {
  9785. svr.stop();
  9786. thread.join();
  9787. ASSERT_FALSE(svr.is_running());
  9788. });
  9789. svr.wait_until_ready();
  9790. {
  9791. Client cli(HOST, PORT);
  9792. cli.set_path_encode(false);
  9793. // The request is rejected before anything is written, so the connection
  9794. // stays silent and the subsequent response read would otherwise block for
  9795. // the full default read timeout. Shorten it -- the assertion is on the
  9796. // error, not the timeout.
  9797. cli.set_read_timeout(1, 0);
  9798. auto res = cli.Get("/a\r\nInjected: pwned");
  9799. EXPECT_FALSE(res);
  9800. EXPECT_EQ(Error::Write, res.error());
  9801. }
  9802. }
  9803. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9804. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9805. // including extension methods.
  9806. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9807. for (const auto &method : good_methods) {
  9808. detail::BufferStream strm;
  9809. auto n = detail::write_request_line(strm, method, "/");
  9810. EXPECT_GT(n, 0);
  9811. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9812. }
  9813. // A method carrying CR/LF would split the request line and smuggle a whole
  9814. // request ahead of the real one. A space or an empty method corrupts the
  9815. // request line. All must be rejected before anything reaches the wire.
  9816. const std::string evil_methods[] = {
  9817. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9818. "GET\r\nInjected: pwned",
  9819. "GET\r",
  9820. "GET\n",
  9821. "GE T",
  9822. "",
  9823. };
  9824. for (const auto &evil : evil_methods) {
  9825. detail::BufferStream strm;
  9826. auto n = detail::write_request_line(strm, evil, "/");
  9827. EXPECT_LT(n, 0);
  9828. EXPECT_TRUE(strm.get_buffer().empty());
  9829. }
  9830. }
  9831. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9832. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9833. // through Client::send must fail with Error::Write and no request, neither
  9834. // the smuggled one nor the real one, may reach the server.
  9835. Server svr;
  9836. std::atomic<int> request_count(0);
  9837. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9838. request_count++;
  9839. res.status = StatusCode::OK_200;
  9840. return Server::HandlerResponse::Handled;
  9841. });
  9842. auto port = svr.bind_to_any_port(HOST);
  9843. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9844. auto se = detail::scope_exit([&] {
  9845. svr.stop();
  9846. thread.join();
  9847. ASSERT_FALSE(svr.is_running());
  9848. });
  9849. svr.wait_until_ready();
  9850. {
  9851. Client cli(HOST, port);
  9852. const std::string evil_methods[] = {
  9853. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9854. "GE T",
  9855. "",
  9856. };
  9857. for (const auto &evil : evil_methods) {
  9858. Request req;
  9859. req.method = evil;
  9860. req.path = "/";
  9861. auto res = cli.send(req);
  9862. EXPECT_FALSE(res);
  9863. EXPECT_EQ(Error::Write, res.error());
  9864. }
  9865. auto handle =
  9866. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9867. EXPECT_FALSE(handle.is_valid());
  9868. EXPECT_EQ(Error::Write, handle.error);
  9869. // A valid request on the same client still goes through.
  9870. auto res = cli.Get("/");
  9871. ASSERT_TRUE(res);
  9872. EXPECT_EQ(StatusCode::OK_200, res->status);
  9873. }
  9874. EXPECT_EQ(1, request_count.load());
  9875. }
  9876. // Sends a raw request and verifies that there isn't a crash or exception.
  9877. static void test_raw_request(const std::string &req,
  9878. std::string *out = nullptr) {
  9879. Server svr;
  9880. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9881. res.set_content("ok", "text/plain");
  9882. });
  9883. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9884. res.set_content("ok", "text/plain");
  9885. });
  9886. svr.Get("/header_field_value_check",
  9887. [&](const Request & /*req*/, Response &res) {
  9888. res.set_content("ok", "text/plain");
  9889. });
  9890. svr.CustomRoute("PROPFIND", "/dav",
  9891. [&](const Request & /*req*/, Response &res) {
  9892. res.status = StatusCode::MultiStatus_207;
  9893. });
  9894. // Server read timeout must be longer than the client read timeout for the
  9895. // bug to reproduce, probably to force the server to process a request
  9896. // without a trailing blank line.
  9897. const time_t client_read_timeout_sec = 1;
  9898. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9899. bool listen_thread_ok = false;
  9900. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9901. auto se = detail::scope_exit([&] {
  9902. svr.stop();
  9903. t.join();
  9904. ASSERT_FALSE(svr.is_running());
  9905. EXPECT_TRUE(listen_thread_ok);
  9906. });
  9907. svr.wait_until_ready();
  9908. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9909. }
  9910. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9911. // A certain header line causes an exception if the header property is parsed
  9912. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9913. test_raw_request(
  9914. "GET /hi HTTP/1.1\r\n"
  9915. " : "
  9916. " "
  9917. " ");
  9918. }
  9919. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9920. // A certain header line causes an exception if the header property *name* is
  9921. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9922. // greedy matcher and requires backtracking when there are a lot of ":"
  9923. // characters.
  9924. // This occurs with libc++ but not libstdc++.
  9925. test_raw_request(
  9926. "GET /hi HTTP/1.1\r\n"
  9927. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9928. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9929. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9930. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9931. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9932. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9933. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9934. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9935. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9936. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9937. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9938. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9939. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9940. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9941. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9942. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9943. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9944. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9945. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9946. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9947. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9948. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9949. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9950. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9951. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9952. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9953. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9954. "&&&%%%");
  9955. }
  9956. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9957. // Make sure this doesn't crash the server.
  9958. // In a previous version of the header line regex, the "\r" rendered the line
  9959. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9960. // a new position where the leading white space ended and the field value
  9961. // began.
  9962. // The crash occurs with libc++ but not libstdc++.
  9963. test_raw_request("GET /hi HTTP/1.1\r\n"
  9964. "a:" +
  9965. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9966. "\r\n"
  9967. "\r\n");
  9968. }
  9969. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9970. const char *rejected[] = {
  9971. // RFC 9112 §3: one SP between the parts, and nothing else
  9972. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9973. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9974. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9975. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9976. // A request-target has no fragment
  9977. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9978. // An HTTP/1.1 request needs a Host
  9979. "GET /hi HTTP/1.1\r\n\r\n",
  9980. };
  9981. for (auto request : rejected) {
  9982. std::string out;
  9983. test_raw_request(request, &out);
  9984. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9985. }
  9986. std::string out;
  9987. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9988. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9989. }
  9990. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9991. // RFC 9112 §6.1
  9992. const char *requests[] = {
  9993. "PUT /put_hi HTTP/1.1\r\n"
  9994. "Host: localhost\r\n"
  9995. "Content-Length: 0\r\n"
  9996. "Transfer-Encoding: chunked\r\n"
  9997. "\r\n"
  9998. "0\r\n\r\n",
  9999. "PUT /put_hi HTTP/1.0\r\n"
  10000. "Connection: keep-alive\r\n"
  10001. "Transfer-Encoding: chunked\r\n"
  10002. "\r\n"
  10003. "0\r\n\r\n",
  10004. };
  10005. for (auto request : requests) {
  10006. std::string out;
  10007. test_raw_request(request, &out);
  10008. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10009. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10010. }
  10011. }
  10012. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10013. std::string out;
  10014. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10015. "Content-Type: text/plain\r\n"
  10016. "Transfer-Encoding: chunked\r\n"
  10017. "\r\n"
  10018. "nothex\r\n",
  10019. &out);
  10020. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10021. }
  10022. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10023. std::string out;
  10024. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10025. "Content-Type: text/plain\r\n"
  10026. "Transfer-Encoding: chunked\r\n"
  10027. "\r\n"
  10028. "3\r\n"
  10029. "xyz\r\n"
  10030. "NaN\r\n",
  10031. &out);
  10032. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10033. }
  10034. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10035. std::string out;
  10036. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10037. "Content-Type: text/plain\r\n"
  10038. "Transfer-Encoding: chunked\r\n"
  10039. "\r\n"
  10040. // Length is too large for 64 bits.
  10041. "1ffffffffffffffff\r\n"
  10042. "xyz\r\n",
  10043. &out);
  10044. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10045. }
  10046. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10047. test_raw_request("GET /hi HTTP/1.1\r\n"
  10048. "Content-Type: text/plain\r\n\r");
  10049. }
  10050. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10051. std::string out;
  10052. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10053. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10054. }
  10055. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10056. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10057. std::string out;
  10058. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10059. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10060. }
  10061. }
  10062. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10063. std::string out;
  10064. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10065. "Host: localhost\r\n"
  10066. "Connection: close\r\n\r\n",
  10067. &out);
  10068. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10069. }
  10070. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10071. Server svr;
  10072. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10073. EXPECT_TRUE(!req.remote_addr.empty());
  10074. });
  10075. thread t = thread([&] { svr.listen(HOST, PORT); });
  10076. auto se = detail::scope_exit([&] {
  10077. svr.stop();
  10078. t.join();
  10079. ASSERT_FALSE(svr.is_running());
  10080. });
  10081. svr.wait_until_ready();
  10082. // Send an invalid request line to trigger Bad Request
  10083. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10084. std::string out;
  10085. ASSERT_TRUE(send_request(5, bad_req, &out));
  10086. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10087. }
  10088. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10089. // answered right away rather than blocking on a read that waits for EOF.
  10090. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10091. std::string out;
  10092. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10093. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10094. }
  10095. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10096. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10097. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10098. for (const auto *method : methods) {
  10099. Server svr;
  10100. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10101. EXPECT_FALSE(svr.is_valid()) << method;
  10102. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10103. }
  10104. }
  10105. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10106. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10107. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10108. for (const auto *method : methods) {
  10109. Server svr;
  10110. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10111. EXPECT_FALSE(svr.is_valid()) << method;
  10112. }
  10113. }
  10114. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10115. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10116. "COPY", "MOVE", "LOCK",
  10117. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10118. Server svr;
  10119. for (const auto *method : methods) {
  10120. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10121. }
  10122. EXPECT_TRUE(svr.is_valid());
  10123. }
  10124. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10125. Server svr;
  10126. svr.CustomRoute("POST", "/x",
  10127. [](const Request &, Response &, const ContentReader &) {});
  10128. EXPECT_FALSE(svr.is_valid());
  10129. }
  10130. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10131. Server svr;
  10132. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10133. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10134. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10135. EXPECT_FALSE(svr.is_valid());
  10136. }
  10137. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10138. Server svr;
  10139. auto captured = Error::Success;
  10140. svr.set_error_logger(
  10141. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10142. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10143. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10144. }
  10145. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10146. std::string out;
  10147. std::string request(
  10148. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\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, InvalidFieldValueContains_LF) {
  10153. std::string out;
  10154. std::string request(
  10155. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\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, InvalidFieldNameContains_PreceedingSpaces) {
  10160. std::string out;
  10161. std::string request(
  10162. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10163. test_raw_request(request, &out);
  10164. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10165. }
  10166. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10167. std::string out;
  10168. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10169. "Host: localhost\r\n"
  10170. "Test: \r\n\r\n",
  10171. &out);
  10172. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10173. }
  10174. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10175. Server svr;
  10176. std::string x_custom;
  10177. std::string cookie;
  10178. std::string xff;
  10179. std::string x_unicode;
  10180. std::string x_iis;
  10181. svr.Get("/check", [&](const Request &req, Response &res) {
  10182. x_custom = req.get_header_value("X-Custom");
  10183. cookie = req.get_header_value("Cookie");
  10184. xff = req.get_header_value("X-Forwarded-For");
  10185. x_unicode = req.get_header_value("X-Unicode");
  10186. x_iis = req.get_header_value("X-IIS");
  10187. res.set_content("ok", "text/plain");
  10188. });
  10189. thread t = thread([&] { svr.listen(HOST, PORT); });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. t.join();
  10193. ASSERT_FALSE(svr.is_running());
  10194. });
  10195. svr.wait_until_ready();
  10196. const std::string req = "GET /check HTTP/1.1\r\n"
  10197. "Host: localhost\r\n"
  10198. "X-Custom: a%0D%0AInjected: b\r\n"
  10199. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10200. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10201. "X-Unicode: %E3%81%82\r\n"
  10202. "X-IIS: %u00E9\r\n"
  10203. "Connection: close\r\n"
  10204. "\r\n";
  10205. std::string res;
  10206. ASSERT_TRUE(send_request(5, req, &res));
  10207. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10208. // Every value must be returned verbatim (wire form), with no decoding.
  10209. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10210. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10211. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10212. EXPECT_EQ("%E3%81%82", x_unicode);
  10213. EXPECT_EQ("%u00E9", x_iis);
  10214. }
  10215. // Applications that previously relied on automatic percent-decoding can
  10216. // reproduce the old behavior by explicitly calling decode_path_component()
  10217. // or, for RFC 3986 conformance, decode_uri_component().
  10218. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10219. Server svr;
  10220. std::string decoded;
  10221. svr.Get("/check", [&](const Request &req, Response &res) {
  10222. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10223. res.set_content("ok", "text/plain");
  10224. });
  10225. thread t = thread([&] { svr.listen(HOST, PORT); });
  10226. auto se = detail::scope_exit([&] {
  10227. svr.stop();
  10228. t.join();
  10229. ASSERT_FALSE(svr.is_running());
  10230. });
  10231. svr.wait_until_ready();
  10232. const std::string req = "GET /check HTTP/1.1\r\n"
  10233. "Host: localhost\r\n"
  10234. "X-Custom: hello%20world\r\n"
  10235. "Connection: close\r\n"
  10236. "\r\n";
  10237. std::string res;
  10238. ASSERT_TRUE(send_request(5, req, &res));
  10239. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10240. EXPECT_EQ("hello world", decoded);
  10241. }
  10242. // Regression test for #2033. Browsers send Referer values that include
  10243. // percent-encoded characters such as %0A inside the URL. Decoding the
  10244. // header value would either trip the post-decode CR/LF/NUL guard (the
  10245. // original bug, returning 400) or, after that guard was relaxed, silently
  10246. // store a literal LF — both unacceptable. The wire form must round-trip.
  10247. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10248. Server svr;
  10249. std::string referer;
  10250. svr.Get("/check", [&](const Request &req, Response &res) {
  10251. referer = req.get_header_value("Referer");
  10252. res.set_content("ok", "text/plain");
  10253. });
  10254. thread t = thread([&] { svr.listen(HOST, PORT); });
  10255. auto se = detail::scope_exit([&] {
  10256. svr.stop();
  10257. t.join();
  10258. ASSERT_FALSE(svr.is_running());
  10259. });
  10260. svr.wait_until_ready();
  10261. const std::string req = "GET /check HTTP/1.1\r\n"
  10262. "Host: localhost\r\n"
  10263. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10264. "Connection: close\r\n"
  10265. "\r\n";
  10266. std::string res;
  10267. ASSERT_TRUE(send_request(5, req, &res));
  10268. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10269. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10270. }
  10271. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10272. Server svr;
  10273. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10274. res.set_header("Cache-Control", "no-cache");
  10275. res.set_chunked_content_provider(
  10276. "text/event-stream", [](size_t offset, DataSink &sink) {
  10277. std::string s = "data:";
  10278. s += std::to_string(offset);
  10279. s += "\n\n";
  10280. auto ret = sink.write(s.data(), s.size());
  10281. EXPECT_TRUE(ret);
  10282. std::this_thread::sleep_for(std::chrono::seconds(1));
  10283. return true;
  10284. });
  10285. });
  10286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10287. svr.wait_until_ready();
  10288. Client client(HOST, PORT);
  10289. const Headers headers = {{"Accept", "text/event-stream"}};
  10290. auto get_thread = std::thread([&client, &headers]() {
  10291. auto res = client.Get(
  10292. "/events", headers,
  10293. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10294. });
  10295. auto se = detail::scope_exit([&] {
  10296. svr.stop();
  10297. get_thread.join();
  10298. listen_thread.join();
  10299. ASSERT_FALSE(svr.is_running());
  10300. });
  10301. // Give GET time to get a few messages.
  10302. std::this_thread::sleep_for(std::chrono::seconds(2));
  10303. }
  10304. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10305. httplib::Server svr;
  10306. svr.Post("/hi",
  10307. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10308. res.status = StatusCode::OK_200;
  10309. });
  10310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10311. svr.wait_until_ready();
  10312. Client cli(HOST, PORT);
  10313. auto res = cli.Post("/hi", "data", "text/plain");
  10314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10315. EXPECT_EQ(StatusCode::OK_200, res->status);
  10316. svr.stop();
  10317. thread.join();
  10318. ASSERT_FALSE(svr.is_running());
  10319. res = cli.Post("/hi", "data", "text/plain");
  10320. ASSERT_FALSE(res);
  10321. }
  10322. TEST(ServerStopTest, ListenFailure) {
  10323. Server svr;
  10324. auto t = thread([&]() {
  10325. auto ret = svr.listen("????", PORT);
  10326. EXPECT_FALSE(ret);
  10327. });
  10328. svr.wait_until_ready();
  10329. svr.stop();
  10330. t.join();
  10331. }
  10332. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10333. TEST(ServerStopTest, Decommision) {
  10334. Server svr;
  10335. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10336. for (int i = 0; i < 4; i++) {
  10337. auto is_even = !(i % 2);
  10338. std::thread t{[&] {
  10339. try {
  10340. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10341. if (is_even) {
  10342. throw std::runtime_error("Some thing that happens to go wrong.");
  10343. }
  10344. svr.listen(HOST, PORT);
  10345. } catch (...) { svr.decommission(); }
  10346. }};
  10347. svr.wait_until_ready();
  10348. // Server is up
  10349. {
  10350. Client cli(HOST, PORT);
  10351. auto res = cli.Get("/hi");
  10352. if (is_even) {
  10353. EXPECT_FALSE(res);
  10354. } else {
  10355. EXPECT_TRUE(res);
  10356. EXPECT_EQ("hi...", res->body);
  10357. }
  10358. }
  10359. svr.stop();
  10360. t.join();
  10361. // Server is down...
  10362. {
  10363. Client cli(HOST, PORT);
  10364. auto res = cli.Get("/hi");
  10365. EXPECT_FALSE(res);
  10366. }
  10367. }
  10368. }
  10369. #endif
  10370. // Helper function for string body upload progress tests
  10371. template <typename SetupHandler, typename ClientCall>
  10372. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10373. ClientCall &&client_call,
  10374. const string &body) {
  10375. Server svr;
  10376. setup_handler(svr);
  10377. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10378. auto se = detail::scope_exit([&] {
  10379. svr.stop();
  10380. t.join();
  10381. });
  10382. svr.wait_until_ready();
  10383. Client cli(HOST, PORT);
  10384. vector<uint64_t> progress_values;
  10385. bool progress_called = false;
  10386. auto res =
  10387. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10388. progress_values.push_back(current);
  10389. progress_called = true;
  10390. return true;
  10391. });
  10392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10393. EXPECT_EQ(200, res->status);
  10394. EXPECT_TRUE(progress_called);
  10395. }
  10396. TEST(UploadProgressTest, PostStringBodyBasic) {
  10397. TestStringBodyUploadProgress(
  10398. [](Server &svr) {
  10399. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10400. res.set_content("received", "text/plain");
  10401. });
  10402. },
  10403. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10404. return cli.Post("/test", body, "text/plain", progress_callback);
  10405. },
  10406. "test data for upload progress");
  10407. }
  10408. TEST(UploadProgressTest, PutStringBodyBasic) {
  10409. TestStringBodyUploadProgress(
  10410. [](Server &svr) {
  10411. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10412. res.set_content("put received", "text/plain");
  10413. });
  10414. },
  10415. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10416. return cli.Put("/test", body, "text/plain", progress_callback);
  10417. },
  10418. "put test data for upload progress");
  10419. }
  10420. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10421. TestStringBodyUploadProgress(
  10422. [](Server &svr) {
  10423. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10424. res.set_content("patch received", "text/plain");
  10425. });
  10426. },
  10427. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10428. return cli.Patch("/test", body, "text/plain", progress_callback);
  10429. },
  10430. "patch test data for upload progress");
  10431. }
  10432. // Helper function for content provider upload progress tests
  10433. template <typename SetupHandler, typename ClientCall>
  10434. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10435. ClientCall &&client_call) {
  10436. Server svr;
  10437. setup_handler(svr);
  10438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10439. auto se = detail::scope_exit([&] {
  10440. svr.stop();
  10441. t.join();
  10442. });
  10443. svr.wait_until_ready();
  10444. Client cli(HOST, PORT);
  10445. vector<uint64_t> progress_values;
  10446. auto res =
  10447. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10448. progress_values.push_back(current);
  10449. return true;
  10450. });
  10451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10452. EXPECT_EQ(200, res->status);
  10453. EXPECT_FALSE(progress_values.empty());
  10454. }
  10455. TEST(UploadProgressTest, PostContentProviderProgress) {
  10456. TestContentProviderUploadProgress(
  10457. [](Server &svr) {
  10458. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10459. res.set_content("provider received", "text/plain");
  10460. });
  10461. },
  10462. [](Client &cli, UploadProgress progress_callback) {
  10463. return cli.Post(
  10464. "/test", 9,
  10465. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10466. sink.os << "test data";
  10467. return true;
  10468. },
  10469. "text/plain", progress_callback);
  10470. });
  10471. }
  10472. // Helper function for multipart upload progress tests
  10473. template <typename SetupHandler, typename ClientCall>
  10474. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10475. ClientCall &&client_call,
  10476. const string &endpoint) {
  10477. Server svr;
  10478. setup_handler(svr);
  10479. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10480. auto se = detail::scope_exit([&] {
  10481. svr.stop();
  10482. t.join();
  10483. });
  10484. svr.wait_until_ready();
  10485. Client cli(HOST, PORT);
  10486. vector<uint64_t> progress_values;
  10487. UploadFormDataItems items = {
  10488. {"field1", "value1", "", ""},
  10489. {"field2", "longer value for progress tracking test", "", ""},
  10490. {"file1", "file content data for upload progress", "test.txt",
  10491. "text/plain"}};
  10492. auto res = client_call(cli, endpoint, items,
  10493. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10494. progress_values.push_back(current);
  10495. return true;
  10496. });
  10497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10498. EXPECT_EQ(200, res->status);
  10499. EXPECT_FALSE(progress_values.empty());
  10500. }
  10501. TEST(UploadProgressTest, PostMultipartProgress) {
  10502. TestMultipartUploadProgress(
  10503. [](Server &svr) {
  10504. svr.Post("/multipart", [](const Request &req, Response &res) {
  10505. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10506. res.set_content("multipart received", "text/plain");
  10507. });
  10508. },
  10509. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10510. UploadProgress progress_callback) {
  10511. return cli.Post(endpoint, items, progress_callback);
  10512. },
  10513. "/multipart");
  10514. }
  10515. // Helper function for basic download progress tests
  10516. template <typename SetupHandler, typename ClientCall>
  10517. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10518. ClientCall &&client_call, const string &endpoint,
  10519. size_t expected_content_size) {
  10520. Server svr;
  10521. setup_handler(svr);
  10522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10523. auto se = detail::scope_exit([&] {
  10524. svr.stop();
  10525. t.join();
  10526. });
  10527. svr.wait_until_ready();
  10528. Client cli(HOST, PORT);
  10529. vector<uint64_t> progress_values;
  10530. auto res = client_call(cli, endpoint,
  10531. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10532. progress_values.push_back(current);
  10533. return true;
  10534. });
  10535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10536. EXPECT_EQ(200, res->status);
  10537. EXPECT_FALSE(progress_values.empty());
  10538. EXPECT_EQ(expected_content_size, res->body.size());
  10539. }
  10540. TEST(DownloadProgressTest, GetBasic) {
  10541. TestBasicDownloadProgress(
  10542. [](Server &svr) {
  10543. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10544. string content(1000, 'D');
  10545. res.set_content(content, "text/plain");
  10546. });
  10547. },
  10548. [](Client &cli, const string &endpoint,
  10549. DownloadProgress progress_callback) {
  10550. return cli.Get(endpoint, progress_callback);
  10551. },
  10552. "/download", 1000u);
  10553. }
  10554. // Helper function for content receiver download progress tests
  10555. template <typename SetupHandler, typename ClientCall>
  10556. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10557. ClientCall &&client_call,
  10558. const string &endpoint,
  10559. size_t expected_content_size) {
  10560. Server svr;
  10561. setup_handler(svr);
  10562. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10563. auto se = detail::scope_exit([&] {
  10564. svr.stop();
  10565. t.join();
  10566. });
  10567. svr.wait_until_ready();
  10568. Client cli(HOST, PORT);
  10569. vector<uint64_t> progress_values;
  10570. string received_body;
  10571. auto res = client_call(
  10572. cli, endpoint,
  10573. [&](const char *data, size_t data_length) -> bool {
  10574. received_body.append(data, data_length);
  10575. return true;
  10576. },
  10577. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10578. progress_values.push_back(current);
  10579. return true;
  10580. });
  10581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10582. EXPECT_EQ(200, res->status);
  10583. EXPECT_FALSE(progress_values.empty());
  10584. EXPECT_EQ(expected_content_size, received_body.size());
  10585. EXPECT_TRUE(res->body.empty());
  10586. }
  10587. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10588. TestContentReceiverDownloadProgress(
  10589. [](Server &svr) {
  10590. svr.Get("/download-receiver",
  10591. [](const Request & /*req*/, Response &res) {
  10592. string content(2000, 'R');
  10593. res.set_content(content, "text/plain");
  10594. });
  10595. },
  10596. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10597. DownloadProgress progress_callback) {
  10598. return cli.Get(endpoint, content_receiver, progress_callback);
  10599. },
  10600. "/download-receiver", 2000u);
  10601. }
  10602. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10603. // A provider reaching a pass with nothing to hand over - an empty buffer
  10604. // popped off a queue, say - must not be taken to mean the body is finished.
  10605. // It used to end the loop with the terminating chunk unwritten while the
  10606. // server still considered the response complete, so the peer waited for an
  10607. // end that never arrived.
  10608. Server svr;
  10609. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10610. auto step = std::make_shared<int>(0);
  10611. res.set_chunked_content_provider("text/plain",
  10612. [step](size_t /*offset*/, DataSink &sink) {
  10613. switch ((*step)++) {
  10614. case 0: sink.write("", 0); break;
  10615. case 1: sink.write("hello", 5); break;
  10616. default: sink.done(); break;
  10617. }
  10618. return true;
  10619. });
  10620. });
  10621. auto port = svr.bind_to_any_port(HOST);
  10622. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10623. auto listen_se = detail::scope_exit([&] {
  10624. svr.stop();
  10625. listen_thread.join();
  10626. ASSERT_FALSE(svr.is_running());
  10627. });
  10628. svr.wait_until_ready();
  10629. Client cli(HOST, port);
  10630. // Without the fix the body is never terminated, so bound the wait rather
  10631. // than letting the test hang on the default read timeout.
  10632. cli.set_read_timeout(5, 0);
  10633. auto res = cli.Get("/stream");
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::OK_200, res->status);
  10636. EXPECT_EQ("hello", res->body);
  10637. }
  10638. TEST(StreamingTest, NoContentLengthStreaming) {
  10639. Server svr;
  10640. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10641. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10642. if (offset < 6) {
  10643. sink.os << (offset < 3 ? "a" : "b");
  10644. } else {
  10645. sink.done();
  10646. }
  10647. return true;
  10648. });
  10649. });
  10650. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10651. auto listen_se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. listen_thread.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. Client client(HOST, PORT);
  10658. auto get_thread = std::thread([&client]() {
  10659. std::string s;
  10660. auto res =
  10661. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10662. s += std::string(data, len);
  10663. return true;
  10664. });
  10665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10666. EXPECT_EQ(StatusCode::OK_200, res->status);
  10667. EXPECT_EQ("aaabbb", s);
  10668. });
  10669. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10670. // Give GET time to get a few messages.
  10671. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10672. }
  10673. TEST(MountTest, Unmount) {
  10674. Server svr;
  10675. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. listen_thread.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. Client cli("localhost", PORT);
  10683. svr.set_mount_point("/mount2", "./www2");
  10684. auto res = cli.Get("/");
  10685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10686. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10687. res = cli.Get("/mount2/dir/test.html");
  10688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10689. EXPECT_EQ(StatusCode::OK_200, res->status);
  10690. svr.set_mount_point("/", "./www");
  10691. res = cli.Get("/dir/");
  10692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10693. EXPECT_EQ(StatusCode::OK_200, res->status);
  10694. svr.remove_mount_point("/");
  10695. res = cli.Get("/dir/");
  10696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10697. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10698. svr.remove_mount_point("/mount2");
  10699. res = cli.Get("/mount2/dir/test.html");
  10700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10702. }
  10703. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10704. Server svr;
  10705. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10706. svr.Get("/api/hello", [](const Request &, Response &res) {
  10707. res.set_content("api", "text/plain");
  10708. });
  10709. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10710. auto se = detail::scope_exit([&] {
  10711. svr.stop();
  10712. listen_thread.join();
  10713. ASSERT_FALSE(svr.is_running());
  10714. });
  10715. svr.wait_until_ready();
  10716. Client cli(HOST, PORT);
  10717. auto res = cli.Get("/dir/test.html");
  10718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10719. EXPECT_EQ(StatusCode::OK_200, res->status);
  10720. res = cli.Get("/api/hello");
  10721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10722. EXPECT_EQ(StatusCode::OK_200, res->status);
  10723. EXPECT_EQ("api", res->body);
  10724. }
  10725. TEST(MountTest, PathSegmentBoundary) {
  10726. Server svr;
  10727. svr.set_mount_point("/mount2", "./www2");
  10728. svr.set_mount_point("/", "./www");
  10729. auto port = svr.bind_to_any_port(HOST);
  10730. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10731. auto se = detail::scope_exit([&] {
  10732. svr.stop();
  10733. listen_thread.join();
  10734. ASSERT_FALSE(svr.is_running());
  10735. });
  10736. svr.wait_until_ready();
  10737. Client cli(HOST, port);
  10738. auto res = cli.Get("/mount2/dir/test.html");
  10739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10740. EXPECT_EQ(StatusCode::OK_200, res->status);
  10741. // "/mount2" must not match part-way through a path segment.
  10742. res = cli.Get("/mount2dir/test.html");
  10743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10744. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10745. // A mount point ending in '/' keeps matching every path below it.
  10746. res = cli.Get("/dir/test.html");
  10747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10748. EXPECT_EQ(StatusCode::OK_200, res->status);
  10749. }
  10750. TEST(MountTest, Redicect) {
  10751. Server svr;
  10752. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10753. auto se = detail::scope_exit([&] {
  10754. svr.stop();
  10755. listen_thread.join();
  10756. ASSERT_FALSE(svr.is_running());
  10757. });
  10758. svr.set_mount_point("/", "./www");
  10759. svr.wait_until_ready();
  10760. Client cli("localhost", PORT);
  10761. auto res = cli.Get("/dir/");
  10762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10763. EXPECT_EQ(StatusCode::OK_200, res->status);
  10764. res = cli.Get("/dir");
  10765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10766. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10767. res = cli.Get("/file");
  10768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10769. EXPECT_EQ(StatusCode::OK_200, res->status);
  10770. res = cli.Get("/file/");
  10771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10772. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10773. cli.set_follow_location(true);
  10774. res = cli.Get("/dir");
  10775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10776. EXPECT_EQ(StatusCode::OK_200, res->status);
  10777. }
  10778. TEST(MountTest, MultibytesPathName) {
  10779. Server svr;
  10780. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10781. auto se = detail::scope_exit([&] {
  10782. svr.stop();
  10783. listen_thread.join();
  10784. ASSERT_FALSE(svr.is_running());
  10785. });
  10786. svr.set_mount_point("/", "./www");
  10787. svr.wait_until_ready();
  10788. Client cli("localhost", PORT);
  10789. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10791. EXPECT_EQ(StatusCode::OK_200, res->status);
  10792. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10793. }
  10794. // A mount point serves no path with an empty segment or one ending in '.' or
  10795. // a space, so a guard in the pre-routing handler sees the path of every file
  10796. // that is served
  10797. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10798. Server svr;
  10799. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10800. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10801. if (req.path == "/dir/test.html") {
  10802. res.status = StatusCode::Unauthorized_401;
  10803. return Server::HandlerResponse::Handled;
  10804. }
  10805. return Server::HandlerResponse::Unhandled;
  10806. });
  10807. auto port = svr.bind_to_any_port(HOST);
  10808. ASSERT_LT(0, port);
  10809. thread t = thread([&] { svr.listen_after_bind(); });
  10810. auto se = detail::scope_exit([&] {
  10811. svr.stop();
  10812. t.join();
  10813. ASSERT_FALSE(svr.is_running());
  10814. });
  10815. svr.wait_until_ready();
  10816. Client cli(HOST, port);
  10817. for (auto path :
  10818. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10819. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10820. "/dir/test.html.", "/dir/test.html%20"}) {
  10821. SCOPED_TRACE(path);
  10822. auto res = cli.Get(path);
  10823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10825. }
  10826. }
  10827. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10828. Server svr;
  10829. svr.set_mount_point("/", "./www");
  10830. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10831. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10832. auto port = svr.bind_to_any_port(HOST);
  10833. ASSERT_GT(port, 0);
  10834. thread t = thread([&] { svr.listen_after_bind(); });
  10835. auto se = detail::scope_exit([&] {
  10836. svr.stop();
  10837. t.join();
  10838. ASSERT_FALSE(svr.is_running());
  10839. });
  10840. svr.wait_until_ready();
  10841. Client cli(HOST, port);
  10842. auto res = cli.Get("/dir/test.abcde");
  10843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10844. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10845. res = cli.Get("/dir/test.html");
  10846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10847. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10848. }
  10849. #ifdef _WIN32
  10850. // Issue #2435: mmap::open() must succeed even when another handle holds
  10851. // the file open for writing (e.g. an active log file).
  10852. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10853. const char *path = "mmap_concurrent_writer_test.txt";
  10854. const char *content = "hello";
  10855. {
  10856. std::ofstream f(path, std::ios::binary);
  10857. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10858. }
  10859. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10860. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10861. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10862. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10863. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10864. detail::mmap m(path);
  10865. ASSERT_TRUE(m.is_open());
  10866. EXPECT_EQ(strlen(content), m.size());
  10867. char buf[8];
  10868. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10869. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10870. }
  10871. #endif
  10872. #ifndef _WIN32
  10873. // A directory or a device has no size to serve.
  10874. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10875. const char *path = "./mmap_not_regular_test_dir";
  10876. ASSERT_EQ(0, ::mkdir(path, 0755));
  10877. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10878. for (auto p : {path, "/dev/null"}) {
  10879. detail::mmap m(p);
  10880. EXPECT_FALSE(m.is_open()) << p;
  10881. EXPECT_EQ(0U, m.size()) << p;
  10882. }
  10883. Server svr;
  10884. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10885. res.set_file_content("/dev/null");
  10886. });
  10887. auto port = svr.bind_to_any_port(HOST);
  10888. thread t = thread([&] { svr.listen_after_bind(); });
  10889. auto se = detail::scope_exit([&] {
  10890. svr.stop();
  10891. t.join();
  10892. });
  10893. svr.wait_until_ready();
  10894. auto res = Client(HOST, port).Get("/null");
  10895. ASSERT_TRUE(res);
  10896. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10897. }
  10898. #endif
  10899. #ifdef __linux__
  10900. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10901. TEST(MmapTest, FileIsNotMapped) {
  10902. const char *path = "mmap_not_mapped_test.txt";
  10903. {
  10904. std::ofstream f(path, std::ios::binary);
  10905. f << "hello";
  10906. }
  10907. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10908. detail::mmap m(path);
  10909. ASSERT_TRUE(m.is_open());
  10910. std::ifstream maps("/proc/self/maps");
  10911. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10912. std::istreambuf_iterator<char>());
  10913. EXPECT_EQ(std::string::npos, mappings.find(path));
  10914. }
  10915. #endif
  10916. TEST(KeepAliveTest, ReadTimeout) {
  10917. Server svr;
  10918. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10919. std::this_thread::sleep_for(std::chrono::seconds(2));
  10920. res.set_content("a", "text/plain");
  10921. });
  10922. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10923. res.set_content("b", "text/plain");
  10924. });
  10925. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10926. auto se = detail::scope_exit([&] {
  10927. svr.stop();
  10928. listen_thread.join();
  10929. ASSERT_FALSE(svr.is_running());
  10930. });
  10931. svr.wait_until_ready();
  10932. Client cli("localhost", PORT);
  10933. cli.set_keep_alive(true);
  10934. cli.set_read_timeout(std::chrono::seconds(1));
  10935. auto resa = cli.Get("/a");
  10936. ASSERT_FALSE(resa);
  10937. EXPECT_EQ(Error::Read, resa.error());
  10938. auto resb = cli.Get("/b");
  10939. ASSERT_TRUE(resb);
  10940. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10941. EXPECT_EQ("b", resb->body);
  10942. }
  10943. TEST(KeepAliveTest, MaxCount) {
  10944. size_t keep_alive_max_count = 3;
  10945. Server svr;
  10946. svr.set_keep_alive_max_count(keep_alive_max_count);
  10947. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10948. res.set_content("Hello World!", "text/plain");
  10949. });
  10950. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10951. auto se = detail::scope_exit([&] {
  10952. svr.stop();
  10953. listen_thread.join();
  10954. ASSERT_FALSE(svr.is_running());
  10955. });
  10956. svr.wait_until_ready();
  10957. Client cli(HOST, PORT);
  10958. cli.set_keep_alive(true);
  10959. for (size_t i = 0; i < 5; i++) {
  10960. auto result = cli.Get("/hi");
  10961. ASSERT_TRUE(result);
  10962. EXPECT_EQ(StatusCode::OK_200, result->status);
  10963. if (i == keep_alive_max_count - 1) {
  10964. EXPECT_EQ("close", result->get_header_value("Connection"));
  10965. } else {
  10966. EXPECT_FALSE(result->has_header("Connection"));
  10967. }
  10968. }
  10969. }
  10970. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10971. // can pull the next one into the server's buffer. The server must serve it
  10972. // without waiting for the socket to become readable again. The keep-alive
  10973. // timeout outlasts the client's read timeout, so a request left waiting for it
  10974. // shows up as a missing response.
  10975. static void serve_pipelining_routes(Server &svr,
  10976. const std::function<void(int)> &client) {
  10977. svr.set_keep_alive_timeout(5);
  10978. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10979. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10980. });
  10981. svr.Post("/echo", [](const Request &req, Response &res) {
  10982. res.set_content("echo " + req.body, "text/plain");
  10983. });
  10984. auto port = svr.bind_to_any_port(HOST);
  10985. thread t = thread([&] { svr.listen_after_bind(); });
  10986. auto se = detail::scope_exit([&] {
  10987. svr.stop();
  10988. t.join();
  10989. });
  10990. svr.wait_until_ready();
  10991. client(port);
  10992. }
  10993. static std::string
  10994. send_pipelined_requests(const std::vector<std::string> &parts) {
  10995. Server svr;
  10996. std::string res;
  10997. serve_pipelining_routes(svr, [&](int port) {
  10998. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10999. });
  11000. return res;
  11001. }
  11002. static void expect_in_order(const std::string &res,
  11003. const std::vector<std::string> &bodies) {
  11004. size_t pos = 0;
  11005. for (const auto &body : bodies) {
  11006. pos = res.find(body, pos);
  11007. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11008. pos += body.size();
  11009. }
  11010. }
  11011. TEST(KeepAliveTest, PipelinedRequests) {
  11012. auto res = send_pipelined_requests(
  11013. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11014. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11015. "Content-Length: 4\r\n\r\nbody"
  11016. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11017. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11018. }
  11019. // The second request starts in the server's buffer and ends on the socket.
  11020. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11021. auto res =
  11022. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11023. "GET /hi/2 HTTP/1.1\r\nHo",
  11024. "st: localhost\r\nConnection: close\r\n\r\n"});
  11025. expect_in_order(res, {"hi 1", "hi 2"});
  11026. }
  11027. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11028. // CRLF after a body does not turn into a 400 for the next request.
  11029. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11030. auto res = send_pipelined_requests(
  11031. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11032. "Content-Length: 4\r\n\r\nbody\r\n"
  11033. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11034. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11035. expect_in_order(res, {"echo body", "hi 2"});
  11036. }
  11037. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11038. // must not be served as the next request.
  11039. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11040. auto res = send_pipelined_requests(
  11041. {"INVALID REQUEST LINE\r\n\r\n"
  11042. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11043. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11044. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11045. }
  11046. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11047. // Over TLS, the next request is held by the TLS library as already decrypted
  11048. // data rather than on the socket.
  11049. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11051. std::string res;
  11052. serve_pipelining_routes(svr, [&](int port) {
  11053. // One part, so all three requests arrive in one TLS record
  11054. EXPECT_TRUE(send_ssl_request_in_parts(
  11055. 2,
  11056. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11057. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11058. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11059. &res, port));
  11060. });
  11061. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11062. }
  11063. #endif
  11064. TEST(KeepAliveTest, Issue1041) {
  11065. Server svr;
  11066. svr.set_keep_alive_timeout(3);
  11067. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11068. res.set_content("Hello World!", "text/plain");
  11069. });
  11070. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11071. auto se = detail::scope_exit([&] {
  11072. svr.stop();
  11073. listen_thread.join();
  11074. ASSERT_FALSE(svr.is_running());
  11075. });
  11076. svr.wait_until_ready();
  11077. Client cli(HOST, PORT);
  11078. cli.set_keep_alive(true);
  11079. auto result = cli.Get("/hi");
  11080. ASSERT_TRUE(result);
  11081. EXPECT_EQ(StatusCode::OK_200, result->status);
  11082. std::this_thread::sleep_for(std::chrono::seconds(5));
  11083. result = cli.Get("/hi");
  11084. ASSERT_TRUE(result);
  11085. EXPECT_EQ(StatusCode::OK_200, result->status);
  11086. }
  11087. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11088. Server svr;
  11089. svr.set_keep_alive_max_count(0);
  11090. std::set<int> remote_ports;
  11091. svr.Get("/hi", [&](const Request &req, Response &res) {
  11092. remote_ports.insert(req.remote_port);
  11093. res.set_content("hi", "text/plain");
  11094. });
  11095. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11096. auto se = detail::scope_exit([&] {
  11097. svr.stop();
  11098. listen_thread.join();
  11099. ASSERT_FALSE(svr.is_running());
  11100. });
  11101. svr.wait_until_ready();
  11102. Client cli(HOST, PORT);
  11103. cli.set_keep_alive(true);
  11104. for (int i = 0; i < 3; i++) {
  11105. auto res = cli.Get("/hi");
  11106. ASSERT_TRUE(res);
  11107. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11108. }
  11109. // All three over one connection
  11110. EXPECT_EQ(1u, remote_ports.size());
  11111. }
  11112. TEST(KeepAliveTest, Issue1959) {
  11113. Server svr;
  11114. svr.set_keep_alive_timeout(5);
  11115. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11116. res.set_content("a", "text/plain");
  11117. });
  11118. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11119. auto se = detail::scope_exit([&] {
  11120. if (!svr.is_running()) return;
  11121. svr.stop();
  11122. listen_thread.join();
  11123. ASSERT_FALSE(svr.is_running());
  11124. });
  11125. svr.wait_until_ready();
  11126. Client cli("localhost", PORT);
  11127. cli.set_keep_alive(true);
  11128. using namespace std::chrono;
  11129. auto start = steady_clock::now();
  11130. cli.Get("/a");
  11131. svr.stop();
  11132. listen_thread.join();
  11133. auto end = steady_clock::now();
  11134. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11135. EXPECT_LT(elapsed, 5000);
  11136. }
  11137. #ifdef CPPHTTPLIB_SSL_ENABLED
  11138. TEST(KeepAliveTest, SSLClientReconnection) {
  11139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11140. ASSERT_TRUE(svr.is_valid());
  11141. svr.set_keep_alive_timeout(1);
  11142. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11143. res.set_content("Hello World!", "text/plain");
  11144. });
  11145. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11146. auto se = detail::scope_exit([&] {
  11147. svr.stop();
  11148. listen_thread.join();
  11149. ASSERT_FALSE(svr.is_running());
  11150. });
  11151. svr.wait_until_ready();
  11152. SSLClient cli(HOST, PORT);
  11153. cli.enable_server_certificate_verification(false);
  11154. cli.set_keep_alive(true);
  11155. auto result = cli.Get("/hi");
  11156. ASSERT_TRUE(result);
  11157. EXPECT_EQ(StatusCode::OK_200, result->status);
  11158. result = cli.Get("/hi");
  11159. ASSERT_TRUE(result);
  11160. EXPECT_EQ(StatusCode::OK_200, result->status);
  11161. std::this_thread::sleep_for(std::chrono::seconds(2));
  11162. // Recoonect
  11163. result = cli.Get("/hi");
  11164. ASSERT_TRUE(result);
  11165. EXPECT_EQ(StatusCode::OK_200, result->status);
  11166. result = cli.Get("/hi");
  11167. ASSERT_TRUE(result);
  11168. EXPECT_EQ(StatusCode::OK_200, result->status);
  11169. }
  11170. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11172. ASSERT_TRUE(svr.is_valid());
  11173. svr.set_keep_alive_timeout(1);
  11174. std::string content = "reconnect";
  11175. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11176. res.set_content("Hello World!", "text/plain");
  11177. });
  11178. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11179. auto se = detail::scope_exit([&] {
  11180. svr.stop();
  11181. listen_thread.join();
  11182. ASSERT_FALSE(svr.is_running());
  11183. });
  11184. svr.wait_until_ready();
  11185. SSLClient cli(HOST, PORT);
  11186. cli.enable_server_certificate_verification(false);
  11187. cli.set_keep_alive(true);
  11188. auto result = cli.Post(
  11189. "/hi", content.size(),
  11190. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11191. sink.write(content.c_str(), content.size());
  11192. return true;
  11193. },
  11194. "text/plain");
  11195. ASSERT_TRUE(result);
  11196. EXPECT_EQ(200, result->status);
  11197. std::this_thread::sleep_for(std::chrono::seconds(2));
  11198. // Recoonect
  11199. result = cli.Post(
  11200. "/hi", content.size(),
  11201. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11202. sink.write(content.c_str(), content.size());
  11203. return true;
  11204. },
  11205. "text/plain");
  11206. ASSERT_TRUE(result);
  11207. EXPECT_EQ(200, result->status);
  11208. result = cli.Post(
  11209. "/hi", content.size(),
  11210. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11211. sink.write(content.c_str(), content.size());
  11212. return true;
  11213. },
  11214. "text/plain");
  11215. ASSERT_TRUE(result);
  11216. EXPECT_EQ(200, result->status);
  11217. }
  11218. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11219. using namespace httplib::tls;
  11220. {
  11221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11222. ASSERT_TRUE(svr.is_valid());
  11223. svr.Get("/sni", [&](const Request &req, Response &res) {
  11224. std::string expected = req.sni();
  11225. EXPECT_EQ(expected, req.get_param_value("expected"));
  11226. res.set_content("ok", "text/plain");
  11227. });
  11228. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11229. auto se = detail::scope_exit([&] {
  11230. svr.stop();
  11231. listen_thread.join();
  11232. ASSERT_FALSE(svr.is_running());
  11233. });
  11234. svr.wait_until_ready();
  11235. {
  11236. SSLClient cli("localhost", PORT);
  11237. cli.enable_server_certificate_verification(false);
  11238. auto res = cli.Get("/sni?expected=localhost");
  11239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11240. }
  11241. {
  11242. SSLClient cli("::1", PORT);
  11243. cli.enable_server_certificate_verification(false);
  11244. auto res = cli.Get("/sni?expected=");
  11245. // NOTE: This may fail if the server is listening on IPv4 only
  11246. // (e.g., when localhost resolves to 127.0.0.1 only)
  11247. if (res) {
  11248. EXPECT_EQ(StatusCode::OK_200, res->status);
  11249. } else {
  11250. EXPECT_EQ(Error::Connection, res.error());
  11251. }
  11252. }
  11253. }
  11254. }
  11255. // The SNI of a failed handshake does not reach the next connection that the
  11256. // same worker thread serves
  11257. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11258. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11259. ASSERT_TRUE(svr.is_valid());
  11260. svr.new_task_queue = [] { return new ThreadPool(1); };
  11261. svr.Get("/sni", [](const Request &req, Response &res) {
  11262. res.set_content(req.sni(), "text/plain");
  11263. });
  11264. auto port = svr.bind_to_any_port("127.0.0.1");
  11265. ASSERT_LT(0, port);
  11266. thread t = thread([&] { svr.listen_after_bind(); });
  11267. auto se = detail::scope_exit([&] {
  11268. svr.stop();
  11269. t.join();
  11270. ASSERT_FALSE(svr.is_running());
  11271. });
  11272. svr.wait_until_ready();
  11273. {
  11274. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11275. SSLClient cli("localhost", port);
  11276. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11277. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11278. auto res = cli.Get("/sni");
  11279. ASSERT_FALSE(res);
  11280. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11281. }
  11282. // An IP host sends no SNI (RFC 6066)
  11283. SSLClient cli("127.0.0.1", port);
  11284. cli.enable_server_certificate_verification(false);
  11285. auto res = cli.Get("/sni");
  11286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11287. EXPECT_EQ("", res->body);
  11288. }
  11289. #endif
  11290. TEST(ClientProblemDetectionTest, ContentProvider) {
  11291. Server svr;
  11292. size_t content_length = 1024 * 1024;
  11293. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11294. res.set_content_provider(
  11295. content_length, "text/plain",
  11296. [&](size_t offset, size_t length, DataSink &sink) {
  11297. auto out_len = std::min(length, static_cast<size_t>(1024));
  11298. std::string out(out_len, '@');
  11299. sink.write(out.data(), out_len);
  11300. return offset < 4096;
  11301. },
  11302. [](bool success) { ASSERT_FALSE(success); });
  11303. });
  11304. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11305. res.set_content_provider(
  11306. 0, "text/plain",
  11307. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11308. EXPECT_TRUE(false);
  11309. return true;
  11310. },
  11311. [](bool success) { ASSERT_FALSE(success); });
  11312. });
  11313. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11314. auto se = detail::scope_exit([&] {
  11315. svr.stop();
  11316. listen_thread.join();
  11317. ASSERT_FALSE(svr.is_running());
  11318. });
  11319. svr.wait_until_ready();
  11320. Client cli("localhost", PORT);
  11321. {
  11322. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11323. size_t /*data_length*/) { return false; });
  11324. ASSERT_FALSE(res);
  11325. }
  11326. {
  11327. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11328. size_t /*data_length*/) { return false; });
  11329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11330. }
  11331. }
  11332. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11333. // A provider that reports success without writing anything and without
  11334. // calling done() used to be handed the same offset and length again on every
  11335. // pass, so it spun for as long as the peer stayed connected.
  11336. Server svr;
  11337. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11338. res.set_content("ok", "text/plain");
  11339. });
  11340. auto port = svr.bind_to_any_port(HOST);
  11341. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11342. auto se = detail::scope_exit([&] {
  11343. svr.stop();
  11344. listen_thread.join();
  11345. ASSERT_FALSE(svr.is_running());
  11346. });
  11347. svr.wait_until_ready();
  11348. std::atomic<int> call_count{0};
  11349. Client cli(HOST, port);
  11350. auto res = cli.Post(
  11351. "/", 1024,
  11352. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11353. // Give up after enough passes to show the spin, so that losing the
  11354. // check below fails this test instead of hanging it.
  11355. return ++call_count < 100;
  11356. },
  11357. "text/plain");
  11358. ASSERT_FALSE(res);
  11359. EXPECT_EQ(Error::Write, res.error());
  11360. EXPECT_EQ(1, call_count.load());
  11361. }
  11362. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11363. // A writer only has to assign `write`. The other three used to be left as
  11364. // empty std::functions, so a provider calling one threw
  11365. // std::bad_function_call out of the thread running it and took the whole
  11366. // process down.
  11367. DataSink sink;
  11368. std::string written;
  11369. sink.write = [&](const char *data, size_t data_len) {
  11370. written.append(data, data_len);
  11371. return true;
  11372. };
  11373. EXPECT_TRUE(sink.is_writable());
  11374. sink.done();
  11375. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11376. EXPECT_TRUE(written.empty());
  11377. }
  11378. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11379. // A sink that cannot carry trailers still has to finish.
  11380. DataSink sink;
  11381. auto done_count = 0;
  11382. sink.done = [&]() { done_count++; };
  11383. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11384. EXPECT_EQ(1, done_count);
  11385. }
  11386. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11387. Server svr;
  11388. const std::string body(4096, 'x');
  11389. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11390. res.set_content_provider(body.size(), "text/plain",
  11391. [&](size_t offset, size_t length, DataSink &sink) {
  11392. sink.write(body.data() + offset, length);
  11393. sink.done();
  11394. return true;
  11395. });
  11396. });
  11397. auto port = svr.bind_to_any_port(HOST);
  11398. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11399. auto se = detail::scope_exit([&] {
  11400. svr.stop();
  11401. listen_thread.join();
  11402. ASSERT_FALSE(svr.is_running());
  11403. });
  11404. svr.wait_until_ready();
  11405. Client cli(HOST, port);
  11406. auto res = cli.Get("/");
  11407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11408. EXPECT_EQ(StatusCode::OK_200, res->status);
  11409. EXPECT_EQ(body, res->body);
  11410. }
  11411. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11412. Server svr;
  11413. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11414. res.set_content_provider(
  11415. 1024, "text/plain",
  11416. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11417. sink.write("hello", 5);
  11418. sink.done(); // short of the 1024 bytes the response promised
  11419. return true;
  11420. });
  11421. });
  11422. auto port = svr.bind_to_any_port(HOST);
  11423. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11424. auto se = detail::scope_exit([&] {
  11425. svr.stop();
  11426. listen_thread.join();
  11427. ASSERT_FALSE(svr.is_running());
  11428. });
  11429. svr.wait_until_ready();
  11430. Client cli(HOST, port);
  11431. cli.set_read_timeout(5, 0);
  11432. // The response is short of its Content-Length, so the client cannot read a
  11433. // complete body. What matters is that this returns at all: a no-op done()
  11434. // would leave the writer looping over a provider that never makes progress.
  11435. auto res = cli.Get("/");
  11436. EXPECT_FALSE(res);
  11437. }
  11438. // Read as the next response by a peer that sees it after a framed body.
  11439. static const std::string smuggled_response =
  11440. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11441. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11442. Server svr;
  11443. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11444. res.set_content_provider(
  11445. 5, "text/plain",
  11446. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11447. auto data = "AAAAA" + smuggled_response;
  11448. sink.write(data.data(), data.size());
  11449. return true;
  11450. });
  11451. });
  11452. thread t = thread([&] { svr.listen(HOST, PORT); });
  11453. auto se = detail::scope_exit([&] {
  11454. svr.stop();
  11455. t.join();
  11456. ASSERT_FALSE(svr.is_running());
  11457. });
  11458. svr.wait_until_ready();
  11459. std::string resp;
  11460. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11461. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11462. resp.clear();
  11463. ASSERT_TRUE(send_request(
  11464. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11465. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11466. }
  11467. TEST(NoContentTest, BodyIsNotSent) {
  11468. Server svr;
  11469. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11470. res.status = StatusCode::NoContent_204;
  11471. res.set_content(smuggled_response, "text/plain");
  11472. });
  11473. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11474. res.status = StatusCode::NotModified_304;
  11475. res.set_chunked_content_provider(
  11476. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11477. sink.write(smuggled_response.data(), smuggled_response.size());
  11478. sink.done();
  11479. return true;
  11480. });
  11481. });
  11482. thread t = thread([&] { svr.listen(HOST, PORT); });
  11483. auto se = detail::scope_exit([&] {
  11484. svr.stop();
  11485. t.join();
  11486. ASSERT_FALSE(svr.is_running());
  11487. });
  11488. svr.wait_until_ready();
  11489. for (auto path : {"/204", "/304"}) {
  11490. std::string resp;
  11491. ASSERT_TRUE(send_request(
  11492. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11493. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11494. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11495. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11496. }
  11497. }
  11498. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11499. Server svr;
  11500. std::atomic<bool> smuggled(false);
  11501. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11502. res.set_content("ok", "text/plain");
  11503. });
  11504. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11505. smuggled = true;
  11506. });
  11507. auto port = svr.bind_to_any_port(HOST);
  11508. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11509. auto se = detail::scope_exit([&] {
  11510. svr.stop();
  11511. listen_thread.join();
  11512. ASSERT_FALSE(svr.is_running());
  11513. });
  11514. svr.wait_until_ready();
  11515. // What follows the body would be read as the next request.
  11516. Client cli(HOST, port);
  11517. auto res = cli.Post(
  11518. "/", 5,
  11519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11520. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11521. sink.write(data.data(), data.size());
  11522. return true;
  11523. },
  11524. "text/plain");
  11525. ASSERT_FALSE(res);
  11526. EXPECT_EQ(Error::Write, res.error());
  11527. EXPECT_FALSE(smuggled);
  11528. }
  11529. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11530. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11531. // The compressed path builds the whole body before connecting, so this
  11532. // fails client-side and never reaches a server.
  11533. Client cli(HOST, PORT);
  11534. cli.set_compress(true);
  11535. auto res = cli.Post(
  11536. "/", 1024,
  11537. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11538. sink.write("hello", 5);
  11539. sink.done(); // short of the 1024 bytes the request announced
  11540. return true;
  11541. },
  11542. "text/plain");
  11543. ASSERT_FALSE(res);
  11544. EXPECT_EQ(Error::Write, res.error());
  11545. }
  11546. #endif
  11547. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11548. Server svr;
  11549. svr.set_error_handler([](Request const &, Response &res) -> void {
  11550. res.set_chunked_content_provider(
  11551. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11552. sink.os << "hello";
  11553. sink.os << "world";
  11554. sink.done();
  11555. return true;
  11556. });
  11557. });
  11558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11559. auto se = detail::scope_exit([&] {
  11560. svr.stop();
  11561. listen_thread.join();
  11562. ASSERT_FALSE(svr.is_running());
  11563. });
  11564. svr.wait_until_ready();
  11565. Client cli("localhost", PORT);
  11566. auto res = cli.Get("/");
  11567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11569. EXPECT_EQ("helloworld", res->body);
  11570. }
  11571. // A body set after a content provider must replace it, not be sent through it.
  11572. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11573. Server svr;
  11574. svr.set_mount_point("/", "./www");
  11575. svr.set_file_request_handler([](const Request &req, Response &res) {
  11576. if (req.path == "/dir/test.html") {
  11577. res.status = StatusCode::Forbidden_403;
  11578. res.set_content(std::string(5000, 'D'), "text/plain");
  11579. } else if (req.path == "/file") {
  11580. res.status = StatusCode::Forbidden_403;
  11581. res.body = "Denied";
  11582. }
  11583. });
  11584. auto port = svr.bind_to_any_port(HOST);
  11585. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11586. auto se = detail::scope_exit([&] {
  11587. svr.stop();
  11588. t.join();
  11589. ASSERT_FALSE(svr.is_running());
  11590. });
  11591. svr.wait_until_ready();
  11592. Client cli(HOST, port);
  11593. {
  11594. auto res = cli.Get("/dir/test.html");
  11595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11596. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11597. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11598. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11599. }
  11600. {
  11601. auto res = cli.Get("/file");
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11604. EXPECT_EQ("Denied", res->body);
  11605. }
  11606. {
  11607. auto res = cli.Get("/dir/index.html");
  11608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11609. EXPECT_EQ(StatusCode::OK_200, res->status);
  11610. EXPECT_EQ(0U, res->body.find("<html>"));
  11611. }
  11612. }
  11613. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11614. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11615. Server svr;
  11616. std::vector<bool> released;
  11617. std::mutex released_mutex;
  11618. auto releaser = [&](bool success) {
  11619. std::lock_guard<std::mutex> guard(released_mutex);
  11620. released.push_back(success);
  11621. };
  11622. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11623. return sink.write(&"hello"[offset], length);
  11624. };
  11625. svr.Get("/sized", [&](const Request &, Response &res) {
  11626. res.status = StatusCode::NotFound_404;
  11627. res.set_content_provider(5, "text/plain", provider, releaser);
  11628. });
  11629. svr.Get("/chunked", [&](const Request &, Response &res) {
  11630. res.status = StatusCode::ServiceUnavailable_503;
  11631. res.set_chunked_content_provider(
  11632. "text/plain",
  11633. [](size_t, DataSink &sink) {
  11634. sink.os << "chunk";
  11635. sink.done();
  11636. return true;
  11637. },
  11638. releaser);
  11639. });
  11640. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11641. res.set_content_provider(5, "text/plain", provider, releaser);
  11642. throw std::runtime_error("after the provider");
  11643. });
  11644. svr.set_error_handler([](const Request &req, Response &res) {
  11645. // Leave the exception handler's content to it.
  11646. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11647. res.set_content(std::string(1000, 'E'), "text/html");
  11648. return Server::HandlerResponse::Handled;
  11649. });
  11650. svr.set_exception_handler(
  11651. [](const Request &, Response &res, std::exception_ptr) {
  11652. res.status = StatusCode::InternalServerError_500;
  11653. res.set_content(std::string(1000, 'X'), "text/html");
  11654. });
  11655. auto port = svr.bind_to_any_port(HOST);
  11656. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11657. auto se = detail::scope_exit([&] {
  11658. svr.stop();
  11659. t.join();
  11660. ASSERT_FALSE(svr.is_running());
  11661. });
  11662. svr.wait_until_ready();
  11663. Client cli(HOST, port);
  11664. {
  11665. auto res = cli.Get("/sized");
  11666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11668. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11669. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11670. }
  11671. {
  11672. auto res = cli.Get("/chunked");
  11673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11674. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11675. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11676. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11677. }
  11678. {
  11679. auto res = cli.Get("/throw");
  11680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11681. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11682. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11683. }
  11684. std::lock_guard<std::mutex> guard(released_mutex);
  11685. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11686. }
  11687. #endif
  11688. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11689. Server svr;
  11690. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11691. return sink.write(&"abc"[offset], length);
  11692. };
  11693. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11694. res.set_file_content("./www/dir/test.html");
  11695. res.set_content("body", "text/plain");
  11696. });
  11697. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11698. res.set_content(std::string(100, 'B'), "text/plain");
  11699. res.set_file_content("./www/dir/test.html");
  11700. });
  11701. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11702. res.set_content(std::string(100, 'B'), "text/plain");
  11703. res.set_content_provider(3, "text/x-provider", abc);
  11704. });
  11705. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11706. res.set_content_provider(3, "text/x-provider", abc);
  11707. res.set_content(std::string(100, 'B'), "text/plain");
  11708. });
  11709. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11710. res.set_content_provider(3, "text/x-provider", abc);
  11711. res.set_file_content("./www/dir/test.html", "text/x-file");
  11712. });
  11713. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11714. res.set_file_content("./www/dir/test.html");
  11715. res.set_header("Content-Type", "text/x-handler");
  11716. });
  11717. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11718. res.set_content_provider(3, "text/plain", abc);
  11719. res.body = "direct";
  11720. });
  11721. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11722. res.set_file_content("./www/dir/test.html");
  11723. res.body = "direct";
  11724. });
  11725. auto port = svr.bind_to_any_port(HOST);
  11726. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11727. auto se = detail::scope_exit([&] {
  11728. svr.stop();
  11729. t.join();
  11730. ASSERT_FALSE(svr.is_running());
  11731. });
  11732. svr.wait_until_ready();
  11733. Client cli(HOST, port);
  11734. auto expect_body = [&](const char *path, const std::string &body,
  11735. const std::string &type) {
  11736. // Uncompressed, so Content-Length can be compared with the body.
  11737. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11738. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11739. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11740. EXPECT_EQ(body, res->body) << path;
  11741. EXPECT_EQ(std::to_string(body.size()),
  11742. res->get_header_value("Content-Length"))
  11743. << path;
  11744. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11745. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11746. };
  11747. expect_body("/file-then-body", "body", "text/plain");
  11748. expect_body("/body-then-file", "test.html", "text/html");
  11749. expect_body("/body-then-provider", "abc", "text/x-provider");
  11750. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11751. expect_body("/provider-then-file", "test.html", "text/x-file");
  11752. expect_body("/file-then-header", "test.html", "text/x-handler");
  11753. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11754. expect_body("/file-then-direct-body", "direct", "text/plain");
  11755. // Ranges are checked against the body, not the dropped provider.
  11756. {
  11757. auto res = cli.Get("/provider-then-direct-body",
  11758. Headers{{make_range_header({{1, 2}})}});
  11759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11761. EXPECT_EQ("ir", res->body);
  11762. }
  11763. {
  11764. auto res = cli.Get("/file-then-direct-body",
  11765. Headers{{make_range_header({{7, 8}})}});
  11766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11767. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11768. }
  11769. }
  11770. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11771. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11772. const char *path = "./truncated_while_served.txt";
  11773. const size_t size = 32 * 1024 * 1024;
  11774. {
  11775. std::ofstream f(path, std::ios::binary);
  11776. f << std::string(size, 'x');
  11777. }
  11778. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11779. // Over TLS, where the bytes are encrypted in this process rather than
  11780. // copied by send().
  11781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11782. svr.Get("/file", [&](const Request &, Response &res) {
  11783. res.set_file_content(path, "text/plain");
  11784. });
  11785. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11786. auto se = detail::scope_exit([&] {
  11787. svr.stop();
  11788. thread.join();
  11789. ASSERT_FALSE(svr.is_running());
  11790. });
  11791. svr.wait_until_ready();
  11792. // The file shrinks once the first bytes are in, as a rewrite in place
  11793. // would, and reading the mapping past its new end used to raise SIGBUS.
  11794. SSLClient cli(HOST, PORT);
  11795. cli.enable_server_certificate_verification(false);
  11796. size_t received = 0;
  11797. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11798. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11799. received += len;
  11800. return true;
  11801. });
  11802. EXPECT_FALSE(res);
  11803. EXPECT_LT(received, size);
  11804. }
  11805. #endif
  11806. // Forward declaration (see the base64_encode note).
  11807. namespace httplib {
  11808. namespace detail {
  11809. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11810. const std::string &content_type,
  11811. EncodingType encoding);
  11812. } // namespace detail
  11813. } // namespace httplib
  11814. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11815. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11816. ASSERT_TRUE(mm->is_open());
  11817. Response res;
  11818. detail::set_file_content_provider(res, mm, "text/html",
  11819. detail::EncodingType::None);
  11820. std::string out;
  11821. DataSink sink;
  11822. sink.write = [&](const char *d, size_t l) {
  11823. out.append(d, l);
  11824. return true;
  11825. };
  11826. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11827. EXPECT_EQ("test.html", out);
  11828. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11829. EXPECT_EQ("test.html", out);
  11830. }
  11831. TEST(LongPollingTest, ClientCloseDetection) {
  11832. Server svr;
  11833. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11834. res.set_chunked_content_provider(
  11835. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11836. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11837. sink.os << "hello";
  11838. auto count = 10;
  11839. while (count > 0 && sink.is_writable()) {
  11840. this_thread::sleep_for(chrono::milliseconds(10));
  11841. count--;
  11842. }
  11843. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11844. return true;
  11845. });
  11846. });
  11847. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11848. auto se = detail::scope_exit([&] {
  11849. svr.stop();
  11850. listen_thread.join();
  11851. ASSERT_FALSE(svr.is_running());
  11852. });
  11853. svr.wait_until_ready();
  11854. Client cli("localhost", PORT);
  11855. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11856. EXPECT_EQ("hello", string(data, data_length));
  11857. return false; // close the socket immediately.
  11858. });
  11859. ASSERT_FALSE(res);
  11860. }
  11861. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11862. Server svr;
  11863. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11864. res.set_chunked_content_provider(
  11865. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11866. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11867. sink.os << "hello";
  11868. EXPECT_TRUE(sink.os.good());
  11869. // Wait for the client to close the connection
  11870. auto count = 10;
  11871. while (count > 0 && sink.is_writable()) {
  11872. this_thread::sleep_for(chrono::milliseconds(10));
  11873. count--;
  11874. }
  11875. // After client disconnect, write repeatedly until the socket
  11876. // write actually fails (small writes may be absorbed by the
  11877. // kernel buffer)
  11878. std::string chunk(1024, 'x');
  11879. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11880. sink.os << chunk;
  11881. }
  11882. EXPECT_TRUE(sink.os.fail());
  11883. return true;
  11884. });
  11885. });
  11886. auto port = svr.bind_to_any_port("localhost");
  11887. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11888. auto se = detail::scope_exit([&] {
  11889. svr.stop();
  11890. listen_thread.join();
  11891. ASSERT_FALSE(svr.is_running());
  11892. });
  11893. svr.wait_until_ready();
  11894. Client cli("localhost", port);
  11895. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11896. EXPECT_EQ("hello", string(data, data_length));
  11897. return false; // close the socket immediately.
  11898. });
  11899. ASSERT_FALSE(res);
  11900. }
  11901. TEST(GetWithParametersTest, GetWithParameters) {
  11902. Server svr;
  11903. svr.Get("/", [&](const Request &req, Response &) {
  11904. EXPECT_EQ("world", req.get_param_value("hello"));
  11905. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11906. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11907. });
  11908. svr.Get("/params", [&](const Request &req, Response &) {
  11909. EXPECT_EQ("world", req.get_param_value("hello"));
  11910. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11911. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11912. });
  11913. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11914. EXPECT_EQ("resource-id", req.matches[1]);
  11915. EXPECT_EQ("foo", req.get_param_value("param1"));
  11916. EXPECT_EQ("bar", req.get_param_value("param2"));
  11917. });
  11918. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11919. EXPECT_EQ("user-id", req.path_params.at("id"));
  11920. EXPECT_EQ("foo", req.get_param_value("param1"));
  11921. EXPECT_EQ("bar", req.get_param_value("param2"));
  11922. });
  11923. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11924. auto se = detail::scope_exit([&] {
  11925. svr.stop();
  11926. listen_thread.join();
  11927. ASSERT_FALSE(svr.is_running());
  11928. });
  11929. svr.wait_until_ready();
  11930. {
  11931. Client cli(HOST, PORT);
  11932. Params params;
  11933. params.emplace("hello", "world");
  11934. params.emplace("hello2", "world2");
  11935. params.emplace("hello3", "world3");
  11936. auto res = cli.Get("/", params, Headers{});
  11937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11938. EXPECT_EQ(StatusCode::OK_200, res->status);
  11939. }
  11940. {
  11941. Client cli(HOST, PORT);
  11942. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11944. EXPECT_EQ(StatusCode::OK_200, res->status);
  11945. }
  11946. {
  11947. Client cli(HOST, PORT);
  11948. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11950. EXPECT_EQ(StatusCode::OK_200, res->status);
  11951. }
  11952. {
  11953. Client cli(HOST, PORT);
  11954. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11956. EXPECT_EQ(StatusCode::OK_200, res->status);
  11957. }
  11958. }
  11959. TEST(GetWithParametersTest, GetWithParameters2) {
  11960. Server svr;
  11961. svr.Get("/", [&](const Request &req, Response &res) {
  11962. auto text = req.get_param_value("hello");
  11963. res.set_content(text, "text/plain");
  11964. });
  11965. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11966. auto se = detail::scope_exit([&] {
  11967. svr.stop();
  11968. listen_thread.join();
  11969. ASSERT_FALSE(svr.is_running());
  11970. });
  11971. svr.wait_until_ready();
  11972. Client cli("localhost", PORT);
  11973. Params params;
  11974. params.emplace("hello", "world");
  11975. std::string body;
  11976. auto res = cli.Get("/", params, Headers{},
  11977. [&](const char *data, size_t data_length) {
  11978. body.append(data, data_length);
  11979. return true;
  11980. });
  11981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11982. EXPECT_EQ(StatusCode::OK_200, res->status);
  11983. EXPECT_EQ("world", body);
  11984. }
  11985. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11986. Server svr;
  11987. svr.Get("/search", [&](const Request &req, Response &res) {
  11988. auto q = req.get_param_value("q");
  11989. res.set_content(q, "text/plain");
  11990. });
  11991. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11992. auto se = detail::scope_exit([&] {
  11993. svr.stop();
  11994. listen_thread.join();
  11995. ASSERT_FALSE(svr.is_running());
  11996. });
  11997. svr.wait_until_ready();
  11998. Client cli("localhost", PORT);
  11999. // Verify that Get(path, params) works without requiring Headers argument
  12000. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12002. EXPECT_EQ(StatusCode::OK_200, res->status);
  12003. EXPECT_EQ("cpp-httplib", res->body);
  12004. }
  12005. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12006. auto host = "httpbingo.org";
  12007. auto path = std::string{"/range/32"};
  12008. #ifdef CPPHTTPLIB_SSL_ENABLED
  12009. SSLClient cli(host);
  12010. #else
  12011. Client cli(host);
  12012. #endif
  12013. cli.set_default_headers({make_range_header({{1, 10}})});
  12014. cli.set_connection_timeout(5);
  12015. {
  12016. auto res = cli.Get(path);
  12017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12018. EXPECT_EQ("bcdefghijk", res->body);
  12019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12020. }
  12021. {
  12022. auto res = cli.Get(path);
  12023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12024. EXPECT_EQ("bcdefghijk", res->body);
  12025. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12026. }
  12027. }
  12028. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12029. Server svr;
  12030. svr.set_default_headers({{"Hello", "World"}});
  12031. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12032. res.set_content("ok", "text/plain");
  12033. });
  12034. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12035. auto se = detail::scope_exit([&] {
  12036. svr.stop();
  12037. listen_thread.join();
  12038. ASSERT_FALSE(svr.is_running());
  12039. });
  12040. svr.wait_until_ready();
  12041. Client cli("localhost", PORT);
  12042. auto res = cli.Get("/");
  12043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12044. EXPECT_EQ(StatusCode::OK_200, res->status);
  12045. EXPECT_EQ("ok", res->body);
  12046. EXPECT_EQ("World", res->get_header_value("Hello"));
  12047. }
  12048. #ifdef CPPHTTPLIB_SSL_ENABLED
  12049. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12051. ASSERT_TRUE(svr.is_valid());
  12052. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12053. std::this_thread::sleep_for(std::chrono::seconds(2));
  12054. res.set_content("a", "text/plain");
  12055. });
  12056. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12057. res.set_content("b", "text/plain");
  12058. });
  12059. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12060. auto se = detail::scope_exit([&] {
  12061. svr.stop();
  12062. listen_thread.join();
  12063. ASSERT_FALSE(svr.is_running());
  12064. });
  12065. svr.wait_until_ready();
  12066. SSLClient cli("localhost", PORT);
  12067. cli.enable_server_certificate_verification(false);
  12068. cli.set_keep_alive(true);
  12069. cli.set_read_timeout(std::chrono::seconds(1));
  12070. auto resa = cli.Get("/a");
  12071. ASSERT_TRUE(!resa);
  12072. EXPECT_EQ(Error::Read, resa.error());
  12073. auto resb = cli.Get("/b");
  12074. ASSERT_TRUE(resb);
  12075. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12076. EXPECT_EQ("b", resb->body);
  12077. }
  12078. // Closing an idle keep-alive connection sends close_notify and returns. The
  12079. // server must not wait for the client's close_notify: an idle client never
  12080. // sends one, so the worker would be held until the read timeout expires, and
  12081. // stop() would wait for it.
  12082. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12084. ASSERT_TRUE(svr.is_valid());
  12085. svr.set_keep_alive_timeout(1);
  12086. svr.set_read_timeout(10, 0);
  12087. svr.Get("/", [](const Request &, Response &res) {
  12088. res.set_content("ok", "text/plain");
  12089. });
  12090. auto port = svr.bind_to_any_port(HOST);
  12091. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12092. auto se = detail::scope_exit([&] {
  12093. if (listen_thread.joinable()) {
  12094. svr.stop();
  12095. listen_thread.join();
  12096. }
  12097. });
  12098. svr.wait_until_ready();
  12099. SSLClient cli(HOST, port);
  12100. cli.enable_server_certificate_verification(false);
  12101. cli.set_keep_alive(true);
  12102. auto res = cli.Get("/");
  12103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12104. EXPECT_EQ(StatusCode::OK_200, res->status);
  12105. // Stay idle past the keep-alive timeout so the server closes the connection.
  12106. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12107. auto start = std::chrono::steady_clock::now();
  12108. svr.stop();
  12109. listen_thread.join();
  12110. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12111. std::chrono::steady_clock::now() - start)
  12112. .count();
  12113. EXPECT_LT(elapsed, 3000);
  12114. }
  12115. #endif
  12116. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12117. protected:
  12118. ServerTestWithAI_PASSIVE()
  12119. : cli_(HOST, PORT)
  12120. #ifdef CPPHTTPLIB_SSL_ENABLED
  12121. ,
  12122. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12123. #endif
  12124. {
  12125. #ifdef CPPHTTPLIB_SSL_ENABLED
  12126. cli_.enable_server_certificate_verification(false);
  12127. #endif
  12128. }
  12129. virtual void SetUp() {
  12130. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12131. res.set_content("Hello World!", "text/plain");
  12132. });
  12133. t_ = thread(
  12134. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12135. svr_.wait_until_ready();
  12136. }
  12137. virtual void TearDown() {
  12138. svr_.stop();
  12139. t_.join();
  12140. }
  12141. #ifdef CPPHTTPLIB_SSL_ENABLED
  12142. SSLClient cli_;
  12143. SSLServer svr_;
  12144. #else
  12145. Client cli_;
  12146. Server svr_;
  12147. #endif
  12148. thread t_;
  12149. };
  12150. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12151. auto res = cli_.Get("/hi");
  12152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12153. EXPECT_EQ(StatusCode::OK_200, res->status);
  12154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12155. EXPECT_EQ("Hello World!", res->body);
  12156. }
  12157. class ServerUpDownTest : public ::testing::Test {
  12158. protected:
  12159. ServerUpDownTest() : cli_(HOST, PORT) {}
  12160. virtual void SetUp() {
  12161. t_ = thread([&]() {
  12162. svr_.bind_to_any_port(HOST);
  12163. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12164. ASSERT_TRUE(svr_.listen_after_bind());
  12165. });
  12166. svr_.wait_until_ready();
  12167. }
  12168. virtual void TearDown() {
  12169. svr_.stop();
  12170. t_.join();
  12171. }
  12172. Client cli_;
  12173. Server svr_;
  12174. thread t_;
  12175. };
  12176. TEST_F(ServerUpDownTest, QuickStartStop) {
  12177. // Should not crash, especially when run with
  12178. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12179. }
  12180. class PayloadMaxLengthTest : public ::testing::Test {
  12181. protected:
  12182. PayloadMaxLengthTest()
  12183. : cli_(HOST, PORT)
  12184. #ifdef CPPHTTPLIB_SSL_ENABLED
  12185. ,
  12186. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12187. #endif
  12188. {
  12189. #ifdef CPPHTTPLIB_SSL_ENABLED
  12190. cli_.enable_server_certificate_verification(false);
  12191. #endif
  12192. }
  12193. virtual void SetUp() {
  12194. svr_.set_payload_max_length(8);
  12195. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12196. res.set_content("test", "text/plain");
  12197. });
  12198. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12199. svr_.wait_until_ready();
  12200. }
  12201. virtual void TearDown() {
  12202. svr_.stop();
  12203. t_.join();
  12204. }
  12205. #ifdef CPPHTTPLIB_SSL_ENABLED
  12206. SSLClient cli_;
  12207. SSLServer svr_;
  12208. #else
  12209. Client cli_;
  12210. Server svr_;
  12211. #endif
  12212. thread t_;
  12213. };
  12214. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12215. auto res = cli_.Post("/test", "123456789", "text/plain");
  12216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12217. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12218. res = cli_.Post("/test", "12345678", "text/plain");
  12219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12220. EXPECT_EQ(StatusCode::OK_200, res->status);
  12221. }
  12222. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12223. // Test chunked encoding with payload exceeding the 8-byte limit
  12224. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12225. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12227. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12228. }
  12229. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12230. // Test chunked encoding with payload within the 8-byte limit
  12231. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12232. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12234. EXPECT_EQ(StatusCode::OK_200, res->status);
  12235. }
  12236. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12237. // Test using send_request to send chunked data exceeding payload limit
  12238. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12239. "Host: " +
  12240. std::string(HOST) + ":" + std::to_string(PORT) +
  12241. "\r\n"
  12242. "Transfer-Encoding: chunked\r\n"
  12243. "Connection: close\r\n"
  12244. "\r\n"
  12245. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12246. "0123456789\r\n"
  12247. "0\r\n" // End chunk
  12248. "\r\n";
  12249. std::string response;
  12250. bool result = send_request(1, chunked_request, &response);
  12251. if (!result) {
  12252. // If send_request fails, it might be because the server closed the
  12253. // connection due to payload limit enforcement, which is acceptable
  12254. SUCCEED()
  12255. << "Server rejected oversized chunked request (connection closed)";
  12256. } else {
  12257. // If we got a response, check if it's an error response or connection was
  12258. // closed early Short response length indicates connection was closed due to
  12259. // payload limit
  12260. if (response.length() <= 10) {
  12261. SUCCEED() << "Server closed connection for oversized chunked request";
  12262. } else {
  12263. // Check for error status codes
  12264. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12265. response.find("Payload Too Large") != std::string::npos ||
  12266. response.find("400") != std::string::npos);
  12267. }
  12268. }
  12269. }
  12270. class LargePayloadMaxLengthTest : public ::testing::Test {
  12271. protected:
  12272. LargePayloadMaxLengthTest()
  12273. : cli_(HOST, PORT)
  12274. #ifdef CPPHTTPLIB_SSL_ENABLED
  12275. ,
  12276. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12277. #endif
  12278. {
  12279. #ifdef CPPHTTPLIB_SSL_ENABLED
  12280. cli_.enable_server_certificate_verification(false);
  12281. #endif
  12282. }
  12283. virtual void SetUp() {
  12284. // Set 10MB payload limit
  12285. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12286. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12287. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12288. res.set_content("Large payload test", "text/plain");
  12289. });
  12290. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12291. svr_.wait_until_ready();
  12292. }
  12293. virtual void TearDown() {
  12294. svr_.stop();
  12295. t_.join();
  12296. }
  12297. #ifdef CPPHTTPLIB_SSL_ENABLED
  12298. SSLClient cli_;
  12299. SSLServer svr_;
  12300. #else
  12301. Client cli_;
  12302. Server svr_;
  12303. #endif
  12304. thread t_;
  12305. };
  12306. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12307. // Test chunked encoding with payload within 10MB limit
  12308. std::string medium_payload(5 * 1024 * 1024,
  12309. 'A'); // 5MB payload, within 10MB limit
  12310. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12312. EXPECT_EQ(StatusCode::OK_200, res->status);
  12313. }
  12314. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12315. // Test chunked encoding with payload exceeding 10MB limit
  12316. std::string large_payload(12 * 1024 * 1024,
  12317. 'B'); // 12MB payload, exceeds 10MB limit
  12318. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12319. // Server may either return 413 or close the connection
  12320. if (res) {
  12321. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12322. } else {
  12323. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12324. }
  12325. }
  12326. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12327. Server svr;
  12328. svr.Get("/", [](const Request &, Response &res) {
  12329. // Claims the most the client accepts, far more than it sends, then drops
  12330. // the connection.
  12331. res.set_content_provider(std::string().max_size(), "text/plain",
  12332. [](size_t, size_t, DataSink &sink) {
  12333. sink.write("abc", 3);
  12334. return false;
  12335. });
  12336. });
  12337. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12338. auto se = detail::scope_exit([&] {
  12339. svr.stop();
  12340. thread.join();
  12341. ASSERT_FALSE(svr.is_running());
  12342. });
  12343. svr.wait_until_ready();
  12344. Client cli(HOST, PORT);
  12345. cli.set_payload_max_length(0);
  12346. EXPECT_FALSE(cli.Get("/"));
  12347. }
  12348. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12349. // Stream API does, not as a plain read failure
  12350. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12351. Server svr;
  12352. svr.Get("/big", [](const Request &, Response &res) {
  12353. res.set_content(std::string(100000, 'b'), "text/plain");
  12354. });
  12355. auto port = svr.bind_to_any_port(HOST);
  12356. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12357. auto se = detail::scope_exit([&] {
  12358. svr.stop();
  12359. thread.join();
  12360. });
  12361. svr.wait_until_ready();
  12362. Client cli(HOST, port);
  12363. cli.set_payload_max_length(1000);
  12364. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12365. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12366. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12367. [](const char *, size_t) { return true; });
  12368. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12369. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12370. // Small on the wire, over the limit once decompressed
  12371. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12372. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12373. #endif
  12374. }
  12375. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12376. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12377. // path.
  12378. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12379. Server svr;
  12380. const size_t LIMIT = 64 * 1024; // 64KB
  12381. svr.set_payload_max_length(LIMIT);
  12382. size_t total = 0;
  12383. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12384. const ContentReader &content_reader) {
  12385. content_reader([&](const char * /*data*/, size_t len) {
  12386. total += len;
  12387. return true;
  12388. });
  12389. res.status = 200;
  12390. res.set_content("stream_ok", "text/plain");
  12391. });
  12392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12393. auto se = detail::scope_exit([&] {
  12394. svr.stop();
  12395. thread.join();
  12396. ASSERT_FALSE(svr.is_running());
  12397. });
  12398. svr.wait_until_ready();
  12399. // Prepare 256KB raw data and gzip-compress it
  12400. std::string raw(256 * 1024, 'A');
  12401. std::string gz;
  12402. {
  12403. z_stream zs{};
  12404. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12405. Z_DEFAULT_STRATEGY);
  12406. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12407. zs.avail_in = static_cast<uInt>(raw.size());
  12408. char outbuf[4096];
  12409. int ret;
  12410. do {
  12411. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12412. zs.avail_out = sizeof(outbuf);
  12413. ret = deflate(&zs, Z_FINISH);
  12414. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12415. } while (ret != Z_STREAM_END);
  12416. deflateEnd(&zs);
  12417. }
  12418. Client cli(HOST, PORT);
  12419. cli.set_connection_timeout(std::chrono::seconds(5));
  12420. Headers headers = {{"Content-Encoding", "gzip"}};
  12421. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12422. "application/octet-stream");
  12423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12424. // Server must reject oversized decompressed payloads with 413.
  12425. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12426. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12427. EXPECT_LE(total, LIMIT);
  12428. }
  12429. #endif
  12430. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12431. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12432. // the payload must be passed through untouched instead of being rejected.
  12433. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12434. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12435. Server svr;
  12436. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12437. res.set_content(body, "image/jpeg");
  12438. res.set_header("Content-Encoding", "UTF-8");
  12439. });
  12440. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12441. res.set_content(body, "image/jpeg");
  12442. res.set_header("Content-Encoding", "identity");
  12443. });
  12444. svr.Post("/echo", [](const Request &req, Response &res) {
  12445. res.set_content(req.body, "image/jpeg");
  12446. });
  12447. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12448. auto se = detail::scope_exit([&] {
  12449. svr.stop();
  12450. t.join();
  12451. ASSERT_FALSE(svr.is_running());
  12452. });
  12453. svr.wait_until_ready();
  12454. Client cli(HOST, PORT);
  12455. {
  12456. auto res = cli.Get("/image");
  12457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12458. EXPECT_EQ(StatusCode::OK_200, res->status);
  12459. EXPECT_EQ(body, res->body);
  12460. }
  12461. {
  12462. auto res = cli.Get("/identity");
  12463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12464. EXPECT_EQ(StatusCode::OK_200, res->status);
  12465. EXPECT_EQ(body, res->body);
  12466. }
  12467. {
  12468. // The same applies to a request body reaching the server.
  12469. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12470. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12472. EXPECT_EQ(StatusCode::OK_200, res->status);
  12473. EXPECT_EQ(body, res->body);
  12474. }
  12475. }
  12476. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12477. // gzip-encoded response even when the build has no zlib support.
  12478. static const char GZIPPED_HELLO_WORLD[] = {
  12479. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12480. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12481. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12482. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12483. // A content coding is a whole token, not something the field value merely
  12484. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12485. // as "fibre" look like Brotli, and turned a multi-coding value like
  12486. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12487. // it was never meant to see.
  12488. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12489. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12490. Server svr;
  12491. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12492. res.set_content(body, "image/jpeg");
  12493. res.set_header("Content-Encoding", "fibre");
  12494. });
  12495. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12496. res.set_content(body, "image/jpeg");
  12497. res.set_header("Content-Encoding", "gzip, br");
  12498. });
  12499. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12500. res.set_content(body, "image/jpeg");
  12501. res.set_header("Content-Encoding", "x-zstd-ish");
  12502. });
  12503. auto port = svr.bind_to_any_port(HOST);
  12504. thread t = thread([&]() { svr.listen_after_bind(); });
  12505. auto se = detail::scope_exit([&] {
  12506. svr.stop();
  12507. t.join();
  12508. ASSERT_FALSE(svr.is_running());
  12509. });
  12510. svr.wait_until_ready();
  12511. Client cli(HOST, port);
  12512. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12513. auto res = cli.Get(path);
  12514. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12515. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12516. // Not a coding we recognize, so the payload comes back untouched
  12517. EXPECT_EQ(body, res->body) << path;
  12518. }
  12519. }
  12520. // A content coding cpp-httplib recognizes but was not built with must be
  12521. // reported as such. Handing the still-compressed payload back to the caller
  12522. // would silently corrupt it.
  12523. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12524. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12525. Server svr;
  12526. // "image/jpeg" keeps the server from applying a content coding of its own,
  12527. // so the hand-crafted Content-Encoding below survives.
  12528. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12529. res.set_content(gzipped, "image/jpeg");
  12530. res.set_header("Content-Encoding", "gzip");
  12531. });
  12532. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12533. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12534. res.set_content(gzipped, "image/jpeg");
  12535. res.set_header("Content-Encoding", "GZIP");
  12536. });
  12537. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12538. auto se = detail::scope_exit([&] {
  12539. svr.stop();
  12540. t.join();
  12541. ASSERT_FALSE(svr.is_running());
  12542. });
  12543. svr.wait_until_ready();
  12544. Client cli(HOST, PORT);
  12545. {
  12546. auto res = cli.Get("/gzipped");
  12547. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12549. EXPECT_EQ("Hello World!", res->body);
  12550. #else
  12551. ASSERT_FALSE(res);
  12552. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12553. #endif
  12554. }
  12555. {
  12556. // open_stream() must behave the same way.
  12557. auto handle = cli.open_stream("GET", "/gzipped");
  12558. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12559. ASSERT_TRUE(handle.is_valid());
  12560. std::string received;
  12561. char buf[256];
  12562. ssize_t n;
  12563. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12564. received.append(buf, static_cast<size_t>(n));
  12565. }
  12566. EXPECT_EQ("Hello World!", received);
  12567. #else
  12568. EXPECT_FALSE(handle.is_valid());
  12569. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12570. #endif
  12571. }
  12572. {
  12573. // A differently-cased coding must not be mistaken for an unknown one, or
  12574. // the body would be handed back still compressed.
  12575. auto res = cli.Get("/gzipped-uppercase");
  12576. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12578. EXPECT_EQ("Hello World!", res->body);
  12579. #else
  12580. ASSERT_FALSE(res);
  12581. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12582. #endif
  12583. }
  12584. }
  12585. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12586. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12587. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12588. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12589. // body a second time and appending a second Content-Encoding field line, so
  12590. // clients that decode one coding per listed value handed back raw gzip bytes.
  12591. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12592. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12593. Server svr;
  12594. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12595. // keeps the server from applying a coding of its own.
  12596. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12597. res.set_content(gzipped, "text/plain");
  12598. res.set_header("Content-Encoding", "gzip");
  12599. });
  12600. auto port = svr.bind_to_any_port(HOST);
  12601. thread t = thread([&]() { svr.listen_after_bind(); });
  12602. auto se = detail::scope_exit([&] {
  12603. svr.stop();
  12604. t.join();
  12605. ASSERT_FALSE(svr.is_running());
  12606. });
  12607. svr.wait_until_ready();
  12608. Client cli(HOST, port);
  12609. Headers headers = {{"Accept-Encoding", "gzip"}};
  12610. auto res = cli.Get("/pre-gzipped", headers);
  12611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12612. EXPECT_EQ(StatusCode::OK_200, res->status);
  12613. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12614. EXPECT_EQ("Hello World!", res->body);
  12615. }
  12616. // set_compress(false) sends every handler response as it is, buffered or
  12617. // streamed
  12618. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12619. const std::string text(1000, 'a');
  12620. Server svr;
  12621. svr.set_compress(false);
  12622. svr.Get("/buffered", [&](const Request &, Response &res) {
  12623. res.set_content(text, "text/plain");
  12624. });
  12625. svr.Get("/streamed", [&](const Request &, Response &res) {
  12626. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12627. sink.write(text.data(), text.size());
  12628. sink.done();
  12629. return true;
  12630. });
  12631. });
  12632. auto port = svr.bind_to_any_port(HOST);
  12633. ASSERT_LT(0, port);
  12634. thread t = thread([&] { svr.listen_after_bind(); });
  12635. auto se = detail::scope_exit([&] {
  12636. svr.stop();
  12637. t.join();
  12638. ASSERT_FALSE(svr.is_running());
  12639. });
  12640. svr.wait_until_ready();
  12641. Client cli(HOST, port);
  12642. cli.set_decompress(false);
  12643. for (auto path : {"/buffered", "/streamed"}) {
  12644. SCOPED_TRACE(path);
  12645. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12647. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12648. EXPECT_EQ(text, res->body);
  12649. }
  12650. }
  12651. // A chunked provider settles its coding where the headers are written and
  12652. // reuses it at write time. Both ends of that have to hold: a handler's own
  12653. // Content-Encoding suppresses the coding, and a response without one is still
  12654. // compressed as it always was.
  12655. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12656. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12657. const std::string plain = "Hello World! Hello World! Hello World!";
  12658. Server svr;
  12659. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12660. res.set_header("Content-Encoding", "gzip");
  12661. res.set_chunked_content_provider(
  12662. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12663. sink.write(gzipped.data(), gzipped.size());
  12664. sink.done();
  12665. return true;
  12666. });
  12667. });
  12668. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12669. res.set_chunked_content_provider(
  12670. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12671. sink.write(plain.data(), plain.size());
  12672. sink.done();
  12673. return true;
  12674. });
  12675. });
  12676. auto port = svr.bind_to_any_port(HOST);
  12677. thread t = thread([&]() { svr.listen_after_bind(); });
  12678. auto se = detail::scope_exit([&] {
  12679. svr.stop();
  12680. t.join();
  12681. ASSERT_FALSE(svr.is_running());
  12682. });
  12683. svr.wait_until_ready();
  12684. Client cli(HOST, port);
  12685. Headers headers = {{"Accept-Encoding", "gzip"}};
  12686. {
  12687. auto res = cli.Get("/pre-gzipped", headers);
  12688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12689. EXPECT_EQ(StatusCode::OK_200, res->status);
  12690. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12691. EXPECT_EQ("Hello World!", res->body);
  12692. }
  12693. {
  12694. auto res = cli.Get("/negotiated", headers);
  12695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12696. EXPECT_EQ(StatusCode::OK_200, res->status);
  12697. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12698. EXPECT_EQ(plain, res->body);
  12699. }
  12700. }
  12701. #endif
  12702. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12703. // the same message as the comma-joined one, so both have to be read the same
  12704. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12705. // single gzip coding, and a body the sender says was encoded twice was handed
  12706. // back after one pass, still compressed but presented as decoded.
  12707. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12708. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12709. Server svr;
  12710. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12711. res.set_content(body, "image/jpeg");
  12712. res.headers.emplace("Content-Encoding", "gzip");
  12713. res.headers.emplace("Content-Encoding", "gzip");
  12714. });
  12715. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12716. res.set_content(body, "image/jpeg");
  12717. res.set_header("Content-Encoding", "gzip, gzip");
  12718. });
  12719. auto port = svr.bind_to_any_port(HOST);
  12720. thread t = thread([&]() { svr.listen_after_bind(); });
  12721. auto se = detail::scope_exit([&] {
  12722. svr.stop();
  12723. t.join();
  12724. ASSERT_FALSE(svr.is_running());
  12725. });
  12726. svr.wait_until_ready();
  12727. Client cli(HOST, port);
  12728. // Two codings is not something cpp-httplib decodes, so both representations
  12729. // take the pass-through path rather than one of them being gunzipped once.
  12730. for (const char *path : {"/split", "/joined"}) {
  12731. auto res = cli.Get(path);
  12732. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12733. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12734. EXPECT_EQ(body, res->body) << path;
  12735. }
  12736. }
  12737. // Regression test for DoS vulnerability: a malicious server sending a response
  12738. // without Content-Length header must not cause unbounded memory consumption on
  12739. // the client side. The client should stop reading after a reasonable limit,
  12740. // similar to the server-side set_payload_max_length protection.
  12741. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12742. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12743. #ifndef _WIN32
  12744. signal(SIGPIPE, SIG_IGN);
  12745. #endif
  12746. auto server_thread = std::thread([] {
  12747. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12748. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12749. default_socket_options(srv);
  12750. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12751. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12752. sockaddr_in addr{};
  12753. addr.sin_family = AF_INET;
  12754. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12755. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12756. int opt = 1;
  12757. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12758. #ifdef _WIN32
  12759. reinterpret_cast<const char *>(&opt),
  12760. #else
  12761. &opt,
  12762. #endif
  12763. sizeof(opt));
  12764. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12765. ::listen(srv, 1);
  12766. sockaddr_in cli_addr{};
  12767. socklen_t cli_len = sizeof(cli_addr);
  12768. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12769. if (cli != INVALID_SOCKET) {
  12770. char buf[4096];
  12771. ::recv(cli, buf, sizeof(buf), 0);
  12772. // Malicious response: no Content-Length, no chunked encoding
  12773. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12774. "Connection: close\r\n"
  12775. "\r\n";
  12776. ::send(cli,
  12777. #ifdef _WIN32
  12778. static_cast<const char *>(response_header.c_str()),
  12779. static_cast<int>(response_header.size()),
  12780. #else
  12781. response_header.c_str(), response_header.size(),
  12782. #endif
  12783. 0);
  12784. // Send 10MB of data
  12785. std::string chunk(64 * 1024, 'A');
  12786. size_t total_sent = 0;
  12787. while (total_sent < MALICIOUS_DATA_SIZE) {
  12788. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12789. auto sent = ::send(cli,
  12790. #ifdef _WIN32
  12791. static_cast<const char *>(chunk.c_str()),
  12792. static_cast<int>(to_send),
  12793. #else
  12794. chunk.c_str(), to_send,
  12795. #endif
  12796. 0);
  12797. if (sent <= 0) break;
  12798. total_sent += static_cast<size_t>(sent);
  12799. }
  12800. detail::close_socket(cli);
  12801. }
  12802. detail::close_socket(srv);
  12803. });
  12804. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12805. size_t total_read = 0;
  12806. {
  12807. Client cli("127.0.0.1", PORT + 2);
  12808. cli.set_read_timeout(5, 0);
  12809. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12810. auto stream = cli.open_stream("GET", "/malicious");
  12811. ASSERT_TRUE(stream.is_valid());
  12812. char buffer[64 * 1024];
  12813. ssize_t n;
  12814. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12815. total_read += static_cast<size_t>(n);
  12816. }
  12817. } // StreamHandle and Client destroyed here, closing the socket
  12818. server_thread.join();
  12819. // With set_payload_max_length, the client must stop reading before consuming
  12820. // all 10MB. The read loop should be cut off at or near the configured limit.
  12821. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12822. << "Client read " << total_read << " bytes, exceeding the configured "
  12823. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12824. }
  12825. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12826. // the entire response body without truncation.
  12827. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12828. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12829. #ifndef _WIN32
  12830. signal(SIGPIPE, SIG_IGN);
  12831. #endif
  12832. auto server_thread = std::thread([] {
  12833. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12834. default_socket_options(srv);
  12835. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12836. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12837. sockaddr_in addr{};
  12838. addr.sin_family = AF_INET;
  12839. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12840. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12841. int opt = 1;
  12842. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12843. #ifdef _WIN32
  12844. reinterpret_cast<const char *>(&opt),
  12845. #else
  12846. &opt,
  12847. #endif
  12848. sizeof(opt));
  12849. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12850. ::listen(srv, 1);
  12851. sockaddr_in cli_addr{};
  12852. socklen_t cli_len = sizeof(cli_addr);
  12853. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12854. if (cli != INVALID_SOCKET) {
  12855. char buf[4096];
  12856. ::recv(cli, buf, sizeof(buf), 0);
  12857. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12858. "Connection: close\r\n"
  12859. "\r\n";
  12860. ::send(cli,
  12861. #ifdef _WIN32
  12862. static_cast<const char *>(response_header.c_str()),
  12863. static_cast<int>(response_header.size()),
  12864. #else
  12865. response_header.c_str(), response_header.size(),
  12866. #endif
  12867. 0);
  12868. std::string chunk(64 * 1024, 'A');
  12869. size_t total_sent = 0;
  12870. while (total_sent < DATA_SIZE) {
  12871. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12872. auto sent = ::send(cli,
  12873. #ifdef _WIN32
  12874. static_cast<const char *>(chunk.c_str()),
  12875. static_cast<int>(to_send),
  12876. #else
  12877. chunk.c_str(), to_send,
  12878. #endif
  12879. 0);
  12880. if (sent <= 0) break;
  12881. total_sent += static_cast<size_t>(sent);
  12882. }
  12883. #ifdef _WIN32
  12884. ::shutdown(cli, SD_SEND);
  12885. #else
  12886. ::shutdown(cli, SHUT_WR);
  12887. #endif
  12888. // Drain until the client closes its end, ensuring all data is delivered
  12889. char drain[1024];
  12890. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12891. detail::close_socket(cli);
  12892. }
  12893. detail::close_socket(srv);
  12894. });
  12895. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12896. size_t total_read = 0;
  12897. {
  12898. Client cli("127.0.0.1", PORT + 2);
  12899. cli.set_read_timeout(5, 0);
  12900. cli.set_payload_max_length(0); // 0 means no limit
  12901. auto stream = cli.open_stream("GET", "/data");
  12902. ASSERT_TRUE(stream.is_valid());
  12903. char buffer[64 * 1024];
  12904. ssize_t n;
  12905. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12906. total_read += static_cast<size_t>(n);
  12907. }
  12908. }
  12909. server_thread.join();
  12910. EXPECT_EQ(total_read, DATA_SIZE)
  12911. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12912. << " bytes without truncation, but only read " << total_read << " bytes.";
  12913. }
  12914. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12915. // enormous Content-Length must not cause the client to pre-allocate a huge
  12916. // response body buffer. The reservation is capped at payload_max_length_, and
  12917. // the read itself fails when the body exceeds the limit.
  12918. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12919. #ifndef _WIN32
  12920. signal(SIGPIPE, SIG_IGN);
  12921. #endif
  12922. auto server_thread = std::thread([] {
  12923. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12924. default_socket_options(srv);
  12925. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12926. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12927. sockaddr_in addr{};
  12928. addr.sin_family = AF_INET;
  12929. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12930. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12931. int opt = 1;
  12932. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12933. #ifdef _WIN32
  12934. reinterpret_cast<const char *>(&opt),
  12935. #else
  12936. &opt,
  12937. #endif
  12938. sizeof(opt));
  12939. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12940. ::listen(srv, 1);
  12941. sockaddr_in cli_addr{};
  12942. socklen_t cli_len = sizeof(cli_addr);
  12943. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12944. if (cli != INVALID_SOCKET) {
  12945. char buf[4096];
  12946. ::recv(cli, buf, sizeof(buf), 0);
  12947. // Malicious response: claim a 20GB body but send only a tiny payload.
  12948. std::string response = "HTTP/1.1 200 OK\r\n"
  12949. "Content-Length: 20000000000\r\n"
  12950. "\r\n"
  12951. "abc";
  12952. ::send(cli,
  12953. #ifdef _WIN32
  12954. static_cast<const char *>(response.c_str()),
  12955. static_cast<int>(response.size()),
  12956. #else
  12957. response.c_str(), response.size(),
  12958. #endif
  12959. 0);
  12960. detail::close_socket(cli);
  12961. }
  12962. detail::close_socket(srv);
  12963. });
  12964. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12965. {
  12966. Client cli("127.0.0.1", PORT + 2);
  12967. cli.set_read_timeout(5, 0);
  12968. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12969. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12970. // (server claims more bytes than payload_max_length permits), but it must
  12971. // not exhaust memory before getting there.
  12972. auto res = cli.Get("/malicious");
  12973. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12974. }
  12975. server_thread.join();
  12976. }
  12977. // Verify that content_receiver bypasses the default payload_max_length,
  12978. // allowing streaming downloads larger than 100MB without requiring an explicit
  12979. // set_payload_max_length call.
  12980. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12981. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12982. #ifndef _WIN32
  12983. signal(SIGPIPE, SIG_IGN);
  12984. #endif
  12985. auto server_thread = std::thread([] {
  12986. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12987. default_socket_options(srv);
  12988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12990. sockaddr_in addr{};
  12991. addr.sin_family = AF_INET;
  12992. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12993. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12994. int opt = 1;
  12995. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12996. #ifdef _WIN32
  12997. reinterpret_cast<const char *>(&opt),
  12998. #else
  12999. &opt,
  13000. #endif
  13001. sizeof(opt));
  13002. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13003. ::listen(srv, 1);
  13004. sockaddr_in cli_addr{};
  13005. socklen_t cli_len = sizeof(cli_addr);
  13006. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13007. if (cli != INVALID_SOCKET) {
  13008. char buf[4096];
  13009. ::recv(cli, buf, sizeof(buf), 0);
  13010. // Response with Content-Length larger than default 100MB limit
  13011. auto content_length = std::to_string(DATA_SIZE);
  13012. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13013. "Content-Length: " +
  13014. content_length +
  13015. "\r\n"
  13016. "Connection: close\r\n"
  13017. "\r\n";
  13018. ::send(cli,
  13019. #ifdef _WIN32
  13020. static_cast<const char *>(response_header.c_str()),
  13021. static_cast<int>(response_header.size()),
  13022. #else
  13023. response_header.c_str(), response_header.size(),
  13024. #endif
  13025. 0);
  13026. std::string chunk(64 * 1024, 'A');
  13027. size_t total_sent = 0;
  13028. while (total_sent < DATA_SIZE) {
  13029. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13030. auto sent = ::send(cli,
  13031. #ifdef _WIN32
  13032. static_cast<const char *>(chunk.c_str()),
  13033. static_cast<int>(to_send),
  13034. #else
  13035. chunk.c_str(), to_send,
  13036. #endif
  13037. 0);
  13038. if (sent <= 0) break;
  13039. total_sent += static_cast<size_t>(sent);
  13040. }
  13041. detail::close_socket(cli);
  13042. }
  13043. detail::close_socket(srv);
  13044. });
  13045. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13046. size_t total_received = 0;
  13047. {
  13048. Client cli("127.0.0.1", PORT + 2);
  13049. cli.set_read_timeout(10, 0);
  13050. // Do NOT call set_payload_max_length — use the default 100MB limit
  13051. auto res =
  13052. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13053. total_received += data_length;
  13054. return true;
  13055. });
  13056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13057. EXPECT_EQ(StatusCode::OK_200, res->status);
  13058. }
  13059. server_thread.join();
  13060. EXPECT_EQ(total_received, DATA_SIZE)
  13061. << "With content_receiver, the client should read all " << DATA_SIZE
  13062. << " bytes despite the default 100MB payload_max_length, but only read "
  13063. << total_received << " bytes.";
  13064. }
  13065. // Verify that an explicit set_payload_max_length smaller than the response is
  13066. // enforced even when a content_receiver is used.
  13067. TEST(ClientVulnerabilityTest,
  13068. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13069. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13070. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13071. #ifndef _WIN32
  13072. signal(SIGPIPE, SIG_IGN);
  13073. #endif
  13074. auto server_thread = std::thread([] {
  13075. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13076. default_socket_options(srv);
  13077. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13078. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13079. sockaddr_in addr{};
  13080. addr.sin_family = AF_INET;
  13081. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13082. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13083. int opt = 1;
  13084. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13085. #ifdef _WIN32
  13086. reinterpret_cast<const char *>(&opt),
  13087. #else
  13088. &opt,
  13089. #endif
  13090. sizeof(opt));
  13091. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13092. ::listen(srv, 1);
  13093. sockaddr_in cli_addr{};
  13094. socklen_t cli_len = sizeof(cli_addr);
  13095. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13096. if (cli != INVALID_SOCKET) {
  13097. char buf[4096];
  13098. ::recv(cli, buf, sizeof(buf), 0);
  13099. auto content_length = std::to_string(DATA_SIZE);
  13100. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13101. "Content-Length: " +
  13102. content_length +
  13103. "\r\n"
  13104. "Connection: close\r\n"
  13105. "\r\n";
  13106. ::send(cli,
  13107. #ifdef _WIN32
  13108. static_cast<const char *>(response_header.c_str()),
  13109. static_cast<int>(response_header.size()),
  13110. #else
  13111. response_header.c_str(), response_header.size(),
  13112. #endif
  13113. 0);
  13114. std::string chunk(64 * 1024, 'A');
  13115. size_t total_sent = 0;
  13116. while (total_sent < DATA_SIZE) {
  13117. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13118. auto sent = ::send(cli,
  13119. #ifdef _WIN32
  13120. static_cast<const char *>(chunk.c_str()),
  13121. static_cast<int>(to_send),
  13122. #else
  13123. chunk.c_str(), to_send,
  13124. #endif
  13125. 0);
  13126. if (sent <= 0) break;
  13127. total_sent += static_cast<size_t>(sent);
  13128. }
  13129. detail::close_socket(cli);
  13130. }
  13131. detail::close_socket(srv);
  13132. });
  13133. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13134. size_t total_received = 0;
  13135. {
  13136. Client cli("127.0.0.1", PORT + 2);
  13137. cli.set_read_timeout(10, 0);
  13138. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13139. auto res =
  13140. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13141. total_received += data_length;
  13142. return true;
  13143. });
  13144. // Should fail because 200MB exceeds the explicit 150MB limit
  13145. EXPECT_FALSE(res);
  13146. }
  13147. server_thread.join();
  13148. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13149. << "Client with content_receiver should respect the explicit "
  13150. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13151. << total_received << " bytes.";
  13152. }
  13153. // Verify that an explicit set_payload_max_length larger than the response
  13154. // allows the content_receiver to read all data successfully.
  13155. TEST(ClientVulnerabilityTest,
  13156. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13157. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13158. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13159. #ifndef _WIN32
  13160. signal(SIGPIPE, SIG_IGN);
  13161. #endif
  13162. auto server_thread = std::thread([] {
  13163. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13164. default_socket_options(srv);
  13165. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13166. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13167. sockaddr_in addr{};
  13168. addr.sin_family = AF_INET;
  13169. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13170. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13171. int opt = 1;
  13172. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13173. #ifdef _WIN32
  13174. reinterpret_cast<const char *>(&opt),
  13175. #else
  13176. &opt,
  13177. #endif
  13178. sizeof(opt));
  13179. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13180. ::listen(srv, 1);
  13181. sockaddr_in cli_addr{};
  13182. socklen_t cli_len = sizeof(cli_addr);
  13183. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13184. if (cli != INVALID_SOCKET) {
  13185. char buf[4096];
  13186. ::recv(cli, buf, sizeof(buf), 0);
  13187. auto content_length = std::to_string(DATA_SIZE);
  13188. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13189. "Content-Length: " +
  13190. content_length +
  13191. "\r\n"
  13192. "Connection: close\r\n"
  13193. "\r\n";
  13194. ::send(cli,
  13195. #ifdef _WIN32
  13196. static_cast<const char *>(response_header.c_str()),
  13197. static_cast<int>(response_header.size()),
  13198. #else
  13199. response_header.c_str(), response_header.size(),
  13200. #endif
  13201. 0);
  13202. std::string chunk(64 * 1024, 'A');
  13203. size_t total_sent = 0;
  13204. while (total_sent < DATA_SIZE) {
  13205. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13206. auto sent = ::send(cli,
  13207. #ifdef _WIN32
  13208. static_cast<const char *>(chunk.c_str()),
  13209. static_cast<int>(to_send),
  13210. #else
  13211. chunk.c_str(), to_send,
  13212. #endif
  13213. 0);
  13214. if (sent <= 0) break;
  13215. total_sent += static_cast<size_t>(sent);
  13216. }
  13217. #ifdef _WIN32
  13218. ::shutdown(cli, SD_SEND);
  13219. #else
  13220. ::shutdown(cli, SHUT_WR);
  13221. #endif
  13222. char drain[1024];
  13223. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13224. detail::close_socket(cli);
  13225. }
  13226. detail::close_socket(srv);
  13227. });
  13228. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13229. size_t total_received = 0;
  13230. {
  13231. Client cli("127.0.0.1", PORT + 2);
  13232. cli.set_read_timeout(10, 0);
  13233. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13234. auto res =
  13235. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13236. total_received += data_length;
  13237. return true;
  13238. });
  13239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13240. EXPECT_EQ(StatusCode::OK_200, res->status);
  13241. }
  13242. server_thread.join();
  13243. EXPECT_EQ(total_received, DATA_SIZE)
  13244. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13245. << " bytes (larger than " << DATA_SIZE
  13246. << " bytes response), content_receiver should read all data, but only "
  13247. "read "
  13248. << total_received << " bytes.";
  13249. }
  13250. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13251. // Regression test for "zip bomb" attack on the client side: a malicious server
  13252. // sends a small gzip-compressed response that decompresses to a huge payload.
  13253. // The client must enforce payload_max_length on the decompressed size.
  13254. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13255. constexpr size_t DECOMPRESSED_SIZE =
  13256. 10 * 1024 * 1024; // 10MB after decompression
  13257. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13258. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13259. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13260. std::string compressed;
  13261. {
  13262. httplib::detail::gzip_compressor compressor;
  13263. bool ok =
  13264. compressor.compress(uncompressed.data(), uncompressed.size(),
  13265. /*last=*/true, [&](const char *buf, size_t len) {
  13266. compressed.append(buf, len);
  13267. return true;
  13268. });
  13269. ASSERT_TRUE(ok);
  13270. }
  13271. // Sanity: compressed data should be much smaller than the decompressed size
  13272. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13273. #ifndef _WIN32
  13274. signal(SIGPIPE, SIG_IGN);
  13275. #endif
  13276. // Set up the listening socket in the main thread so the server is guaranteed
  13277. // to be ready before the client connects (eliminates race condition).
  13278. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13279. default_socket_options(srv);
  13280. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13281. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13282. sockaddr_in addr{};
  13283. addr.sin_family = AF_INET;
  13284. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13285. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13286. int opt = 1;
  13287. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13288. #ifdef _WIN32
  13289. reinterpret_cast<const char *>(&opt),
  13290. #else
  13291. &opt,
  13292. #endif
  13293. sizeof(opt));
  13294. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13295. ASSERT_EQ(0, ::listen(srv, 1));
  13296. auto server_thread = std::thread([&compressed, srv] {
  13297. sockaddr_in cli_addr{};
  13298. socklen_t cli_len = sizeof(cli_addr);
  13299. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13300. if (cli != INVALID_SOCKET) {
  13301. // Read the full HTTP request (until \r\n\r\n)
  13302. char buf[4096];
  13303. size_t total = 0;
  13304. while (total < sizeof(buf)) {
  13305. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13306. if (n <= 0) break;
  13307. total += static_cast<size_t>(n);
  13308. // Check for end of headers
  13309. if (total >= 4) {
  13310. std::string req(buf, total);
  13311. if (req.find("\r\n\r\n") != std::string::npos) break;
  13312. }
  13313. }
  13314. // Malicious response: gzip-compressed body, no Content-Length
  13315. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13316. "Content-Encoding: gzip\r\n"
  13317. "Connection: close\r\n"
  13318. "\r\n";
  13319. ::send(cli,
  13320. #ifdef _WIN32
  13321. static_cast<const char *>(response_header.c_str()),
  13322. static_cast<int>(response_header.size()),
  13323. #else
  13324. response_header.c_str(), response_header.size(),
  13325. #endif
  13326. 0);
  13327. // Send the compressed payload (small on the wire, huge when decompressed)
  13328. size_t total_sent = 0;
  13329. while (total_sent < compressed.size()) {
  13330. auto to_send = std::min(compressed.size() - total_sent,
  13331. static_cast<size_t>(64 * 1024));
  13332. auto sent =
  13333. ::send(cli,
  13334. #ifdef _WIN32
  13335. static_cast<const char *>(compressed.c_str() + total_sent),
  13336. static_cast<int>(to_send),
  13337. #else
  13338. compressed.c_str() + total_sent, to_send,
  13339. #endif
  13340. 0);
  13341. if (sent <= 0) break;
  13342. total_sent += static_cast<size_t>(sent);
  13343. }
  13344. detail::close_socket(cli);
  13345. }
  13346. });
  13347. auto se = detail::scope_exit([&] {
  13348. detail::close_socket(srv);
  13349. server_thread.join();
  13350. });
  13351. size_t total_decompressed = 0;
  13352. {
  13353. Client cli("127.0.0.1", PORT + 3);
  13354. cli.set_read_timeout(5, 0);
  13355. cli.set_decompress(true);
  13356. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13357. auto stream = cli.open_stream("GET", "/zipbomb");
  13358. ASSERT_TRUE(stream.is_valid());
  13359. char buffer[64 * 1024];
  13360. ssize_t n;
  13361. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13362. total_decompressed += static_cast<size_t>(n);
  13363. }
  13364. }
  13365. // The decompressed size must be capped by payload_max_length. Without
  13366. // protection, the client would decompress the full 10MB from a tiny
  13367. // compressed payload, enabling a zip bomb DoS attack.
  13368. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13369. << "Client decompressed " << total_decompressed
  13370. << " bytes from a gzip response. The decompressed size should be "
  13371. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13372. }
  13373. #endif
  13374. TEST(HostAndPortPropertiesTest, NoSSL) {
  13375. httplib::Client cli("www.google.com", 1234);
  13376. ASSERT_EQ("www.google.com", cli.host());
  13377. ASSERT_EQ(1234, cli.port());
  13378. }
  13379. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13380. httplib::Client cli("www.google.com:1234");
  13381. ASSERT_EQ("www.google.com", cli.host());
  13382. ASSERT_EQ(1234, cli.port());
  13383. }
  13384. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13385. // Port number that overflows int — should not crash, client becomes invalid
  13386. httplib::Client cli("http://www.google.com:99999999999999999999");
  13387. ASSERT_FALSE(cli.is_valid());
  13388. }
  13389. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13390. // Port 99999 exceeds valid range (1-65535) — should not crash
  13391. httplib::Client cli("http://www.google.com:99999");
  13392. ASSERT_FALSE(cli.is_valid());
  13393. auto res = cli.Get("/");
  13394. EXPECT_FALSE(res);
  13395. EXPECT_EQ(Error::Connection, res.error());
  13396. }
  13397. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13398. httplib::Client cli("http://user:pass@localhost:1234");
  13399. ASSERT_FALSE(cli.is_valid());
  13400. EXPECT_FALSE(cli.Get("/"));
  13401. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13402. }
  13403. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13404. httplib::Client cli("http://www.google.com:80abc");
  13405. ASSERT_FALSE(cli.is_valid());
  13406. }
  13407. #ifdef CPPHTTPLIB_SSL_ENABLED
  13408. TEST(HostAndPortPropertiesTest, SSL) {
  13409. httplib::SSLClient cli("www.google.com");
  13410. ASSERT_EQ("www.google.com", cli.host());
  13411. ASSERT_EQ(443, cli.port());
  13412. }
  13413. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13414. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13415. std::string cert;
  13416. read_file(CA_CERT_FILE, cert);
  13417. httplib::SSLClient httplib_client("www.google.com");
  13418. // Load CA store first time
  13419. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13420. // Load CA store second time (update)
  13421. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13422. // Verify client is still valid and can make connections
  13423. httplib_client.enable_server_certificate_verification(true);
  13424. auto res = httplib_client.Get("/");
  13425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13426. // Google may return 200 or 301 depending on various factors
  13427. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13428. res->status == StatusCode::MovedPermanently_301);
  13429. }
  13430. TEST(SSLClientTest, ServerNameIndication_Online) {
  13431. auto host = "httpbingo.org";
  13432. auto path = std::string{"/get"};
  13433. SSLClient cli(host, 443);
  13434. auto res = cli.Get(path);
  13435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13436. ASSERT_EQ(StatusCode::OK_200, res->status);
  13437. }
  13438. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13439. // Use a site that will cause SSL verification failure due to self-signed cert
  13440. SSLClient cli("self-signed.badssl.com", 443);
  13441. cli.enable_server_certificate_verification(true);
  13442. auto res = cli.Get("/");
  13443. ASSERT_TRUE(!res);
  13444. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13445. // Verify backend error is captured for SSLServerVerification
  13446. // This occurs when certificate verification fails
  13447. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13448. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13449. EXPECT_NE(0UL, res.ssl_backend_error());
  13450. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13451. res.ssl_error());
  13452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13453. #if !defined(_WIN32) || \
  13454. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13455. // On non-Windows or when Windows Schannel is disabled, the error comes
  13456. // from OpenSSL's verification
  13457. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13458. res.ssl_backend_error());
  13459. #endif
  13460. #endif
  13461. }
  13462. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13463. // Use a site where hostname doesn't match the certificate
  13464. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13465. SSLClient cli("wrong.host.badssl.com", 443);
  13466. cli.enable_server_certificate_verification(true);
  13467. cli.enable_server_hostname_verification(true);
  13468. auto res = cli.Get("/");
  13469. ASSERT_TRUE(!res);
  13470. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13471. // Verify backend error is captured for hostname verification failure
  13472. EXPECT_NE(0UL, res.ssl_backend_error());
  13473. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13474. res.ssl_error());
  13475. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13476. #if !defined(_WIN32) || \
  13477. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13478. // On non-Windows or when Windows Schannel is disabled, the error comes
  13479. // from OpenSSL's hostname verification
  13480. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13481. res.ssl_backend_error());
  13482. #endif
  13483. #endif
  13484. }
  13485. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13486. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13487. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13488. SSLClient cli("www.google.com", 443);
  13489. cli.enable_server_certificate_verification(true);
  13490. auto res = cli.Get("/");
  13491. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13492. }
  13493. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13494. SSLClient cli("www.google.com", 443);
  13495. cli.enable_server_certificate_verification(true);
  13496. cli.enable_windows_certificate_verification(false);
  13497. auto res = cli.Get("/");
  13498. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13499. }
  13500. // The server sends an intermediate cross-signed by a root Windows trusts,
  13501. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13502. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13503. SSLClient cli("accounts.spotify.com", 443);
  13504. auto res = cli.Get("/");
  13505. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13506. << " ssl_backend_error=" << res.ssl_backend_error();
  13507. }
  13508. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13509. // policy status, which no backend reports for a self-signed certificate.
  13510. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13511. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13512. ASSERT_TRUE(svr.is_valid());
  13513. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13514. auto se = detail::scope_exit([&] {
  13515. svr.stop();
  13516. t.join();
  13517. ASSERT_FALSE(svr.is_running());
  13518. });
  13519. svr.wait_until_ready();
  13520. SSLClient cli("127.0.0.1", PORT);
  13521. cli.set_connection_timeout(30);
  13522. auto res = cli.Get("/");
  13523. ASSERT_FALSE(res);
  13524. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13525. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13526. }
  13527. #endif
  13528. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13529. Client cli("https://google.com");
  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, ServerCertificateVerification2_Online) {
  13535. SSLClient cli("google.com");
  13536. cli.set_ca_cert_path(CA_CERT_FILE);
  13537. auto res = cli.Get("/");
  13538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13539. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13540. }
  13541. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13542. SSLClient cli("google.com");
  13543. cli.enable_server_certificate_verification(true);
  13544. cli.set_ca_cert_path("hello");
  13545. auto res = cli.Get("/");
  13546. ASSERT_TRUE(!res);
  13547. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13548. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13549. // should be set
  13550. EXPECT_EQ(0, res.ssl_error());
  13551. // Verify backend error is captured for SSLLoadingCerts
  13552. // This error occurs when loading CA certificates fails
  13553. EXPECT_NE(0UL, res.ssl_backend_error());
  13554. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13555. // OpenSSL specific error codes:
  13556. // > openssl errstr 0x80000002
  13557. // error:80000002:system library::No such file or directory
  13558. // > openssl errstr 0xA000126
  13559. // error:0A000126:SSL routines::unexpected eof while reading
  13560. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13561. res.ssl_backend_error() == 0xA000126);
  13562. #endif
  13563. }
  13564. TEST(SSLClientTest, ServerCertificateVerification4) {
  13565. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13566. ASSERT_TRUE(svr.is_valid());
  13567. svr.Get("/test", [&](const Request &, Response &res) {
  13568. res.set_content("test", "text/plain");
  13569. svr.stop();
  13570. ASSERT_TRUE(true);
  13571. });
  13572. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13573. auto se = detail::scope_exit([&] {
  13574. t.join();
  13575. ASSERT_FALSE(svr.is_running());
  13576. });
  13577. svr.wait_until_ready();
  13578. SSLClient cli("127.0.0.1", PORT);
  13579. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13580. cli.enable_server_certificate_verification(true);
  13581. cli.set_connection_timeout(30);
  13582. auto res = cli.Get("/test");
  13583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13584. ASSERT_EQ(StatusCode::OK_200, res->status);
  13585. }
  13586. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13587. std::string cert;
  13588. read_file(CA_CERT_FILE, cert);
  13589. SSLClient cli("google.com");
  13590. cli.load_ca_cert_store(cert.data(), cert.size());
  13591. const auto res = cli.Get("/");
  13592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13593. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13594. }
  13595. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13596. // clang-format off
  13597. static constexpr char cert[] =
  13598. "GlobalSign Root CA\n"
  13599. "==================\n"
  13600. "-----BEGIN CERTIFICATE-----\n"
  13601. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13602. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13603. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13604. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13605. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13606. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13607. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13608. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13609. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13610. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13611. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13612. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13613. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13614. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13615. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13616. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13617. "-----END CERTIFICATE-----\n";
  13618. // clang-format on
  13619. SSLClient cli("google.com");
  13620. cli.load_ca_cert_store(cert, sizeof(cert));
  13621. const auto res = cli.Get("/");
  13622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13623. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13624. }
  13625. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13626. SSLClient cli("www.youtube.com");
  13627. cli.set_ca_cert_path(CA_CERT_FILE);
  13628. cli.enable_server_certificate_verification(true);
  13629. cli.set_follow_location(true);
  13630. auto res = cli.Get("/");
  13631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13632. ASSERT_EQ(StatusCode::OK_200, res->status);
  13633. }
  13634. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13635. SSLClient cli("wWw.YouTube.Com");
  13636. cli.set_ca_cert_path(CA_CERT_FILE);
  13637. cli.enable_server_certificate_verification(true);
  13638. cli.enable_server_hostname_verification(true);
  13639. cli.set_follow_location(true);
  13640. auto res = cli.Get("/");
  13641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13642. ASSERT_EQ(StatusCode::OK_200, res->status);
  13643. }
  13644. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13645. SSLClient cli("gOoGlE.COm");
  13646. cli.enable_server_certificate_verification(true);
  13647. cli.enable_server_hostname_verification(true);
  13648. cli.set_follow_location(true);
  13649. auto res = cli.Get("/");
  13650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13651. ASSERT_EQ(StatusCode::OK_200, res->status);
  13652. }
  13653. TEST(SSLClientTest, Issue2004_Online) {
  13654. Client client("https://google.com");
  13655. client.set_follow_location(true);
  13656. auto res = client.Get("/");
  13657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13658. ASSERT_EQ(StatusCode::OK_200, res->status);
  13659. auto body = res->body;
  13660. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13661. }
  13662. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13663. // Create SSLClient with invalid cert/key to make is_valid() return false
  13664. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13665. "nonexistent_key.pem");
  13666. // is_valid() should be false due to cert loading failure
  13667. ASSERT_FALSE(cli.is_valid());
  13668. auto res = cli.Get("/");
  13669. ASSERT_FALSE(res);
  13670. EXPECT_EQ(Error::SSLConnection, res.error());
  13671. }
  13672. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13673. // Test for Issue #2251: SSL error not properly reported when client cert
  13674. // and key paths are swapped or mismatched
  13675. // This simulates the scenario where user accidentally swaps the cert and key
  13676. // files
  13677. // Using client cert file as private key and vice versa (completely wrong)
  13678. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13679. // Should fail validation due to cert/key mismatch
  13680. ASSERT_FALSE(cli.is_valid());
  13681. // Attempt to make a request should fail with proper error
  13682. auto res = cli.Get("/");
  13683. ASSERT_FALSE(res);
  13684. EXPECT_EQ(Error::SSLConnection, res.error());
  13685. // SSL error should be recorded in the Result object (this is the key fix for
  13686. // Issue #2251)
  13687. auto backend_error = res.ssl_backend_error();
  13688. EXPECT_NE(0u, backend_error);
  13689. }
  13690. // Tests cert/key mismatch detection at the TLS context level
  13691. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13692. // Test that using mismatched cert/key causes connection failure.
  13693. // We verify this at the SSLClient level rather than through internal
  13694. // TLS API functions.
  13695. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13696. cli.enable_server_certificate_verification(false);
  13697. cli.set_connection_timeout(2);
  13698. // The mismatch should cause a connection or handshake error
  13699. auto res = cli.Get("/test");
  13700. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13701. // Either way, the request should fail
  13702. EXPECT_FALSE(res);
  13703. }
  13704. #endif
  13705. #if 0
  13706. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13707. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13708. ASSERT_TRUE(cli != nullptr);
  13709. cli->set_address_family(AF_INET6);
  13710. cli->set_interface("en0");
  13711. auto res = cli->Get("/get");
  13712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13713. ASSERT_EQ(StatusCode::OK_200, res->status);
  13714. }
  13715. #endif
  13716. // Client certificate tests - work with all TLS backends
  13717. #ifdef CPPHTTPLIB_SSL_ENABLED
  13718. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13719. void ClientCertPresent(
  13720. const std::string &client_cert_file,
  13721. const std::string &client_private_key_file,
  13722. const std::string &client_encrypted_private_key_pass = std::string(),
  13723. const ClientCertServerSetup &setup = nullptr) {
  13724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13725. ASSERT_TRUE(svr.is_valid());
  13726. if (setup) { setup(svr); }
  13727. svr.Get("/test", [&](const Request &req, Response &res) {
  13728. res.set_content("test", "text/plain");
  13729. auto cert = req.peer_cert();
  13730. ASSERT_TRUE(static_cast<bool>(cert));
  13731. std::string common_name = cert.subject_cn();
  13732. EXPECT_EQ("Common Name", common_name);
  13733. });
  13734. auto port = svr.bind_to_any_port(HOST);
  13735. ASSERT_LT(0, port);
  13736. thread t = thread([&]() { svr.listen_after_bind(); });
  13737. auto se = detail::scope_exit([&] {
  13738. svr.stop();
  13739. t.join();
  13740. ASSERT_FALSE(svr.is_running());
  13741. });
  13742. svr.wait_until_ready();
  13743. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13744. client_encrypted_private_key_pass);
  13745. cli.enable_server_certificate_verification(false);
  13746. cli.set_connection_timeout(30);
  13747. auto res = cli.Get("/test");
  13748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13749. ASSERT_EQ(StatusCode::OK_200, res->status);
  13750. }
  13751. TEST(SSLClientServerTest, ClientCertPresent) {
  13752. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13753. }
  13754. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13755. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13756. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13757. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13758. }
  13759. // Expects svr, which must require client certificates, to reject a client
  13760. // that has none
  13761. void RejectsClientWithoutCert(SSLServer &svr) {
  13762. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13763. auto port = svr.bind_to_any_port(HOST);
  13764. ASSERT_LT(0, port);
  13765. thread t = thread([&]() { svr.listen_after_bind(); });
  13766. auto se = detail::scope_exit([&] {
  13767. svr.stop();
  13768. t.join();
  13769. ASSERT_FALSE(svr.is_running());
  13770. });
  13771. svr.wait_until_ready();
  13772. SSLClient cli(HOST, port);
  13773. cli.set_connection_timeout(30);
  13774. // Skip the server certificate check, so that the request fails because the
  13775. // client certificate is missing rather than because cert.pem is not trusted
  13776. cli.enable_server_certificate_verification(false);
  13777. auto res = cli.Get("/test");
  13778. ASSERT_FALSE(res);
  13779. // The server rejects the client during the handshake, or on TLS 1.3 right
  13780. // after it, which the client notices on its first write or read
  13781. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13782. res.error() == Error::Write || res.error() == Error::Read)
  13783. << to_string(res.error());
  13784. if (res.error() == Error::SSLConnection) {
  13785. EXPECT_NE(0UL, res.ssl_backend_error());
  13786. }
  13787. // A rejection noticed on the write keeps the TLS error the write hit
  13788. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13789. }
  13790. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13791. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13792. ASSERT_TRUE(svr.is_valid());
  13793. if (setup) { setup(svr); }
  13794. RejectsClientWithoutCert(svr);
  13795. }
  13796. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13797. // A server that requires client certificates must keep requiring them after
  13798. // setup changes it, and keep accepting a client that has one
  13799. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13800. ClientCertMissing(setup);
  13801. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13802. setup);
  13803. }
  13804. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13805. ClientCertStillRequired([](SSLServer &svr) {
  13806. ASSERT_TRUE(tls::set_verify_callback(
  13807. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13808. });
  13809. }
  13810. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13811. ClientCertStillRequired([](SSLServer &svr) {
  13812. ASSERT_TRUE(tls::set_verify_callback(
  13813. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13814. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13815. });
  13816. }
  13817. // The client verifies the server certificate during the handshake, so a
  13818. // server that fails the check never gets the client certificate, even when a
  13819. // verifier of the client's own accepts it
  13820. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13821. struct Case {
  13822. const char *trusted_ca;
  13823. const char *host;
  13824. Error error;
  13825. };
  13826. // cert2.pem names localhost: the first client does not trust it, and the
  13827. // second trusts it but asks for another name
  13828. for (const auto &c :
  13829. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13830. Case{SERVER_CERT2_FILE, "example.com",
  13831. Error::SSLServerHostnameVerification}}) {
  13832. for (auto with_verifier : {false, true}) {
  13833. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13834. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13835. CLIENT_CA_CERT_FILE);
  13836. ASSERT_TRUE(svr.is_valid());
  13837. std::atomic<bool> got_client_cert{false};
  13838. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13839. [&](const tls::VerifyContext &) {
  13840. got_client_cert = true;
  13841. return true;
  13842. }));
  13843. auto port = svr.bind_to_any_port("127.0.0.1");
  13844. ASSERT_LT(0, port);
  13845. thread t = thread([&] { svr.listen_after_bind(); });
  13846. svr.wait_until_ready();
  13847. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13848. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13849. cli.set_ca_cert_path(c.trusted_ca);
  13850. if (with_verifier) {
  13851. cli.set_server_certificate_verifier(
  13852. [](const tls::VerifyContext &) { return true; });
  13853. }
  13854. auto res = cli.Get("/");
  13855. EXPECT_FALSE(res);
  13856. EXPECT_EQ(c.error, res.error());
  13857. svr.stop();
  13858. t.join();
  13859. EXPECT_FALSE(got_client_cert);
  13860. }
  13861. }
  13862. }
  13863. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13864. std::string cert_pem, key_pem, ca_pem;
  13865. read_file(SERVER_CERT_FILE, cert_pem);
  13866. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13867. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13868. ASSERT_TRUE(
  13869. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13870. }
  13871. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13873. ASSERT_TRUE(svr.is_valid());
  13874. UpdateCertsPemWithClientCA(svr);
  13875. RejectsClientWithoutCert(svr);
  13876. }
  13877. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13878. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13879. }
  13880. // A TLS error from one request must not show up in a later request's Result
  13881. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13882. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13883. ASSERT_TRUE(svr.is_valid());
  13884. svr.Get("/test", [](const Request &, Response &res) {
  13885. res.set_content("test", "text/plain");
  13886. });
  13887. auto port = svr.bind_to_any_port(HOST);
  13888. ASSERT_LT(0, port);
  13889. thread t = thread([&]() { svr.listen_after_bind(); });
  13890. auto se = detail::scope_exit([&] {
  13891. svr.stop();
  13892. t.join();
  13893. ASSERT_FALSE(svr.is_running());
  13894. });
  13895. svr.wait_until_ready();
  13896. SSLClient cli(HOST, port);
  13897. cli.set_connection_timeout(30);
  13898. cli.enable_server_hostname_verification(false);
  13899. // cert.pem is not trusted, so the handshake fails
  13900. ASSERT_FALSE(cli.Get("/test"));
  13901. cli.enable_server_certificate_verification(false);
  13902. auto res = cli.Get("/test");
  13903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13904. EXPECT_EQ(0, res.ssl_error());
  13905. EXPECT_EQ(0UL, res.ssl_backend_error());
  13906. }
  13907. // PEM memory-based constructor tests (works with all TLS backends).
  13908. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13909. // terminator after it.
  13910. void PemMemoryClientCertPresent(
  13911. const std::string &client_cert_file,
  13912. const std::string &client_private_key_file,
  13913. const std::string &client_encrypted_private_key_pass = std::string(),
  13914. bool exact_size = false) {
  13915. // Read PEM files into memory
  13916. std::string server_cert_pem, server_key_pem;
  13917. std::string client_ca_pem;
  13918. std::string client_cert_pem, client_key_pem;
  13919. read_file(SERVER_CERT_FILE, server_cert_pem);
  13920. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13921. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13922. read_file(client_cert_file, client_cert_pem);
  13923. read_file(client_private_key_file, client_key_pem);
  13924. std::list<std::vector<char>> exact_copies;
  13925. auto data = [&](const std::string &pem) -> const char * {
  13926. if (!exact_size) { return pem.c_str(); }
  13927. exact_copies.emplace_back(pem.begin(), pem.end());
  13928. return exact_copies.back().data();
  13929. };
  13930. // Create server with PEM memory
  13931. SSLServer::PemMemory server_pem = {
  13932. data(server_cert_pem),
  13933. server_cert_pem.size(),
  13934. data(server_key_pem),
  13935. server_key_pem.size(),
  13936. data(client_ca_pem),
  13937. client_ca_pem.size(),
  13938. nullptr // no password for server key
  13939. };
  13940. SSLServer svr(server_pem);
  13941. ASSERT_TRUE(svr.is_valid());
  13942. svr.Get("/test", [&](const Request &req, Response &res) {
  13943. res.set_content("test", "text/plain");
  13944. auto cert = req.peer_cert();
  13945. ASSERT_TRUE(static_cast<bool>(cert));
  13946. EXPECT_EQ("Common Name", cert.subject_cn());
  13947. });
  13948. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13949. auto se = detail::scope_exit([&] {
  13950. svr.stop();
  13951. t.join();
  13952. ASSERT_FALSE(svr.is_running());
  13953. });
  13954. svr.wait_until_ready();
  13955. // Create client with PEM memory
  13956. const char *password = client_encrypted_private_key_pass.empty()
  13957. ? nullptr
  13958. : client_encrypted_private_key_pass.c_str();
  13959. SSLClient::PemMemory client_pem = {
  13960. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13961. client_key_pem.size(), password};
  13962. SSLClient cli(HOST, PORT, client_pem);
  13963. cli.enable_server_certificate_verification(false);
  13964. cli.set_connection_timeout(30);
  13965. auto res = cli.Get("/test");
  13966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13967. ASSERT_EQ(StatusCode::OK_200, res->status);
  13968. }
  13969. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13970. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13971. }
  13972. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13973. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13974. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13975. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13976. }
  13977. // A server built from PEM memory with a client CA requires client certificates,
  13978. // also when the CA is a NUL-terminated string passed with a length of 0
  13979. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13980. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13981. read_file(SERVER_CERT_FILE, server_cert_pem);
  13982. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13983. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13984. SSLServer::PemMemory server_pem = {
  13985. server_cert_pem.c_str(),
  13986. server_cert_pem.size(),
  13987. server_key_pem.c_str(),
  13988. server_key_pem.size(),
  13989. client_ca_pem.c_str(),
  13990. client_ca_pem.size(),
  13991. nullptr // no password for server key
  13992. };
  13993. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13994. SCOPED_TRACE(client_ca_pem_len);
  13995. server_pem.client_ca_pem_len = client_ca_pem_len;
  13996. SSLServer svr(server_pem);
  13997. ASSERT_TRUE(svr.is_valid());
  13998. RejectsClientWithoutCert(svr);
  13999. }
  14000. // An empty CA fails to load instead of turning the check off
  14001. server_pem.client_ca_pem = "";
  14002. server_pem.client_ca_pem_len = 0;
  14003. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14004. }
  14005. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14006. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14007. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14008. true);
  14009. }
  14010. // A length shorter than the PEM cuts it short, so it no longer loads
  14011. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14012. std::string cert, key;
  14013. read_file(SERVER_CERT_FILE, cert);
  14014. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14015. for (auto cut_cert : {true, false}) {
  14016. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14017. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14018. SSLServer::PemMemory server_pem = {
  14019. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14020. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14021. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14022. key_len, nullptr};
  14023. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14024. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14025. key.c_str(), key_len, nullptr};
  14026. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14027. }
  14028. }
  14029. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14030. class NoListenSSLServer : public SSLServer {
  14031. public:
  14032. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14033. const char *client_ca_cert_file_path,
  14034. const char *client_ca_cert_dir_path = nullptr)
  14035. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14036. client_ca_cert_dir_path),
  14037. stop_(false) {}
  14038. std::atomic_bool stop_;
  14039. private:
  14040. bool process_and_close_socket(socket_t /*sock*/) override {
  14041. // Don't create SSL context
  14042. while (!stop_.load()) {
  14043. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14044. }
  14045. return true;
  14046. }
  14047. };
  14048. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14049. CLIENT_CA_CERT_FILE);
  14050. ASSERT_TRUE(svr.is_valid());
  14051. svr.Get("/test", [&](const Request &, Response &res) {
  14052. res.set_content("test", "text/plain");
  14053. });
  14054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14055. auto se = detail::scope_exit([&] {
  14056. svr.stop_ = true;
  14057. svr.stop();
  14058. t.join();
  14059. ASSERT_FALSE(svr.is_running());
  14060. });
  14061. svr.wait_until_ready();
  14062. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14063. cli.enable_server_certificate_verification(false);
  14064. cli.set_connection_timeout(1);
  14065. auto res = cli.Get("/test");
  14066. ASSERT_TRUE(!res);
  14067. EXPECT_EQ(Error::SSLConnection, res.error());
  14068. // Timeout results in WantRead error code (maps to backend-specific value)
  14069. EXPECT_NE(0, res.ssl_error());
  14070. }
  14071. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14072. // Test SSLServer with client certificate verification using the standard
  14073. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14075. CLIENT_CA_CERT_DIR);
  14076. ASSERT_TRUE(svr.is_valid());
  14077. svr.Get("/test", [&](const Request &req, Response &res) {
  14078. res.set_content("test", "text/plain");
  14079. auto cert = req.peer_cert();
  14080. ASSERT_TRUE(static_cast<bool>(cert));
  14081. auto common_name = cert.subject_cn();
  14082. EXPECT_EQ("Common Name", common_name);
  14083. });
  14084. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14085. auto se = detail::scope_exit([&] {
  14086. svr.stop();
  14087. t.join();
  14088. ASSERT_FALSE(svr.is_running());
  14089. });
  14090. svr.wait_until_ready();
  14091. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14092. cli.enable_server_certificate_verification(false);
  14093. cli.set_connection_timeout(30);
  14094. auto res = cli.Get("/test");
  14095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14096. ASSERT_EQ(StatusCode::OK_200, res->status);
  14097. }
  14098. // Test verify_hostname on every backend: a host is named by a SAN only
  14099. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14100. using namespace httplib::tls;
  14101. // We need a running server to test against
  14102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14103. ASSERT_TRUE(svr.is_valid());
  14104. svr.Get("/test", [](const Request &, Response &res) {
  14105. res.set_content("ok", "text/plain");
  14106. });
  14107. thread t([&]() { svr.listen(HOST, PORT); });
  14108. auto se = detail::scope_exit([&] {
  14109. svr.stop();
  14110. t.join();
  14111. });
  14112. svr.wait_until_ready();
  14113. bool verify_callback_called = false;
  14114. bool verify_result_wrong = false;
  14115. SSLClient cli(HOST, PORT);
  14116. cli.enable_server_certificate_verification(true);
  14117. cli.set_ca_cert_path(CA_CERT_FILE);
  14118. cli.set_connection_timeout(5);
  14119. // Note: Test certificate has CN="Common Name", not "localhost"
  14120. bool verify_result_cn = false;
  14121. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14122. verify_callback_called = true;
  14123. if (!ctx.cert) return false;
  14124. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14125. verify_result_cn = ctx.check_hostname("Common Name");
  14126. // Test 2: wrong hostname should not match
  14127. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14128. return true; // Accept for the purpose of this test
  14129. });
  14130. auto res = cli.Get("/test");
  14131. // The request may succeed or fail depending on cert configuration
  14132. // but the callback should have been called
  14133. ASSERT_TRUE(verify_callback_called)
  14134. << "Verify callback should have been called";
  14135. EXPECT_FALSE(verify_result_cn)
  14136. << "verify_hostname must not match the certificate CN (no SAN)";
  14137. // Wrong hostname should not match
  14138. EXPECT_FALSE(verify_result_wrong)
  14139. << "verify_hostname should not match 'wronghost.example.com'";
  14140. }
  14141. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14142. // backend verifies it.
  14143. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14144. // Certificate CN is "localhost" and it carries no SAN.
  14145. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14146. ASSERT_TRUE(svr.is_valid());
  14147. svr.Get("/test", [](const Request &, Response &res) {
  14148. res.set_content("ok", "text/plain");
  14149. });
  14150. auto port = svr.bind_to_any_port(HOST);
  14151. thread t([&]() { svr.listen_after_bind(); });
  14152. auto se = detail::scope_exit([&] {
  14153. svr.stop();
  14154. t.join();
  14155. });
  14156. svr.wait_until_ready();
  14157. SSLClient cli("localhost", port);
  14158. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14159. cli.enable_server_certificate_verification(true);
  14160. cli.set_connection_timeout(5);
  14161. auto res = cli.Get("/test");
  14162. ASSERT_FALSE(res);
  14163. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14164. // The same certificate is accepted once host name verification is off, so the
  14165. // failure above is the host name and not the chain.
  14166. cli.enable_server_hostname_verification(false);
  14167. res = cli.Get("/test");
  14168. ASSERT_TRUE(res) << to_string(res.error());
  14169. EXPECT_EQ(StatusCode::OK_200, res->status);
  14170. }
  14171. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14172. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14173. // X509_check_ip behavior and must hold for every backend.
  14174. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14175. using namespace httplib::tls;
  14176. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14177. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14178. ASSERT_TRUE(svr.is_valid());
  14179. svr.Get("/test", [](const Request &, Response &res) {
  14180. res.set_content("ok", "text/plain");
  14181. });
  14182. thread t([&]() { svr.listen(HOST, PORT); });
  14183. auto se = detail::scope_exit([&] {
  14184. svr.stop();
  14185. t.join();
  14186. });
  14187. svr.wait_until_ready();
  14188. bool verify_callback_called = false;
  14189. bool ip_matched_via_cn = true;
  14190. SSLClient cli(HOST, PORT);
  14191. cli.enable_server_certificate_verification(true);
  14192. cli.set_ca_cert_path(CA_CERT_FILE);
  14193. cli.set_connection_timeout(5);
  14194. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14195. verify_callback_called = true;
  14196. if (!ctx.cert) return false;
  14197. // The IP appears only in the CN, so it must NOT be accepted.
  14198. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14199. return true; // Accept for the purpose of this test
  14200. });
  14201. cli.Get("/test");
  14202. ASSERT_TRUE(verify_callback_called)
  14203. << "Verify callback should have been called";
  14204. EXPECT_FALSE(ip_matched_via_cn)
  14205. << "An IP host must not be authenticated via the certificate CN";
  14206. }
  14207. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14208. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14209. using namespace httplib::tls;
  14210. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14211. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14212. ASSERT_TRUE(svr.is_valid());
  14213. svr.Get("/test", [](const Request &, Response &res) {
  14214. res.set_content("ok", "text/plain");
  14215. });
  14216. thread t([&]() { svr.listen(HOST, PORT); });
  14217. auto se = detail::scope_exit([&] {
  14218. svr.stop();
  14219. t.join();
  14220. });
  14221. svr.wait_until_ready();
  14222. bool verify_callback_called = false;
  14223. bool san_matched = false;
  14224. bool wrong_ipv6_matched = true;
  14225. bool cn_ipv6_matched = true;
  14226. SSLClient cli(HOST, PORT);
  14227. cli.enable_server_certificate_verification(true);
  14228. cli.set_ca_cert_path(CA_CERT_FILE);
  14229. cli.set_connection_timeout(5);
  14230. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14231. verify_callback_called = true;
  14232. if (!ctx.cert) return false;
  14233. // Matches the IPv6 iPAddress SAN.
  14234. san_matched = ctx.check_hostname("2001:db8::1");
  14235. // A different IPv6 address must not match.
  14236. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14237. // "::1" lives only in the CN, so it must not be accepted.
  14238. cn_ipv6_matched = ctx.check_hostname("::1");
  14239. return true; // Accept for the purpose of this test
  14240. });
  14241. cli.Get("/test");
  14242. ASSERT_TRUE(verify_callback_called)
  14243. << "Verify callback should have been called";
  14244. EXPECT_TRUE(san_matched)
  14245. << "verify_hostname should match an IPv6 iPAddress SAN";
  14246. EXPECT_FALSE(wrong_ipv6_matched)
  14247. << "verify_hostname should not match a non-matching IPv6 address";
  14248. EXPECT_FALSE(cn_ipv6_matched)
  14249. << "An IPv6 host must not be authenticated via the certificate CN";
  14250. }
  14251. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14252. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14253. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14254. using namespace httplib::tls;
  14255. // SANs: DNS:a.zz, IP:42.46.122.122
  14256. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14257. ASSERT_TRUE(svr.is_valid());
  14258. svr.Get("/test", [](const Request &, Response &res) {
  14259. res.set_content("ok", "text/plain");
  14260. });
  14261. auto port = svr.bind_to_any_port(HOST);
  14262. thread t([&]() { svr.listen_after_bind(); });
  14263. auto se = detail::scope_exit([&] {
  14264. svr.stop();
  14265. t.join();
  14266. });
  14267. svr.wait_until_ready();
  14268. bool verify_callback_called = false;
  14269. bool dns_san_matched = false;
  14270. bool ip_san_matched = false;
  14271. bool ip_matched_via_dns_san = true;
  14272. bool dns_matched_via_ip_san = true;
  14273. bool cn_matched_next_to_dns_san = true;
  14274. SSLClient cli(HOST, port);
  14275. cli.enable_server_certificate_verification(true);
  14276. cli.set_ca_cert_path(CA_CERT_FILE);
  14277. cli.set_connection_timeout(5);
  14278. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14279. verify_callback_called = true;
  14280. if (!ctx.cert) return false;
  14281. dns_san_matched = ctx.check_hostname("a.zz");
  14282. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14283. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14284. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14285. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14286. return true; // Accept for the purpose of this test
  14287. });
  14288. cli.Get("/test");
  14289. ASSERT_TRUE(verify_callback_called)
  14290. << "Verify callback should have been called";
  14291. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14292. EXPECT_TRUE(ip_san_matched)
  14293. << "verify_hostname should match an iPAddress SAN";
  14294. EXPECT_FALSE(ip_matched_via_dns_san)
  14295. << "An IP host must not be authenticated via a dNSName SAN";
  14296. EXPECT_FALSE(dns_matched_via_ip_san)
  14297. << "A DNS host must not be authenticated via an iPAddress SAN";
  14298. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14299. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14300. }
  14301. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14302. // "www.*.example.test" names one host and not every host under example.test.
  14303. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14304. using namespace httplib::tls;
  14305. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14306. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14307. ASSERT_TRUE(svr.is_valid());
  14308. svr.Get("/test", [](const Request &, Response &res) {
  14309. res.set_content("ok", "text/plain");
  14310. });
  14311. auto port = svr.bind_to_any_port(HOST);
  14312. thread t([&]() { svr.listen_after_bind(); });
  14313. auto se = detail::scope_exit([&] {
  14314. svr.stop();
  14315. t.join();
  14316. });
  14317. svr.wait_until_ready();
  14318. bool verify_callback_called = false;
  14319. bool leftmost_wildcard_matched = false;
  14320. bool wildcard_spanned_labels = true;
  14321. bool inner_wildcard_matched = true;
  14322. SSLClient cli(HOST, port);
  14323. cli.enable_server_certificate_verification(true);
  14324. cli.set_ca_cert_path(CA_CERT_FILE);
  14325. cli.set_connection_timeout(5);
  14326. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14327. verify_callback_called = true;
  14328. if (!ctx.cert) return false;
  14329. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14330. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14331. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14332. return true; // Accept for the purpose of this test
  14333. });
  14334. cli.Get("/test");
  14335. ASSERT_TRUE(verify_callback_called)
  14336. << "Verify callback should have been called";
  14337. EXPECT_TRUE(leftmost_wildcard_matched)
  14338. << "A leftmost wildcard should match a single label";
  14339. EXPECT_FALSE(wildcard_spanned_labels)
  14340. << "A wildcard label must not match more than one label";
  14341. EXPECT_FALSE(inner_wildcard_matched)
  14342. << "A wildcard outside the leftmost label must not be honoured";
  14343. }
  14344. // sans() must report each SAN entry under its own type.
  14345. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14346. using namespace httplib::tls;
  14347. // SANs: DNS:a.zz, IP:42.46.122.122
  14348. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14349. ASSERT_TRUE(svr.is_valid());
  14350. svr.Get("/test", [](const Request &, Response &res) {
  14351. res.set_content("ok", "text/plain");
  14352. });
  14353. auto port = svr.bind_to_any_port(HOST);
  14354. thread t([&]() { svr.listen_after_bind(); });
  14355. auto se = detail::scope_exit([&] {
  14356. svr.stop();
  14357. t.join();
  14358. });
  14359. svr.wait_until_ready();
  14360. bool verify_callback_called = false;
  14361. std::vector<SanEntry> sans;
  14362. SSLClient cli(HOST, port);
  14363. cli.enable_server_certificate_verification(true);
  14364. cli.set_ca_cert_path(CA_CERT_FILE);
  14365. cli.set_connection_timeout(5);
  14366. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14367. verify_callback_called = true;
  14368. if (!ctx.cert) return false;
  14369. sans = ctx.sans();
  14370. return true; // Accept for the purpose of this test
  14371. });
  14372. cli.Get("/test");
  14373. ASSERT_TRUE(verify_callback_called)
  14374. << "Verify callback should have been called";
  14375. auto has_san = [&](SanType type, const std::string &value) {
  14376. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14377. return san.type == type && san.value == value;
  14378. });
  14379. };
  14380. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14381. << "sans() should report the dNSName SAN";
  14382. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14383. << "sans() should report the iPAddress SAN";
  14384. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14385. << "sans() must not report the dNSName SAN as an address";
  14386. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14387. << "sans() must not report the iPAddress SAN as a DNS name";
  14388. }
  14389. #endif
  14390. // mbedTLS-specific callback constructor test
  14391. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14392. #ifdef CPPHTTPLIB_SSL_ENABLED
  14393. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14395. ASSERT_TRUE(svr.is_valid());
  14396. // Set up a handler to verify client certificate is present
  14397. bool client_cert_verified = false;
  14398. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14399. // Verify that client certificate was provided
  14400. client_cert_verified = true;
  14401. res.set_content("success", "text/plain");
  14402. });
  14403. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14404. auto se = detail::scope_exit([&] {
  14405. svr.stop();
  14406. t.join();
  14407. ASSERT_FALSE(svr.is_running());
  14408. });
  14409. svr.wait_until_ready();
  14410. // Client with certificate
  14411. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14412. cli.enable_server_certificate_verification(false);
  14413. cli.set_connection_timeout(30);
  14414. auto res = cli.Get("/test");
  14415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14416. ASSERT_EQ(StatusCode::OK_200, res->status);
  14417. ASSERT_TRUE(client_cert_verified);
  14418. EXPECT_EQ("success", res->body);
  14419. }
  14420. #endif
  14421. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14422. // backends
  14423. #ifdef CPPHTTPLIB_SSL_ENABLED
  14424. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14425. using namespace httplib::tls;
  14426. // Test that when client CA cert file is provided,
  14427. // the server properly requests and validates client certificates
  14428. // Create a server with client authentication
  14429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14430. ASSERT_TRUE(svr.is_valid());
  14431. bool handler_called = false;
  14432. svr.Get("/test", [&](const Request &req, Response &res) {
  14433. handler_called = true;
  14434. // Verify that a client certificate was provided
  14435. auto cert = req.peer_cert();
  14436. ASSERT_TRUE(static_cast<bool>(cert));
  14437. // Get the issuer name
  14438. std::string issuer_str = cert.issuer_name();
  14439. ASSERT_FALSE(issuer_str.empty());
  14440. // The client certificate should be issued by our test CA
  14441. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14442. res.set_content("authenticated", "text/plain");
  14443. });
  14444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14445. auto se = detail::scope_exit([&] {
  14446. svr.stop();
  14447. t.join();
  14448. ASSERT_FALSE(svr.is_running());
  14449. });
  14450. svr.wait_until_ready();
  14451. // Connect with a client certificate issued by the CA
  14452. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14453. cli.enable_server_certificate_verification(false);
  14454. cli.set_connection_timeout(30);
  14455. auto res = cli.Get("/test");
  14456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14457. ASSERT_EQ(StatusCode::OK_200, res->status);
  14458. ASSERT_TRUE(handler_called);
  14459. EXPECT_EQ("authenticated", res->body);
  14460. }
  14461. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14462. using namespace httplib::tls;
  14463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14464. ASSERT_TRUE(svr.is_valid());
  14465. svr.Get("/test", [](const Request &, Response &res) {
  14466. res.set_content("ok", "text/plain");
  14467. });
  14468. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14469. auto se = detail::scope_exit([&] {
  14470. svr.stop();
  14471. t.join();
  14472. });
  14473. svr.wait_until_ready();
  14474. SSLClient cli(HOST, PORT);
  14475. cli.enable_server_certificate_verification(false);
  14476. cli.set_connection_timeout(30);
  14477. bool cert_checked = false;
  14478. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14479. if (ctx.cert) {
  14480. auto sans = ctx.sans();
  14481. // Test certificate may or may not have SANs - just verify the API
  14482. // works If SANs exist, verify the types are valid
  14483. for (const auto &san : sans) {
  14484. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14485. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14486. san.type == SanType::OTHER);
  14487. EXPECT_FALSE(san.value.empty());
  14488. }
  14489. cert_checked = true;
  14490. }
  14491. return true;
  14492. });
  14493. auto res = cli.Get("/test");
  14494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14495. EXPECT_TRUE(cert_checked);
  14496. }
  14497. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14498. using namespace httplib::tls;
  14499. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14500. ASSERT_TRUE(svr.is_valid());
  14501. svr.Get("/test", [](const Request &, Response &res) {
  14502. res.set_content("ok", "text/plain");
  14503. });
  14504. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14505. auto se = detail::scope_exit([&] {
  14506. svr.stop();
  14507. t.join();
  14508. });
  14509. svr.wait_until_ready();
  14510. SSLClient cli(HOST, PORT);
  14511. cli.enable_server_certificate_verification(false);
  14512. cli.set_connection_timeout(30);
  14513. bool validity_checked = false;
  14514. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14515. if (ctx.cert) {
  14516. time_t not_before = 0, not_after = 0;
  14517. bool result = ctx.validity(not_before, not_after);
  14518. EXPECT_TRUE(result);
  14519. // Verify that not_before < now < not_after for a valid cert
  14520. time_t now = time(nullptr);
  14521. EXPECT_LT(not_before, now);
  14522. EXPECT_GT(not_after, now);
  14523. validity_checked = true;
  14524. }
  14525. return true;
  14526. });
  14527. auto res = cli.Get("/test");
  14528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14529. EXPECT_TRUE(validity_checked);
  14530. }
  14531. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14532. using namespace httplib::tls;
  14533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14534. ASSERT_TRUE(svr.is_valid());
  14535. svr.Get("/test", [](const Request &, Response &res) {
  14536. res.set_content("ok", "text/plain");
  14537. });
  14538. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14539. auto se = detail::scope_exit([&] {
  14540. svr.stop();
  14541. t.join();
  14542. });
  14543. svr.wait_until_ready();
  14544. SSLClient cli(HOST, PORT);
  14545. cli.enable_server_certificate_verification(false);
  14546. cli.set_connection_timeout(30);
  14547. bool serial_checked = false;
  14548. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14549. if (ctx.cert) {
  14550. std::string serial = ctx.serial();
  14551. EXPECT_FALSE(serial.empty());
  14552. // Serial should be a hex string
  14553. for (char c : serial) {
  14554. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14555. (c >= 'a' && c <= 'f'));
  14556. }
  14557. serial_checked = true;
  14558. }
  14559. return true;
  14560. });
  14561. auto res = cli.Get("/test");
  14562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14563. EXPECT_TRUE(serial_checked);
  14564. }
  14565. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14566. // Test 1: Valid CA file - no error should be recorded
  14567. {
  14568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14569. CLIENT_CA_CERT_FILE);
  14570. ASSERT_TRUE(svr.is_valid());
  14571. // With valid setup, last_ssl_error should be 0
  14572. EXPECT_EQ(0, svr.ssl_last_error());
  14573. }
  14574. // Test 2: Invalid CA file content
  14575. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14576. {
  14577. // Create a temporary file with completely invalid content
  14578. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14579. {
  14580. std::ofstream ofs(temp_invalid_ca);
  14581. ofs << "This is not a certificate file at all\n";
  14582. ofs << "Just plain text content\n";
  14583. }
  14584. // Create server with invalid CA file
  14585. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14586. // Clean up temporary file
  14587. std::remove(temp_invalid_ca);
  14588. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14589. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14590. // Note: SSL_CTX_load_verify_locations typically fails first,
  14591. // but our error handling code path is still exercised
  14592. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14593. }
  14594. }
  14595. TEST(VerifyCallbackTest, VerifyContextFields) {
  14596. using namespace httplib::tls;
  14597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14598. ASSERT_TRUE(svr.is_valid());
  14599. svr.Get("/test", [](const Request &, Response &res) {
  14600. res.set_content("ok", "text/plain");
  14601. });
  14602. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14603. auto se = detail::scope_exit([&] {
  14604. svr.stop();
  14605. t.join();
  14606. });
  14607. svr.wait_until_ready();
  14608. SSLClient cli(HOST, PORT);
  14609. cli.enable_server_certificate_verification(false);
  14610. cli.set_connection_timeout(30);
  14611. int callback_count = 0;
  14612. bool saw_leaf_cert = false;
  14613. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14614. if (ctx.cert) {
  14615. callback_count++;
  14616. // We should see at least one certificate (the leaf)
  14617. std::string cn = ctx.subject_cn();
  14618. if (!cn.empty()) { saw_leaf_cert = true; }
  14619. // Verify context fields are populated
  14620. EXPECT_NE(ctx.session, nullptr);
  14621. EXPECT_GE(ctx.depth, 0);
  14622. }
  14623. return true;
  14624. });
  14625. auto res = cli.Get("/test");
  14626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14627. EXPECT_GT(callback_count, 0);
  14628. EXPECT_TRUE(saw_leaf_cert);
  14629. }
  14630. // A verifier that accepts runs alongside the built-in verification, and is the
  14631. // only check once that is turned off.
  14632. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14633. using namespace httplib::tls;
  14634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14635. ASSERT_TRUE(svr.is_valid());
  14636. svr.Get("/test", [](const Request &, Response &res) {
  14637. res.set_content("ok", "text/plain");
  14638. });
  14639. auto port = svr.bind_to_any_port(HOST);
  14640. thread t([&]() { svr.listen_after_bind(); });
  14641. auto se = detail::scope_exit([&] {
  14642. svr.stop();
  14643. t.join();
  14644. });
  14645. svr.wait_until_ready();
  14646. SSLClient cli(HOST, port);
  14647. cli.enable_server_hostname_verification(false);
  14648. auto calls = 0;
  14649. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14650. calls++;
  14651. return true;
  14652. });
  14653. // cert.pem is not trusted
  14654. auto res = cli.Get("/test");
  14655. ASSERT_FALSE(res);
  14656. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14657. EXPECT_GT(calls, 0);
  14658. cli.enable_server_certificate_verification(false);
  14659. res = cli.Get("/test");
  14660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14661. EXPECT_EQ("ok", res->body);
  14662. }
  14663. // A verifier belongs to the client that set it, not to the thread that set it.
  14664. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14665. using namespace httplib::tls;
  14666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14667. ASSERT_TRUE(svr.is_valid());
  14668. svr.Get("/test", [](const Request &, Response &res) {
  14669. res.set_content("ok", "text/plain");
  14670. });
  14671. auto port = svr.bind_to_any_port(HOST);
  14672. thread t([&]() { svr.listen_after_bind(); });
  14673. auto se = detail::scope_exit([&] {
  14674. svr.stop();
  14675. t.join();
  14676. });
  14677. svr.wait_until_ready();
  14678. auto rejecting_calls = 0;
  14679. SSLClient rejecting(HOST, port);
  14680. rejecting.enable_server_certificate_verification(false);
  14681. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14682. rejecting_calls++;
  14683. return false;
  14684. });
  14685. auto accepting_calls = 0;
  14686. SSLClient accepting(HOST, port);
  14687. accepting.enable_server_certificate_verification(false);
  14688. // Set on another thread than the requests below.
  14689. thread([&]() {
  14690. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14691. accepting_calls++;
  14692. return true;
  14693. });
  14694. }).join();
  14695. // Requested on another thread than the verifier was set on.
  14696. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14697. EXPECT_GT(rejecting_calls, 0);
  14698. auto res = accepting.Get("/test");
  14699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14700. EXPECT_GT(accepting_calls, 0);
  14701. }
  14702. // A verifier replaced while a handshake runs it lives until it returns.
  14703. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14704. using namespace httplib::tls;
  14705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14706. ASSERT_TRUE(svr.is_valid());
  14707. svr.Get("/test", [](const Request &, Response &res) {
  14708. res.set_content("ok", "text/plain");
  14709. });
  14710. auto port = svr.bind_to_any_port(HOST);
  14711. thread t([&]() { svr.listen_after_bind(); });
  14712. auto se = detail::scope_exit([&] {
  14713. svr.stop();
  14714. t.join();
  14715. });
  14716. svr.wait_until_ready();
  14717. SSLClient cli(HOST, port);
  14718. cli.enable_server_certificate_verification(false);
  14719. std::promise<void> entered;
  14720. std::promise<void> replaced;
  14721. auto replaced_future = replaced.get_future();
  14722. auto first_call = true;
  14723. // Long enough to live on the heap
  14724. std::string expected(64, 'v');
  14725. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14726. if (first_call) {
  14727. first_call = false;
  14728. entered.set_value();
  14729. replaced_future.wait();
  14730. }
  14731. return expected == std::string(64, 'v');
  14732. });
  14733. thread request([&]() {
  14734. auto res = cli.Get("/test");
  14735. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14736. });
  14737. entered.get_future().wait();
  14738. cli.set_server_certificate_verifier(
  14739. [](const VerifyContext &) { return true; });
  14740. replaced.set_value();
  14741. request.join();
  14742. }
  14743. // VerifyContext::session is the same handle the other tls:: functions take.
  14744. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14745. using namespace httplib::tls;
  14746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14747. ASSERT_TRUE(svr.is_valid());
  14748. svr.Get("/test", [](const Request &, Response &res) {
  14749. res.set_content("ok", "text/plain");
  14750. });
  14751. auto port = svr.bind_to_any_port(HOST);
  14752. thread t([&]() { svr.listen_after_bind(); });
  14753. auto se = detail::scope_exit([&] {
  14754. svr.stop();
  14755. t.join();
  14756. });
  14757. svr.wait_until_ready();
  14758. SSLClient cli(HOST, port);
  14759. cli.enable_server_certificate_verification(false);
  14760. session_t verifier_session = nullptr;
  14761. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14762. verifier_session = ctx.session;
  14763. return true;
  14764. });
  14765. session_t session_verifier_session = nullptr;
  14766. cli.set_session_verifier([&](session_t session) {
  14767. session_verifier_session = session;
  14768. return SSLVerifierResponse::NoDecisionMade;
  14769. });
  14770. auto res = cli.Get("/test");
  14771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14772. EXPECT_NE(nullptr, verifier_session);
  14773. EXPECT_EQ(session_verifier_session, verifier_session);
  14774. }
  14775. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14776. using httplib::tls::TlsError;
  14777. // Test that verify_error_to_string returns empty for success
  14778. std::string success_str = TlsError::verify_error_to_string(0);
  14779. EXPECT_TRUE(success_str.empty());
  14780. // Test that verify_error_to_string returns non-empty for error codes
  14781. // Using a common error code (certificate expired)
  14782. std::string error_str =
  14783. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14784. EXPECT_FALSE(error_str.empty());
  14785. }
  14786. TEST(SessionVerifierTest, CertificateAccepted) {
  14787. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14788. ASSERT_TRUE(svr.is_valid());
  14789. svr.Get("/test", [](const Request &, Response &res) {
  14790. res.set_content("ok", "text/plain");
  14791. });
  14792. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14793. auto se = detail::scope_exit([&] {
  14794. svr.stop();
  14795. t.join();
  14796. });
  14797. svr.wait_until_ready();
  14798. SSLClient cli(HOST, PORT);
  14799. cli.enable_server_certificate_verification(false);
  14800. cli.set_connection_timeout(30);
  14801. bool callback_called = false;
  14802. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14803. EXPECT_NE(session, nullptr);
  14804. callback_called = true;
  14805. return SSLVerifierResponse::CertificateAccepted;
  14806. });
  14807. auto res = cli.Get("/test");
  14808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14809. EXPECT_EQ(200, res->status);
  14810. EXPECT_TRUE(callback_called);
  14811. }
  14812. TEST(SessionVerifierTest, CertificateRejected) {
  14813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14814. ASSERT_TRUE(svr.is_valid());
  14815. svr.Get("/test", [](const Request &, Response &res) {
  14816. res.set_content("ok", "text/plain");
  14817. });
  14818. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14819. auto se = detail::scope_exit([&] {
  14820. svr.stop();
  14821. t.join();
  14822. });
  14823. svr.wait_until_ready();
  14824. SSLClient cli(HOST, PORT);
  14825. cli.enable_server_certificate_verification(false);
  14826. cli.set_connection_timeout(30);
  14827. bool callback_called = false;
  14828. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14829. EXPECT_NE(session, nullptr);
  14830. callback_called = true;
  14831. return SSLVerifierResponse::CertificateRejected;
  14832. });
  14833. auto res = cli.Get("/test");
  14834. EXPECT_FALSE(res);
  14835. EXPECT_TRUE(callback_called);
  14836. }
  14837. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14839. ASSERT_TRUE(svr.is_valid());
  14840. svr.Get("/test", [](const Request &, Response &res) {
  14841. res.set_content("ok", "text/plain");
  14842. });
  14843. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14844. auto se = detail::scope_exit([&] {
  14845. svr.stop();
  14846. t.join();
  14847. });
  14848. svr.wait_until_ready();
  14849. // NoDecisionMade with verification disabled should succeed (no default check)
  14850. SSLClient cli(HOST, PORT);
  14851. cli.enable_server_certificate_verification(false);
  14852. cli.set_connection_timeout(30);
  14853. bool callback_called = false;
  14854. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14855. EXPECT_NE(session, nullptr);
  14856. callback_called = true;
  14857. return SSLVerifierResponse::NoDecisionMade;
  14858. });
  14859. auto res = cli.Get("/test");
  14860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14861. EXPECT_EQ(200, res->status);
  14862. EXPECT_TRUE(callback_called);
  14863. }
  14864. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14866. ASSERT_TRUE(svr.is_valid());
  14867. svr.Get("/test", [](const Request &, Response &res) {
  14868. res.set_content("ok", "text/plain");
  14869. });
  14870. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14871. auto se = detail::scope_exit([&] {
  14872. svr.stop();
  14873. t.join();
  14874. });
  14875. svr.wait_until_ready();
  14876. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14877. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14878. // so we only check that the request fails, not whether the callback was
  14879. // called.
  14880. SSLClient cli(HOST, PORT);
  14881. cli.enable_server_certificate_verification(true);
  14882. cli.set_connection_timeout(30);
  14883. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14884. EXPECT_NE(session, nullptr);
  14885. return SSLVerifierResponse::NoDecisionMade;
  14886. });
  14887. auto res = cli.Get("/test");
  14888. EXPECT_FALSE(res);
  14889. }
  14890. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14891. // Test SSL server using PemMemory constructor with client CA certificates
  14892. // Read PEM files
  14893. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14894. read_file(SERVER_CERT_FILE, server_cert_pem);
  14895. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14896. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14897. // Create SSLServer with PemMemory constructor including client CA
  14898. SSLServer::PemMemory server_pem = {
  14899. server_cert_pem.c_str(),
  14900. server_cert_pem.size(),
  14901. server_key_pem.c_str(),
  14902. server_key_pem.size(),
  14903. client_ca_pem.c_str(),
  14904. client_ca_pem.size(),
  14905. nullptr // no password for server key
  14906. };
  14907. SSLServer svr(server_pem);
  14908. ASSERT_TRUE(svr.is_valid());
  14909. // No SSL error should be recorded for valid setup
  14910. EXPECT_EQ(0, svr.ssl_last_error());
  14911. // Set up server endpoints
  14912. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14913. res.set_content("ok", "text/plain");
  14914. });
  14915. // Start server in a thread
  14916. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14917. svr.wait_until_ready();
  14918. // Connect with client certificate (using constructor with paths)
  14919. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14920. cli.enable_server_certificate_verification(false);
  14921. auto res = cli.Get("/test-pem-ca");
  14922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14923. EXPECT_EQ(200, res->status);
  14924. EXPECT_EQ("ok", res->body);
  14925. svr.stop();
  14926. server_thread.join();
  14927. }
  14928. #endif
  14929. #ifdef _WIN32
  14930. TEST(CleanupTest, WSACleanup) {
  14931. int ret = WSACleanup();
  14932. ASSERT_EQ(0, ret);
  14933. }
  14934. #endif
  14935. #ifndef CPPHTTPLIB_SSL_ENABLED
  14936. TEST(NoSSLSupport, SimpleInterface) {
  14937. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14938. }
  14939. #endif
  14940. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14941. TEST(InvalidScheme, SimpleInterface) {
  14942. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14943. }
  14944. #endif
  14945. TEST(NoScheme, SimpleInterface) {
  14946. Client cli("yahoo.com:80");
  14947. ASSERT_TRUE(cli.is_valid());
  14948. }
  14949. TEST(SendAPI, SimpleInterface_Online) {
  14950. Client cli("http://yahoo.com");
  14951. Request req;
  14952. req.method = "GET";
  14953. req.path = "/";
  14954. auto res = cli.send(req);
  14955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14956. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14957. }
  14958. TEST(SendAPI, WithParamsInRequest) {
  14959. Server svr;
  14960. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14961. EXPECT_TRUE(req.has_param("test"));
  14962. EXPECT_EQ("test_value", req.get_param_value("test"));
  14963. });
  14964. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14965. auto se = detail::scope_exit([&] {
  14966. svr.stop();
  14967. t.join();
  14968. ASSERT_FALSE(svr.is_running());
  14969. });
  14970. svr.wait_until_ready();
  14971. Client cli(HOST, PORT);
  14972. {
  14973. Request req;
  14974. req.method = "GET";
  14975. req.path = "/";
  14976. req.params.emplace("test", "test_value");
  14977. auto res = cli.send(req);
  14978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14979. }
  14980. {
  14981. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14983. }
  14984. }
  14985. TEST(ClientImplMethods, GetSocketTest) {
  14986. httplib::Server svr;
  14987. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14988. res.status = StatusCode::OK_200;
  14989. });
  14990. auto port = svr.bind_to_any_port("127.0.0.1");
  14991. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14992. auto se = detail::scope_exit([&] {
  14993. svr.stop();
  14994. thread.join();
  14995. ASSERT_FALSE(svr.is_running());
  14996. });
  14997. svr.wait_until_ready();
  14998. {
  14999. httplib::Client cli("127.0.0.1", port);
  15000. cli.set_keep_alive(true);
  15001. // Use the behavior of cpp-httplib of opening the connection
  15002. // only when the first request happens. If that changes,
  15003. // this test would be obsolete.
  15004. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15005. // This also implicitly tests the server. But other tests would fail much
  15006. // earlier than this one to be considered.
  15007. auto res = cli.Get("/");
  15008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15009. EXPECT_EQ(StatusCode::OK_200, res->status);
  15010. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15011. }
  15012. }
  15013. #ifdef CPPHTTPLIB_SSL_ENABLED
  15014. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15015. Client cli("http://yahoo.com");
  15016. auto res = cli.Get("/");
  15017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15018. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15019. cli.set_follow_location(true);
  15020. res = cli.Get("/");
  15021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15022. EXPECT_EQ(StatusCode::OK_200, res->status);
  15023. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15024. }
  15025. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15026. Client cli("https://yahoo.com");
  15027. auto res = cli.Get("/");
  15028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15029. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15030. cli.set_follow_location(true);
  15031. res = cli.Get("/");
  15032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15033. EXPECT_EQ(StatusCode::OK_200, res->status);
  15034. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15035. }
  15036. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15037. Client cli("https://yahoo.com");
  15038. auto res = cli.Get("/");
  15039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15040. ASSERT_FALSE(!res);
  15041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15042. ASSERT_FALSE(res == nullptr);
  15043. ASSERT_TRUE(res != nullptr);
  15044. EXPECT_EQ(Error::Success, res.error());
  15045. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15046. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15047. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15048. cli.set_follow_location(true);
  15049. res = cli.Get("/");
  15050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15051. EXPECT_EQ(Error::Success, res.error());
  15052. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15053. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15054. EXPECT_EQ(StatusCode::OK_200, res->status);
  15055. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15056. }
  15057. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15058. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15059. Client cli("https://cdnjs.cloudflare.com");
  15060. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15061. Headers{{"Accept-Encoding", "br"}});
  15062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15063. EXPECT_EQ(StatusCode::OK_200, res->status);
  15064. EXPECT_EQ(287630U, res->body.size());
  15065. EXPECT_EQ("application/javascript; charset=utf-8",
  15066. res->get_header_value("Content-Type"));
  15067. }
  15068. #endif
  15069. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15070. #undef REDIR_HOST // Silence compiler warning
  15071. #define REDIR_HOST "https://httpbingo.org"
  15072. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15073. Client cli(REDIR_HOST);
  15074. cli.set_follow_location(true);
  15075. auto res =
  15076. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15078. EXPECT_EQ(StatusCode::OK_200, res->status);
  15079. }
  15080. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15081. Client cli(REDIR_HOST);
  15082. cli.set_follow_location(true);
  15083. Params params;
  15084. params.emplace("url", "http://example.com");
  15085. params.emplace("status_code", "302");
  15086. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15088. EXPECT_EQ(StatusCode::OK_200, res->status);
  15089. }
  15090. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15091. Client cli(REDIR_HOST);
  15092. cli.set_follow_location(true);
  15093. Params params;
  15094. params.emplace("url", "http://example.com");
  15095. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15097. EXPECT_EQ(StatusCode::OK_200, res->status);
  15098. }
  15099. TEST(HttpToHttpsRedirectTest, CertFile) {
  15100. auto ssl_port = PORT + 1;
  15101. Server svr;
  15102. ASSERT_TRUE(svr.is_valid());
  15103. svr.Get("/index", [&](const Request &, Response &res) {
  15104. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15105. "/index");
  15106. svr.stop();
  15107. });
  15108. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15109. ASSERT_TRUE(ssl_svr.is_valid());
  15110. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15111. res.set_content("test", "text/plain");
  15112. ssl_svr.stop();
  15113. });
  15114. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15115. thread t2 =
  15116. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15117. auto se = detail::scope_exit([&] {
  15118. t2.join();
  15119. t.join();
  15120. ASSERT_FALSE(svr.is_running());
  15121. });
  15122. svr.wait_until_ready();
  15123. ssl_svr.wait_until_ready();
  15124. Client cli("127.0.0.1", PORT);
  15125. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15126. cli.enable_server_certificate_verification(true);
  15127. cli.set_follow_location(true);
  15128. cli.set_connection_timeout(30);
  15129. auto res = cli.Get("/index");
  15130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15131. ASSERT_EQ(StatusCode::OK_200, res->status);
  15132. }
  15133. TEST(SSLClientRedirectTest, CertFile) {
  15134. auto ssl_port = PORT + 1;
  15135. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15136. ASSERT_TRUE(ssl_svr1.is_valid());
  15137. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15138. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15139. "/index");
  15140. ssl_svr1.stop();
  15141. });
  15142. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15143. ASSERT_TRUE(ssl_svr2.is_valid());
  15144. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15145. res.set_content("test", "text/plain");
  15146. ssl_svr2.stop();
  15147. });
  15148. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15149. thread t2 =
  15150. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15151. auto se = detail::scope_exit([&] {
  15152. t2.join();
  15153. t.join();
  15154. ASSERT_FALSE(ssl_svr1.is_running());
  15155. });
  15156. ssl_svr1.wait_until_ready();
  15157. ssl_svr2.wait_until_ready();
  15158. SSLClient cli("127.0.0.1", PORT);
  15159. std::string cert;
  15160. read_file(SERVER_CERT2_FILE, cert);
  15161. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15162. cli.enable_server_certificate_verification(true);
  15163. cli.set_follow_location(true);
  15164. cli.set_connection_timeout(30);
  15165. auto res = cli.Get("/index");
  15166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15167. ASSERT_EQ(StatusCode::OK_200, res->status);
  15168. }
  15169. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15170. // another port, so the client follows it with a new client.
  15171. static Result GetThroughTlsRedirectToDifferentPort(
  15172. const std::function<void(SSLClient &)> &setup,
  15173. const char *target_cert = SERVER_CERT2_FILE,
  15174. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15175. auto ssl_port = PORT + 1;
  15176. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15177. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15178. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15179. "/index");
  15180. });
  15181. SSLServer ssl_svr2(target_cert, target_key);
  15182. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15183. res.set_content("test", "text/plain");
  15184. });
  15185. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15186. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15187. auto se = detail::scope_exit([&] {
  15188. ssl_svr2.stop();
  15189. ssl_svr1.stop();
  15190. t2.join();
  15191. t.join();
  15192. });
  15193. ssl_svr1.wait_until_ready();
  15194. ssl_svr2.wait_until_ready();
  15195. SSLClient cli("127.0.0.1", PORT);
  15196. cli.set_follow_location(true);
  15197. cli.set_connection_timeout(30);
  15198. setup(cli);
  15199. return cli.Get("/index");
  15200. }
  15201. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15202. auto calls = 0;
  15203. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15204. cli.enable_server_certificate_verification(false);
  15205. // Accept the first server only.
  15206. cli.set_session_verifier([&](tls::session_t) {
  15207. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15208. : SSLVerifierResponse::CertificateRejected;
  15209. });
  15210. });
  15211. ASSERT_FALSE(res);
  15212. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15213. EXPECT_EQ(2, calls);
  15214. }
  15215. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15216. std::string pinned;
  15217. auto res = GetThroughTlsRedirectToDifferentPort(
  15218. [&](SSLClient &cli) {
  15219. cli.enable_server_certificate_verification(false);
  15220. // Pin the first certificate seen.
  15221. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15222. if (pinned.empty()) { pinned = ctx.serial(); }
  15223. return ctx.serial() == pinned;
  15224. });
  15225. },
  15226. // A certificate other than the first server's.
  15227. SERVER_CERT_FILE);
  15228. EXPECT_FALSE(res);
  15229. EXPECT_FALSE(pinned.empty());
  15230. }
  15231. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15232. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15233. std::string cert;
  15234. read_file(SERVER_CERT2_FILE, cert);
  15235. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15236. });
  15237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15238. EXPECT_EQ(StatusCode::OK_200, res->status);
  15239. }
  15240. // The target's certificate is signed by the root CA, which the first server's
  15241. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15242. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15243. auto res = GetThroughTlsRedirectToDifferentPort(
  15244. [](SSLClient &cli) {
  15245. std::string root_ca, cert;
  15246. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15247. read_file(SERVER_CERT2_FILE, cert);
  15248. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15249. cli.load_ca_cert_store(cert.data(), cert.size());
  15250. cli.enable_server_hostname_verification(false);
  15251. },
  15252. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15254. EXPECT_EQ(StatusCode::OK_200, res->status);
  15255. }
  15256. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15257. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15258. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15259. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15260. auto res = GetThroughTlsRedirectToDifferentPort(
  15261. [](SSLClient &cli) {
  15262. std::string root_ca, cert;
  15263. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15264. read_file(SERVER_CERT2_FILE, cert);
  15265. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15266. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15267. cli.enable_server_hostname_verification(false);
  15268. },
  15269. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15270. ASSERT_FALSE(res);
  15271. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15272. }
  15273. #endif
  15274. #endif
  15275. #ifdef CPPHTTPLIB_SSL_ENABLED
  15276. // Test that set_ca_cert_store() skips system certs (consistent with
  15277. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15278. // should be trusted - system certs should NOT be loaded.
  15279. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15280. // Load a specific cert that is NOT a system CA cert
  15281. std::string cert;
  15282. read_file(SERVER_CERT2_FILE, cert);
  15283. SSLClient cli("google.com");
  15284. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15285. cli.enable_server_certificate_verification(true);
  15286. // This should FAIL because:
  15287. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15288. // 2. System certs should NOT be loaded when custom store is set
  15289. // If system certs WERE loaded, this would succeed
  15290. auto res = cli.Get("/");
  15291. ASSERT_FALSE(res);
  15292. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15293. }
  15294. // Same as above, but through the native store handle path. Regression test:
  15295. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15296. // merged system certs into the user-provided store.
  15297. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15298. std::string cert;
  15299. read_file(SERVER_CERT2_FILE, cert);
  15300. SSLClient cli("google.com");
  15301. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15302. cli.enable_server_certificate_verification(true);
  15303. auto res = cli.Get("/");
  15304. ASSERT_FALSE(res);
  15305. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15306. }
  15307. // A custom store set via the native handle must still verify a server whose
  15308. // cert it does contain.
  15309. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15310. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15311. ASSERT_TRUE(svr.is_valid());
  15312. svr.Get("/test", [&](const Request &, Response &res) {
  15313. res.set_content("test", "text/plain");
  15314. });
  15315. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15316. auto se = detail::scope_exit([&] {
  15317. svr.stop();
  15318. t.join();
  15319. ASSERT_FALSE(svr.is_running());
  15320. });
  15321. svr.wait_until_ready();
  15322. SSLClient cli("127.0.0.1", PORT);
  15323. std::string cert;
  15324. read_file(SERVER_CERT2_FILE, cert);
  15325. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15326. cli.enable_server_certificate_verification(true);
  15327. cli.set_connection_timeout(30);
  15328. auto res = cli.Get("/test");
  15329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15330. ASSERT_EQ(StatusCode::OK_200, res->status);
  15331. }
  15332. // CA certs loaded through the universal Client must be transferred to the
  15333. // client created internally for following an HTTPS redirect. Regression test:
  15334. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15335. // the CA data for redirect transfer.
  15336. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15337. auto ssl_port = PORT + 1;
  15338. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15339. ASSERT_TRUE(ssl_svr1.is_valid());
  15340. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15341. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15342. "/index");
  15343. });
  15344. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15345. ASSERT_TRUE(ssl_svr2.is_valid());
  15346. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15347. res.set_content("test", "text/plain");
  15348. });
  15349. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15350. thread t2 =
  15351. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15352. auto se = detail::scope_exit([&] {
  15353. ssl_svr2.stop();
  15354. ssl_svr1.stop();
  15355. t2.join();
  15356. t.join();
  15357. ASSERT_FALSE(ssl_svr1.is_running());
  15358. });
  15359. ssl_svr1.wait_until_ready();
  15360. ssl_svr2.wait_until_ready();
  15361. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15362. std::string cert;
  15363. read_file(SERVER_CERT2_FILE, cert);
  15364. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15365. cli.enable_server_certificate_verification(true);
  15366. cli.set_follow_location(true);
  15367. cli.set_connection_timeout(30);
  15368. auto res = cli.Get("/index");
  15369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15370. ASSERT_EQ(StatusCode::OK_200, res->status);
  15371. }
  15372. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15373. // so a host signed by a system CA verifies even though a custom CA is set
  15374. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15375. std::string cert;
  15376. read_file(SERVER_CERT2_FILE, cert);
  15377. SSLClient cli("google.com");
  15378. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15379. cli.enable_system_ca(true);
  15380. cli.enable_server_certificate_verification(true);
  15381. auto res = cli.Get("/");
  15382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15383. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15384. }
  15385. // The custom CA remains effective when combined with the system CA
  15386. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15387. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15388. ASSERT_TRUE(svr.is_valid());
  15389. svr.Get("/test", [&](const Request &, Response &res) {
  15390. res.set_content("test", "text/plain");
  15391. });
  15392. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15393. auto se = detail::scope_exit([&] {
  15394. svr.stop();
  15395. t.join();
  15396. ASSERT_FALSE(svr.is_running());
  15397. });
  15398. svr.wait_until_ready();
  15399. SSLClient cli("127.0.0.1", PORT);
  15400. std::string cert;
  15401. read_file(SERVER_CERT2_FILE, cert);
  15402. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15403. cli.enable_system_ca(true);
  15404. cli.enable_server_certificate_verification(true);
  15405. cli.set_connection_timeout(30);
  15406. auto res = cli.Get("/test");
  15407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15408. ASSERT_EQ(StatusCode::OK_200, res->status);
  15409. }
  15410. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15411. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15412. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15413. static CFDictionaryRef
  15414. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15415. const SecTrustSettingsResult *result) {
  15416. auto constraint =
  15417. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15418. &kCFTypeDictionaryValueCallBacks);
  15419. if (policy) {
  15420. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15421. }
  15422. if (policy_string) {
  15423. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15424. kCFStringEncodingUTF8);
  15425. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15426. CFRelease(str);
  15427. }
  15428. if (result) {
  15429. auto number_value = static_cast<SInt32>(*result);
  15430. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15431. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15432. CFRelease(number);
  15433. }
  15434. return constraint;
  15435. }
  15436. static SecTrustSettingsResult
  15437. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15438. auto trust_settings =
  15439. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15440. for (auto constraint : constraints) {
  15441. CFArrayAppendValue(trust_settings, constraint);
  15442. CFRelease(constraint);
  15443. }
  15444. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15445. CFRelease(trust_settings);
  15446. return result;
  15447. }
  15448. // The system CA loader takes a Keychain certificate as a trusted root only
  15449. // when its Trust Settings say so for SSL, not merely because it has some.
  15450. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15451. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15452. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15453. const auto deny = kSecTrustSettingsResultDeny;
  15454. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15455. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15456. auto x509_policy = SecPolicyCreateBasicX509();
  15457. // "Always Trust", which stores no constraint at all
  15458. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15459. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15460. ssl_trust_settings_result(
  15461. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15462. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15463. ssl_trust_settings_result(
  15464. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15465. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15466. ssl_trust_settings_result(
  15467. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15468. // "Never Trust", for everything or for SSL
  15469. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15470. ssl_trust_settings_result(
  15471. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15472. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15473. ssl_trust_settings_result(
  15474. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15475. // Trusted for another policy, for one host, or not at all
  15476. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15477. ssl_trust_settings_result(
  15478. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15479. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15480. ssl_trust_settings_result({make_usage_constraint(
  15481. ssl_policy, "www.example.com", &trust_root)}));
  15482. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15483. ssl_trust_settings_result(
  15484. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15485. // The first constraint that applies to SSL decides
  15486. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15487. ssl_trust_settings_result(
  15488. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15489. make_usage_constraint(nullptr, nullptr, &deny)}));
  15490. CFRelease(x509_policy);
  15491. CFRelease(ssl_policy);
  15492. }
  15493. #endif
  15494. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15495. // skip chain verification entirely (only the certificate identity was
  15496. // checked), so a server presenting an untrusted certificate with a matching
  15497. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15498. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15499. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15500. ASSERT_TRUE(svr.is_valid());
  15501. svr.Get("/test", [&](const Request &, Response &res) {
  15502. res.set_content("test", "text/plain");
  15503. });
  15504. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15505. auto se = detail::scope_exit([&] {
  15506. svr.stop();
  15507. t.join();
  15508. ASSERT_FALSE(svr.is_running());
  15509. });
  15510. svr.wait_until_ready();
  15511. SSLClient cli("127.0.0.1", PORT);
  15512. std::string cert;
  15513. // A trusted CA that did not sign the server certificate. The server cert
  15514. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15515. // this connection.
  15516. read_file(CLIENT_CA_CERT_FILE, cert);
  15517. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15518. cli.enable_server_certificate_verification(true);
  15519. cli.set_connection_timeout(30);
  15520. auto res = cli.Get("/test");
  15521. ASSERT_FALSE(res);
  15522. }
  15523. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15524. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15525. // CA that failed to come through fails verification instead of trusting them.
  15526. // (wolfSSL does not list the system CAs it loaded.)
  15527. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15528. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15529. ASSERT_TRUE(svr.is_valid());
  15530. auto port = svr.bind_to_any_port("127.0.0.1");
  15531. ASSERT_LT(0, port);
  15532. thread t = thread([&] { svr.listen_after_bind(); });
  15533. auto se = detail::scope_exit([&] {
  15534. svr.stop();
  15535. t.join();
  15536. ASSERT_FALSE(svr.is_running());
  15537. });
  15538. svr.wait_until_ready();
  15539. // The CAs a client trusts once its first request has loaded them
  15540. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15541. Client cli("https://127.0.0.1:" + std::to_string(port));
  15542. setup(cli);
  15543. cli.Get("/");
  15544. return tls::get_ca_names(cli.tls_context()).size();
  15545. };
  15546. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15547. EXPECT_EQ(0u,
  15548. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15549. }
  15550. #endif
  15551. // A TLS setting changed between requests applies to the next one, not just to
  15552. // the next connection
  15553. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15554. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15555. ASSERT_TRUE(svr.is_valid());
  15556. svr.Get("/", [](const Request &req, Response &res) {
  15557. res.set_content(std::to_string(req.remote_port), "text/plain");
  15558. });
  15559. auto port = svr.bind_to_any_port("127.0.0.1");
  15560. ASSERT_LT(0, port);
  15561. thread t = thread([&] { svr.listen_after_bind(); });
  15562. auto se = detail::scope_exit([&] {
  15563. svr.stop();
  15564. t.join();
  15565. ASSERT_FALSE(svr.is_running());
  15566. });
  15567. svr.wait_until_ready();
  15568. SSLClient cli("127.0.0.1", port);
  15569. cli.set_keep_alive(true);
  15570. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15571. cli.enable_server_certificate_verification(false);
  15572. // The port the request went out from, so a new one means a new connection
  15573. auto client_port = [&] {
  15574. auto res = cli.Get("/");
  15575. return res ? res->body : std::string();
  15576. };
  15577. auto last = client_port();
  15578. ASSERT_FALSE(last.empty());
  15579. // Setting a value it already has keeps the connection
  15580. cli.enable_server_certificate_verification(false);
  15581. cli.enable_server_hostname_verification(true);
  15582. EXPECT_EQ(last, client_port());
  15583. cli.enable_server_certificate_verification(true);
  15584. auto res = cli.Get("/");
  15585. EXPECT_FALSE(res);
  15586. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15587. std::string ca;
  15588. read_file(SERVER_CERT2_FILE, ca);
  15589. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15590. last = client_port();
  15591. ASSERT_FALSE(last.empty());
  15592. std::vector<std::function<void()>> setters = {
  15593. [&] { cli.enable_server_hostname_verification(false); },
  15594. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15595. [&] {
  15596. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15597. },
  15598. [&] {
  15599. cli.set_server_certificate_verifier(
  15600. [](const tls::VerifyContext &) { return true; });
  15601. },
  15602. [&] {
  15603. cli.set_session_verifier(
  15604. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15605. },
  15606. };
  15607. for (const auto &setter : setters) {
  15608. setter();
  15609. auto next = client_port();
  15610. ASSERT_FALSE(next.empty());
  15611. EXPECT_NE(last, next);
  15612. last = next;
  15613. }
  15614. cli.set_session_verifier(
  15615. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15616. auto handle = cli.open_stream("GET", "/");
  15617. EXPECT_FALSE(handle.is_valid());
  15618. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15619. }
  15620. // A PEM given to create_ca_store() needs no NUL after it
  15621. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15622. std::string pem;
  15623. read_file(SERVER_CERT2_FILE, pem);
  15624. auto buf = pem + "X";
  15625. auto store = tls::create_ca_store(buf.data(), pem.size());
  15626. EXPECT_TRUE(store != nullptr);
  15627. SSLClient cli("localhost");
  15628. cli.set_ca_cert_store(store);
  15629. }
  15630. // enable_system_ca(false) prevents system CA loading entirely
  15631. TEST(SSLClientTest, DisableSystemCa_Online) {
  15632. SSLClient cli("google.com");
  15633. cli.enable_system_ca(false);
  15634. cli.enable_server_certificate_verification(true);
  15635. auto res = cli.Get("/");
  15636. ASSERT_FALSE(res);
  15637. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15638. // itself when the CA chain is empty
  15639. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15640. res.error() == Error::SSLConnection);
  15641. }
  15642. // The universal Client forwards enable_system_ca()
  15643. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15644. std::string cert;
  15645. read_file(SERVER_CERT2_FILE, cert);
  15646. Client cli("https://google.com");
  15647. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15648. cli.enable_system_ca(true);
  15649. cli.enable_server_certificate_verification(true);
  15650. auto res = cli.Get("/");
  15651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15652. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15653. }
  15654. // The system CA policy must carry over to the client created internally for
  15655. // following a cross-host HTTPS redirect
  15656. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15657. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15658. ASSERT_TRUE(svr.is_valid());
  15659. svr.Get("/index", [&](const Request &, Response &res) {
  15660. res.set_redirect("https://www.google.com/");
  15661. });
  15662. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15663. auto se = detail::scope_exit([&] {
  15664. svr.stop();
  15665. t.join();
  15666. ASSERT_FALSE(svr.is_running());
  15667. });
  15668. svr.wait_until_ready();
  15669. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15670. std::string cert;
  15671. read_file(SERVER_CERT2_FILE, cert);
  15672. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15673. cli.enable_system_ca(true);
  15674. cli.enable_server_certificate_verification(true);
  15675. cli.set_follow_location(true);
  15676. cli.set_connection_timeout(30);
  15677. // Receiving any response proves the redirect client completed the TLS
  15678. // handshake with a system-CA-signed host
  15679. auto res = cli.Get("/index");
  15680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15681. }
  15682. TEST(MultipartFormDataTest, LargeData) {
  15683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15684. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15685. const ContentReader &content_reader) {
  15686. if (req.is_multipart_form_data()) {
  15687. std::vector<FormData> items;
  15688. content_reader(
  15689. [&](const FormData &file) {
  15690. items.push_back(file);
  15691. return true;
  15692. },
  15693. [&](const char *data, size_t data_length) {
  15694. items.back().content.append(data, data_length);
  15695. return true;
  15696. });
  15697. EXPECT_TRUE(std::string(items[0].name) == "document");
  15698. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15699. EXPECT_TRUE(items[0].filename == "2MB_data");
  15700. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15701. EXPECT_TRUE(items[1].name == "hello");
  15702. EXPECT_TRUE(items[1].content == "world");
  15703. EXPECT_TRUE(items[1].filename == "");
  15704. EXPECT_TRUE(items[1].content_type == "");
  15705. } else {
  15706. std::string body;
  15707. content_reader([&](const char *data, size_t data_length) {
  15708. body.append(data, data_length);
  15709. return true;
  15710. });
  15711. }
  15712. });
  15713. auto port = svr.bind_to_any_port(HOST);
  15714. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15715. auto se = detail::scope_exit([&] {
  15716. svr.stop();
  15717. t.join();
  15718. ASSERT_FALSE(svr.is_running());
  15719. });
  15720. svr.wait_until_ready();
  15721. {
  15722. std::string data(1024 * 1024 * 2, '.');
  15723. std::stringstream buffer;
  15724. buffer << data;
  15725. SSLClient cli(HOST, port);
  15726. cli.enable_server_certificate_verification(false);
  15727. UploadFormDataItems items{
  15728. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15729. {"hello", "world", "", ""},
  15730. };
  15731. auto res = cli.Post("/post", items);
  15732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15733. ASSERT_EQ(StatusCode::OK_200, res->status);
  15734. }
  15735. }
  15736. TEST(MultipartFormDataTest, DataProviderItems) {
  15737. std::random_device seed_gen;
  15738. std::mt19937 random(seed_gen());
  15739. std::string rand1;
  15740. rand1.resize(1000);
  15741. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15742. std::string rand2;
  15743. rand2.resize(3000);
  15744. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15746. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15747. const ContentReader &content_reader) {
  15748. ASSERT_FALSE(req.is_multipart_form_data());
  15749. std::string body;
  15750. content_reader([&](const char *data, size_t data_length) {
  15751. body.append(data, data_length);
  15752. return true;
  15753. });
  15754. EXPECT_EQ(body, "");
  15755. });
  15756. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15757. const ContentReader &content_reader) {
  15758. ASSERT_TRUE(req.is_multipart_form_data());
  15759. std::vector<FormData> items;
  15760. content_reader(
  15761. [&](const FormData &file) {
  15762. items.push_back(file);
  15763. return true;
  15764. },
  15765. [&](const char *data, size_t data_length) {
  15766. items.back().content.append(data, data_length);
  15767. return true;
  15768. });
  15769. ASSERT_TRUE(items.size() == 2);
  15770. EXPECT_EQ(std::string(items[0].name), "name1");
  15771. EXPECT_EQ(items[0].content, "Testing123");
  15772. EXPECT_EQ(items[0].filename, "filename1");
  15773. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15774. EXPECT_EQ(items[1].name, "name2");
  15775. EXPECT_EQ(items[1].content, "Testing456");
  15776. EXPECT_EQ(items[1].filename, "");
  15777. EXPECT_EQ(items[1].content_type, "");
  15778. });
  15779. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15780. const ContentReader &content_reader) {
  15781. ASSERT_TRUE(req.is_multipart_form_data());
  15782. std::vector<FormData> items;
  15783. content_reader(
  15784. [&](const FormData &file) {
  15785. items.push_back(file);
  15786. return true;
  15787. },
  15788. [&](const char *data, size_t data_length) {
  15789. items.back().content.append(data, data_length);
  15790. return true;
  15791. });
  15792. ASSERT_TRUE(items.size() == 2);
  15793. EXPECT_EQ(items[0].name, "name3");
  15794. EXPECT_EQ(items[0].content, rand1);
  15795. EXPECT_EQ(items[0].filename, "filename3");
  15796. EXPECT_EQ(items[0].content_type, "");
  15797. EXPECT_EQ(items[1].name, "name4");
  15798. EXPECT_EQ(items[1].content, rand2);
  15799. EXPECT_EQ(items[1].filename, "filename4");
  15800. EXPECT_EQ(items[1].content_type, "");
  15801. });
  15802. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15803. const ContentReader &content_reader) {
  15804. ASSERT_TRUE(req.is_multipart_form_data());
  15805. std::vector<FormData> items;
  15806. content_reader(
  15807. [&](const FormData &file) {
  15808. items.push_back(file);
  15809. return true;
  15810. },
  15811. [&](const char *data, size_t data_length) {
  15812. items.back().content.append(data, data_length);
  15813. return true;
  15814. });
  15815. ASSERT_TRUE(items.size() == 4);
  15816. EXPECT_EQ(std::string(items[0].name), "name1");
  15817. EXPECT_EQ(items[0].content, "Testing123");
  15818. EXPECT_EQ(items[0].filename, "filename1");
  15819. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15820. EXPECT_EQ(items[1].name, "name2");
  15821. EXPECT_EQ(items[1].content, "Testing456");
  15822. EXPECT_EQ(items[1].filename, "");
  15823. EXPECT_EQ(items[1].content_type, "");
  15824. EXPECT_EQ(items[2].name, "name3");
  15825. EXPECT_EQ(items[2].content, rand1);
  15826. EXPECT_EQ(items[2].filename, "filename3");
  15827. EXPECT_EQ(items[2].content_type, "");
  15828. EXPECT_EQ(items[3].name, "name4");
  15829. EXPECT_EQ(items[3].content, rand2);
  15830. EXPECT_EQ(items[3].filename, "filename4");
  15831. EXPECT_EQ(items[3].content_type, "");
  15832. });
  15833. auto port = svr.bind_to_any_port("localhost");
  15834. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15835. auto se = detail::scope_exit([&] {
  15836. svr.stop();
  15837. t.join();
  15838. ASSERT_FALSE(svr.is_running());
  15839. });
  15840. svr.wait_until_ready();
  15841. {
  15842. SSLClient cli("localhost", port);
  15843. cli.enable_server_certificate_verification(false);
  15844. UploadFormDataItems items{
  15845. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15846. {"name2", "Testing456", "", ""}, // not a file
  15847. };
  15848. {
  15849. auto res = cli.Post("/post-none", {}, {}, {});
  15850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15851. ASSERT_EQ(StatusCode::OK_200, res->status);
  15852. }
  15853. FormDataProviderItems providers;
  15854. {
  15855. auto res =
  15856. cli.Post("/post-items", {}, items, providers); // empty providers
  15857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15858. ASSERT_EQ(StatusCode::OK_200, res->status);
  15859. }
  15860. providers.push_back({"name3",
  15861. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15862. // test the offset is given correctly at each step
  15863. if (!offset)
  15864. sink.os.write(rand1.data(), 30);
  15865. else if (offset == 30)
  15866. sink.os.write(rand1.data() + 30, 300);
  15867. else if (offset == 330)
  15868. sink.os.write(rand1.data() + 330, 670);
  15869. else if (offset == rand1.size())
  15870. sink.done();
  15871. return true;
  15872. },
  15873. "filename3",
  15874. {}});
  15875. providers.push_back({"name4",
  15876. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15877. // test the offset is given correctly at each step
  15878. if (!offset)
  15879. sink.os.write(rand2.data(), 2000);
  15880. else if (offset == 2000)
  15881. sink.os.write(rand2.data() + 2000, 1);
  15882. else if (offset == 2001)
  15883. sink.os.write(rand2.data() + 2001, 999);
  15884. else if (offset == rand2.size())
  15885. sink.done();
  15886. return true;
  15887. },
  15888. "filename4",
  15889. {}});
  15890. {
  15891. auto res = cli.Post("/post-providers", {}, {}, providers);
  15892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15893. ASSERT_EQ(StatusCode::OK_200, res->status);
  15894. }
  15895. {
  15896. auto res = cli.Post("/post-both", {}, items, providers);
  15897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15898. ASSERT_EQ(StatusCode::OK_200, res->status);
  15899. }
  15900. }
  15901. }
  15902. TEST(MultipartFormDataTest, BadHeader) {
  15903. Server svr;
  15904. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15905. res.set_content("ok", "text/plain");
  15906. });
  15907. thread t = thread([&] { svr.listen(HOST, PORT); });
  15908. auto se = detail::scope_exit([&] {
  15909. svr.stop();
  15910. t.join();
  15911. ASSERT_FALSE(svr.is_running());
  15912. });
  15913. svr.wait_until_ready();
  15914. const std::string body =
  15915. "This is the preamble. It is to be ignored, though it\r\n"
  15916. "is a handy place for composition agents to include an\r\n"
  15917. "explanatory note to non-MIME conformant readers.\r\n"
  15918. "\r\n"
  15919. "\r\n"
  15920. "--simple boundary\r\n"
  15921. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15922. ": BAD...\r\n"
  15923. "\r\n"
  15924. "value1\r\n"
  15925. "--simple boundary\r\n"
  15926. "Content-Disposition: form-data; name=\"field2\"; "
  15927. "filename=\"example.txt\"\r\n"
  15928. "\r\n"
  15929. "value2\r\n"
  15930. "--simple boundary--\r\n"
  15931. "This is the epilogue. It is also to be ignored.\r\n";
  15932. std::string content_type =
  15933. R"(multipart/form-data; boundary="simple boundary")";
  15934. Client cli(HOST, PORT);
  15935. auto res = cli.Post("/post", body, content_type.c_str());
  15936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15937. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15938. }
  15939. TEST(MultipartFormDataTest, WithPreamble) {
  15940. Server svr;
  15941. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15942. res.set_content("ok", "text/plain");
  15943. });
  15944. thread t = thread([&] { svr.listen(HOST, PORT); });
  15945. auto se = detail::scope_exit([&] {
  15946. svr.stop();
  15947. t.join();
  15948. ASSERT_FALSE(svr.is_running());
  15949. });
  15950. svr.wait_until_ready();
  15951. const std::string body =
  15952. "This is the preamble. It is to be ignored, though it\r\n"
  15953. "is a handy place for composition agents to include an\r\n"
  15954. "explanatory note to non-MIME conformant readers.\r\n"
  15955. "\r\n"
  15956. "\r\n"
  15957. "--simple boundary\r\n"
  15958. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15959. "\r\n"
  15960. "value1\r\n"
  15961. "--simple boundary\r\n"
  15962. "Content-Disposition: form-data; name=\"field2\"; "
  15963. "filename=\"example.txt\"\r\n"
  15964. "\r\n"
  15965. "value2\r\n"
  15966. "--simple boundary--\r\n"
  15967. "This is the epilogue. It is also to be ignored.\r\n";
  15968. std::string content_type =
  15969. R"(multipart/form-data; boundary="simple boundary")";
  15970. Client cli(HOST, PORT);
  15971. auto res = cli.Post("/post", body, content_type.c_str());
  15972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15973. EXPECT_EQ(StatusCode::OK_200, res->status);
  15974. }
  15975. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15977. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15978. const ContentReader &content_reader) {
  15979. if (req.is_multipart_form_data()) {
  15980. std::vector<FormData> items;
  15981. content_reader(
  15982. [&](const FormData &file) {
  15983. items.push_back(file);
  15984. return true;
  15985. },
  15986. [&](const char *data, size_t data_length) {
  15987. items.back().content.append(data, data_length);
  15988. return true;
  15989. });
  15990. EXPECT_TRUE(std::string(items[0].name) == "document");
  15991. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15992. EXPECT_TRUE(items[0].filename == "2MB_data");
  15993. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15994. EXPECT_TRUE(items[1].name == "hello");
  15995. EXPECT_TRUE(items[1].content == "world");
  15996. EXPECT_TRUE(items[1].filename == "");
  15997. EXPECT_TRUE(items[1].content_type == "");
  15998. } else {
  15999. std::string body;
  16000. content_reader([&](const char *data, size_t data_length) {
  16001. body.append(data, data_length);
  16002. return true;
  16003. });
  16004. }
  16005. });
  16006. auto port = svr.bind_to_any_port("localhost");
  16007. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16008. auto se = detail::scope_exit([&] {
  16009. svr.stop();
  16010. t.join();
  16011. ASSERT_FALSE(svr.is_running());
  16012. });
  16013. svr.wait_until_ready();
  16014. {
  16015. std::string data(1024 * 1024 * 2, '.');
  16016. std::stringstream buffer;
  16017. buffer << data;
  16018. SSLClient cli("localhost", port);
  16019. cli.enable_server_certificate_verification(false);
  16020. UploadFormDataItems items{
  16021. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16022. {"hello", "world", "", ""},
  16023. };
  16024. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16026. ASSERT_EQ(StatusCode::OK_200, res->status);
  16027. }
  16028. }
  16029. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16030. std::string data(1024 * 1024 * 2, '&');
  16031. std::stringstream buffer;
  16032. buffer << data;
  16033. Client cli("https://localhost:8080");
  16034. UploadFormDataItems items{
  16035. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16036. {"hello", "world", "", ""},
  16037. };
  16038. for (const char &c : " \t\r\n") {
  16039. auto res =
  16040. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16041. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16042. ASSERT_FALSE(res);
  16043. }
  16044. }
  16045. TEST(MultipartFormDataTest, PutFormData) {
  16046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16047. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16048. const ContentReader &content_reader) {
  16049. if (req.is_multipart_form_data()) {
  16050. std::vector<FormData> items;
  16051. content_reader(
  16052. [&](const FormData &file) {
  16053. items.push_back(file);
  16054. return true;
  16055. },
  16056. [&](const char *data, size_t data_length) {
  16057. items.back().content.append(data, data_length);
  16058. return true;
  16059. });
  16060. EXPECT_TRUE(std::string(items[0].name) == "document");
  16061. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16062. EXPECT_TRUE(items[0].filename == "2MB_data");
  16063. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16064. EXPECT_TRUE(items[1].name == "hello");
  16065. EXPECT_TRUE(items[1].content == "world");
  16066. EXPECT_TRUE(items[1].filename == "");
  16067. EXPECT_TRUE(items[1].content_type == "");
  16068. } else {
  16069. std::string body;
  16070. content_reader([&](const char *data, size_t data_length) {
  16071. body.append(data, data_length);
  16072. return true;
  16073. });
  16074. }
  16075. });
  16076. auto port = svr.bind_to_any_port("localhost");
  16077. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16078. auto se = detail::scope_exit([&] {
  16079. svr.stop();
  16080. t.join();
  16081. ASSERT_FALSE(svr.is_running());
  16082. });
  16083. svr.wait_until_ready();
  16084. {
  16085. std::string data(1024 * 1024 * 2, '&');
  16086. std::stringstream buffer;
  16087. buffer << data;
  16088. SSLClient cli("localhost", port);
  16089. cli.enable_server_certificate_verification(false);
  16090. UploadFormDataItems items{
  16091. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16092. {"hello", "world", "", ""},
  16093. };
  16094. auto res = cli.Put("/put", items);
  16095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16096. ASSERT_EQ(StatusCode::OK_200, res->status);
  16097. }
  16098. }
  16099. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16101. svr.Put("/put_customboundary",
  16102. [&](const Request &req, const Response & /*res*/,
  16103. const ContentReader &content_reader) {
  16104. if (req.is_multipart_form_data()) {
  16105. std::vector<FormData> items;
  16106. content_reader(
  16107. [&](const FormData &file) {
  16108. items.push_back(file);
  16109. return true;
  16110. },
  16111. [&](const char *data, size_t data_length) {
  16112. items.back().content.append(data, data_length);
  16113. return true;
  16114. });
  16115. EXPECT_TRUE(std::string(items[0].name) == "document");
  16116. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16117. EXPECT_TRUE(items[0].filename == "2MB_data");
  16118. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16119. EXPECT_TRUE(items[1].name == "hello");
  16120. EXPECT_TRUE(items[1].content == "world");
  16121. EXPECT_TRUE(items[1].filename == "");
  16122. EXPECT_TRUE(items[1].content_type == "");
  16123. } else {
  16124. std::string body;
  16125. content_reader([&](const char *data, size_t data_length) {
  16126. body.append(data, data_length);
  16127. return true;
  16128. });
  16129. }
  16130. });
  16131. auto port = svr.bind_to_any_port("localhost");
  16132. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16133. auto se = detail::scope_exit([&] {
  16134. svr.stop();
  16135. t.join();
  16136. ASSERT_FALSE(svr.is_running());
  16137. });
  16138. svr.wait_until_ready();
  16139. {
  16140. std::string data(1024 * 1024 * 2, '&');
  16141. std::stringstream buffer;
  16142. buffer << data;
  16143. SSLClient cli("localhost", port);
  16144. cli.enable_server_certificate_verification(false);
  16145. UploadFormDataItems items{
  16146. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16147. {"hello", "world", "", ""},
  16148. };
  16149. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16151. ASSERT_EQ(StatusCode::OK_200, res->status);
  16152. }
  16153. }
  16154. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16155. std::string data(1024 * 1024 * 2, '&');
  16156. std::stringstream buffer;
  16157. buffer << data;
  16158. Client cli("https://localhost:8080");
  16159. cli.enable_server_certificate_verification(false);
  16160. UploadFormDataItems items{
  16161. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16162. {"hello", "world", "", ""},
  16163. };
  16164. for (const char &c : " \t\r\n") {
  16165. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16166. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16167. ASSERT_FALSE(res);
  16168. }
  16169. }
  16170. TEST(MultipartFormDataTest, AlternateFilename) {
  16171. auto handled = false;
  16172. Server svr;
  16173. svr.Post("/test", [&](const Request &req, Response &res) {
  16174. ASSERT_EQ(2u, req.form.files.size());
  16175. ASSERT_EQ(1u, req.form.fields.size());
  16176. // Test files
  16177. const auto &file1 = req.form.get_file("file1");
  16178. ASSERT_EQ("file1", file1.name);
  16179. ASSERT_EQ("A.txt", file1.filename);
  16180. ASSERT_EQ("text/plain", file1.content_type);
  16181. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16182. const auto &file2 = req.form.get_file("file2");
  16183. ASSERT_EQ("file2", file2.name);
  16184. ASSERT_EQ("a.html", file2.filename);
  16185. ASSERT_EQ("text/html", file2.content_type);
  16186. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16187. file2.content);
  16188. // Test text field
  16189. const auto &text = req.form.get_field("text");
  16190. ASSERT_EQ("text default", text);
  16191. res.set_content("ok", "text/plain");
  16192. handled = true;
  16193. });
  16194. thread t = thread([&] { svr.listen(HOST, PORT); });
  16195. auto se = detail::scope_exit([&] {
  16196. svr.stop();
  16197. t.join();
  16198. ASSERT_FALSE(svr.is_running());
  16199. ASSERT_TRUE(handled);
  16200. });
  16201. svr.wait_until_ready();
  16202. auto req = "POST /test HTTP/1.1\r\n"
  16203. "Host: localhost\r\n"
  16204. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16205. "Content-Length: 399\r\n"
  16206. "\r\n"
  16207. "----------\r\n"
  16208. "Content-Disposition: form-data; name=\"text\"\r\n"
  16209. "\r\n"
  16210. "text default\r\n"
  16211. "----------\r\n"
  16212. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16213. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16214. "Content-Type: text/plain\r\n"
  16215. "\r\n"
  16216. "Content of a.txt.\r\n"
  16217. "\r\n"
  16218. "----------\r\n"
  16219. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16220. "\"a.html\"\r\n"
  16221. "Content-Type: text/html\r\n"
  16222. "\r\n"
  16223. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16224. "\r\n"
  16225. "------------\r\n";
  16226. ASSERT_TRUE(send_request(1, req));
  16227. }
  16228. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16229. auto handled = false;
  16230. Server svr;
  16231. svr.Post("/test", [&](const Request &req, Response &res) {
  16232. // Case-insensitive "utf-8''" prefix with a long value
  16233. const auto &file = req.form.get_file("file1");
  16234. ASSERT_EQ("file1", file.name);
  16235. // 8000 chars exercises both the Content-Disposition parser and the
  16236. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16237. // Prior to the fix, std::regex_match on this header would cause O(N)
  16238. // stack recursion in libstdc++, leading to SIGSEGV.
  16239. std::string expected_filename(8000, 'A');
  16240. ASSERT_EQ(expected_filename, file.filename);
  16241. res.set_content("ok", "text/plain");
  16242. handled = true;
  16243. });
  16244. thread t = thread([&] { svr.listen(HOST, PORT); });
  16245. auto se = detail::scope_exit([&] {
  16246. svr.stop();
  16247. t.join();
  16248. ASSERT_FALSE(svr.is_running());
  16249. ASSERT_TRUE(handled);
  16250. });
  16251. svr.wait_until_ready();
  16252. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16253. // Regression test for GHSA-qq6v-r583-3h69
  16254. std::string long_filename(8000, 'A');
  16255. std::string body = "----------\r\n"
  16256. "Content-Disposition: form-data; name=\"file1\"; "
  16257. "filename*=\"Utf-8''" +
  16258. long_filename +
  16259. "\"\r\n"
  16260. "\r\n"
  16261. "hello\r\n"
  16262. "------------\r\n";
  16263. auto req = "POST /test HTTP/1.1\r\n"
  16264. "Host: localhost\r\n"
  16265. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16266. "Content-Length: " +
  16267. std::to_string(body.size()) + "\r\n\r\n" + body;
  16268. ASSERT_TRUE(send_request(1, req));
  16269. }
  16270. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16271. auto handled = false;
  16272. Server svr;
  16273. svr.Post("/test", [&](const Request &req, Response &) {
  16274. ASSERT_EQ(2u, req.form.fields.size());
  16275. const auto &text1 = req.form.get_field("text1");
  16276. ASSERT_EQ("text1", text1);
  16277. const auto &text2 = req.form.get_field("text2");
  16278. ASSERT_EQ("text2", text2);
  16279. handled = true;
  16280. });
  16281. thread t = thread([&] { svr.listen(HOST, PORT); });
  16282. auto se = detail::scope_exit([&] {
  16283. svr.stop();
  16284. t.join();
  16285. ASSERT_FALSE(svr.is_running());
  16286. ASSERT_TRUE(handled);
  16287. });
  16288. svr.wait_until_ready();
  16289. auto req = "POST /test HTTP/1.1\r\n"
  16290. "Host: localhost\r\n"
  16291. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16292. "Content-Length: 146\r\n"
  16293. "\r\n----------\r\n"
  16294. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16295. "\r\n"
  16296. "text1"
  16297. "\r\n----------\r\n"
  16298. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16299. "\r\n"
  16300. "text2"
  16301. "\r\n------------";
  16302. std::string response;
  16303. ASSERT_TRUE(send_request(1, req, &response));
  16304. ASSERT_EQ("200", response.substr(9, 3));
  16305. }
  16306. TEST(MultipartFormDataTest, ContentLength) {
  16307. auto handled = false;
  16308. Server svr;
  16309. svr.Post("/test", [&](const Request &req, Response &) {
  16310. ASSERT_EQ(2u, req.form.fields.size());
  16311. const auto &text1 = req.form.get_field("text1");
  16312. ASSERT_EQ("text1", text1);
  16313. const auto &text2 = req.form.get_field("text2");
  16314. ASSERT_EQ("text2", text2);
  16315. handled = true;
  16316. });
  16317. thread t = thread([&] { svr.listen(HOST, PORT); });
  16318. auto se = detail::scope_exit([&] {
  16319. svr.stop();
  16320. t.join();
  16321. ASSERT_FALSE(svr.is_running());
  16322. ASSERT_TRUE(handled);
  16323. });
  16324. svr.wait_until_ready();
  16325. auto req = "POST /test HTTP/1.1\r\n"
  16326. "Host: localhost\r\n"
  16327. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16328. "Content-Length: 167\r\n"
  16329. "\r\n----------\r\n"
  16330. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16331. "Content-Length: 5\r\n"
  16332. "\r\n"
  16333. "text1"
  16334. "\r\n----------\r\n"
  16335. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16336. "\r\n"
  16337. "text2"
  16338. "\r\n------------\r\n";
  16339. std::string response;
  16340. ASSERT_TRUE(send_request(1, req, &response));
  16341. ASSERT_EQ("200", response.substr(9, 3));
  16342. }
  16343. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16344. auto handled = false;
  16345. Server svr;
  16346. svr.Post("/test", [&](const Request &req, Response &) {
  16347. ASSERT_EQ(2u, req.form.fields.size());
  16348. const auto &text1 = req.form.get_field("text1");
  16349. ASSERT_EQ("text1", text1);
  16350. // TODO: Add header access for text fields if needed
  16351. const auto &text2 = req.form.get_field("text2");
  16352. ASSERT_EQ("text2", text2);
  16353. // TODO: Header access for text fields needs to be implemented
  16354. // auto &headers = it->second.headers;
  16355. // ASSERT_EQ(3U, headers.size());
  16356. // auto custom_header = headers.find("x-whatever");
  16357. // ASSERT_TRUE(custom_header != headers.end());
  16358. // ASSERT_NE("customvalue", custom_header->second);
  16359. // ASSERT_EQ("CustomValue", custom_header->second);
  16360. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16361. handled = true;
  16362. });
  16363. thread t = thread([&] { svr.listen(HOST, PORT); });
  16364. auto se = detail::scope_exit([&] {
  16365. svr.stop();
  16366. t.join();
  16367. ASSERT_FALSE(svr.is_running());
  16368. ASSERT_TRUE(handled);
  16369. });
  16370. svr.wait_until_ready();
  16371. auto req = "POST /test HTTP/1.1\r\n"
  16372. "Host: localhost\r\n"
  16373. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16374. "Content-Length: 232\r\n"
  16375. "\r\n----------\r\n"
  16376. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16377. "Content-Length: 5\r\n"
  16378. "X-Test: 1\r\n"
  16379. "\r\n"
  16380. "text1"
  16381. "\r\n----------\r\n"
  16382. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16383. "Content-Type: text/plain\r\n"
  16384. "X-Whatever: CustomValue\r\n"
  16385. "\r\n"
  16386. "text2"
  16387. "\r\n------------\r\n"
  16388. "That should be disregarded. Not even read";
  16389. std::string response;
  16390. ASSERT_TRUE(send_request(1, req, &response));
  16391. ASSERT_EQ("200", response.substr(9, 3));
  16392. }
  16393. TEST(MultipartFormDataTest, LargeHeader) {
  16394. auto handled = false;
  16395. Server svr;
  16396. svr.Post("/test", [&](const Request &req, Response &) {
  16397. ASSERT_EQ(1u, req.form.fields.size());
  16398. const auto &text = req.form.get_field("name1");
  16399. ASSERT_EQ("text1", text);
  16400. handled = true;
  16401. });
  16402. thread t = thread([&] { svr.listen(HOST, PORT); });
  16403. auto se = detail::scope_exit([&] {
  16404. svr.stop();
  16405. t.join();
  16406. ASSERT_FALSE(svr.is_running());
  16407. ASSERT_TRUE(handled);
  16408. });
  16409. svr.wait_until_ready();
  16410. auto boundary = std::string("cpp-httplib-multipart-data");
  16411. std::string content = "--" + boundary +
  16412. "\r\n"
  16413. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16414. "\r\n"
  16415. "text1\r\n"
  16416. "--" +
  16417. boundary + "--\r\n";
  16418. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16419. "Host: localhost\r\n"
  16420. "Content-Type: multipart/form-data;boundary=" +
  16421. boundary +
  16422. "\r\n"
  16423. "Content-Length: " +
  16424. std::to_string(content.size()) +
  16425. "\r\n"
  16426. "Dummy-Header: ";
  16427. std::string header_suffix = "\r\n"
  16428. "\r\n";
  16429. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16430. size_t header_dummy_size =
  16431. read_buff_size -
  16432. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16433. auto header_dummy = std::string(header_dummy_size, '@');
  16434. auto req = header_prefix + header_dummy + header_suffix + content;
  16435. std::string response;
  16436. ASSERT_TRUE(send_request(1, req, &response));
  16437. ASSERT_EQ("200", response.substr(9, 3));
  16438. }
  16439. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16440. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16441. // (not chunked Transfer-Encoding) after the streaming refactor.
  16442. auto handled = false;
  16443. Server svr;
  16444. svr.Post("/upload", [&](const Request &req, Response &res) {
  16445. auto cl_it = req.headers.find("Content-Length");
  16446. EXPECT_TRUE(cl_it != req.headers.end());
  16447. auto te_it = req.headers.find("Transfer-Encoding");
  16448. EXPECT_TRUE(te_it == req.headers.end());
  16449. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16450. res.set_content("ok", "text/plain");
  16451. handled = true;
  16452. });
  16453. auto port = svr.bind_to_any_port(HOST);
  16454. auto t = thread([&] { svr.listen_after_bind(); });
  16455. auto se = detail::scope_exit([&] {
  16456. svr.stop();
  16457. t.join();
  16458. ASSERT_FALSE(svr.is_running());
  16459. ASSERT_TRUE(handled);
  16460. });
  16461. svr.wait_until_ready();
  16462. UploadFormDataItems items = {
  16463. {"field1", "hello", "", "text/plain"},
  16464. {"file1", "world", "test.txt", "application/octet-stream"},
  16465. };
  16466. Client cli(HOST, port);
  16467. auto res = cli.Post("/upload", {}, items);
  16468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16469. EXPECT_EQ(StatusCode::OK_200, res->status);
  16470. }
  16471. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16472. // Verify that make_multipart_content_provider coalesces many small segments
  16473. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16474. constexpr size_t kItemCount = 1000;
  16475. UploadFormDataItems items;
  16476. items.reserve(kItemCount);
  16477. for (size_t i = 0; i < kItemCount; i++) {
  16478. items.push_back(
  16479. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16480. }
  16481. const std::string boundary = "----test-boundary";
  16482. auto content_length = detail::get_multipart_content_length(items, boundary);
  16483. auto provider = detail::make_multipart_content_provider(items, boundary);
  16484. // Drive the provider the same way write_content_with_progress does
  16485. size_t write_count = 0;
  16486. size_t total_bytes = 0;
  16487. DataSink sink;
  16488. size_t offset = 0;
  16489. sink.write = [&](const char *d, size_t l) -> bool {
  16490. (void)d;
  16491. write_count++;
  16492. total_bytes += l;
  16493. offset += l;
  16494. return true;
  16495. };
  16496. sink.is_writable = []() -> bool { return true; };
  16497. while (offset < content_length) {
  16498. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16499. }
  16500. EXPECT_EQ(content_length, total_bytes);
  16501. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16502. // With buffering into 64KB blocks, write_count should be much smaller.
  16503. auto segment_count = 3 * kItemCount + 1;
  16504. EXPECT_LT(write_count, segment_count / 10);
  16505. }
  16506. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16507. // Integration test: send many UploadFormDataItems and verify the server
  16508. // receives all of them correctly (#2410).
  16509. constexpr size_t kItemCount = 500;
  16510. auto handled = false;
  16511. Server svr;
  16512. svr.Post("/upload", [&](const Request &req, Response &res) {
  16513. EXPECT_EQ(kItemCount, req.form.fields.size());
  16514. for (size_t i = 0; i < kItemCount; i++) {
  16515. auto key = "field" + std::to_string(i);
  16516. auto val = "value" + std::to_string(i);
  16517. auto it = req.form.fields.find(key);
  16518. if (it != req.form.fields.end()) {
  16519. EXPECT_EQ(val, it->second.content);
  16520. } else {
  16521. ADD_FAILURE() << "Missing field: " << key;
  16522. }
  16523. }
  16524. res.set_content("ok", "text/plain");
  16525. handled = true;
  16526. });
  16527. auto port = svr.bind_to_any_port(HOST);
  16528. auto t = thread([&] { svr.listen_after_bind(); });
  16529. auto se = detail::scope_exit([&] {
  16530. svr.stop();
  16531. t.join();
  16532. ASSERT_FALSE(svr.is_running());
  16533. ASSERT_TRUE(handled);
  16534. });
  16535. svr.wait_until_ready();
  16536. UploadFormDataItems items;
  16537. items.reserve(kItemCount);
  16538. for (size_t i = 0; i < kItemCount; i++) {
  16539. items.push_back(
  16540. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16541. }
  16542. Client cli(HOST, port);
  16543. auto res = cli.Post("/upload", items);
  16544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16545. EXPECT_EQ(StatusCode::OK_200, res->status);
  16546. }
  16547. TEST(MultipartFormDataTest, MakeFileProvider) {
  16548. // Verify make_file_provider sends a file's contents correctly.
  16549. const std::string file_content(4096, 'Z');
  16550. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16551. {
  16552. std::ofstream ofs(tmp_path, std::ios::binary);
  16553. ofs.write(file_content.data(),
  16554. static_cast<std::streamsize>(file_content.size()));
  16555. }
  16556. auto handled = false;
  16557. Server svr;
  16558. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16559. const ContentReader &content_reader) {
  16560. ASSERT_TRUE(req.is_multipart_form_data());
  16561. std::vector<FormData> items;
  16562. content_reader(
  16563. [&](const FormData &file) {
  16564. items.push_back(file);
  16565. return true;
  16566. },
  16567. [&](const char *data, size_t data_length) {
  16568. items.back().content.append(data, data_length);
  16569. return true;
  16570. });
  16571. ASSERT_EQ(1u, items.size());
  16572. EXPECT_EQ("myfile", items[0].name);
  16573. EXPECT_EQ("data.bin", items[0].filename);
  16574. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16575. EXPECT_EQ(file_content, items[0].content);
  16576. handled = true;
  16577. });
  16578. auto port = svr.bind_to_any_port(HOST);
  16579. auto t = thread([&] { svr.listen_after_bind(); });
  16580. auto se = detail::scope_exit([&] {
  16581. svr.stop();
  16582. t.join();
  16583. ASSERT_FALSE(svr.is_running());
  16584. ASSERT_TRUE(handled);
  16585. std::remove(tmp_path.c_str());
  16586. });
  16587. svr.wait_until_ready();
  16588. FormDataProviderItems providers;
  16589. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16590. "application/octet-stream"));
  16591. Client cli(HOST, port);
  16592. auto res = cli.Post("/upload", {}, {}, providers);
  16593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16594. EXPECT_EQ(StatusCode::OK_200, res->status);
  16595. }
  16596. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16597. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16598. // (100) headers is rejected with a 400 Bad Request response.
  16599. Server svr;
  16600. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16601. res.set_content("ok", "text/plain");
  16602. });
  16603. thread t = thread([&] { svr.listen(HOST, PORT); });
  16604. auto se = detail::scope_exit([&] {
  16605. svr.stop();
  16606. t.join();
  16607. ASSERT_FALSE(svr.is_running());
  16608. });
  16609. svr.wait_until_ready();
  16610. // Build a multipart part with 101 custom headers (exceeding
  16611. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16612. std::stringstream body;
  16613. body << "--simpleboundary\r\n"
  16614. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16615. for (int i = 0; i < 101; i++) {
  16616. body << "X-Custom-Header-" << i << ": value\r\n";
  16617. }
  16618. body << "\r\n"
  16619. << "value1\r\n"
  16620. << "--simpleboundary--\r\n";
  16621. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16622. Client cli(HOST, PORT);
  16623. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16625. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16626. }
  16627. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16628. // A body that never contains the declared boundary must not be accumulated
  16629. // while the parser waits for it. Buffering it would also make every read
  16630. // rescan everything seen so far, which is quadratic in the body size.
  16631. Server svr;
  16632. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16633. res.set_content("ok", "text/plain");
  16634. });
  16635. auto port = svr.bind_to_any_port(HOST);
  16636. thread t = thread([&] { svr.listen_after_bind(); });
  16637. auto se = detail::scope_exit([&] {
  16638. svr.stop();
  16639. t.join();
  16640. ASSERT_FALSE(svr.is_running());
  16641. });
  16642. svr.wait_until_ready();
  16643. Client cli(HOST, port);
  16644. cli.set_read_timeout(60, 0);
  16645. cli.set_write_timeout(60, 0);
  16646. // '-' is the worst case: it matches the first character of the boundary, so
  16647. // every position has to be checked against it.
  16648. auto post_dashes = [&](size_t size) {
  16649. const std::string body(size, '-');
  16650. auto start = std::chrono::steady_clock::now();
  16651. auto res =
  16652. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16653. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16654. std::chrono::steady_clock::now() - start)
  16655. .count();
  16656. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16657. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16658. return ms;
  16659. };
  16660. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16661. // Windows.
  16662. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16663. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16664. // Comparing the two sizes rather than checking an absolute duration keeps
  16665. // this meaningful across build types and CI load, both of which move the
  16666. // absolute numbers by more than an order of magnitude. Four times the bytes
  16667. // costs about four times the time when parsing is linear, and about sixteen
  16668. // times when the body is buffered and rescanned.
  16669. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16670. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16671. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16672. << "ms, which suggests the body is being buffered and rescanned";
  16673. }
  16674. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16675. // A boundary can only be followed by CRLF or by "--", so anything else is
  16676. // malformed no matter what comes next. The parser must say so right away
  16677. // instead of buffering the rest of the declared body.
  16678. Server svr;
  16679. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16680. res.set_content("ok", "text/plain");
  16681. });
  16682. auto port = svr.bind_to_any_port(HOST);
  16683. thread t = thread([&] { svr.listen_after_bind(); });
  16684. auto se = detail::scope_exit([&] {
  16685. svr.stop();
  16686. t.join();
  16687. ASSERT_FALSE(svr.is_running());
  16688. });
  16689. svr.wait_until_ready();
  16690. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16691. // buffers instead of failing would still be waiting for the remaining bytes.
  16692. const std::string body = "--zzzz\r\n"
  16693. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16694. "\r\n"
  16695. "text1"
  16696. "\r\n--zzzzXX";
  16697. const std::string req = "POST /post HTTP/1.1\r\n"
  16698. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16699. "Content-Length: 1048576\r\n"
  16700. "\r\n" +
  16701. body;
  16702. std::string response;
  16703. ASSERT_TRUE(send_request(3, req, &response, port));
  16704. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16705. EXPECT_EQ("400", response.substr(9, 3));
  16706. }
  16707. // Posts a multipart body split into two writes, so that the server sees the
  16708. // split at whatever offset the caller chose, and expects the single "text1"
  16709. // field to come through.
  16710. static void expect_split_multipart_ok(const std::string &body1,
  16711. const std::string &body2) {
  16712. auto handled = false;
  16713. Server svr;
  16714. svr.Post("/post", [&](const Request &req, Response &) {
  16715. EXPECT_EQ(1u, req.form.fields.size());
  16716. EXPECT_EQ("text1", req.form.get_field("text1"));
  16717. handled = true;
  16718. });
  16719. auto port = svr.bind_to_any_port(HOST);
  16720. thread t = thread([&] { svr.listen_after_bind(); });
  16721. auto se = detail::scope_exit([&] {
  16722. svr.stop();
  16723. t.join();
  16724. ASSERT_FALSE(svr.is_running());
  16725. ASSERT_TRUE(handled);
  16726. });
  16727. svr.wait_until_ready();
  16728. // "Connection: close" makes the server close once it has answered, so the
  16729. // response drain ends immediately instead of idling until the read timeout.
  16730. const std::string head =
  16731. "POST /post HTTP/1.1\r\n"
  16732. "Host: localhost\r\n"
  16733. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16734. "Connection: close\r\n"
  16735. "Content-Length: " +
  16736. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16737. std::string response;
  16738. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16739. ASSERT_GE(response.size(), 12u) << "no response";
  16740. EXPECT_EQ("200", response.substr(9, 3));
  16741. }
  16742. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16743. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16744. // ignored, including when it does not arrive in the same read as the
  16745. // close-delimiter itself.
  16746. expect_split_multipart_ok("--zzzz\r\n"
  16747. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16748. "\r\n"
  16749. "text1"
  16750. "\r\n--zzzz--",
  16751. "\r\nthis epilogue must be ignored\r\n");
  16752. }
  16753. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16754. // The initial boundary may be preceded by a preamble of any length and may
  16755. // straddle a read boundary. Discarding data while waiting for it must not
  16756. // throw away a partial boundary sitting at the end of the buffer.
  16757. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16758. "zz\r\n"
  16759. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16760. "\r\n"
  16761. "text1"
  16762. "\r\n--zzzz--\r\n");
  16763. }
  16764. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16765. // The received boundary was only checked for being non-empty, so it could be
  16766. // as long as a header is allowed to be. The parser scans the body for
  16767. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16768. // costs a nearly full comparison at nearly every position, making the
  16769. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16770. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16771. Server svr;
  16772. svr.Post("/post", [](const Request &req, Response &res) {
  16773. EXPECT_EQ(1u, req.form.fields.size());
  16774. EXPECT_EQ("text1", req.form.get_field("text1"));
  16775. res.set_content("ok", "text/plain");
  16776. });
  16777. auto port = svr.bind_to_any_port(HOST);
  16778. thread t = thread([&] { svr.listen_after_bind(); });
  16779. auto se = detail::scope_exit([&] {
  16780. svr.stop();
  16781. t.join();
  16782. ASSERT_FALSE(svr.is_running());
  16783. });
  16784. svr.wait_until_ready();
  16785. Client cli(HOST, port);
  16786. auto post_with_boundary_of_length = [&](size_t len) {
  16787. const std::string boundary(len, 'a');
  16788. const std::string body =
  16789. "--" + boundary +
  16790. "\r\n"
  16791. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16792. "\r\n"
  16793. "text1"
  16794. "\r\n--" +
  16795. boundary + "--\r\n";
  16796. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16797. };
  16798. auto res = post_with_boundary_of_length(70);
  16799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16800. EXPECT_EQ(StatusCode::OK_200, res->status);
  16801. res = post_with_boundary_of_length(71);
  16802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16803. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16804. }
  16805. TEST(MakeFileBodyTest, Basic) {
  16806. const std::string file_content(4096, 'Z');
  16807. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16808. {
  16809. std::ofstream ofs(tmp_path, std::ios::binary);
  16810. ofs.write(file_content.data(),
  16811. static_cast<std::streamsize>(file_content.size()));
  16812. }
  16813. auto handled = false;
  16814. Server svr;
  16815. svr.Post("/upload", [&](const Request &req, Response &res) {
  16816. EXPECT_EQ(file_content, req.body);
  16817. handled = true;
  16818. res.status = StatusCode::OK_200;
  16819. });
  16820. auto port = svr.bind_to_any_port(HOST);
  16821. auto t = thread([&] { svr.listen_after_bind(); });
  16822. auto se = detail::scope_exit([&] {
  16823. svr.stop();
  16824. t.join();
  16825. ASSERT_FALSE(svr.is_running());
  16826. ASSERT_TRUE(handled);
  16827. std::remove(tmp_path.c_str());
  16828. });
  16829. svr.wait_until_ready();
  16830. auto fb = make_file_body(tmp_path);
  16831. ASSERT_GT(fb.first, 0u);
  16832. Client cli(HOST, port);
  16833. auto res =
  16834. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16836. EXPECT_EQ(StatusCode::OK_200, res->status);
  16837. }
  16838. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16839. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16840. {
  16841. std::ofstream ofs(path, std::ios::binary);
  16842. const std::string content(100, 'A');
  16843. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16844. }
  16845. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16846. auto body = make_file_body(path);
  16847. ASSERT_EQ(100u, body.first);
  16848. ASSERT_TRUE(static_cast<bool>(body.second));
  16849. // Rewritten shorter after its length was measured - and, on a server, after
  16850. // that length has already gone out as Content-Length.
  16851. {
  16852. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16853. const std::string content(10, 'A');
  16854. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16855. }
  16856. std::string written;
  16857. DataSink sink;
  16858. sink.write = [&](const char *d, size_t l) {
  16859. written.append(d, l);
  16860. return true;
  16861. };
  16862. // The provider has to report failure. write_content_with_progress() advances
  16863. // its offset only by what was written, so a provider that returns true
  16864. // without completing the length it promised is called again straight away,
  16865. // and again.
  16866. EXPECT_FALSE(body.second(0, body.first, sink));
  16867. EXPECT_EQ(std::string(10, 'A'), written);
  16868. }
  16869. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16870. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16871. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16872. {
  16873. std::ofstream ofs(path, std::ios::binary);
  16874. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16875. }
  16876. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16877. auto body = make_file_body(path);
  16878. ASSERT_EQ(content.size(), body.first);
  16879. ASSERT_TRUE(static_cast<bool>(body.second));
  16880. std::string written;
  16881. DataSink sink;
  16882. sink.write = [&](const char *d, size_t l) {
  16883. written.append(d, l);
  16884. return true;
  16885. };
  16886. EXPECT_TRUE(body.second(0, body.first, sink));
  16887. EXPECT_EQ(content, written);
  16888. }
  16889. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16890. static constexpr unsigned int number_of_tasks{1000000};
  16891. std::atomic_uint count{0};
  16892. std::unique_ptr<TaskQueue> task_queue{
  16893. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16894. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16895. auto queued = task_queue->enqueue(
  16896. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16897. EXPECT_TRUE(queued);
  16898. }
  16899. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16900. task_queue->shutdown();
  16901. #else
  16902. EXPECT_NO_THROW(task_queue->shutdown());
  16903. #endif
  16904. EXPECT_EQ(number_of_tasks, count.load());
  16905. }
  16906. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16907. static constexpr unsigned int number_of_tasks{1000000};
  16908. static constexpr unsigned int qlimit{2};
  16909. unsigned int queued_count{0};
  16910. std::atomic_uint count{0};
  16911. std::unique_ptr<TaskQueue> task_queue{
  16912. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16913. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16914. if (task_queue->enqueue(
  16915. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16916. queued_count++;
  16917. }
  16918. }
  16919. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16920. task_queue->shutdown();
  16921. #else
  16922. EXPECT_NO_THROW(task_queue->shutdown());
  16923. #endif
  16924. EXPECT_EQ(queued_count, count.load());
  16925. EXPECT_TRUE(queued_count <= number_of_tasks);
  16926. EXPECT_TRUE(queued_count >= qlimit);
  16927. }
  16928. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16929. // Use a short idle timeout so a dynamic thread spawns, times out and
  16930. // exits during the test, and the pool keeps working afterwards.
  16931. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16932. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16933. /*idle_timeout_sec=*/1}};
  16934. std::atomic_uint count{0};
  16935. std::condition_variable cv;
  16936. std::mutex mtx;
  16937. bool release = false;
  16938. // Block the base thread so the second task spawns a dynamic thread.
  16939. EXPECT_TRUE(task_queue->enqueue([&] {
  16940. std::unique_lock<std::mutex> lock(mtx);
  16941. while (!release) {
  16942. cv.wait(lock);
  16943. }
  16944. count++;
  16945. }));
  16946. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16947. // Let the dynamic thread finish its task and exceed the idle timeout.
  16948. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16949. {
  16950. std::unique_lock<std::mutex> lock(mtx);
  16951. release = true;
  16952. }
  16953. cv.notify_all();
  16954. // The pool must still accept and run tasks after the dynamic thread exited.
  16955. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16956. task_queue->shutdown();
  16957. EXPECT_EQ(3u, count.load());
  16958. }
  16959. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16960. static constexpr size_t number_of_tasks{32};
  16961. std::unique_ptr<TaskQueue> task_queue{
  16962. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16963. // Let the base threads go idle so the burst below finds them waiting.
  16964. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16965. std::mutex mtx;
  16966. std::condition_variable cv;
  16967. size_t running = 0;
  16968. bool release = false;
  16969. for (size_t i = 0; i < number_of_tasks; i++) {
  16970. EXPECT_TRUE(task_queue->enqueue([&] {
  16971. std::unique_lock<std::mutex> lock(mtx);
  16972. running++;
  16973. cv.notify_all();
  16974. cv.wait(lock, [&] { return release; });
  16975. }));
  16976. }
  16977. {
  16978. std::unique_lock<std::mutex> lock(mtx);
  16979. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16980. [&] { return running == number_of_tasks; }));
  16981. release = true;
  16982. }
  16983. cv.notify_all();
  16984. task_queue->shutdown();
  16985. }
  16986. TEST(TaskQueueTest, MaxQueuedRequests) {
  16987. static constexpr unsigned int qlimit{3};
  16988. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16989. std::condition_variable sem_cv;
  16990. std::mutex sem_mtx;
  16991. int credits = 0;
  16992. bool queued;
  16993. /* Fill up the queue with tasks that will block until we give them credits to
  16994. * complete. */
  16995. for (unsigned int n = 0; n <= qlimit;) {
  16996. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16997. std::unique_lock<std::mutex> lock(sem_mtx);
  16998. while (credits <= 0) {
  16999. sem_cv.wait(lock);
  17000. }
  17001. /* Consume the credit and signal the test code if they are all gone. */
  17002. if (--credits == 0) { sem_cv.notify_one(); }
  17003. });
  17004. if (n < qlimit) {
  17005. /* The first qlimit enqueues must succeed. */
  17006. EXPECT_TRUE(queued);
  17007. } else {
  17008. /* The last one will succeed only when the worker thread
  17009. * starts and dequeues the first blocking task. Although
  17010. * not necessary for the correctness of this test, we sleep for
  17011. * a short while to avoid busy waiting. */
  17012. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17013. }
  17014. if (queued) { n++; }
  17015. }
  17016. /* Further enqueues must fail since the queue is full. */
  17017. for (auto i = 0; i < 4; i++) {
  17018. queued = task_queue->enqueue([] {});
  17019. EXPECT_FALSE(queued);
  17020. }
  17021. /* Give the credits to allow the previous tasks to complete. */
  17022. {
  17023. std::unique_lock<std::mutex> lock(sem_mtx);
  17024. credits += qlimit + 1;
  17025. }
  17026. sem_cv.notify_all();
  17027. /* Wait for all the credits to be consumed. */
  17028. {
  17029. std::unique_lock<std::mutex> lock(sem_mtx);
  17030. while (credits > 0) {
  17031. sem_cv.wait(lock);
  17032. }
  17033. }
  17034. /* Check that we are able again to enqueue at least qlimit tasks. */
  17035. for (unsigned int i = 0; i < qlimit; i++) {
  17036. queued = task_queue->enqueue([] {});
  17037. EXPECT_TRUE(queued);
  17038. }
  17039. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17040. task_queue->shutdown();
  17041. #else
  17042. EXPECT_NO_THROW(task_queue->shutdown());
  17043. #endif
  17044. }
  17045. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17046. Server svr;
  17047. std::string method;
  17048. std::string body;
  17049. auto has_content_length = false;
  17050. auto has_transfer_encoding = false;
  17051. std::atomic<int> bad_requests{0};
  17052. // Leftover body bytes get parsed as a malformed request and answered with
  17053. // 400
  17054. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17055. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17056. });
  17057. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17058. res.set_redirect("/down", StatusCode::SeeOther_303);
  17059. });
  17060. svr.Get("/down", [&](const Request &req, Response &res) {
  17061. method = req.method;
  17062. body = req.body;
  17063. has_content_length = req.has_header("Content-Length");
  17064. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17065. res.set_content("ok", "text/plain");
  17066. });
  17067. auto port = svr.bind_to_any_port(HOST);
  17068. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17069. auto se = detail::scope_exit([&] {
  17070. svr.stop();
  17071. thread.join();
  17072. ASSERT_FALSE(svr.is_running());
  17073. });
  17074. svr.wait_until_ready();
  17075. const std::string payload = "SECRET-BODY";
  17076. auto check = [&](Client &cli, const Result &res) {
  17077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17078. EXPECT_EQ(StatusCode::OK_200, res->status);
  17079. EXPECT_EQ("ok", res->body);
  17080. EXPECT_EQ("GET", method);
  17081. EXPECT_TRUE(body.empty());
  17082. EXPECT_FALSE(has_content_length);
  17083. EXPECT_FALSE(has_transfer_encoding);
  17084. // Nothing of the original body may be left on the connection
  17085. auto res2 = cli.Get("/down");
  17086. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17087. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17088. EXPECT_EQ("ok", res2->body);
  17089. EXPECT_EQ(0, bad_requests);
  17090. };
  17091. // With content length
  17092. {
  17093. Client cli(HOST, port);
  17094. cli.set_keep_alive(true);
  17095. cli.set_follow_location(true);
  17096. auto res = cli.Post(
  17097. "/up", payload.size(),
  17098. [&](size_t offset, size_t length, DataSink &sink) {
  17099. return sink.write(payload.data() + offset, length);
  17100. },
  17101. "text/plain");
  17102. check(cli, res);
  17103. }
  17104. // Without content length (chunked)
  17105. {
  17106. Client cli(HOST, port);
  17107. cli.set_keep_alive(true);
  17108. cli.set_follow_location(true);
  17109. auto res = cli.Post(
  17110. "/up",
  17111. [&](size_t /*offset*/, DataSink &sink) {
  17112. sink.write(payload.data(), payload.size());
  17113. sink.done();
  17114. return true;
  17115. },
  17116. "text/plain");
  17117. check(cli, res);
  17118. }
  17119. }
  17120. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17121. Server svr;
  17122. std::string target;
  17123. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17124. // Echo the still-encoded name back in the Location
  17125. const std::string prefix = "/start/";
  17126. res.status = StatusCode::Found_302;
  17127. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17128. });
  17129. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17130. target = req.target;
  17131. res.set_content("ok", "text/plain");
  17132. });
  17133. auto port = svr.bind_to_any_port(HOST);
  17134. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17135. auto se = detail::scope_exit([&] {
  17136. svr.stop();
  17137. thread.join();
  17138. ASSERT_FALSE(svr.is_running());
  17139. });
  17140. svr.wait_until_ready();
  17141. // Decoding the Location path would turn the first four into a path
  17142. // separator, a query delimiter, a fragment delimiter and a different
  17143. // percent-encoded octet. The rest must keep reaching the server as they are.
  17144. const std::vector<std::string> names = {
  17145. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17146. };
  17147. for (auto path_encode : {true, false}) {
  17148. Client cli(HOST, port);
  17149. cli.set_follow_location(true);
  17150. cli.set_path_encode(path_encode);
  17151. for (const auto &name : names) {
  17152. target.clear();
  17153. auto res = cli.Get("/start/" + name);
  17154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17155. EXPECT_EQ(StatusCode::OK_200, res->status);
  17156. EXPECT_EQ("/dest/" + name, target);
  17157. }
  17158. }
  17159. }
  17160. TEST(RedirectTest, NotModifiedIsReturned) {
  17161. Server svr;
  17162. svr.Get("/cached", [](const Request &, Response &res) {
  17163. res.status = StatusCode::NotModified_304;
  17164. });
  17165. auto port = svr.bind_to_any_port(HOST);
  17166. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17167. auto se = detail::scope_exit([&] {
  17168. svr.stop();
  17169. thread.join();
  17170. ASSERT_FALSE(svr.is_running());
  17171. });
  17172. svr.wait_until_ready();
  17173. Client cli(HOST, port);
  17174. cli.set_follow_location(true);
  17175. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17177. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17178. }
  17179. TEST(RedirectTest, NoLocationIsReturned) {
  17180. Server svr;
  17181. svr.Get("/no-location", [](const Request &, Response &res) {
  17182. res.status = StatusCode::Found_302;
  17183. res.set_content("no location", "text/plain");
  17184. });
  17185. auto port = svr.bind_to_any_port(HOST);
  17186. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17187. auto se = detail::scope_exit([&] {
  17188. svr.stop();
  17189. thread.join();
  17190. ASSERT_FALSE(svr.is_running());
  17191. });
  17192. svr.wait_until_ready();
  17193. Client cli(HOST, port);
  17194. cli.set_follow_location(true);
  17195. auto res = cli.Get("/no-location");
  17196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17197. EXPECT_EQ(StatusCode::Found_302, res->status);
  17198. EXPECT_EQ("no location", res->body);
  17199. // The callbacks see the body of the response that is returned
  17200. auto handler_called = false;
  17201. auto progress_called = false;
  17202. std::string body;
  17203. auto res2 = cli.Get(
  17204. "/no-location",
  17205. [&](const Response &) {
  17206. handler_called = true;
  17207. return true;
  17208. },
  17209. [&](const char *data, size_t data_length) {
  17210. body.append(data, data_length);
  17211. return true;
  17212. },
  17213. [&](size_t, size_t) {
  17214. progress_called = true;
  17215. return true;
  17216. });
  17217. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17218. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17219. EXPECT_TRUE(handler_called);
  17220. EXPECT_TRUE(progress_called);
  17221. EXPECT_EQ("no location", body);
  17222. }
  17223. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17224. Server svr;
  17225. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17226. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17227. });
  17228. svr.Get("/hello", [](const Request &req, Response &res) {
  17229. res.set_content(req.get_param_value("key"), "text/plain");
  17230. });
  17231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17232. auto se = detail::scope_exit([&] {
  17233. svr.stop();
  17234. thread.join();
  17235. ASSERT_FALSE(svr.is_running());
  17236. });
  17237. svr.wait_until_ready();
  17238. {
  17239. Client cli(HOST, PORT);
  17240. cli.set_follow_location(true);
  17241. auto res = cli.Get("/");
  17242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17243. EXPECT_EQ(StatusCode::OK_200, res->status);
  17244. EXPECT_EQ("val&key2=val2", res->body);
  17245. }
  17246. }
  17247. #endif
  17248. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17249. Server svr;
  17250. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17251. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17252. });
  17253. svr.Get("/hello", [](const Request &req, Response &res) {
  17254. res.set_content(req.get_param_value("key"), "text/plain");
  17255. });
  17256. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17257. auto se = detail::scope_exit([&] {
  17258. svr.stop();
  17259. thread.join();
  17260. ASSERT_FALSE(svr.is_running());
  17261. });
  17262. svr.wait_until_ready();
  17263. {
  17264. Client cli(HOST, PORT);
  17265. cli.set_follow_location(true);
  17266. auto res = cli.Get("/");
  17267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17268. EXPECT_EQ(StatusCode::OK_200, res->status);
  17269. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17270. }
  17271. }
  17272. TEST(RedirectTest, RedirectWithPlusInPath) {
  17273. Server svr;
  17274. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17275. res.set_redirect("/a+b");
  17276. });
  17277. // Route pattern uses regex; escape + as \\+
  17278. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17279. res.set_content(req.path, "text/plain");
  17280. });
  17281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17282. auto se = detail::scope_exit([&] {
  17283. svr.stop();
  17284. thread.join();
  17285. ASSERT_FALSE(svr.is_running());
  17286. });
  17287. svr.wait_until_ready();
  17288. {
  17289. Client cli(HOST, PORT);
  17290. cli.set_follow_location(true);
  17291. auto res = cli.Get("/");
  17292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17293. EXPECT_EQ(StatusCode::OK_200, res->status);
  17294. EXPECT_EQ("/a+b", res->body);
  17295. }
  17296. }
  17297. TEST(RedirectTest, ResolveRelativeLocation) {
  17298. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17299. const std::vector<std::pair<std::string, std::string>> cases = {
  17300. {"g", "/b/c/g"},
  17301. {"./g", "/b/c/g"},
  17302. {"g/", "/b/c/g/"},
  17303. {"?y", "/b/c/d;p?y"},
  17304. {"g?y", "/b/c/g?y"},
  17305. {"#s", "/b/c/d;p?q#s"},
  17306. {"g#s", "/b/c/g#s"},
  17307. {"g?y#s", "/b/c/g?y#s"},
  17308. {";x", "/b/c/;x"},
  17309. {"g;x", "/b/c/g;x"},
  17310. {".", "/b/c/"},
  17311. {"./", "/b/c/"},
  17312. {"..", "/b/"},
  17313. {"../", "/b/"},
  17314. {"../g", "/b/g"},
  17315. {"../..", "/"},
  17316. {"../../", "/"},
  17317. {"../../g", "/g"},
  17318. {"../../../g", "/g"},
  17319. {"g.", "/b/c/g."},
  17320. {".g", "/b/c/.g"},
  17321. {"g..", "/b/c/g.."},
  17322. {"..g", "/b/c/..g"},
  17323. {"./../g", "/b/g"},
  17324. {"./g/.", "/b/c/g/"},
  17325. {"g/./h", "/b/c/g/h"},
  17326. {"g/../h", "/b/c/h"},
  17327. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17328. {"g;x=1/../y", "/b/c/y"},
  17329. {"g?y/./x", "/b/c/g?y/./x"},
  17330. {"g#s/../x", "/b/c/g#s/../x"},
  17331. // Not relative-path references, so left for parse_url.
  17332. {"/g", "/g"},
  17333. {"//g", "//g"},
  17334. {"http://g/x", "http://g/x"},
  17335. {"g:h", "g:h"},
  17336. };
  17337. for (const auto &c : cases) {
  17338. EXPECT_EQ(c.second,
  17339. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17340. << c.first;
  17341. }
  17342. }
  17343. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17344. Server svr;
  17345. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17346. res.set_redirect(req.get_param_value("to"));
  17347. });
  17348. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17349. res.set_content(req.target, "text/plain");
  17350. });
  17351. svr.Get("/other", [](const Request &req, Response &res) {
  17352. res.set_content(req.target, "text/plain");
  17353. });
  17354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17355. auto se = detail::scope_exit([&] {
  17356. svr.stop();
  17357. thread.join();
  17358. ASSERT_FALSE(svr.is_running());
  17359. });
  17360. svr.wait_until_ready();
  17361. const std::vector<std::pair<std::string, std::string>> cases = {
  17362. {"next", "/dir/next"},
  17363. {"./next?x=1", "/dir/next?x=1"},
  17364. {"../other", "/other"},
  17365. };
  17366. for (const auto &c : cases) {
  17367. Client cli(HOST, PORT);
  17368. cli.set_follow_location(true);
  17369. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17370. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17371. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17372. EXPECT_EQ(c.second, res->body) << c.first;
  17373. }
  17374. }
  17375. #ifdef CPPHTTPLIB_SSL_ENABLED
  17376. TEST(RedirectTest, Issue2185_Online) {
  17377. SSLClient client("github.com");
  17378. client.set_follow_location(true);
  17379. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17380. "Coollab-Windows.zip");
  17381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17382. EXPECT_EQ(StatusCode::OK_200, res->status);
  17383. EXPECT_EQ(9920427U, res->body.size());
  17384. }
  17385. #endif
  17386. TEST(VulnerabilityTest, CRLFInjection) {
  17387. Server svr;
  17388. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17389. res.set_content("Hello 1", "text/plain");
  17390. });
  17391. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17392. res.set_content("Hello 2", "text/plain");
  17393. });
  17394. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17395. res.set_content("Hello 3", "text/plain");
  17396. });
  17397. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17398. res.set_content("Hello 4", "text/plain");
  17399. });
  17400. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17401. for (const auto &x : req.headers) {
  17402. auto key = x.first;
  17403. EXPECT_STRNE("evil", key.c_str());
  17404. }
  17405. });
  17406. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17407. auto se = detail::scope_exit([&] {
  17408. svr.stop();
  17409. thread.join();
  17410. ASSERT_FALSE(svr.is_running());
  17411. });
  17412. svr.wait_until_ready();
  17413. {
  17414. Client cli(HOST, PORT);
  17415. cli.Post("/test1", "A=B",
  17416. "application/x-www-form-urlencoded\r\nevil: hello1");
  17417. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17418. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17419. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17420. }
  17421. }
  17422. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17423. auto server_thread = std::thread([] {
  17424. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17425. default_socket_options(srv);
  17426. sockaddr_in addr{};
  17427. addr.sin_family = AF_INET;
  17428. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17429. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17430. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17431. ::listen(srv, 1);
  17432. sockaddr_in cli_addr{};
  17433. socklen_t cli_len = sizeof(cli_addr);
  17434. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17435. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17436. std::string buf_all;
  17437. char buf[2048];
  17438. ssize_t n;
  17439. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17440. buf_all.append(buf, static_cast<size_t>(n));
  17441. size_t pos;
  17442. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17443. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17444. auto e = request_block.find("\r\n");
  17445. if (e != std::string::npos) {
  17446. auto request_line = request_block.substr(0, e);
  17447. std::string msg =
  17448. "CRLF injection detected in request line: '" + request_line + "'";
  17449. EXPECT_FALSE(true) << msg;
  17450. }
  17451. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17452. ::send(cli,
  17453. #ifdef _WIN32
  17454. static_cast<const char *>(resp.c_str()),
  17455. static_cast<int>(resp.size()),
  17456. #else
  17457. resp.c_str(), resp.size(),
  17458. #endif
  17459. 0);
  17460. buf_all.erase(0, pos + 4);
  17461. }
  17462. }
  17463. detail::close_socket(cli);
  17464. detail::close_socket(srv);
  17465. });
  17466. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17467. auto cli = Client("127.0.0.1", PORT + 1);
  17468. auto headers = Headers{
  17469. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17470. {"Connection", "keep-alive"}};
  17471. auto res = cli.Get("/hi", headers);
  17472. EXPECT_FALSE(res);
  17473. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17474. server_thread.join();
  17475. }
  17476. // A request rejected before any byte reaches the socket must fail right away
  17477. // instead of waiting for a response the server will never send.
  17478. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17479. // The kernel completes the TCP handshake from the listen backlog, so the
  17480. // client connects, but nothing ever reads, responds or closes.
  17481. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17482. default_socket_options(srv);
  17483. sockaddr_in addr{};
  17484. addr.sin_family = AF_INET;
  17485. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17486. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17487. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17488. ASSERT_EQ(0, ::listen(srv, 8));
  17489. auto cli = Client("127.0.0.1", PORT + 1);
  17490. cli.set_read_timeout(10, 0);
  17491. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17492. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17493. std::chrono::steady_clock::now() - start)
  17494. .count();
  17495. };
  17496. {
  17497. Request req;
  17498. req.method = "GE T";
  17499. req.path = "/";
  17500. auto start = std::chrono::steady_clock::now();
  17501. auto res = cli.send(req);
  17502. EXPECT_FALSE(res);
  17503. EXPECT_EQ(Error::Write, res.error());
  17504. EXPECT_LT(elapsed_ms(start), 1000);
  17505. }
  17506. {
  17507. auto start = std::chrono::steady_clock::now();
  17508. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17509. EXPECT_FALSE(res);
  17510. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17511. EXPECT_LT(elapsed_ms(start), 1000);
  17512. }
  17513. EXPECT_FALSE(cli.is_socket_open());
  17514. detail::close_socket(srv);
  17515. }
  17516. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17517. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17518. default_socket_options(srv);
  17519. sockaddr_in addr{};
  17520. addr.sin_family = AF_INET;
  17521. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17522. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17523. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17524. ASSERT_EQ(0, ::listen(srv, 1));
  17525. std::string received;
  17526. auto server_thread = std::thread([&] {
  17527. auto sock = ::accept(srv, nullptr, nullptr);
  17528. if (sock == INVALID_SOCKET) { return; }
  17529. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17530. char buf[2048];
  17531. ssize_t n;
  17532. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17533. received.append(buf, static_cast<size_t>(n));
  17534. }
  17535. detail::close_socket(sock);
  17536. });
  17537. {
  17538. auto cli = Client("127.0.0.1", PORT + 1);
  17539. // "Z" sorts after the default headers, so writing straight to the socket
  17540. // would have sent the request line and those headers before the rejection.
  17541. auto handle =
  17542. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17543. EXPECT_FALSE(handle.is_valid());
  17544. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17545. }
  17546. server_thread.join();
  17547. detail::close_socket(srv);
  17548. EXPECT_TRUE(received.empty()) << received;
  17549. }
  17550. TEST(PathParamsTest, StaticMatch) {
  17551. const auto pattern = "/users/all";
  17552. detail::PathParamsMatcher matcher(pattern);
  17553. Request request;
  17554. request.path = "/users/all";
  17555. ASSERT_TRUE(matcher.match(request));
  17556. std::unordered_map<std::string, std::string> expected_params = {};
  17557. EXPECT_EQ(request.path_params, expected_params);
  17558. }
  17559. TEST(PathParamsTest, StaticMismatch) {
  17560. const auto pattern = "/users/all";
  17561. detail::PathParamsMatcher matcher(pattern);
  17562. Request request;
  17563. request.path = "/users/1";
  17564. ASSERT_FALSE(matcher.match(request));
  17565. }
  17566. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17567. const auto pattern = "/users/:id/subscriptions";
  17568. detail::PathParamsMatcher matcher(pattern);
  17569. Request request;
  17570. request.path = "/users/42/subscriptions";
  17571. ASSERT_TRUE(matcher.match(request));
  17572. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17573. EXPECT_EQ(request.path_params, expected_params);
  17574. }
  17575. TEST(PathParamsTest, SingleParamInTheEnd) {
  17576. const auto pattern = "/users/:id";
  17577. detail::PathParamsMatcher matcher(pattern);
  17578. Request request;
  17579. request.path = "/users/24";
  17580. ASSERT_TRUE(matcher.match(request));
  17581. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17582. EXPECT_EQ(request.path_params, expected_params);
  17583. }
  17584. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17585. const auto pattern = "/users/:id/";
  17586. detail::PathParamsMatcher matcher(pattern);
  17587. Request request;
  17588. request.path = "/users/42/";
  17589. ASSERT_TRUE(matcher.match(request));
  17590. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17591. EXPECT_EQ(request.path_params, expected_params);
  17592. }
  17593. TEST(PathParamsTest, EmptyParam) {
  17594. const auto pattern = "/users/:id/";
  17595. detail::PathParamsMatcher matcher(pattern);
  17596. Request request;
  17597. request.path = "/users//";
  17598. ASSERT_TRUE(matcher.match(request));
  17599. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17600. EXPECT_EQ(request.path_params, expected_params);
  17601. }
  17602. TEST(PathParamsTest, FragmentMismatch) {
  17603. const auto pattern = "/users/:id/";
  17604. detail::PathParamsMatcher matcher(pattern);
  17605. Request request;
  17606. request.path = "/admins/24/";
  17607. ASSERT_FALSE(matcher.match(request));
  17608. }
  17609. TEST(PathParamsTest, ExtraFragments) {
  17610. const auto pattern = "/users/:id";
  17611. detail::PathParamsMatcher matcher(pattern);
  17612. Request request;
  17613. request.path = "/users/42/subscriptions";
  17614. ASSERT_FALSE(matcher.match(request));
  17615. }
  17616. TEST(PathParamsTest, MissingTrailingParam) {
  17617. const auto pattern = "/users/:id";
  17618. detail::PathParamsMatcher matcher(pattern);
  17619. Request request;
  17620. request.path = "/users";
  17621. ASSERT_FALSE(matcher.match(request));
  17622. }
  17623. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17624. const auto pattern = "/users/:id/subscriptions";
  17625. detail::PathParamsMatcher matcher(pattern);
  17626. Request request;
  17627. request.path = "/users/subscriptions";
  17628. ASSERT_FALSE(matcher.match(request));
  17629. }
  17630. TEST(PathParamsTest, MultipleParams) {
  17631. const auto pattern = "/users/:userid/subscriptions/:subid";
  17632. detail::PathParamsMatcher matcher(pattern);
  17633. Request request;
  17634. request.path = "/users/42/subscriptions/2";
  17635. ASSERT_TRUE(matcher.match(request));
  17636. std::unordered_map<std::string, std::string> expected_params = {
  17637. {"userid", "42"}, {"subid", "2"}};
  17638. EXPECT_EQ(request.path_params, expected_params);
  17639. }
  17640. TEST(PathParamsTest, SequenceOfParams) {
  17641. const auto pattern = "/values/:x/:y/:z";
  17642. detail::PathParamsMatcher matcher(pattern);
  17643. Request request;
  17644. request.path = "/values/1/2/3";
  17645. ASSERT_TRUE(matcher.match(request));
  17646. std::unordered_map<std::string, std::string> expected_params = {
  17647. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17648. EXPECT_EQ(request.path_params, expected_params);
  17649. }
  17650. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17651. const auto pattern = "/prefix:suffix";
  17652. detail::PathParamsMatcher matcher(pattern);
  17653. Request request;
  17654. request.path = "/prefix:suffix";
  17655. ASSERT_TRUE(matcher.match(request));
  17656. const std::unordered_map<std::string, std::string> expected_params = {};
  17657. EXPECT_EQ(request.path_params, expected_params);
  17658. }
  17659. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17660. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17661. // calling thread's stack on a long enough path for a quantified pattern;
  17662. // RegexMatcher must refuse to run regex matching on paths beyond
  17663. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17664. detail::RegexMatcher matcher("/files/(.*)");
  17665. Request within_limit;
  17666. within_limit.path = "/files/" + std::string(10, 'A');
  17667. EXPECT_TRUE(matcher.match(within_limit));
  17668. Request over_limit;
  17669. over_limit.path =
  17670. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17671. EXPECT_FALSE(matcher.match(over_limit));
  17672. }
  17673. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17674. Server svr;
  17675. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17676. res.set_content("ok", "text/plain");
  17677. });
  17678. auto port = svr.bind_to_any_port(HOST);
  17679. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17680. auto se = detail::scope_exit([&] {
  17681. svr.stop();
  17682. thread.join();
  17683. ASSERT_FALSE(svr.is_running());
  17684. });
  17685. svr.wait_until_ready();
  17686. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17687. // request URI limit; this used to be able to crash the process.
  17688. std::string path =
  17689. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17690. std::string req = "GET " + path +
  17691. " HTTP/1.1\r\n"
  17692. "Host: " +
  17693. std::string(HOST) + ":" + std::to_string(port) +
  17694. "\r\n"
  17695. "Connection: close\r\n"
  17696. "\r\n";
  17697. std::string response;
  17698. ASSERT_TRUE(send_request(5, req, &response, port));
  17699. EXPECT_NE(std::string::npos, response.find("404"));
  17700. }
  17701. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17702. Server svr;
  17703. auto handler = [](const Request & /*req*/, Response &res) {
  17704. res.set_content("hit", "text/plain");
  17705. };
  17706. // No regex metacharacter, so this one is compared literally
  17707. svr.Get("/literal/route", handler);
  17708. // '.' is a regex metacharacter, so this one must keep regex semantics
  17709. svr.Get("/a.c", handler);
  17710. auto port = svr.bind_to_any_port(HOST);
  17711. std::thread t([&]() { svr.listen_after_bind(); });
  17712. auto se = detail::scope_exit([&] {
  17713. svr.stop();
  17714. t.join();
  17715. ASSERT_FALSE(svr.is_running());
  17716. });
  17717. svr.wait_until_ready();
  17718. Client cli(HOST, port);
  17719. struct {
  17720. const char *path;
  17721. int status;
  17722. } cases[] = {
  17723. {"/literal/route", StatusCode::OK_200},
  17724. {"/literal/routes", StatusCode::NotFound_404},
  17725. {"/literal/rout", StatusCode::NotFound_404},
  17726. {"/abc", StatusCode::OK_200},
  17727. {"/a.c", StatusCode::OK_200},
  17728. };
  17729. for (const auto &x : cases) {
  17730. auto res = cli.Get(x.path);
  17731. ASSERT_TRUE(res) << x.path;
  17732. EXPECT_EQ(x.status, res->status) << x.path;
  17733. }
  17734. }
  17735. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17736. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17737. // from exhausting the stack, so it must only constrain routes that actually
  17738. // run a regular expression. A literal route is matched by comparison and
  17739. // stays usable at any length.
  17740. Server svr;
  17741. const std::string pattern =
  17742. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17743. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17744. res.set_content("hit", "text/plain");
  17745. });
  17746. auto port = svr.bind_to_any_port(HOST);
  17747. std::thread t([&]() { svr.listen_after_bind(); });
  17748. auto se = detail::scope_exit([&] {
  17749. svr.stop();
  17750. t.join();
  17751. ASSERT_FALSE(svr.is_running());
  17752. });
  17753. svr.wait_until_ready();
  17754. Client cli(HOST, port);
  17755. auto res = cli.Get(pattern);
  17756. ASSERT_TRUE(res);
  17757. EXPECT_EQ(StatusCode::OK_200, res->status);
  17758. }
  17759. TEST(ParseUrlTest, VariousPatterns) {
  17760. {
  17761. detail::UrlComponents uc;
  17762. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17763. EXPECT_EQ("http", uc.scheme);
  17764. EXPECT_EQ("example.com", uc.host);
  17765. EXPECT_EQ("8080", uc.port);
  17766. EXPECT_EQ("/path", uc.path);
  17767. EXPECT_EQ("?q=1", uc.query);
  17768. }
  17769. {
  17770. detail::UrlComponents uc;
  17771. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17772. EXPECT_EQ("https", uc.scheme);
  17773. EXPECT_EQ("example.com", uc.host);
  17774. EXPECT_TRUE(uc.port.empty());
  17775. EXPECT_EQ("/path", uc.path);
  17776. }
  17777. {
  17778. detail::UrlComponents uc;
  17779. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17780. EXPECT_EQ("::1", uc.host);
  17781. EXPECT_EQ("8080", uc.port);
  17782. EXPECT_EQ("/path", uc.path);
  17783. }
  17784. {
  17785. detail::UrlComponents uc;
  17786. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17787. }
  17788. {
  17789. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17790. // the path while the connection still targets the bracketed host.
  17791. detail::UrlComponents uc;
  17792. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17793. }
  17794. {
  17795. detail::UrlComponents uc;
  17796. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17797. }
  17798. {
  17799. detail::UrlComponents uc;
  17800. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17801. EXPECT_EQ("::1", uc.host);
  17802. EXPECT_TRUE(uc.port.empty());
  17803. EXPECT_EQ("/path", uc.path);
  17804. }
  17805. {
  17806. detail::UrlComponents uc;
  17807. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17808. EXPECT_TRUE(uc.scheme.empty());
  17809. EXPECT_EQ("example.com", uc.host);
  17810. EXPECT_EQ("/path", uc.path);
  17811. EXPECT_EQ("?q=1", uc.query);
  17812. }
  17813. {
  17814. detail::UrlComponents uc;
  17815. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17816. EXPECT_TRUE(uc.host.empty());
  17817. EXPECT_EQ("/path", uc.path);
  17818. EXPECT_EQ("?q=1", uc.query);
  17819. }
  17820. {
  17821. detail::UrlComponents uc;
  17822. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17823. EXPECT_EQ("example.com", uc.host);
  17824. EXPECT_EQ("8080", uc.port);
  17825. }
  17826. {
  17827. // Unix socket path — must not be parsed as host
  17828. detail::UrlComponents uc;
  17829. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17830. EXPECT_TRUE(uc.host.empty());
  17831. }
  17832. {
  17833. detail::UrlComponents uc;
  17834. ASSERT_TRUE(detail::parse_url("", uc));
  17835. EXPECT_TRUE(uc.host.empty());
  17836. EXPECT_TRUE(uc.path.empty());
  17837. }
  17838. {
  17839. detail::UrlComponents uc;
  17840. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17841. }
  17842. {
  17843. detail::UrlComponents uc;
  17844. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17845. }
  17846. {
  17847. // Accepted by parse_url; callers restrict to http/https
  17848. detail::UrlComponents uc;
  17849. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17850. EXPECT_EQ("ftp", uc.scheme);
  17851. }
  17852. {
  17853. detail::UrlComponents uc;
  17854. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17855. }
  17856. {
  17857. detail::UrlComponents uc;
  17858. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17859. }
  17860. }
  17861. TEST(ParseUrlTest, FragmentHandling) {
  17862. {
  17863. detail::UrlComponents uc;
  17864. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17865. EXPECT_EQ("/path", uc.path);
  17866. EXPECT_TRUE(uc.query.empty());
  17867. }
  17868. {
  17869. detail::UrlComponents uc;
  17870. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17871. EXPECT_TRUE(uc.path.empty());
  17872. EXPECT_TRUE(uc.query.empty());
  17873. }
  17874. }
  17875. TEST(ParseUrlTest, UserinfoHandling) {
  17876. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17877. // parsers would see evil.com as the host.
  17878. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17879. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17880. for (auto url : urls) {
  17881. detail::UrlComponents uc;
  17882. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17883. }
  17884. }
  17885. TEST(ParseUrlTest, IPv6EdgeCases) {
  17886. {
  17887. detail::UrlComponents uc;
  17888. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17889. EXPECT_TRUE(uc.scheme.empty());
  17890. EXPECT_EQ("::1", uc.host);
  17891. EXPECT_EQ("8080", uc.port);
  17892. }
  17893. {
  17894. // Zone ID '%25' is not in [a-fA-F0-9:]
  17895. detail::UrlComponents uc;
  17896. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17897. }
  17898. }
  17899. TEST(ParseUrlTest, SchemeEdgeCases) {
  17900. {
  17901. detail::UrlComponents uc;
  17902. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17903. }
  17904. {
  17905. detail::UrlComponents uc;
  17906. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17907. }
  17908. {
  17909. detail::UrlComponents uc;
  17910. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17911. }
  17912. }
  17913. TEST(ParseUrlTest, PortEdgeCases) {
  17914. {
  17915. detail::UrlComponents uc;
  17916. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17917. EXPECT_TRUE(uc.port.empty());
  17918. EXPECT_EQ("/path", uc.path);
  17919. }
  17920. {
  17921. // parse_url accepts any port string; validation is done by parse_port
  17922. detail::UrlComponents uc;
  17923. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17924. EXPECT_EQ("abc", uc.port);
  17925. }
  17926. }
  17927. TEST(ParseUrlTest, WebSocketPatterns) {
  17928. {
  17929. detail::UrlComponents uc;
  17930. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17931. EXPECT_EQ("ws", uc.scheme);
  17932. EXPECT_EQ("echo.example.com", uc.host);
  17933. EXPECT_EQ("8080", uc.port);
  17934. EXPECT_EQ("/ws", uc.path);
  17935. }
  17936. {
  17937. detail::UrlComponents uc;
  17938. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17939. EXPECT_EQ("wss", uc.scheme);
  17940. EXPECT_EQ("echo.example.com", uc.host);
  17941. EXPECT_TRUE(uc.port.empty());
  17942. EXPECT_EQ("/ws", uc.path);
  17943. }
  17944. }
  17945. TEST(ParseUrlTest, QueryOnly) {
  17946. detail::UrlComponents uc;
  17947. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17948. EXPECT_TRUE(uc.host.empty());
  17949. EXPECT_TRUE(uc.path.empty());
  17950. EXPECT_EQ("?q=1&r=2", uc.query);
  17951. }
  17952. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17953. detail::UrlComponents uc;
  17954. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17955. EXPECT_TRUE(uc.scheme.empty());
  17956. EXPECT_EQ("example.com", uc.host);
  17957. EXPECT_EQ("443", uc.port);
  17958. EXPECT_EQ("/path", uc.path);
  17959. }
  17960. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17961. // If ipv6 regex working, regex match codepath is taken.
  17962. // else port will default to 80 in Client impl
  17963. int clientImplMagicPort = 80;
  17964. int port = 4321;
  17965. // above ports must be different to avoid false negative
  17966. EXPECT_NE(clientImplMagicPort, port);
  17967. std::string ipV6TestURL = "http://[ff06::c3]";
  17968. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17969. CLIENT_PRIVATE_KEY_FILE);
  17970. EXPECT_EQ(cli.port(), port);
  17971. }
  17972. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17973. auto file_path = "./www/dir/index.html";
  17974. auto dir_path = "./www/dir";
  17975. detail::FileStat stat_file(file_path);
  17976. EXPECT_TRUE(stat_file.is_file());
  17977. EXPECT_FALSE(stat_file.is_dir());
  17978. detail::FileStat stat_dir(dir_path);
  17979. EXPECT_FALSE(stat_dir.is_file());
  17980. EXPECT_TRUE(stat_dir.is_dir());
  17981. }
  17982. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17983. // IPv4 with default HTTP port (80)
  17984. EXPECT_EQ("example.com",
  17985. detail::make_host_and_port_string("example.com", 80, false));
  17986. // IPv4 with default HTTPS port (443)
  17987. EXPECT_EQ("example.com",
  17988. detail::make_host_and_port_string("example.com", 443, true));
  17989. // IPv4 with non-default HTTP port
  17990. EXPECT_EQ("example.com:8080",
  17991. detail::make_host_and_port_string("example.com", 8080, false));
  17992. // IPv4 with non-default HTTPS port
  17993. EXPECT_EQ("example.com:8443",
  17994. detail::make_host_and_port_string("example.com", 8443, true));
  17995. // IPv6 with default HTTP port (80)
  17996. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17997. // IPv6 with default HTTPS port (443)
  17998. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17999. // IPv6 with non-default HTTP port
  18000. EXPECT_EQ("[::1]:8080",
  18001. detail::make_host_and_port_string("::1", 8080, false));
  18002. // IPv6 with non-default HTTPS port
  18003. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18004. // IPv6 full address with default port
  18005. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18006. detail::make_host_and_port_string(
  18007. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18008. // IPv6 full address with non-default port
  18009. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18010. detail::make_host_and_port_string(
  18011. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18012. // IPv6 localhost with non-default port
  18013. EXPECT_EQ("[::1]:3000",
  18014. detail::make_host_and_port_string("::1", 3000, false));
  18015. // IPv6 with zone ID (link-local address) with default port
  18016. EXPECT_EQ("[fe80::1%eth0]",
  18017. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18018. // IPv6 with zone ID (link-local address) with non-default port
  18019. EXPECT_EQ("[fe80::1%eth0]:8080",
  18020. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18021. // Edge case: Port 443 with is_ssl=false (should add port)
  18022. EXPECT_EQ("example.com:443",
  18023. detail::make_host_and_port_string("example.com", 443, false));
  18024. // Edge case: Port 80 with is_ssl=true (should add port)
  18025. EXPECT_EQ("example.com:80",
  18026. detail::make_host_and_port_string("example.com", 80, true));
  18027. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18028. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18029. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18030. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18031. // Security fix: Already bracketed IPv6 should not get double brackets
  18032. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18033. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18034. EXPECT_EQ("[::1]:8080",
  18035. detail::make_host_and_port_string("[::1]", 8080, false));
  18036. EXPECT_EQ("[2001:db8::1]:8080",
  18037. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18038. EXPECT_EQ("[fe80::1%eth0]",
  18039. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18040. EXPECT_EQ("[fe80::1%eth0]:8080",
  18041. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18042. // Edge case: Empty host (should return as-is)
  18043. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18044. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18045. // This is a known limitation but shouldn't crash
  18046. EXPECT_EQ("[host:name]",
  18047. detail::make_host_and_port_string("host:name", 80, false));
  18048. // Port number edge cases (no validation, but should not crash)
  18049. EXPECT_EQ("example.com:0",
  18050. detail::make_host_and_port_string("example.com", 0, false));
  18051. EXPECT_EQ("example.com:-1",
  18052. detail::make_host_and_port_string("example.com", -1, false));
  18053. EXPECT_EQ("example.com:65535",
  18054. detail::make_host_and_port_string("example.com", 65535, false));
  18055. EXPECT_EQ("example.com:65536",
  18056. detail::make_host_and_port_string("example.com", 65536, false));
  18057. }
  18058. #ifdef CPPHTTPLIB_SSL_ENABLED
  18059. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18060. httplib::SSLClient cli("roblox.com", 443);
  18061. cli.set_follow_location(true);
  18062. auto res = cli.Get("/");
  18063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18064. EXPECT_EQ(StatusCode::OK_200, res->status);
  18065. }
  18066. #endif
  18067. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18068. Server svr;
  18069. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18070. EXPECT_EQ(res.status, 400);
  18071. });
  18072. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18073. auto se = detail::scope_exit([&] {
  18074. svr.stop();
  18075. thread.join();
  18076. ASSERT_FALSE(svr.is_running());
  18077. });
  18078. svr.wait_until_ready();
  18079. Client cli(HOST, PORT);
  18080. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18081. }
  18082. TEST(InvalidHeaderCharsTest, is_field_name) {
  18083. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18084. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18085. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18086. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18087. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18088. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18089. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18090. EXPECT_FALSE(detail::fields::is_field_name(""));
  18091. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18092. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18093. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18094. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18095. }
  18096. TEST(InvalidHeaderCharsTest, is_field_value) {
  18097. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18098. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18099. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18100. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18101. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18102. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18103. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18104. EXPECT_TRUE(detail::fields::is_field_value(""));
  18105. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18106. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18107. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18108. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18109. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18110. }
  18111. TEST(InvalidHeaderCharsTest, OnServer) {
  18112. Server svr;
  18113. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18114. std::string header = "Not Set";
  18115. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18116. res.set_header(header, "value");
  18117. res.set_content("Page Content Page Content", "text/plain");
  18118. });
  18119. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18120. std::string header = "Not Set";
  18121. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18122. res.set_header("X-Test", header);
  18123. res.set_content("Page Content Page Content", "text/plain");
  18124. });
  18125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18126. auto se = detail::scope_exit([&] {
  18127. svr.stop();
  18128. thread.join();
  18129. ASSERT_FALSE(svr.is_running());
  18130. });
  18131. svr.wait_until_ready();
  18132. Client cli(HOST, PORT);
  18133. {
  18134. auto res = cli.Get(
  18135. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18137. EXPECT_EQ("Page Content Page Content", res->body);
  18138. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18139. }
  18140. {
  18141. auto res = cli.Get(
  18142. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18144. EXPECT_EQ("Page Content Page Content", res->body);
  18145. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18146. }
  18147. }
  18148. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18149. auto handled = false;
  18150. Server svr;
  18151. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18152. thread t = thread([&] { svr.listen(HOST, PORT); });
  18153. auto se = detail::scope_exit([&] {
  18154. svr.stop();
  18155. t.join();
  18156. ASSERT_FALSE(svr.is_running());
  18157. ASSERT_FALSE(handled);
  18158. });
  18159. svr.wait_until_ready();
  18160. auto req = "POST /test HTTP/1.1\r\n"
  18161. "Content-Length: x\r\n"
  18162. "\r\n";
  18163. std::string response;
  18164. ASSERT_TRUE(send_request(1, req, &response));
  18165. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18166. response.substr(0, response.find("\r\n")));
  18167. }
  18168. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18169. // case-insensitive, and a server that receives a 100-continue expectation in
  18170. // an HTTP/1.0 request MUST ignore it.
  18171. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18172. std::string response;
  18173. ASSERT_TRUE(send_request(1, req, &response, port));
  18174. *got_100 = response.find("100 Continue") != std::string::npos;
  18175. }
  18176. class ExpectTokenTest : public ::testing::Test {
  18177. protected:
  18178. void SetUp() override {
  18179. svr_.Post("/p", [](const Request &, Response &res) {
  18180. res.set_content("ok", "text/plain");
  18181. });
  18182. port_ = svr_.bind_to_any_port(HOST);
  18183. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18184. svr_.wait_until_ready();
  18185. }
  18186. void TearDown() override {
  18187. svr_.stop();
  18188. if (thread_.joinable()) { thread_.join(); }
  18189. }
  18190. std::string request(const char *version, const char *expect_value) const {
  18191. return std::string("POST /p ") + version +
  18192. "\r\n"
  18193. "Host: localhost\r\n"
  18194. "Content-Length: 2\r\n"
  18195. "Connection: close\r\n"
  18196. "Expect: " +
  18197. expect_value +
  18198. "\r\n"
  18199. "\r\n"
  18200. "hi";
  18201. }
  18202. Server svr_;
  18203. int port_ = 0;
  18204. thread thread_;
  18205. };
  18206. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18207. bool got_100 = false;
  18208. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18209. EXPECT_TRUE(got_100);
  18210. }
  18211. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18212. bool got_100 = true;
  18213. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18214. EXPECT_FALSE(got_100);
  18215. }
  18216. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18217. bool got_100 = false;
  18218. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18219. EXPECT_TRUE(got_100);
  18220. }
  18221. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18222. bool got_100 = false;
  18223. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18224. EXPECT_TRUE(got_100);
  18225. }
  18226. // `100 Continue` is sent only when the server starts reading the body, so a
  18227. // request rejected before that never invites the client to send it. The
  18228. // requests below carry the expectation but withhold the body, as a client
  18229. // waiting for `100 Continue` would.
  18230. // A POST that expects `100 Continue` and withholds its two-byte body.
  18231. static std::string expect_headers_only(const std::string &path) {
  18232. return "POST " + path +
  18233. " HTTP/1.1\r\n"
  18234. "Host: localhost\r\n"
  18235. "Content-Length: 2\r\n"
  18236. "Expect: 100-continue\r\n"
  18237. "\r\n";
  18238. }
  18239. class ExpectLazyContinueTest : public ::testing::Test {
  18240. protected:
  18241. void SetUp() override {
  18242. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18243. if (req.path == "/pre-routing") {
  18244. res.status = StatusCode::Unauthorized_401;
  18245. return Server::HandlerResponse::Handled;
  18246. }
  18247. return Server::HandlerResponse::Unhandled;
  18248. });
  18249. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18250. if (req.matched_route == "/pre-request") {
  18251. res.status = StatusCode::Forbidden_403;
  18252. return Server::HandlerResponse::Handled;
  18253. }
  18254. return Server::HandlerResponse::Unhandled;
  18255. });
  18256. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18257. res.set_content("ok", "text/plain");
  18258. });
  18259. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18260. res.set_content("ok", "text/plain");
  18261. });
  18262. svr_.Post("/reader-used", [](const Request &, Response &res,
  18263. const ContentReader &content_reader) {
  18264. std::string body;
  18265. content_reader([&](const char *data, size_t len) {
  18266. body.append(data, len);
  18267. return true;
  18268. });
  18269. res.set_content(body, "text/plain");
  18270. });
  18271. svr_.Post("/reader-unused",
  18272. [](const Request &, Response &res, const ContentReader &) {
  18273. res.set_content("ignored", "text/plain");
  18274. });
  18275. port_ = svr_.bind_to_any_port(HOST);
  18276. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18277. svr_.wait_until_ready();
  18278. }
  18279. void TearDown() override {
  18280. svr_.stop();
  18281. if (thread_.joinable()) { thread_.join(); }
  18282. }
  18283. // Sends `req` and reads until the server closes the connection. Returns
  18284. // false if the read had to wait for the client-side timeout instead.
  18285. bool send_until_closed(const std::string &req, std::string *resp) const {
  18286. auto start = std::chrono::steady_clock::now();
  18287. if (!send_request(3, req, resp, port_)) { return false; }
  18288. auto elapsed = std::chrono::steady_clock::now() - start;
  18289. return elapsed < std::chrono::seconds(2);
  18290. }
  18291. // The final response comes without `100 Continue`, and the server closes
  18292. // the connection since the body may or may not follow.
  18293. void expect_final_without_interim(const std::string &path,
  18294. const char *status_line) const {
  18295. std::string resp;
  18296. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18297. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18298. EXPECT_EQ(0u, resp.find(status_line));
  18299. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18300. }
  18301. Server svr_;
  18302. int port_ = 0;
  18303. thread thread_;
  18304. };
  18305. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18306. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18307. }
  18308. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18309. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18310. }
  18311. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18312. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18313. }
  18314. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18315. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18316. }
  18317. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18318. // The body follows once `100 Continue` has had time to arrive.
  18319. auto req = expect_headers_only("/reader-used");
  18320. req.insert(req.size() - 2, "Connection: close\r\n");
  18321. std::string resp;
  18322. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18323. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18324. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18325. EXPECT_NE(std::string::npos, resp.find("hi"));
  18326. }
  18327. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18328. // Large enough for the client to add `Expect: 100-continue` itself.
  18329. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18330. std::atomic<bool> body_sent{false};
  18331. Client cli(HOST, port_);
  18332. auto res = cli.Post(
  18333. "/pre-request", length,
  18334. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18335. body_sent = true;
  18336. std::string chunk(len, 'x');
  18337. sink.write(chunk.data(), chunk.size());
  18338. return true;
  18339. },
  18340. "application/octet-stream");
  18341. ASSERT_TRUE(res);
  18342. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18343. EXPECT_FALSE(body_sent);
  18344. }
  18345. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18346. Server svr;
  18347. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18348. return StatusCode::ExpectationFailed_417;
  18349. });
  18350. svr.Post("/p", [](const Request &, Response &res) {
  18351. res.set_content("ok", "text/plain");
  18352. });
  18353. auto port = svr.bind_to_any_port(HOST);
  18354. thread t = thread([&] { svr.listen_after_bind(); });
  18355. auto se = detail::scope_exit([&] {
  18356. svr.stop();
  18357. t.join();
  18358. });
  18359. svr.wait_until_ready();
  18360. std::string resp;
  18361. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18362. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18363. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18364. // Exactly one response: the route handler must not run after the 417.
  18365. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18366. }
  18367. #ifndef _WIN32
  18368. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18369. static constexpr char reject[] = "Unauthorized";
  18370. static constexpr char accept[] = "Upload accepted";
  18371. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18372. Server svr;
  18373. svr.set_expect_100_continue_handler(
  18374. [](const Request & /*req*/, Response &res) {
  18375. res.status = StatusCode::Unauthorized_401;
  18376. res.set_content(reject, "text/plain");
  18377. return res.status;
  18378. });
  18379. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18380. res.set_content(accept, "text/plain");
  18381. });
  18382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18383. auto se = detail::scope_exit([&] {
  18384. svr.stop();
  18385. thread.join();
  18386. ASSERT_FALSE(svr.is_running());
  18387. });
  18388. svr.wait_until_ready();
  18389. {
  18390. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18391. curl_easy_init(), &curl_easy_cleanup};
  18392. ASSERT_NE(curl, nullptr);
  18393. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18394. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18395. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18396. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18397. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18398. &curl_slist_free_all};
  18399. ASSERT_NE(list, nullptr);
  18400. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18401. struct read_data {
  18402. uint64_t read_size;
  18403. uint64_t total_size;
  18404. } data = {0, total_size};
  18405. using read_callback_t =
  18406. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18407. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18408. void *userdata) -> size_t {
  18409. read_data *d = (read_data *)userdata;
  18410. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18411. std::fill_n(ptr, size * nmemb, 'A');
  18412. d->read_size += size * nmemb;
  18413. return size * nmemb;
  18414. };
  18415. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18416. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18417. std::vector<char> buffer;
  18418. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18419. using write_callback_t =
  18420. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18421. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18422. void *userdata) -> size_t {
  18423. std::vector<char> *buf = (std::vector<char> *)userdata;
  18424. buf->reserve(buf->size() + size * nmemb + 1);
  18425. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18426. return size * nmemb;
  18427. };
  18428. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18429. {
  18430. const auto res = curl_easy_perform(curl.get());
  18431. ASSERT_EQ(res, CURLE_OK);
  18432. }
  18433. {
  18434. auto response_code = long{};
  18435. const auto res =
  18436. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18437. ASSERT_EQ(res, CURLE_OK);
  18438. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18439. }
  18440. {
  18441. auto dl = curl_off_t{};
  18442. const auto res =
  18443. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18444. ASSERT_EQ(res, CURLE_OK);
  18445. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18446. }
  18447. {
  18448. buffer.push_back('\0');
  18449. ASSERT_STRCASEEQ(buffer.data(), reject);
  18450. }
  18451. }
  18452. }
  18453. #endif
  18454. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18455. // Regression test for #2458.
  18456. //
  18457. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18458. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18459. // ticket can make the client socket spuriously readable during the
  18460. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18461. // the client withholds the body and then blocks reading a response that never
  18462. // comes, failing with `Failed to read connection`.
  18463. //
  18464. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18465. // within the timeout. This raw OpenSSL server deliberately never sends
  18466. // `100 Continue`; the client must still deliver the body and receive 200.
  18467. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18468. signal(SIGPIPE, SIG_IGN);
  18469. const auto port = PORT + 4;
  18470. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18471. ASSERT_NE(srv, INVALID_SOCKET);
  18472. int opt = 1;
  18473. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18474. sockaddr_in addr{};
  18475. addr.sin_family = AF_INET;
  18476. addr.sin_port = htons(static_cast<uint16_t>(port));
  18477. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18478. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18479. ASSERT_EQ(0, ::listen(srv, 1));
  18480. std::atomic<size_t> server_body_bytes{0};
  18481. auto server_thread = std::thread([&] {
  18482. sockaddr_in cli_addr{};
  18483. socklen_t cli_len = sizeof(cli_addr);
  18484. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18485. if (cli == INVALID_SOCKET) { return; }
  18486. // Bound the lifetime of the server side so a buggy client (which never
  18487. // sends the body) cannot make this thread block forever on join.
  18488. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18489. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18490. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18491. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18492. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18493. SSL *ssl = SSL_new(ctx);
  18494. SSL_set_fd(ssl, static_cast<int>(cli));
  18495. if (SSL_accept(ssl) > 0) {
  18496. // Read the request headers. Reading here also flushes the TLS 1.3
  18497. // session tickets to the client. Deliberately do NOT send
  18498. // `100 Continue`.
  18499. std::string buf;
  18500. char tmp[1024];
  18501. while (buf.find("\r\n\r\n") == std::string::npos) {
  18502. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18503. if (n <= 0) { break; }
  18504. buf.append(tmp, static_cast<size_t>(n));
  18505. }
  18506. // A correct client sends the body now; count what arrives.
  18507. auto pos = buf.find("\r\n\r\n");
  18508. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18509. while (body < 4096) {
  18510. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18511. if (n <= 0) { break; }
  18512. body += static_cast<size_t>(n);
  18513. }
  18514. server_body_bytes = body;
  18515. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18516. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18517. SSL_shutdown(ssl);
  18518. }
  18519. SSL_free(ssl);
  18520. detail::close_socket(cli);
  18521. SSL_CTX_free(ctx);
  18522. });
  18523. auto se = detail::scope_exit([&] {
  18524. server_thread.join();
  18525. detail::close_socket(srv);
  18526. });
  18527. SSLClient cli("127.0.0.1", port);
  18528. cli.enable_server_certificate_verification(false);
  18529. cli.set_connection_timeout(5, 0);
  18530. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18531. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18532. std::string body(4096, 'A');
  18533. auto res = cli.Put("/api/test", body, "application/json");
  18534. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18535. EXPECT_EQ(StatusCode::OK_200, res->status);
  18536. EXPECT_EQ(body.size(), server_body_bytes.load());
  18537. }
  18538. #endif
  18539. template <typename S, typename C>
  18540. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18541. svr.Get("/stream", [&](const Request &, Response &res) {
  18542. auto data = new std::string("01234567890123456789");
  18543. res.set_content_provider(
  18544. data->size(), "text/plain",
  18545. [&, data](size_t offset, size_t length, DataSink &sink) {
  18546. const size_t DATA_CHUNK_SIZE = 4;
  18547. const auto &d = *data;
  18548. std::this_thread::sleep_for(std::chrono::seconds(1));
  18549. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18550. return true;
  18551. },
  18552. [data](bool success) {
  18553. EXPECT_FALSE(success);
  18554. delete data;
  18555. });
  18556. });
  18557. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18558. auto i = new size_t(0);
  18559. res.set_content_provider(
  18560. "text/plain",
  18561. [i](size_t, DataSink &sink) {
  18562. if (*i < 5) {
  18563. std::this_thread::sleep_for(std::chrono::seconds(1));
  18564. sink.write("abcd", 4);
  18565. (*i)++;
  18566. } else {
  18567. sink.done();
  18568. }
  18569. return true;
  18570. },
  18571. [i](bool success) {
  18572. EXPECT_FALSE(success);
  18573. delete i;
  18574. });
  18575. });
  18576. svr.Get("/chunked", [&](const Request &, Response &res) {
  18577. auto i = new size_t(0);
  18578. res.set_chunked_content_provider(
  18579. "text/plain",
  18580. [i](size_t, DataSink &sink) {
  18581. if (*i < 5) {
  18582. std::this_thread::sleep_for(std::chrono::seconds(1));
  18583. sink.os << "abcd";
  18584. (*i)++;
  18585. } else {
  18586. sink.done();
  18587. }
  18588. return true;
  18589. },
  18590. [i](bool success) {
  18591. EXPECT_FALSE(success);
  18592. delete i;
  18593. });
  18594. });
  18595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18596. auto se = detail::scope_exit([&] {
  18597. svr.stop();
  18598. listen_thread.join();
  18599. ASSERT_FALSE(svr.is_running());
  18600. });
  18601. svr.wait_until_ready();
  18602. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18603. {
  18604. auto start = std::chrono::steady_clock::now();
  18605. auto res = cli.Get("/stream");
  18606. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18607. std::chrono::steady_clock::now() - start)
  18608. .count();
  18609. ASSERT_FALSE(res);
  18610. EXPECT_EQ(Error::Read, res.error());
  18611. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18612. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18613. }
  18614. {
  18615. auto start = std::chrono::steady_clock::now();
  18616. auto res = cli.Get("/stream_without_length");
  18617. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18618. std::chrono::steady_clock::now() - start)
  18619. .count();
  18620. ASSERT_FALSE(res);
  18621. EXPECT_EQ(Error::Read, res.error());
  18622. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18623. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18624. }
  18625. {
  18626. auto start = std::chrono::steady_clock::now();
  18627. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18628. EXPECT_EQ("abcd", string(data, data_length));
  18629. return true;
  18630. });
  18631. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18632. std::chrono::steady_clock::now() - start)
  18633. .count();
  18634. ASSERT_FALSE(res);
  18635. EXPECT_EQ(Error::Read, res.error());
  18636. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18637. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18638. }
  18639. }
  18640. TEST(MaxTimeoutTest, ContentStream) {
  18641. time_t timeout = 2000;
  18642. time_t threshold = 200;
  18643. Server svr;
  18644. Client cli("localhost", PORT);
  18645. max_timeout_test(svr, cli, timeout, threshold);
  18646. }
  18647. #ifdef CPPHTTPLIB_SSL_ENABLED
  18648. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18649. time_t timeout = 2000;
  18650. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18652. SSLClient cli("localhost", PORT);
  18653. cli.enable_server_certificate_verification(false);
  18654. max_timeout_test(svr, cli, timeout, threshold);
  18655. }
  18656. #endif
  18657. class EventDispatcher {
  18658. public:
  18659. EventDispatcher() {}
  18660. bool wait_event(DataSink *sink) {
  18661. unique_lock<mutex> lk(m_);
  18662. int id = id_;
  18663. // Wait with timeout to prevent hanging if client disconnects
  18664. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18665. [&] { return cid_ == id; })) {
  18666. return false; // Timeout occurred
  18667. }
  18668. sink->write(message_.data(), message_.size());
  18669. return true;
  18670. }
  18671. void send_event(const string &message) {
  18672. lock_guard<mutex> lk(m_);
  18673. cid_ = id_++;
  18674. message_ = message;
  18675. cv_.notify_all();
  18676. }
  18677. private:
  18678. mutex m_;
  18679. condition_variable cv_;
  18680. atomic_int id_{0};
  18681. atomic_int cid_{-1};
  18682. string message_;
  18683. };
  18684. TEST(ClientInThreadTest, Issue2068) {
  18685. EventDispatcher ed;
  18686. Server svr;
  18687. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18688. res.set_chunked_content_provider("text/event-stream",
  18689. [&](size_t /*offset*/, DataSink &sink) {
  18690. return ed.wait_event(&sink);
  18691. });
  18692. });
  18693. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18694. svr.wait_until_ready();
  18695. thread event_thread([&] {
  18696. int id = 0;
  18697. while (svr.is_running()) {
  18698. this_thread::sleep_for(chrono::milliseconds(500));
  18699. std::stringstream ss;
  18700. ss << "data: " << id << "\n\n";
  18701. ed.send_event(ss.str());
  18702. id++;
  18703. }
  18704. });
  18705. auto se = detail::scope_exit([&] {
  18706. svr.stop();
  18707. listen_thread.join();
  18708. event_thread.join();
  18709. ASSERT_FALSE(svr.is_running());
  18710. });
  18711. {
  18712. auto client = detail::make_unique<Client>(HOST, PORT);
  18713. client->set_read_timeout(std::chrono::minutes(10));
  18714. std::atomic<bool> stop{false};
  18715. std::thread t([&] {
  18716. client->Get("/event1",
  18717. [&](const char *, size_t) -> bool { return !stop; });
  18718. });
  18719. std::this_thread::sleep_for(std::chrono::seconds(2));
  18720. stop = true;
  18721. client->stop();
  18722. t.join();
  18723. // Reset client after thread has finished
  18724. client.reset();
  18725. }
  18726. }
  18727. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18728. auto handled = false;
  18729. Server svr;
  18730. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18731. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18732. auto se = detail::scope_exit([&] {
  18733. svr.stop();
  18734. t.join();
  18735. ASSERT_FALSE(svr.is_running());
  18736. ASSERT_FALSE(handled);
  18737. });
  18738. svr.wait_until_ready();
  18739. // Two Content-Length headers with different values — must be rejected
  18740. auto req = "POST /test HTTP/1.1\r\n"
  18741. "Content-Length: 5\r\n"
  18742. "Content-Length: 10\r\n"
  18743. "\r\n"
  18744. "hello";
  18745. std::string response;
  18746. ASSERT_TRUE(send_request(1, req, &response));
  18747. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18748. response.substr(0, response.find("\r\n")));
  18749. }
  18750. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18751. auto handled = false;
  18752. Server svr;
  18753. svr.Post("/test", [&](const Request &, Response &res) {
  18754. handled = true;
  18755. res.set_content("ok", "text/plain");
  18756. });
  18757. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18758. auto se = detail::scope_exit([&] {
  18759. svr.stop();
  18760. t.join();
  18761. ASSERT_FALSE(svr.is_running());
  18762. ASSERT_TRUE(handled);
  18763. });
  18764. svr.wait_until_ready();
  18765. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18766. auto req = "POST /test HTTP/1.1\r\n"
  18767. "Host: localhost\r\n"
  18768. "Content-Length: 5\r\n"
  18769. "Content-Length: 5\r\n"
  18770. "\r\n"
  18771. "hello";
  18772. std::string response;
  18773. ASSERT_TRUE(send_request(1, req, &response));
  18774. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18775. }
  18776. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18777. Server svr;
  18778. svr.Get("/test", [](const Request &, Response &res) {
  18779. res.set_content("ok", "text/plain");
  18780. });
  18781. auto port = svr.bind_to_any_port(HOST);
  18782. thread t = thread([&] { svr.listen_after_bind(); });
  18783. auto se = detail::scope_exit([&] {
  18784. svr.stop();
  18785. t.join();
  18786. ASSERT_FALSE(svr.is_running());
  18787. });
  18788. svr.wait_until_ready();
  18789. auto status_line = [&](const std::string &host_lines) {
  18790. std::string res;
  18791. send_request(
  18792. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18793. &res, port);
  18794. return res.substr(0, res.find("\r\n"));
  18795. };
  18796. const char *accepted[] = {
  18797. "Host: localhost\r\n",
  18798. "Host: a.example:8080\r\n",
  18799. "Host: my_service\r\n",
  18800. "Host: [::1]:8080\r\n",
  18801. "Host: [fe80::1%25eth0]\r\n",
  18802. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18803. };
  18804. for (auto host_lines : accepted) {
  18805. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18806. }
  18807. const char *rejected[] = {
  18808. "Host: a.example\r\nHost: b.example\r\n",
  18809. "Host: a.example\r\nHost: a.example\r\n",
  18810. "Host: a@b.example\r\n",
  18811. "Host: a.example/b\r\n",
  18812. "Host: a.example\\b\r\n",
  18813. "Host: a.example?b\r\n",
  18814. "Host: a.example#b\r\n",
  18815. "Host: a.example b.example\r\n",
  18816. };
  18817. for (auto host_lines : rejected) {
  18818. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18819. << host_lines;
  18820. }
  18821. }
  18822. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18823. Server svr;
  18824. svr.Get("/", [](const Request &req, Response &res) {
  18825. EXPECT_EQ(2U, req.trailers.size());
  18826. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18827. // Denied
  18828. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18829. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18830. // Accepted
  18831. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18832. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18833. EXPECT_TRUE(req.has_trailer("X-World"));
  18834. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18835. res.set_content("ok", "text/plain");
  18836. });
  18837. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18838. auto se = detail::scope_exit([&] {
  18839. svr.stop();
  18840. t.join();
  18841. ASSERT_FALSE(svr.is_running());
  18842. });
  18843. svr.wait_until_ready();
  18844. const std::string req = "GET / HTTP/1.1\r\n"
  18845. "Transfer-Encoding: chunked\r\n"
  18846. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18847. "\r\n"
  18848. "0\r\n"
  18849. "Content-Length: 10\r\n"
  18850. "Host: internal.local\r\n"
  18851. "Content-Type: malicious/content\r\n"
  18852. "Cookie: any\r\n"
  18853. "Set-Cookie: any\r\n"
  18854. "X-Forwarded-For: attacker.com\r\n"
  18855. "X-Real-Ip: 1.1.1.1\r\n"
  18856. "X-Hello: hello\r\n"
  18857. "X-World: world\r\n"
  18858. "\r\n";
  18859. std::string res;
  18860. ASSERT_TRUE(send_request(1, req, &res));
  18861. }
  18862. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18863. // several field lines, and the combined value is what has to be parsed. A
  18864. // Trailer field split across lines therefore declares every name it lists;
  18865. // reading only the first line silently drops the trailers the later lines
  18866. // declare. The prohibited-trailer filter still applies to every line.
  18867. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18868. Server svr;
  18869. size_t observed_trailer_count = 0;
  18870. std::string observed_hello;
  18871. std::string observed_world;
  18872. bool observed_content_length = true;
  18873. svr.Get("/", [&](const Request &req, Response &res) {
  18874. observed_trailer_count = req.trailers.size();
  18875. observed_hello = req.get_trailer_value("X-Hello");
  18876. observed_world = req.get_trailer_value("X-World");
  18877. observed_content_length = req.has_trailer("Content-Length");
  18878. res.set_content("ok", "text/plain");
  18879. });
  18880. auto port = svr.bind_to_any_port(HOST);
  18881. thread t = thread([&]() { svr.listen_after_bind(); });
  18882. auto se = detail::scope_exit([&] {
  18883. svr.stop();
  18884. t.join();
  18885. ASSERT_FALSE(svr.is_running());
  18886. });
  18887. svr.wait_until_ready();
  18888. const std::string req = "GET / HTTP/1.1\r\n"
  18889. "Host: localhost\r\n"
  18890. "Transfer-Encoding: chunked\r\n"
  18891. "Trailer: X-Hello\r\n"
  18892. "Trailer: X-World, Content-Length\r\n"
  18893. "\r\n"
  18894. "0\r\n"
  18895. "X-Hello: hello\r\n"
  18896. "X-World: world\r\n"
  18897. "Content-Length: 10\r\n"
  18898. "\r\n";
  18899. std::string res;
  18900. ASSERT_TRUE(send_request(1, req, &res, port));
  18901. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18902. // Accepted: both field lines contribute to the declared set
  18903. EXPECT_EQ(2U, observed_trailer_count);
  18904. EXPECT_EQ(observed_hello, "hello");
  18905. EXPECT_EQ(observed_world, "world");
  18906. // Denied: a prohibited name stays prohibited on a later field line
  18907. EXPECT_FALSE(observed_content_length);
  18908. }
  18909. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18910. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18911. // unbounded run of fields that are never declared, because the counter would
  18912. // only advance for declared fields.
  18913. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18914. Server svr;
  18915. bool handler_called = false;
  18916. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18917. handler_called = true;
  18918. res.set_content("ok", "text/plain");
  18919. });
  18920. auto port = svr.bind_to_any_port(HOST);
  18921. thread t = thread([&]() { svr.listen_after_bind(); });
  18922. auto se = detail::scope_exit([&] {
  18923. svr.stop();
  18924. t.join();
  18925. ASSERT_FALSE(svr.is_running());
  18926. });
  18927. svr.wait_until_ready();
  18928. // Declare nothing, then send far more undeclared trailer fields than the
  18929. // header-count limit. Parsing must stop and reject the request rather than
  18930. // read every line.
  18931. std::string req = "GET / HTTP/1.1\r\n"
  18932. "Transfer-Encoding: chunked\r\n"
  18933. "\r\n"
  18934. "0\r\n";
  18935. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18936. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18937. }
  18938. req += "\r\n";
  18939. std::string res;
  18940. ASSERT_TRUE(send_request(1, req, &res, port));
  18941. // The request is rejected before the handler runs.
  18942. EXPECT_FALSE(handler_called);
  18943. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18944. }
  18945. // The set of declared trailer names is capped so a peer cannot grow it without
  18946. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18947. // declared past the cap is not honored, even if the field is actually sent.
  18948. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18949. Server svr;
  18950. // One name inside the cap and one past it, so the test tracks the cap rather
  18951. // than a fixed count.
  18952. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18953. const std::string within_cap_name = "X-T-0";
  18954. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18955. bool observed_within_cap = false;
  18956. bool observed_past_cap = false;
  18957. svr.Get("/", [&](const Request &req, Response &res) {
  18958. observed_within_cap = req.has_trailer(within_cap_name);
  18959. observed_past_cap = req.has_trailer(past_cap_name);
  18960. res.set_content("ok", "text/plain");
  18961. });
  18962. auto port = svr.bind_to_any_port(HOST);
  18963. thread t = thread([&]() { svr.listen_after_bind(); });
  18964. auto se = detail::scope_exit([&] {
  18965. svr.stop();
  18966. t.join();
  18967. ASSERT_FALSE(svr.is_running());
  18968. });
  18969. svr.wait_until_ready();
  18970. // Declare more trailer names than the cap in a single Trailer field, then
  18971. // actually send the first (within the cap) and the last (past it).
  18972. std::string trailer_decl = "Trailer: ";
  18973. for (int i = 0; i < declared_count; i++) {
  18974. if (i != 0) { trailer_decl += ", "; }
  18975. trailer_decl += "X-T-" + std::to_string(i);
  18976. }
  18977. trailer_decl += "\r\n";
  18978. const std::string req = "GET / HTTP/1.1\r\n"
  18979. "Host: localhost\r\n"
  18980. "Transfer-Encoding: chunked\r\n" +
  18981. trailer_decl +
  18982. "\r\n"
  18983. "0\r\n" +
  18984. within_cap_name + ": a\r\n" + past_cap_name +
  18985. ": b\r\n"
  18986. "\r\n";
  18987. std::string res;
  18988. ASSERT_TRUE(send_request(1, req, &res, port));
  18989. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18990. // A name within the cap is honored; one declared past the cap is dropped.
  18991. EXPECT_TRUE(observed_within_cap);
  18992. EXPECT_FALSE(observed_past_cap);
  18993. }
  18994. // A direct client that is not listed in trusted_proxies must not be able to
  18995. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18996. // the peer address on the actual TCP connection determines whether the
  18997. // header is honored.
  18998. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18999. Server svr;
  19000. // Deliberately does NOT include the loopback address the test client
  19001. // actually connects from, so the direct connection is not a trusted proxy.
  19002. svr.set_trusted_proxies({"203.0.113.66"});
  19003. std::string observed_remote_addr;
  19004. svr.Get("/ip", [&](const Request &req, Response &res) {
  19005. observed_remote_addr = req.remote_addr;
  19006. res.set_content("ok", "text/plain");
  19007. });
  19008. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19009. auto se = detail::scope_exit([&] {
  19010. svr.stop();
  19011. t.join();
  19012. ASSERT_FALSE(svr.is_running());
  19013. });
  19014. svr.wait_until_ready();
  19015. Client cli(HOST, PORT);
  19016. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19018. EXPECT_EQ(StatusCode::OK_200, res->status);
  19019. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19020. // ignored entirely and the real connection-level address retained.
  19021. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19022. observed_remote_addr == "127.0.0.1");
  19023. }
  19024. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19025. Server svr;
  19026. std::string observed_remote_addr;
  19027. std::string observed_xff;
  19028. svr.Get("/ip", [&](const Request &req, Response &res) {
  19029. observed_remote_addr = req.remote_addr;
  19030. observed_xff = req.get_header_value("X-Forwarded-For");
  19031. res.set_content("ok", "text/plain");
  19032. });
  19033. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19034. auto se = detail::scope_exit([&] {
  19035. svr.stop();
  19036. t.join();
  19037. ASSERT_FALSE(svr.is_running());
  19038. });
  19039. svr.wait_until_ready();
  19040. Client cli(HOST, PORT);
  19041. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19043. EXPECT_EQ(StatusCode::OK_200, res->status);
  19044. EXPECT_EQ(observed_xff, "203.0.113.66");
  19045. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19046. observed_remote_addr == "127.0.0.1");
  19047. }
  19048. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19049. Server svr;
  19050. svr.set_trusted_proxies({"203.0.113.66"});
  19051. std::string observed_remote_addr;
  19052. std::string observed_xff;
  19053. svr.Get("/ip", [&](const Request &req, Response &res) {
  19054. observed_remote_addr = req.remote_addr;
  19055. observed_xff = req.get_header_value("X-Forwarded-For");
  19056. res.set_content("ok", "text/plain");
  19057. });
  19058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19059. auto se = detail::scope_exit([&] {
  19060. svr.stop();
  19061. t.join();
  19062. ASSERT_FALSE(svr.is_running());
  19063. });
  19064. svr.wait_until_ready();
  19065. Client cli(HOST, PORT);
  19066. auto res = cli.Get("/ip");
  19067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19068. EXPECT_EQ(StatusCode::OK_200, res->status);
  19069. EXPECT_EQ(observed_xff, "");
  19070. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19071. observed_remote_addr == "127.0.0.1");
  19072. }
  19073. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19074. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19075. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19076. Server svr;
  19077. svr.set_trusted_proxies({"127.0.0.1"});
  19078. svr.Get("/ip", [](const Request &req, Response &res) {
  19079. res.set_content(req.remote_addr, "text/plain");
  19080. });
  19081. auto port = svr.bind_to_any_port("::");
  19082. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19083. thread t = thread([&] { svr.listen_after_bind(); });
  19084. auto se = detail::scope_exit([&] {
  19085. svr.stop();
  19086. t.join();
  19087. ASSERT_FALSE(svr.is_running());
  19088. });
  19089. svr.wait_until_ready();
  19090. Client cli("127.0.0.1", port);
  19091. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19093. EXPECT_EQ("198.51.100.23", res->body);
  19094. }
  19095. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19096. Server svr;
  19097. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19098. svr.Get("/ip", [](const Request &req, Response &res) {
  19099. res.set_content(req.remote_addr, "text/plain");
  19100. });
  19101. auto port = svr.bind_to_any_port(HOST);
  19102. ASSERT_GT(port, 0);
  19103. thread t = thread([&] { svr.listen_after_bind(); });
  19104. auto se = detail::scope_exit([&] {
  19105. svr.stop();
  19106. t.join();
  19107. ASSERT_FALSE(svr.is_running());
  19108. });
  19109. svr.wait_until_ready();
  19110. Client cli(HOST, port);
  19111. auto res = cli.Get(
  19112. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19114. EXPECT_EQ("198.51.100.23", res->body);
  19115. }
  19116. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19117. Server svr;
  19118. // Include the loopback address the test client actually connects from, so
  19119. // the direct connection itself is recognized as the trusted proxy hop.
  19120. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19121. std::string observed_remote_addr;
  19122. std::string observed_xff;
  19123. svr.Get("/ip", [&](const Request &req, Response &res) {
  19124. observed_remote_addr = req.remote_addr;
  19125. observed_xff = req.get_header_value("X-Forwarded-For");
  19126. res.set_content("ok", "text/plain");
  19127. });
  19128. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19129. auto se = detail::scope_exit([&] {
  19130. svr.stop();
  19131. t.join();
  19132. ASSERT_FALSE(svr.is_running());
  19133. });
  19134. svr.wait_until_ready();
  19135. Client cli(HOST, PORT);
  19136. auto res = cli.Get(
  19137. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19139. EXPECT_EQ(StatusCode::OK_200, res->status);
  19140. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19141. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19142. }
  19143. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19144. Server svr;
  19145. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19146. std::string observed_remote_addr;
  19147. std::string observed_xff;
  19148. svr.Get("/ip", [&](const Request &req, Response &res) {
  19149. observed_remote_addr = req.remote_addr;
  19150. observed_xff = req.get_header_value("X-Forwarded-For");
  19151. res.set_content("ok", "text/plain");
  19152. });
  19153. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19154. auto se = detail::scope_exit([&] {
  19155. svr.stop();
  19156. t.join();
  19157. ASSERT_FALSE(svr.is_running());
  19158. });
  19159. svr.wait_until_ready();
  19160. Client cli(HOST, PORT);
  19161. auto res = cli.Get(
  19162. "/ip",
  19163. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19165. EXPECT_EQ(StatusCode::OK_200, res->status);
  19166. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19167. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19168. }
  19169. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19170. Server svr;
  19171. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19172. std::string observed_remote_addr;
  19173. std::string observed_xff;
  19174. svr.Get("/ip", [&](const Request &req, Response &res) {
  19175. observed_remote_addr = req.remote_addr;
  19176. observed_xff = req.get_header_value("X-Forwarded-For");
  19177. res.set_content("ok", "text/plain");
  19178. });
  19179. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19180. auto se = detail::scope_exit([&] {
  19181. svr.stop();
  19182. t.join();
  19183. ASSERT_FALSE(svr.is_running());
  19184. });
  19185. svr.wait_until_ready();
  19186. Client cli(HOST, PORT);
  19187. auto res = cli.Get(
  19188. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19190. EXPECT_EQ(StatusCode::OK_200, res->status);
  19191. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19192. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19193. // and must not be selected.
  19194. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19195. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19196. }
  19197. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19198. Server svr;
  19199. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19200. std::string observed_remote_addr;
  19201. svr.Get("/ip", [&](const Request &req, Response &res) {
  19202. observed_remote_addr = req.remote_addr;
  19203. res.set_content("ok", "text/plain");
  19204. });
  19205. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19206. auto se = detail::scope_exit([&] {
  19207. svr.stop();
  19208. t.join();
  19209. ASSERT_FALSE(svr.is_running());
  19210. });
  19211. svr.wait_until_ready();
  19212. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19213. // a forged address and the trusted proxy's own address; the forged value must
  19214. // not win over the address the trusted proxy actually recorded.
  19215. Client cli(HOST, PORT);
  19216. auto res = cli.Get(
  19217. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19219. EXPECT_EQ(StatusCode::OK_200, res->status);
  19220. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19221. }
  19222. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19223. Server svr;
  19224. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19225. std::string observed_remote_addr;
  19226. std::string observed_xff;
  19227. svr.Get("/ip", [&](const Request &req, Response &res) {
  19228. observed_remote_addr = req.remote_addr;
  19229. observed_xff = req.get_header_value("X-Forwarded-For");
  19230. res.set_content("ok", "text/plain");
  19231. });
  19232. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19233. auto se = detail::scope_exit([&] {
  19234. svr.stop();
  19235. t.join();
  19236. ASSERT_FALSE(svr.is_running());
  19237. });
  19238. svr.wait_until_ready();
  19239. Client cli(HOST, PORT);
  19240. auto res = cli.Get(
  19241. "/ip",
  19242. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19244. EXPECT_EQ(StatusCode::OK_200, res->status);
  19245. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19246. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19247. }
  19248. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19249. Server svr;
  19250. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19251. std::string observed_remote_addr;
  19252. std::string observed_xff;
  19253. svr.Get("/ip", [&](const Request &req, Response &res) {
  19254. observed_remote_addr = req.remote_addr;
  19255. observed_xff = req.get_header_value("X-Forwarded-For");
  19256. res.set_content("ok", "text/plain");
  19257. });
  19258. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19259. auto se = detail::scope_exit([&] {
  19260. svr.stop();
  19261. t.join();
  19262. ASSERT_FALSE(svr.is_running());
  19263. });
  19264. svr.wait_until_ready();
  19265. std::string raw_req =
  19266. "GET /ip HTTP/1.1\r\n"
  19267. "Host: localhost\r\n"
  19268. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19269. "Connection: close\r\n"
  19270. "\r\n";
  19271. std::string out;
  19272. ASSERT_TRUE(send_request(5, raw_req, &out));
  19273. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19274. // Header parser trims surrounding whitespace of the header value
  19275. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19276. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19277. }
  19278. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19279. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19280. // their own X-Forwarded-For as a separate field line rather than extending the
  19281. // one the client sent, so every occurrence has to be taken into account.
  19282. // Reading only the first one hands back the address the client chose.
  19283. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19284. Server svr;
  19285. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19286. std::string observed_remote_addr;
  19287. size_t observed_xff_count = 0;
  19288. svr.Get("/ip", [&](const Request &req, Response &res) {
  19289. observed_remote_addr = req.remote_addr;
  19290. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19291. res.set_content("ok", "text/plain");
  19292. });
  19293. auto port = svr.bind_to_any_port(HOST);
  19294. thread t = thread([&]() { svr.listen_after_bind(); });
  19295. auto se = detail::scope_exit([&] {
  19296. svr.stop();
  19297. t.join();
  19298. ASSERT_FALSE(svr.is_running());
  19299. });
  19300. svr.wait_until_ready();
  19301. // The client supplies the first field line; the trusted proxy appends the
  19302. // address it observed as a second one.
  19303. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19304. "Host: localhost\r\n"
  19305. "X-Forwarded-For: 1.2.3.4\r\n"
  19306. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19307. "Connection: close\r\n"
  19308. "\r\n";
  19309. std::string out;
  19310. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19311. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19312. EXPECT_EQ(observed_xff_count, 2U);
  19313. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19314. // The same chain spread over one field line per hop derives the same client
  19315. // address, i.e. the split and the comma-joined representations agree.
  19316. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19317. "Host: localhost\r\n"
  19318. "X-Forwarded-For: 1.2.3.4\r\n"
  19319. "X-Forwarded-For: 198.51.100.23\r\n"
  19320. "X-Forwarded-For: 192.0.2.45\r\n"
  19321. "Connection: close\r\n"
  19322. "\r\n";
  19323. out.clear();
  19324. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19325. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19326. EXPECT_EQ(observed_xff_count, 3U);
  19327. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19328. }
  19329. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19330. // crash the server (it used to call front() on an empty vector inside
  19331. // get_client_ip). The connection-level remote address must be retained instead.
  19332. static void run_malformed_xff_test(const std::string &xff_value) {
  19333. Server svr;
  19334. svr.set_trusted_proxies({"192.0.2.45"});
  19335. std::string observed_remote_addr;
  19336. svr.Get("/ip", [&](const Request &req, Response &res) {
  19337. observed_remote_addr = req.remote_addr;
  19338. res.set_content("ok", "text/plain");
  19339. });
  19340. int port = 0;
  19341. thread t = thread([&]() {
  19342. port = svr.bind_to_any_port(HOST);
  19343. svr.listen_after_bind();
  19344. });
  19345. auto se = detail::scope_exit([&] {
  19346. svr.stop();
  19347. t.join();
  19348. ASSERT_FALSE(svr.is_running());
  19349. });
  19350. svr.wait_until_ready();
  19351. Client cli(HOST, port);
  19352. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19354. EXPECT_EQ(StatusCode::OK_200, res->status);
  19355. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19356. observed_remote_addr == "127.0.0.1");
  19357. }
  19358. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19359. run_malformed_xff_test("");
  19360. }
  19361. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19362. run_malformed_xff_test(",");
  19363. }
  19364. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19365. run_malformed_xff_test(", , ,");
  19366. }
  19367. // The same rule applies to Accept: a request whose acceptable types are spread
  19368. // over several field lines must be negotiated against all of them.
  19369. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19370. // case-insensitive connection options. Comparing the whole field value against
  19371. // one option misses a client that sends several of them, and misses every
  19372. // casing but the one written in the comparison.
  19373. //
  19374. // Sends req, reads the response, then reuses the same socket for a second
  19375. // request to find out whether the server kept the connection.
  19376. static void probe_connection_reuse(int port, const std::string &req,
  19377. bool *announced_close, bool *reusable) {
  19378. auto error = Error::Success;
  19379. auto sock = detail::create_client_socket(
  19380. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19381. /*connection_timeout_sec=*/5, 0,
  19382. /*read_timeout_sec=*/1, 0,
  19383. /*write_timeout_sec=*/5, 0, std::string(), error);
  19384. ASSERT_NE(sock, INVALID_SOCKET);
  19385. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19386. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19387. "Host: localhost\r\n"
  19388. "Connection: close\r\n"
  19389. "\r\n";
  19390. std::string first_response;
  19391. std::string second_response;
  19392. detail::process_client_socket(
  19393. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19394. [&](Stream &strm) {
  19395. if (strm.write(req.data(), req.size()) !=
  19396. static_cast<ssize_t>(req.size())) {
  19397. return false;
  19398. }
  19399. char buf[512];
  19400. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19401. // Headers plus the two-byte body of the handler below
  19402. while (reader.getline()) {
  19403. first_response += reader.ptr();
  19404. if (first_response.find("ok") != std::string::npos) { break; }
  19405. }
  19406. if (strm.write(second.data(), second.size()) !=
  19407. static_cast<ssize_t>(second.size())) {
  19408. return true;
  19409. }
  19410. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19411. while (reader2.getline()) {
  19412. second_response += reader2.ptr();
  19413. if (second_response.find("ok") != std::string::npos) { break; }
  19414. }
  19415. return true;
  19416. });
  19417. *announced_close =
  19418. first_response.find("Connection: close") != std::string::npos;
  19419. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19420. }
  19421. class ConnectionTokenTest : public ::testing::Test {
  19422. protected:
  19423. void SetUp() override {
  19424. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19425. res.set_content("ok", "text/plain");
  19426. });
  19427. port_ = svr_.bind_to_any_port(HOST);
  19428. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19429. svr_.wait_until_ready();
  19430. }
  19431. void TearDown() override {
  19432. svr_.stop();
  19433. if (thread_.joinable()) { thread_.join(); }
  19434. }
  19435. Server svr_;
  19436. int port_ = 0;
  19437. thread thread_;
  19438. };
  19439. // "close" alongside another option still closes the connection, and the
  19440. // response says so rather than leaving the peer to discover it.
  19441. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19442. bool announced_close = false;
  19443. bool reusable = true;
  19444. probe_connection_reuse(port_,
  19445. "GET /keepalive HTTP/1.1\r\n"
  19446. "Host: localhost\r\n"
  19447. "Connection: keep-alive, close\r\n"
  19448. "\r\n",
  19449. &announced_close, &reusable);
  19450. EXPECT_TRUE(announced_close);
  19451. EXPECT_FALSE(reusable);
  19452. }
  19453. // "close" split over two field lines is the same list, so it is honored too.
  19454. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19455. bool announced_close = false;
  19456. bool reusable = true;
  19457. probe_connection_reuse(port_,
  19458. "GET /keepalive HTTP/1.1\r\n"
  19459. "Host: localhost\r\n"
  19460. "Connection: keep-alive\r\n"
  19461. "Connection: close\r\n"
  19462. "\r\n",
  19463. &announced_close, &reusable);
  19464. EXPECT_TRUE(announced_close);
  19465. EXPECT_FALSE(reusable);
  19466. }
  19467. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19468. // keep-alive in the spelling everyone actually sends keeps its connection.
  19469. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19470. bool announced_close = false;
  19471. bool reusable = false;
  19472. probe_connection_reuse(port_,
  19473. "GET /keepalive HTTP/1.0\r\n"
  19474. "Host: localhost\r\n"
  19475. "Connection: keep-alive\r\n"
  19476. "\r\n",
  19477. &announced_close, &reusable);
  19478. EXPECT_FALSE(announced_close);
  19479. EXPECT_TRUE(reusable);
  19480. }
  19481. // A token the value merely contains is not the token itself.
  19482. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19483. bool announced_close = false;
  19484. bool reusable = false;
  19485. probe_connection_reuse(port_,
  19486. "GET /keepalive HTTP/1.1\r\n"
  19487. "Host: localhost\r\n"
  19488. "Connection: notclose\r\n"
  19489. "\r\n",
  19490. &announced_close, &reusable);
  19491. EXPECT_FALSE(announced_close);
  19492. EXPECT_TRUE(reusable);
  19493. }
  19494. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19495. Server svr;
  19496. std::vector<std::string> observed_types;
  19497. svr.Get("/", [&](const Request &req, Response &res) {
  19498. observed_types = req.accept_content_types;
  19499. res.set_content("ok", "text/plain");
  19500. });
  19501. auto port = svr.bind_to_any_port(HOST);
  19502. thread t = thread([&]() { svr.listen_after_bind(); });
  19503. auto se = detail::scope_exit([&] {
  19504. svr.stop();
  19505. t.join();
  19506. ASSERT_FALSE(svr.is_running());
  19507. });
  19508. svr.wait_until_ready();
  19509. Client cli(HOST, port);
  19510. Headers headers;
  19511. headers.emplace("Accept", "text/plain;q=0.5");
  19512. headers.emplace("Accept", "application/json");
  19513. auto res = cli.Get("/", headers);
  19514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19515. EXPECT_EQ(StatusCode::OK_200, res->status);
  19516. // Sorted by q-value, so the second field line's type comes first
  19517. ASSERT_EQ(2U, observed_types.size());
  19518. EXPECT_EQ("application/json", observed_types[0]);
  19519. EXPECT_EQ("text/plain", observed_types[1]);
  19520. }
  19521. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19522. // empty field line must not contribute a bare comma to the combined value.
  19523. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19524. Server svr;
  19525. std::vector<std::string> observed_types;
  19526. svr.Get("/", [&](const Request &req, Response &res) {
  19527. observed_types = req.accept_content_types;
  19528. res.set_content("ok", "text/plain");
  19529. });
  19530. auto port = svr.bind_to_any_port(HOST);
  19531. thread t = thread([&]() { svr.listen_after_bind(); });
  19532. auto se = detail::scope_exit([&] {
  19533. svr.stop();
  19534. t.join();
  19535. ASSERT_FALSE(svr.is_running());
  19536. });
  19537. svr.wait_until_ready();
  19538. // Empty first field line, then a real one
  19539. std::string raw_req = "GET / HTTP/1.1\r\n"
  19540. "Host: localhost\r\n"
  19541. "Accept:\r\n"
  19542. "Accept: application/json\r\n"
  19543. "Connection: close\r\n"
  19544. "\r\n";
  19545. std::string out;
  19546. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19547. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19548. ASSERT_EQ(1U, observed_types.size());
  19549. EXPECT_EQ("application/json", observed_types[0]);
  19550. }
  19551. // The skip in get_combined_header_value() is what keeps an empty field line
  19552. // from contributing a bare comma. Only a trailing empty field line exercises
  19553. // it: a leading one is already covered by the "combined is still empty" check,
  19554. // and parse_accept_header() now ignores the empty element either way, so the
  19555. // request-level test above can no longer tell the two apart.
  19556. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19557. Headers headers;
  19558. headers.emplace("Accept", "text/html");
  19559. headers.emplace("Accept", "");
  19560. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19561. headers.clear();
  19562. headers.emplace("Accept", "");
  19563. headers.emplace("Accept", "application/json");
  19564. EXPECT_EQ("application/json",
  19565. detail::get_combined_header_value(headers, "Accept"));
  19566. }
  19567. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19568. // An encoding offered on a later Accept-Encoding field line is still offered.
  19569. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19570. Server svr;
  19571. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19572. res.set_content(std::string(1024, 'x'), "text/plain");
  19573. });
  19574. auto port = svr.bind_to_any_port(HOST);
  19575. thread t = thread([&]() { svr.listen_after_bind(); });
  19576. auto se = detail::scope_exit([&] {
  19577. svr.stop();
  19578. t.join();
  19579. ASSERT_FALSE(svr.is_running());
  19580. });
  19581. svr.wait_until_ready();
  19582. Client cli(HOST, port);
  19583. cli.set_decompress(false);
  19584. Headers headers;
  19585. headers.emplace("Accept-Encoding", "identity");
  19586. headers.emplace("Accept-Encoding", "gzip");
  19587. auto res = cli.Get("/", headers);
  19588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19589. EXPECT_EQ(StatusCode::OK_200, res->status);
  19590. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19591. }
  19592. #endif
  19593. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19594. // Transfer-Encoding is not its body.
  19595. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19596. Server svr;
  19597. svr.set_payload_max_length(8);
  19598. svr.Post("/test", [](const Request &, Response &res) {
  19599. res.set_content("ok", "text/plain");
  19600. });
  19601. auto port = svr.bind_to_any_port(HOST);
  19602. ASSERT_GT(port, 0);
  19603. thread t = thread([&] { svr.listen_after_bind(); });
  19604. auto se = detail::scope_exit([&] {
  19605. svr.stop();
  19606. t.join();
  19607. ASSERT_FALSE(svr.is_running());
  19608. });
  19609. svr.wait_until_ready();
  19610. std::string resp;
  19611. ASSERT_TRUE(send_request(1,
  19612. "POST /test HTTP/1.1\r\n"
  19613. "Host: localhost\r\n"
  19614. "Connection: close\r\n"
  19615. "\r\n" +
  19616. std::string(16, 'X'),
  19617. &resp, port));
  19618. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19619. }
  19620. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19621. Server svr;
  19622. svr.Post("/post", [&](const Request &req, Response &res) {
  19623. res.set_content(req.body, "text/plain");
  19624. });
  19625. svr.Put("/put", [&](const Request &req, Response &res) {
  19626. res.set_content(req.body, "text/plain");
  19627. });
  19628. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19629. res.set_content(req.body, "text/plain");
  19630. });
  19631. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19632. res.set_content(req.body, "text/plain");
  19633. });
  19634. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19635. auto se = detail::scope_exit([&] {
  19636. svr.stop();
  19637. t.join();
  19638. ASSERT_FALSE(svr.is_running());
  19639. });
  19640. svr.wait_until_ready();
  19641. std::string resp;
  19642. // POST without Content-Length
  19643. ASSERT_TRUE(send_request(5,
  19644. "POST /post HTTP/1.1\r\n"
  19645. "Host: localhost\r\n"
  19646. "Connection: close\r\n"
  19647. "\r\n",
  19648. &resp));
  19649. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19650. // PUT without Content-Length
  19651. resp.clear();
  19652. ASSERT_TRUE(send_request(5,
  19653. "PUT /put HTTP/1.1\r\n"
  19654. "Host: localhost\r\n"
  19655. "Connection: close\r\n"
  19656. "\r\n",
  19657. &resp));
  19658. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19659. // PATCH without Content-Length
  19660. resp.clear();
  19661. ASSERT_TRUE(send_request(5,
  19662. "PATCH /patch HTTP/1.1\r\n"
  19663. "Host: localhost\r\n"
  19664. "Connection: close\r\n"
  19665. "\r\n",
  19666. &resp));
  19667. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19668. // DELETE without Content-Length
  19669. resp.clear();
  19670. ASSERT_TRUE(send_request(5,
  19671. "DELETE /delete HTTP/1.1\r\n"
  19672. "Host: localhost\r\n"
  19673. "Connection: close\r\n"
  19674. "\r\n",
  19675. &resp));
  19676. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19677. }
  19678. //==============================================================================
  19679. // open_stream() Tests
  19680. //==============================================================================
  19681. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19682. std::string result;
  19683. char buf[8192];
  19684. ssize_t n;
  19685. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19686. result.append(buf, static_cast<size_t>(n));
  19687. }
  19688. return result;
  19689. }
  19690. // Mock stream for unit tests
  19691. class MockStream : public Stream {
  19692. public:
  19693. std::string data;
  19694. size_t pos = 0;
  19695. ssize_t error_after = -1; // -1 = no error
  19696. explicit MockStream(const std::string &d, ssize_t err = -1)
  19697. : data(d), error_after(err) {}
  19698. bool is_readable() const override { return true; }
  19699. bool wait_readable() const override { return true; }
  19700. bool wait_writable() const override { return true; }
  19701. ssize_t read(char *ptr, size_t size) override {
  19702. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19703. if (pos >= data.size()) return 0;
  19704. size_t limit =
  19705. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19706. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19707. std::memcpy(ptr, data.data() + pos, to_read);
  19708. pos += to_read;
  19709. return static_cast<ssize_t>(to_read);
  19710. }
  19711. ssize_t write(const char *, size_t) override { return -1; }
  19712. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19713. ip = "127.0.0.1";
  19714. port = 0;
  19715. }
  19716. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19717. ip = "127.0.0.1";
  19718. port = 0;
  19719. }
  19720. socket_t socket() const override { return INVALID_SOCKET; }
  19721. time_t duration() const override { return 0; }
  19722. };
  19723. TEST(StreamHandleTest, Basic) {
  19724. ClientImpl::StreamHandle handle;
  19725. EXPECT_FALSE(handle.is_valid());
  19726. handle.response = detail::make_unique<Response>();
  19727. handle.error = Error::Connection;
  19728. EXPECT_FALSE(handle.is_valid());
  19729. handle.error = Error::Success;
  19730. EXPECT_TRUE(handle.is_valid());
  19731. }
  19732. TEST(BodyReaderTest, Basic) {
  19733. MockStream stream("Hello, World!");
  19734. detail::BodyReader reader;
  19735. reader.stream = &stream;
  19736. reader.content_length = 13;
  19737. char buf[32];
  19738. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19739. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19740. EXPECT_TRUE(reader.eof);
  19741. }
  19742. TEST(BodyReaderTest, NoStream) {
  19743. detail::BodyReader reader;
  19744. char buf[32];
  19745. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19746. EXPECT_EQ(Error::Connection, reader.last_error);
  19747. }
  19748. TEST(BodyReaderTest, Error) {
  19749. MockStream stream("Hello, World!", 5);
  19750. detail::BodyReader reader;
  19751. reader.stream = &stream;
  19752. reader.content_length = 13;
  19753. char buf[32];
  19754. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19755. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19756. EXPECT_EQ(Error::Read, reader.last_error);
  19757. }
  19758. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19759. // Mock-based StreamHandle tests relying on private internals are removed.
  19760. class OpenStreamTest : public ::testing::Test {
  19761. protected:
  19762. void SetUp() override {
  19763. svr_.Get("/hello", [](const Request &, Response &res) {
  19764. res.set_content("Hello World!", "text/plain");
  19765. });
  19766. svr_.Get("/large", [](const Request &, Response &res) {
  19767. res.set_content(std::string(10000, 'X'), "text/plain");
  19768. });
  19769. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19770. res.set_content("Hello World!", "image/jpeg");
  19771. res.set_header("Content-Encoding", "UTF-8");
  19772. });
  19773. svr_.Get("/chunked", [](const Request &, Response &res) {
  19774. res.set_chunked_content_provider("text/plain",
  19775. [](size_t offset, DataSink &sink) {
  19776. if (offset < 15) {
  19777. sink.write("chunk", 5);
  19778. return true;
  19779. }
  19780. sink.done();
  19781. return true;
  19782. });
  19783. });
  19784. svr_.Get("/compressible", [](const Request &, Response &res) {
  19785. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19786. DataSink &sink) {
  19787. if (offset < 100 * 1024) {
  19788. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19789. sink.write(chunk.data(), chunk.size());
  19790. return true;
  19791. }
  19792. sink.done();
  19793. return true;
  19794. });
  19795. });
  19796. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19797. [](const Request & /*req*/, Response &res) {
  19798. auto i = new int(0);
  19799. res.set_header("Trailer", "Content-Length, X-Allowed");
  19800. res.set_chunked_content_provider(
  19801. "text/plain",
  19802. [i](size_t /*offset*/, DataSink &sink) {
  19803. switch (*i) {
  19804. case 0: sink.os << "123"; break;
  19805. case 1: sink.os << "456"; break;
  19806. case 2: sink.os << "789"; break;
  19807. case 3: {
  19808. sink.done_with_trailer(
  19809. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19810. } break;
  19811. }
  19812. (*i)++;
  19813. return true;
  19814. },
  19815. [i](bool success) {
  19816. EXPECT_TRUE(success);
  19817. delete i;
  19818. });
  19819. });
  19820. // Echo headers endpoint for header-related tests
  19821. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19822. std::string body;
  19823. for (const auto &h : req.headers) {
  19824. body.append(h.first);
  19825. body.push_back(':');
  19826. body.append(h.second);
  19827. body.push_back('\n');
  19828. }
  19829. res.set_content(body, "text/plain");
  19830. });
  19831. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19832. std::string body;
  19833. for (const auto &h : req.headers) {
  19834. body.append(h.first);
  19835. body.push_back(':');
  19836. body.append(h.second);
  19837. body.push_back('\n');
  19838. }
  19839. res.set_content(body, "text/plain");
  19840. });
  19841. port_ = svr_.bind_to_any_port("127.0.0.1");
  19842. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19843. svr_.wait_until_ready();
  19844. }
  19845. void TearDown() override {
  19846. svr_.stop();
  19847. if (thread_.joinable()) thread_.join();
  19848. }
  19849. Server svr_;
  19850. std::thread thread_;
  19851. int port_ = 0;
  19852. };
  19853. TEST_F(OpenStreamTest, Basic) {
  19854. Client cli("127.0.0.1", port_);
  19855. auto handle = cli.open_stream("GET", "/hello");
  19856. EXPECT_TRUE(handle.is_valid());
  19857. EXPECT_EQ("Hello World!", read_all(handle));
  19858. }
  19859. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19860. Client cli("127.0.0.1", port_);
  19861. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19862. ASSERT_TRUE(handle.is_valid());
  19863. EXPECT_EQ("Hello World!", read_all(handle));
  19864. }
  19865. TEST_F(OpenStreamTest, SmallBuffer) {
  19866. Client cli("127.0.0.1", port_);
  19867. auto handle = cli.open_stream("GET", "/hello");
  19868. std::string result;
  19869. char buf[4];
  19870. ssize_t n;
  19871. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19872. result.append(buf, static_cast<size_t>(n));
  19873. EXPECT_EQ("Hello World!", result);
  19874. }
  19875. TEST_F(OpenStreamTest, DefaultHeaders) {
  19876. Client cli("127.0.0.1", port_);
  19877. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19878. {
  19879. auto handle = cli.open_stream("GET", "/echo-headers");
  19880. ASSERT_TRUE(handle.is_valid());
  19881. auto body = read_all(handle);
  19882. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19883. std::string::npos);
  19884. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19885. std::string::npos);
  19886. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19887. }
  19888. // open_stream POST with body and no explicit content_type should NOT add
  19889. // text/plain Content-Type (behavior differs from non-streaming path), but
  19890. // should include Content-Length
  19891. {
  19892. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19893. ASSERT_TRUE(handle.is_valid());
  19894. auto body = read_all(handle);
  19895. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19896. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19897. }
  19898. // open_stream POST with explicit Content-Type should preserve it
  19899. {
  19900. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19901. {{"Content-Type", "application/custom"}},
  19902. "{}", "application/custom");
  19903. ASSERT_TRUE(handle.is_valid());
  19904. auto body = read_all(handle);
  19905. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19906. }
  19907. // User-specified User-Agent must not be overwritten for stream API
  19908. {
  19909. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19910. {{"User-Agent", "MyAgent/1.2"}});
  19911. ASSERT_TRUE(handle.is_valid());
  19912. auto body = read_all(handle);
  19913. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19914. }
  19915. }
  19916. TEST_F(OpenStreamTest, Large) {
  19917. Client cli("127.0.0.1", port_);
  19918. auto handle = cli.open_stream("GET", "/large");
  19919. EXPECT_EQ(10000u, read_all(handle).size());
  19920. }
  19921. TEST_F(OpenStreamTest, ConnectionError) {
  19922. Client cli("127.0.0.1", 9999);
  19923. auto handle = cli.open_stream("GET", "/hello");
  19924. EXPECT_FALSE(handle.is_valid());
  19925. }
  19926. TEST_F(OpenStreamTest, Chunked) {
  19927. Client cli("127.0.0.1", port_);
  19928. auto handle = cli.open_stream("GET", "/chunked");
  19929. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19930. "Transfer-Encoding") == "chunked");
  19931. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19932. }
  19933. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19934. Client cli("127.0.0.1", port_);
  19935. auto handle =
  19936. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19937. ASSERT_TRUE(handle.is_valid());
  19938. // Consume body to allow trailers to be received/parsed
  19939. auto body = read_all(handle);
  19940. // Explicitly parse trailers (ensure trailers are available for assertion)
  19941. handle.parse_trailers_if_needed();
  19942. EXPECT_EQ(std::string("123456789"), body);
  19943. // The response should include a Trailer header declaring both names
  19944. ASSERT_TRUE(handle.response);
  19945. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19946. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19947. handle.response->get_header_value("Trailer"));
  19948. // Prohibited trailer must not be present
  19949. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19950. // Allowed trailer should be present
  19951. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19952. EXPECT_EQ(std::string("yes"),
  19953. handle.response->get_trailer_value("X-Allowed"));
  19954. // Verify trailers are NOT present as regular headers
  19955. EXPECT_EQ(std::string(""),
  19956. handle.response->get_header_value("Content-Length"));
  19957. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19958. }
  19959. // Accepts one connection on an OS-assigned port, which it hands over through
  19960. // port_promise, reads the request head and sends back response. after_send,
  19961. // if given, runs on the connection before it is closed.
  19962. static std::thread
  19963. serve_single_response(std::promise<int> &port_promise,
  19964. const std::string &response,
  19965. std::function<void(socket_t)> after_send = nullptr) {
  19966. return std::thread([&port_promise, response, after_send] {
  19967. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19968. default_socket_options(srv);
  19969. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19970. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19971. sockaddr_in addr{};
  19972. addr.sin_family = AF_INET;
  19973. addr.sin_port = htons(0); // Let OS assign a free port
  19974. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19975. int opt = 1;
  19976. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19977. #ifdef _WIN32
  19978. reinterpret_cast<const char *>(&opt),
  19979. #else
  19980. &opt,
  19981. #endif
  19982. sizeof(opt));
  19983. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19984. ::listen(srv, 1) != 0) {
  19985. port_promise.set_value(-1);
  19986. detail::close_socket(srv);
  19987. return;
  19988. }
  19989. socklen_t addr_len = sizeof(addr);
  19990. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19991. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19992. sockaddr_in cli_addr{};
  19993. socklen_t cli_len = sizeof(cli_addr);
  19994. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19995. if (cli != INVALID_SOCKET) {
  19996. // Read the complete HTTP request (until the blank line that terminates
  19997. // headers) before sending the response. If the server closes the socket
  19998. // while the client's request data is still unread in the kernel receive
  19999. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20000. // connection on both sides: it discards the client's receive buffer
  20001. // (which already holds our response) and causes any in-progress write on
  20002. // the client to fail with ECONNRESET. Reading all request data first
  20003. // ensures close() emits a graceful FIN.
  20004. {
  20005. char rbuf[256];
  20006. std::string req;
  20007. while (req.find("\r\n\r\n") == std::string::npos) {
  20008. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20009. if (n <= 0) { break; }
  20010. req.append(rbuf, static_cast<size_t>(n));
  20011. }
  20012. }
  20013. ::send(cli,
  20014. #ifdef _WIN32
  20015. static_cast<const char *>(response.c_str()),
  20016. static_cast<int>(response.size()),
  20017. #else
  20018. response.c_str(), response.size(),
  20019. #endif
  20020. 0);
  20021. if (after_send) { after_send(cli); }
  20022. detail::close_socket(cli);
  20023. }
  20024. detail::close_socket(srv);
  20025. });
  20026. }
  20027. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20028. #ifndef _WIN32
  20029. signal(SIGPIPE, SIG_IGN);
  20030. #endif
  20031. std::promise<int> port_promise;
  20032. auto port_future = port_promise.get_future();
  20033. auto server_thread =
  20034. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20035. "Content-Type: text/plain\r\n"
  20036. "Content-Length: not-a-number\r\n"
  20037. "Connection: close\r\n"
  20038. "\r\n"
  20039. "hello");
  20040. auto port = port_future.get();
  20041. ASSERT_GT(port, 0);
  20042. Client cli("127.0.0.1", port);
  20043. auto handle = cli.open_stream("GET", "/");
  20044. EXPECT_FALSE(handle.is_valid());
  20045. server_thread.join();
  20046. }
  20047. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20048. #ifndef _WIN32
  20049. signal(SIGPIPE, SIG_IGN);
  20050. #endif
  20051. std::promise<int> port_promise;
  20052. auto port_future = port_promise.get_future();
  20053. auto server_thread = serve_single_response(
  20054. port_promise, "HTTP/1.1 200 OK\r\n"
  20055. "Content-Type: text/plain\r\n"
  20056. "Content-Length: 99999999999999999999999999\r\n"
  20057. "Connection: close\r\n"
  20058. "\r\n"
  20059. "hello");
  20060. auto port = port_future.get();
  20061. ASSERT_GT(port, 0);
  20062. // Historically std::stoull would throw std::out_of_range here and crash
  20063. // the process, then parsing silently clamped to a bogus framing length and
  20064. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20065. // so the stream fails to open, matching the not-a-number case above. The
  20066. // process still must NOT terminate.
  20067. Client cli("127.0.0.1", port);
  20068. auto handle = cli.open_stream("GET", "/");
  20069. EXPECT_FALSE(handle.is_valid());
  20070. server_thread.join();
  20071. }
  20072. #ifndef _WIN32
  20073. // As above for the body of a streamed request: a send() cut short by the write
  20074. // timeout must not leave the rest of the body unsent.
  20075. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20076. signal(SIGPIPE, SIG_IGN);
  20077. Server svr;
  20078. svr.set_socket_options([](socket_t sock) {
  20079. int size = 8192;
  20080. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20081. reinterpret_cast<const char *>(&size), sizeof(size));
  20082. });
  20083. svr.Post("/size", [](const Request &, Response &res,
  20084. const ContentReader &content_reader) {
  20085. // Outlast the client's write timeout before reading the body.
  20086. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20087. size_t received = 0;
  20088. content_reader([&](const char *, size_t len) {
  20089. received += len;
  20090. return true;
  20091. });
  20092. res.set_content(std::to_string(received), "text/plain");
  20093. });
  20094. auto port = svr.bind_to_any_port(HOST);
  20095. std::thread t([&]() { svr.listen_after_bind(); });
  20096. auto se = detail::scope_exit([&] {
  20097. svr.stop();
  20098. t.join();
  20099. });
  20100. svr.wait_until_ready();
  20101. Client cli(HOST, port);
  20102. cli.set_write_timeout(0, 500000);
  20103. cli.set_socket_options([](socket_t sock) {
  20104. int size = 8192;
  20105. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20106. reinterpret_cast<const char *>(&size), sizeof(size));
  20107. });
  20108. const std::string body(4 * 1024 * 1024, 'A');
  20109. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20110. "application/octet-stream");
  20111. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20112. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20113. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20114. }
  20115. #endif
  20116. // Serves `response` to the single request `fn` makes with a fresh client.
  20117. template <typename Fn>
  20118. static void with_single_response(const std::string &response, Fn fn) {
  20119. #ifndef _WIN32
  20120. signal(SIGPIPE, SIG_IGN);
  20121. #endif
  20122. std::promise<int> port_promise;
  20123. auto port_future = port_promise.get_future();
  20124. auto server_thread = serve_single_response(port_promise, response);
  20125. auto se = detail::scope_exit([&] { server_thread.join(); });
  20126. auto port = port_future.get();
  20127. ASSERT_GT(port, 0);
  20128. Client cli("127.0.0.1", port);
  20129. fn(cli);
  20130. }
  20131. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20132. // too, also in a build without the decoder for the advertised coding.
  20133. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20134. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20135. const auto response = "HTTP/1.1 200 OK\r\n"
  20136. "Content-Encoding: gzip\r\n"
  20137. "Content-Length: " +
  20138. std::to_string(gzipped.size()) +
  20139. "\r\n"
  20140. "Connection: close\r\n\r\n" +
  20141. gzipped;
  20142. with_single_response(response, [&](Client &cli) {
  20143. cli.set_decompress(false);
  20144. auto handle = cli.open_stream("GET", "/");
  20145. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20146. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20147. EXPECT_EQ(gzipped, read_all(handle));
  20148. EXPECT_FALSE(handle.has_read_error());
  20149. });
  20150. with_single_response(response, [&](Client &cli) {
  20151. cli.set_decompress(false);
  20152. auto res = stream::Get(cli, "/", 7);
  20153. ASSERT_TRUE(res) << to_string(res.error());
  20154. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20155. EXPECT_EQ(gzipped, res.read_all());
  20156. EXPECT_FALSE(res.has_read_error());
  20157. });
  20158. }
  20159. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20160. // Neither Content-Length nor chunked: the body ends at the close
  20161. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20162. "Connection: close\r\n"
  20163. "\r\n"
  20164. "hello";
  20165. with_single_response(close_delimited, [](Client &cli) {
  20166. auto handle = cli.open_stream("GET", "/");
  20167. ASSERT_TRUE(handle.is_valid());
  20168. EXPECT_EQ("hello", read_all(handle));
  20169. EXPECT_FALSE(handle.has_read_error());
  20170. });
  20171. // A close before the end of the Content-Length is still an error
  20172. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20173. "Content-Length: 10\r\n"
  20174. "\r\n"
  20175. "hello";
  20176. with_single_response(short_content_length, [](Client &cli) {
  20177. auto handle = cli.open_stream("GET", "/");
  20178. ASSERT_TRUE(handle.is_valid());
  20179. read_all(handle);
  20180. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20181. });
  20182. // So is a close before the last chunk
  20183. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20184. "Transfer-Encoding: chunked\r\n"
  20185. "\r\n"
  20186. "5\r\nhello\r\n";
  20187. with_single_response(short_chunked, [](Client &cli) {
  20188. auto handle = cli.open_stream("GET", "/");
  20189. ASSERT_TRUE(handle.is_valid());
  20190. read_all(handle);
  20191. EXPECT_TRUE(handle.has_read_error());
  20192. });
  20193. }
  20194. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20195. const char *responses[] = {
  20196. "HTTP/1.1 103 Early Hints\r\n"
  20197. "Link: </style.css>; rel=preload\r\n"
  20198. "\r\n"
  20199. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20200. "HTTP/1.1 100 Continue\r\n"
  20201. "X-Note: interim\r\n"
  20202. "\r\n"
  20203. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20204. };
  20205. for (auto response : responses) {
  20206. with_single_response(response, [](Client &cli) {
  20207. auto res = cli.Get("/");
  20208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20209. EXPECT_EQ(StatusCode::OK_200, res->status);
  20210. EXPECT_EQ("ok", res->body);
  20211. });
  20212. }
  20213. }
  20214. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20215. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20216. const std::string final_response =
  20217. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20218. std::string interims;
  20219. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20220. interims += interim;
  20221. }
  20222. with_single_response(interims + final_response, [](Client &cli) {
  20223. auto res = cli.Get("/");
  20224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20225. EXPECT_EQ("ok", res->body);
  20226. });
  20227. with_single_response(interims + interim + final_response, [](Client &cli) {
  20228. auto res = cli.Get("/");
  20229. ASSERT_FALSE(res);
  20230. EXPECT_EQ(Error::Read, res.error());
  20231. });
  20232. }
  20233. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20234. #ifndef _WIN32
  20235. signal(SIGPIPE, SIG_IGN);
  20236. #endif
  20237. // The server answers the head without asking for the body. Bytes it then
  20238. // reads on the connection would be taken for the body the request declared.
  20239. auto closed_by_client = false;
  20240. std::promise<int> port_promise;
  20241. auto server_thread = serve_single_response(
  20242. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20243. [&](socket_t sock) {
  20244. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20245. char buf[256];
  20246. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20247. });
  20248. Client cli("127.0.0.1", port_promise.get_future().get());
  20249. cli.set_keep_alive(true);
  20250. cli.set_read_timeout(1, 0);
  20251. // Long enough for the client to send Expect: 100-continue.
  20252. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20254. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20255. cli.Get("/second");
  20256. server_thread.join();
  20257. EXPECT_TRUE(closed_by_client);
  20258. }
  20259. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20260. // Long enough for the client to send Expect: 100-continue
  20261. with_single_response(
  20262. "HTTP/1.1 103 Early Hints\r\n"
  20263. "Link: </style.css>; rel=preload\r\n"
  20264. "\r\n"
  20265. "HTTP/1.1 401 Unauthorized\r\n"
  20266. "Content-Length: 0\r\n\r\n",
  20267. [](Client &cli) {
  20268. cli.set_read_timeout(2, 0);
  20269. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20271. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20272. });
  20273. }
  20274. #ifdef CPPHTTPLIB_SSL_ENABLED
  20275. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20276. #ifndef _WIN32
  20277. signal(SIGPIPE, SIG_IGN);
  20278. #endif
  20279. auto reused = false;
  20280. std::promise<int> port_promise;
  20281. auto server_thread = serve_single_response(
  20282. port_promise,
  20283. "HTTP/1.1 401 Unauthorized\r\n"
  20284. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20285. "Content-Length: 0\r\n\r\n",
  20286. [&](socket_t sock) {
  20287. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20288. char buf[256];
  20289. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20290. });
  20291. Client cli("127.0.0.1", port_promise.get_future().get());
  20292. cli.set_keep_alive(true);
  20293. cli.set_digest_auth("user", "pass");
  20294. cli.set_read_timeout(1, 0);
  20295. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20296. server_thread.join();
  20297. EXPECT_FALSE(reused);
  20298. }
  20299. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20300. // Any other answer to CONNECT would read as the origin's response.
  20301. struct {
  20302. const char *response;
  20303. bool passed_on;
  20304. } cases[] = {
  20305. {"HTTP/1.1 201 Created\r\n"
  20306. "Set-Cookie: session=from-proxy\r\n"
  20307. "Content-Length: 0\r\n\r\n",
  20308. false},
  20309. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20310. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20311. "Content-Length: 0\r\n\r\n",
  20312. true},
  20313. };
  20314. for (const auto &c : cases) {
  20315. std::promise<int> port_promise;
  20316. auto server_thread = serve_single_response(port_promise, c.response);
  20317. SSLClient cli("example.com", 443);
  20318. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20319. auto res = cli.Get("/");
  20320. server_thread.join();
  20321. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20322. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20323. if (res) {
  20324. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20325. }
  20326. }
  20327. }
  20328. #endif
  20329. // Records the client's error logger calls as "error METHOD path", or
  20330. // "error null" for a call without a request
  20331. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20332. return [&log](const Error &err, const Request *req) {
  20333. log.push_back(to_string(err) + " " +
  20334. (req ? req->method + " " + req->path : "null"));
  20335. };
  20336. }
  20337. // A failed request is reported once, with the request the caller made
  20338. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20339. Server svr;
  20340. svr.Get("/big", [](const Request &, Response &res) {
  20341. res.set_content(std::string(100000, 'b'), "text/plain");
  20342. });
  20343. auto port = svr.bind_to_any_port(HOST);
  20344. std::thread t([&]() { svr.listen_after_bind(); });
  20345. auto se = detail::scope_exit([&] {
  20346. svr.stop();
  20347. t.join();
  20348. });
  20349. svr.wait_until_ready();
  20350. Client cli(HOST, port);
  20351. std::vector<std::string> log;
  20352. cli.set_error_logger(record_errors(log));
  20353. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20354. cli.Get("/big", [](const char *, size_t) { return false; });
  20355. EXPECT_EQ(expected, log);
  20356. log.clear();
  20357. cli.Get("/big", [](size_t, size_t) { return false; });
  20358. EXPECT_EQ(expected, log);
  20359. }
  20360. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20361. // Fails while the body is read
  20362. auto broken = [](const Request &, Response &res) {
  20363. res.set_content_provider(10, "text/plain",
  20364. [](size_t, size_t, DataSink &) { return false; });
  20365. };
  20366. Server other;
  20367. other.Get("/broken", broken);
  20368. auto other_port = other.bind_to_any_port(HOST);
  20369. std::thread other_t([&]() { other.listen_after_bind(); });
  20370. auto other_se = detail::scope_exit([&] {
  20371. other.stop();
  20372. other_t.join();
  20373. });
  20374. other.wait_until_ready();
  20375. Server svr;
  20376. svr.Get("/broken", broken);
  20377. svr.Get("/same-origin",
  20378. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20379. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20380. res.set_redirect("http://" + std::string(HOST) + ":" +
  20381. std::to_string(other_port) + "/broken");
  20382. });
  20383. auto port = svr.bind_to_any_port(HOST);
  20384. std::thread t([&]() { svr.listen_after_bind(); });
  20385. auto se = detail::scope_exit([&] {
  20386. svr.stop();
  20387. t.join();
  20388. });
  20389. svr.wait_until_ready();
  20390. Client cli(HOST, port);
  20391. cli.set_follow_location(true);
  20392. std::vector<std::string> log;
  20393. cli.set_error_logger(record_errors(log));
  20394. for (auto path : {"/same-origin", "/cross-origin"}) {
  20395. log.clear();
  20396. auto res = cli.Get(path);
  20397. ASSERT_FALSE(res);
  20398. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20399. log);
  20400. }
  20401. }
  20402. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20403. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20404. std::vector<std::string> log;
  20405. cli.set_error_logger(record_errors(log));
  20406. auto handle = cli.open_stream("GET", "/x");
  20407. EXPECT_FALSE(handle.is_valid());
  20408. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20409. log);
  20410. });
  20411. }
  20412. #ifdef CPPHTTPLIB_SSL_ENABLED
  20413. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20414. // Not a TLS server, so the handshake fails. It waits for a request line in
  20415. // the handshake bytes, so a short read timeout lets it close quickly.
  20416. Server svr;
  20417. svr.set_read_timeout(0, 100000);
  20418. svr.Get("/x", [](const Request &, Response &res) {
  20419. res.set_content("x", "text/plain");
  20420. });
  20421. auto port = svr.bind_to_any_port(HOST);
  20422. std::thread t([&]() { svr.listen_after_bind(); });
  20423. auto se = detail::scope_exit([&] {
  20424. svr.stop();
  20425. t.join();
  20426. });
  20427. svr.wait_until_ready();
  20428. std::vector<std::string> log;
  20429. SSLClient cli(HOST, port);
  20430. cli.enable_server_certificate_verification(false);
  20431. cli.set_error_logger(record_errors(log));
  20432. auto res = cli.Get("/x");
  20433. ASSERT_FALSE(res);
  20434. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20435. log.clear();
  20436. auto handle = cli.open_stream("GET", "/x");
  20437. EXPECT_FALSE(handle.is_valid());
  20438. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20439. log.clear();
  20440. SSLClient no_ca(HOST, port);
  20441. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20442. no_ca.set_error_logger(record_errors(log));
  20443. res = no_ca.Get("/x");
  20444. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20445. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20446. }
  20447. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20448. #ifndef _WIN32
  20449. signal(SIGPIPE, SIG_IGN);
  20450. #endif
  20451. // Refused, answered with a challenge, or closed without an answer
  20452. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20453. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20454. "Content-Length: 0\r\n\r\n",
  20455. ""}) {
  20456. std::promise<int> port_promise;
  20457. auto server_thread = serve_single_response(port_promise, response);
  20458. SSLClient cli("example.com", 443);
  20459. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20460. std::vector<std::string> log;
  20461. cli.set_error_logger(record_errors(log));
  20462. auto res = cli.Get("/");
  20463. server_thread.join();
  20464. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20465. << response;
  20466. }
  20467. }
  20468. #endif
  20469. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20470. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20471. // the chunked coding and drop Content-Length, so a front-end that trusts
  20472. // Content-Length would disagree about where the body ends (response
  20473. // smuggling). The client must reject such a response.
  20474. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20475. for (const char *te : {"chunked", "gzip, chunked"}) {
  20476. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20477. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20478. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20479. "5\r\nhello\r\n0\r\n\r\n";
  20480. with_single_response(response, [&](Client &cli) {
  20481. auto res = cli.Get("/");
  20482. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20483. EXPECT_EQ(Error::Read, res.error()) << te;
  20484. });
  20485. with_single_response(response, [&](Client &cli) {
  20486. auto handle = cli.open_stream("GET", "/");
  20487. EXPECT_FALSE(handle.is_valid()) << te;
  20488. EXPECT_EQ(Error::Read, handle.error) << te;
  20489. });
  20490. }
  20491. }
  20492. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20493. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20494. // closing the connection (unlike a request, which must be rejected).
  20495. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20496. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20497. "Transfer-Encoding: chunked\r\n"
  20498. "Connection: close\r\n"
  20499. "\r\n"
  20500. "5\r\nhello\r\n0\r\n\r\n",
  20501. "HTTP/1.1 200 OK\r\n"
  20502. "Transfer-Encoding: gzip\r\n"
  20503. "Connection: close\r\n"
  20504. "\r\n"
  20505. "hello"}) {
  20506. with_single_response(response, [&](Client &cli) {
  20507. auto res = cli.Get("/");
  20508. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20509. EXPECT_EQ("hello", res->body);
  20510. });
  20511. with_single_response(response, [&](Client &cli) {
  20512. auto handle = cli.open_stream("GET", "/");
  20513. ASSERT_TRUE(handle.is_valid()) << response;
  20514. EXPECT_EQ("hello", read_all(handle));
  20515. });
  20516. }
  20517. }
  20518. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20519. // framing headers describe nothing to read and must not be rejected.
  20520. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20521. const std::string framing = "Content-Length: 5\r\n"
  20522. "Transfer-Encoding: chunked\r\n"
  20523. "Connection: close\r\n"
  20524. "\r\n";
  20525. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20526. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20527. });
  20528. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20529. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20530. });
  20531. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20532. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20533. with_single_response(response, [&](Client &cli) {
  20534. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20535. });
  20536. with_single_response(response, [&](Client &cli) {
  20537. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20538. });
  20539. }
  20540. }
  20541. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20542. // header section, so a stream opened on one has nothing to read, whatever
  20543. // framing or coding headers it carries.
  20544. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20545. struct Case {
  20546. const char *method;
  20547. const char *status;
  20548. };
  20549. // A reader of the declared body reports an early close when nothing
  20550. // follows, and hands back what does.
  20551. struct Framing {
  20552. const char *headers;
  20553. const char *after;
  20554. };
  20555. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20556. Case{"GET", "304 Not Modified"}}) {
  20557. for (const auto &f :
  20558. {Framing{"Content-Length: 5\r\n", ""},
  20559. Framing{"Content-Length: 5\r\n", "hello"},
  20560. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20561. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20562. // Not decoded, so a build without Brotli opens it too
  20563. Framing{"Content-Encoding: br\r\n", ""}}) {
  20564. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20565. "Connection: close\r\n"
  20566. "\r\n" +
  20567. f.after;
  20568. with_single_response(response, [&](Client &cli) {
  20569. auto handle = cli.open_stream(c.method, "/");
  20570. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20571. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20572. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20573. });
  20574. }
  20575. }
  20576. }
  20577. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20578. // response, is faulty framing, so the connection is not reused after it.
  20579. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20580. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20581. "Content-Length: 0\r\n"
  20582. "Transfer-Encoding: chunked\r\n"
  20583. "\r\n"
  20584. "5\r\nhello\r\n0\r\n\r\n",
  20585. "HTTP/1.0 200 Connection established\r\n"
  20586. "Connection: keep-alive\r\n"
  20587. "Transfer-Encoding: chunked\r\n"
  20588. "\r\n"
  20589. "5\r\nhello\r\n0\r\n\r\n"}) {
  20590. with_single_response(response, [&](Client &cli) {
  20591. cli.set_keep_alive(true);
  20592. auto res = cli.Get("/");
  20593. ASSERT_TRUE(res) << response;
  20594. EXPECT_EQ("hello", res->body);
  20595. EXPECT_FALSE(cli.is_socket_open()) << response;
  20596. });
  20597. }
  20598. }
  20599. // A payload max length of 0 means no limit, however the body is framed.
  20600. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20601. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20602. "Transfer-Encoding: chunked\r\n"
  20603. "\r\n"
  20604. "5\r\nhello\r\n0\r\n\r\n",
  20605. "HTTP/1.1 200 OK\r\n"
  20606. "Connection: close\r\n"
  20607. "\r\n"
  20608. "hello"}) {
  20609. with_single_response(response, [&](Client &cli) {
  20610. cli.set_payload_max_length(0);
  20611. auto res = cli.Get("/");
  20612. ASSERT_TRUE(res) << response;
  20613. EXPECT_EQ("hello", res->body) << response;
  20614. });
  20615. }
  20616. }
  20617. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20618. Server svr;
  20619. svr.set_payload_max_length(0);
  20620. svr.Post("/echo", [](const Request &req, Response &res) {
  20621. res.set_content(req.body, "text/plain");
  20622. });
  20623. auto port = svr.bind_to_any_port(HOST);
  20624. thread t = thread([&] { svr.listen_after_bind(); });
  20625. auto se = detail::scope_exit([&] {
  20626. svr.stop();
  20627. t.join();
  20628. ASSERT_FALSE(svr.is_running());
  20629. });
  20630. svr.wait_until_ready();
  20631. Client cli(HOST, port);
  20632. auto res = cli.Post(
  20633. "/echo",
  20634. [](size_t /*offset*/, DataSink &sink) {
  20635. sink.write("hello", 5);
  20636. sink.done();
  20637. return true;
  20638. },
  20639. "text/plain");
  20640. ASSERT_TRUE(res);
  20641. EXPECT_EQ(StatusCode::OK_200, res->status);
  20642. EXPECT_EQ("hello", res->body);
  20643. }
  20644. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20645. TEST_F(OpenStreamTest, Gzip) {
  20646. Client cli("127.0.0.1", port_);
  20647. auto handle = cli.open_stream("GET", "/compressible", {},
  20648. {{"Accept-Encoding", "gzip"}});
  20649. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20650. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20651. }
  20652. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20653. Client cli("127.0.0.1", port_);
  20654. auto handle =
  20655. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20656. {{"Accept-Encoding", "gzip"}});
  20657. ASSERT_TRUE(handle.is_valid());
  20658. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20659. EXPECT_EQ("123456789", read_all(handle));
  20660. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20661. }
  20662. #endif
  20663. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20664. TEST_F(OpenStreamTest, Brotli) {
  20665. Client cli("127.0.0.1", port_);
  20666. auto handle =
  20667. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20668. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20669. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20670. }
  20671. #endif
  20672. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20673. TEST_F(OpenStreamTest, Zstd) {
  20674. Client cli("127.0.0.1", port_);
  20675. auto handle = cli.open_stream("GET", "/compressible", {},
  20676. {{"Accept-Encoding", "zstd"}});
  20677. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20678. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20679. }
  20680. #endif
  20681. #ifdef CPPHTTPLIB_SSL_ENABLED
  20682. class SSLOpenStreamTest : public ::testing::Test {
  20683. protected:
  20684. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20685. void SetUp() override {
  20686. svr_.Get("/hello", [](const Request &, Response &res) {
  20687. res.set_content("Hello SSL World!", "text/plain");
  20688. });
  20689. svr_.Get("/chunked", [](const Request &, Response &res) {
  20690. res.set_chunked_content_provider("text/plain",
  20691. [](size_t offset, DataSink &sink) {
  20692. if (offset < 15) {
  20693. sink.write("chunk", 5);
  20694. return true;
  20695. }
  20696. sink.done();
  20697. return true;
  20698. });
  20699. });
  20700. svr_.Post("/echo", [](const Request &req, Response &res) {
  20701. res.set_content(req.body, req.get_header_value("Content-Type"));
  20702. });
  20703. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20704. std::string body = req.body;
  20705. res.set_chunked_content_provider(
  20706. "text/plain", [body](size_t offset, DataSink &sink) {
  20707. if (offset < body.size()) {
  20708. sink.write(body.data() + offset, body.size() - offset);
  20709. }
  20710. sink.done();
  20711. return true;
  20712. });
  20713. });
  20714. port_ = svr_.bind_to_any_port("127.0.0.1");
  20715. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20716. svr_.wait_until_ready();
  20717. }
  20718. void TearDown() override {
  20719. svr_.stop();
  20720. if (thread_.joinable()) thread_.join();
  20721. }
  20722. SSLServer svr_;
  20723. std::thread thread_;
  20724. int port_ = 0;
  20725. };
  20726. TEST_F(SSLOpenStreamTest, Basic) {
  20727. SSLClient cli("127.0.0.1", port_);
  20728. cli.enable_server_certificate_verification(false);
  20729. auto handle = cli.open_stream("GET", "/hello");
  20730. ASSERT_TRUE(handle.is_valid());
  20731. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20732. }
  20733. TEST_F(SSLOpenStreamTest, Chunked) {
  20734. SSLClient cli("127.0.0.1", port_);
  20735. cli.enable_server_certificate_verification(false);
  20736. auto handle = cli.open_stream("GET", "/chunked");
  20737. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20738. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20739. "Transfer-Encoding") == "chunked");
  20740. auto body = read_all(handle);
  20741. EXPECT_EQ("chunkchunkchunk", body);
  20742. }
  20743. TEST_F(SSLOpenStreamTest, Post) {
  20744. SSLClient cli("127.0.0.1", port_);
  20745. cli.enable_server_certificate_verification(false);
  20746. auto handle =
  20747. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20748. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20749. EXPECT_EQ(200, handle.response->status);
  20750. auto body = read_all(handle);
  20751. EXPECT_EQ("Hello SSL POST", body);
  20752. }
  20753. TEST_F(SSLOpenStreamTest, PostChunked) {
  20754. SSLClient cli("127.0.0.1", port_);
  20755. cli.enable_server_certificate_verification(false);
  20756. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20757. "Chunked SSL Data", "text/plain");
  20758. ASSERT_TRUE(handle.is_valid());
  20759. EXPECT_EQ(200, handle.response->status);
  20760. auto body = read_all(handle);
  20761. EXPECT_EQ("Chunked SSL Data", body);
  20762. }
  20763. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20764. // Content-Length is terminated by the server closing the connection. When the
  20765. // SSL peer sends a close_notify after the body, the client must treat it as a
  20766. // clean EOF and return a successful response rather than an error.
  20767. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20769. ASSERT_TRUE(svr.is_valid());
  20770. svr.set_keep_alive_max_count(1);
  20771. const std::string expected_body = "Hello from connection-close response!";
  20772. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20773. res.set_content_provider("text/plain",
  20774. [&](size_t offset, DataSink &sink) -> bool {
  20775. if (offset < expected_body.size()) {
  20776. sink.write(expected_body.data() + offset,
  20777. expected_body.size() - offset);
  20778. }
  20779. sink.done();
  20780. return true;
  20781. });
  20782. });
  20783. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20784. auto se = detail::scope_exit([&] {
  20785. svr.stop();
  20786. listen_thread.join();
  20787. ASSERT_FALSE(svr.is_running());
  20788. });
  20789. svr.wait_until_ready();
  20790. SSLClient cli(HOST, PORT);
  20791. cli.enable_server_certificate_verification(false);
  20792. auto res = cli.Get("/no-content-length");
  20793. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20794. EXPECT_EQ(StatusCode::OK_200, res->status);
  20795. EXPECT_EQ(expected_body, res->body);
  20796. }
  20797. #endif // CPPHTTPLIB_SSL_ENABLED
  20798. //==============================================================================
  20799. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20800. // results for various scenarios.
  20801. //==============================================================================
  20802. TEST(ParityTest, GetVsOpenStream) {
  20803. Server svr;
  20804. const std::string path = "/parity";
  20805. const std::string content = "Parity test content: hello world";
  20806. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20807. res.set_content(content, "text/plain");
  20808. });
  20809. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20810. auto se = detail::scope_exit([&] {
  20811. svr.stop();
  20812. t.join();
  20813. ASSERT_FALSE(svr.is_running());
  20814. });
  20815. svr.wait_until_ready();
  20816. Client cli(HOST, PORT);
  20817. // Non-stream path
  20818. auto r1 = cli.Get(path);
  20819. ASSERT_TRUE(r1);
  20820. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20821. // Stream path
  20822. auto h = cli.open_stream("GET", path);
  20823. ASSERT_TRUE(h.is_valid());
  20824. EXPECT_EQ(r1->body, read_all(h));
  20825. }
  20826. // Helper to compress data with provided compressor type T
  20827. template <typename Compressor>
  20828. static std::string compress_payload_for_parity(const std::string &in) {
  20829. std::string out;
  20830. Compressor compressor;
  20831. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20832. [&](const char *data, size_t n) {
  20833. out.append(data, n);
  20834. return true;
  20835. });
  20836. EXPECT_TRUE(ok);
  20837. return out;
  20838. }
  20839. // Helper function for compression parity tests
  20840. template <typename Compressor>
  20841. static void test_compression_parity(const std::string &original,
  20842. const std::string &path,
  20843. const std::string &encoding) {
  20844. const std::string compressed =
  20845. compress_payload_for_parity<Compressor>(original);
  20846. Server svr;
  20847. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20848. res.set_content(compressed, "application/octet-stream");
  20849. res.set_header("Content-Encoding", encoding);
  20850. });
  20851. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20852. auto se = detail::scope_exit([&] {
  20853. svr.stop();
  20854. t.join();
  20855. ASSERT_FALSE(svr.is_running());
  20856. });
  20857. svr.wait_until_ready();
  20858. Client cli(HOST, PORT);
  20859. // Non-streaming
  20860. {
  20861. auto res = cli.Get(path);
  20862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20863. EXPECT_EQ(StatusCode::OK_200, res->status);
  20864. EXPECT_EQ(original, res->body);
  20865. }
  20866. // Streaming
  20867. {
  20868. auto h = cli.open_stream("GET", path);
  20869. ASSERT_TRUE(h.is_valid());
  20870. EXPECT_EQ(original, read_all(h));
  20871. }
  20872. }
  20873. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20874. TEST(ParityTest, Gzip) {
  20875. test_compression_parity<detail::gzip_compressor>(
  20876. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20877. }
  20878. #endif
  20879. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20880. TEST(ParityTest, Brotli) {
  20881. test_compression_parity<detail::brotli_compressor>(
  20882. "Hello, brotli parity test payload", "/parity-br", "br");
  20883. }
  20884. #endif
  20885. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20886. TEST(ParityTest, Zstd) {
  20887. test_compression_parity<detail::zstd_compressor>(
  20888. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20889. }
  20890. #endif
  20891. //==============================================================================
  20892. // New Stream API Tests
  20893. //==============================================================================
  20894. inline std::string read_body(httplib::stream::Result &result) {
  20895. std::string body;
  20896. while (result.next()) {
  20897. body.append(result.data(), result.size());
  20898. }
  20899. return body;
  20900. }
  20901. TEST(ClientConnectionTest, Basic) {
  20902. httplib::ClientConnection conn;
  20903. EXPECT_FALSE(conn.is_open());
  20904. conn.sock = 1;
  20905. EXPECT_TRUE(conn.is_open());
  20906. httplib::ClientConnection conn2(std::move(conn));
  20907. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20908. conn2.sock = INVALID_SOCKET;
  20909. }
  20910. // Unified test server for all stream::* tests
  20911. class StreamApiTest : public ::testing::Test {
  20912. protected:
  20913. void SetUp() override {
  20914. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20915. res.set_content("Hello World!", "text/plain");
  20916. });
  20917. svr_.Get("/echo-params",
  20918. [](const httplib::Request &req, httplib::Response &res) {
  20919. std::string r;
  20920. for (const auto &p : req.params) {
  20921. if (!r.empty()) r += "&";
  20922. r += p.first + "=" + p.second;
  20923. }
  20924. res.set_content(r, "text/plain");
  20925. });
  20926. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20927. res.set_content(req.body, req.get_header_value("Content-Type"));
  20928. });
  20929. svr_.Post("/echo-headers",
  20930. [](const httplib::Request &req, httplib::Response &res) {
  20931. std::string r;
  20932. for (const auto &h : req.headers)
  20933. r += h.first + ": " + h.second + "\n";
  20934. res.set_content(r, "text/plain");
  20935. });
  20936. svr_.Post("/echo-params",
  20937. [](const httplib::Request &req, httplib::Response &res) {
  20938. std::string r = "params:";
  20939. for (const auto &p : req.params)
  20940. r += p.first + "=" + p.second + ";";
  20941. res.set_content(r + " body:" + req.body, "text/plain");
  20942. });
  20943. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20944. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20945. });
  20946. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20947. res.set_content("PUT:" + req.body, "text/plain");
  20948. });
  20949. svr_.Patch("/echo",
  20950. [](const httplib::Request &req, httplib::Response &res) {
  20951. res.set_content("PATCH:" + req.body, "text/plain");
  20952. });
  20953. svr_.Delete(
  20954. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20955. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20956. "text/plain");
  20957. });
  20958. svr_.Get("/head-test",
  20959. [](const httplib::Request &, httplib::Response &res) {
  20960. res.set_content("body for HEAD", "text/plain");
  20961. });
  20962. svr_.Options("/options",
  20963. [](const httplib::Request &, httplib::Response &res) {
  20964. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20965. });
  20966. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20967. svr_.wait_until_ready();
  20968. }
  20969. void TearDown() override {
  20970. svr_.stop();
  20971. if (thread_.joinable()) thread_.join();
  20972. }
  20973. httplib::Server svr_;
  20974. std::thread thread_;
  20975. };
  20976. // stream::Get tests
  20977. TEST_F(StreamApiTest, GetBasic) {
  20978. httplib::Client cli(HOST, PORT);
  20979. auto result = httplib::stream::Get(cli, "/hello");
  20980. ASSERT_TRUE(result.is_valid());
  20981. EXPECT_EQ(200, result.status());
  20982. EXPECT_EQ("Hello World!", read_body(result));
  20983. }
  20984. TEST_F(StreamApiTest, GetWithParams) {
  20985. httplib::Client cli(HOST, PORT);
  20986. httplib::Params params{{"foo", "bar"}};
  20987. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20988. ASSERT_TRUE(result.is_valid());
  20989. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20990. }
  20991. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20992. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20993. httplib::Client cli(HOST, PORT);
  20994. cli.set_payload_max_length(0);
  20995. auto result = httplib::stream::Get(cli, "/hello");
  20996. ASSERT_TRUE(result.is_valid());
  20997. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20998. EXPECT_EQ("Hello World!", read_body(result));
  20999. }
  21000. #endif
  21001. TEST_F(StreamApiTest, GetConnectionError) {
  21002. httplib::Client cli(HOST, 9999);
  21003. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21004. }
  21005. TEST_F(StreamApiTest, Get404) {
  21006. httplib::Client cli(HOST, PORT);
  21007. auto result = httplib::stream::Get(cli, "/nonexistent");
  21008. EXPECT_TRUE(result.is_valid());
  21009. EXPECT_EQ(404, result.status());
  21010. }
  21011. // stream::Post tests
  21012. TEST_F(StreamApiTest, PostBasic) {
  21013. httplib::Client cli(HOST, PORT);
  21014. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21015. "application/json");
  21016. ASSERT_TRUE(result.is_valid());
  21017. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21018. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21019. }
  21020. TEST_F(StreamApiTest, PostWithHeaders) {
  21021. httplib::Client cli(HOST, PORT);
  21022. httplib::Headers headers{{"X-Custom", "value"}};
  21023. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21024. "text/plain");
  21025. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21026. }
  21027. TEST_F(StreamApiTest, PostWithParams) {
  21028. httplib::Client cli(HOST, PORT);
  21029. httplib::Params params{{"k", "v"}};
  21030. auto result =
  21031. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21032. auto body = read_body(result);
  21033. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21034. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21035. }
  21036. TEST_F(StreamApiTest, PostLarge) {
  21037. httplib::Client cli(HOST, PORT);
  21038. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21039. size_t total = 0;
  21040. while (result.next()) {
  21041. total += result.size();
  21042. }
  21043. EXPECT_EQ(100u * 1024u, total);
  21044. }
  21045. // stream::Put/Patch tests
  21046. TEST_F(StreamApiTest, PutAndPatch) {
  21047. httplib::Client cli(HOST, PORT);
  21048. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21049. EXPECT_EQ("PUT:test", read_body(put));
  21050. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21051. EXPECT_EQ("PATCH:test", read_body(patch));
  21052. }
  21053. // stream::Delete tests
  21054. TEST_F(StreamApiTest, Delete) {
  21055. httplib::Client cli(HOST, PORT);
  21056. auto del1 = httplib::stream::Delete(cli, "/resource");
  21057. EXPECT_EQ("Deleted", read_body(del1));
  21058. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21059. EXPECT_EQ("Deleted:data", read_body(del2));
  21060. }
  21061. // stream::Head/Options tests
  21062. TEST_F(StreamApiTest, HeadAndOptions) {
  21063. httplib::Client cli(HOST, PORT);
  21064. auto head = httplib::stream::Head(cli, "/head-test");
  21065. EXPECT_TRUE(head.is_valid());
  21066. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21067. auto opts = httplib::stream::Options(cli, "/options");
  21068. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21069. }
  21070. // SSL stream::* tests
  21071. #ifdef CPPHTTPLIB_SSL_ENABLED
  21072. class SSLStreamApiTest : public ::testing::Test {
  21073. protected:
  21074. void SetUp() override {
  21075. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21076. res.set_content("Hello SSL!", "text/plain");
  21077. });
  21078. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21079. res.set_content(req.body, "text/plain");
  21080. });
  21081. port_ = svr_.bind_to_any_port("127.0.0.1");
  21082. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21083. svr_.wait_until_ready();
  21084. }
  21085. void TearDown() override {
  21086. svr_.stop();
  21087. if (thread_.joinable()) thread_.join();
  21088. }
  21089. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21090. std::thread thread_;
  21091. int port_ = 0;
  21092. };
  21093. TEST_F(SSLStreamApiTest, GetAndPost) {
  21094. httplib::SSLClient cli("127.0.0.1", port_);
  21095. cli.enable_server_certificate_verification(false);
  21096. auto get = httplib::stream::Get(cli, "/hello");
  21097. EXPECT_EQ("Hello SSL!", read_body(get));
  21098. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21099. EXPECT_EQ("test", read_body(post));
  21100. }
  21101. #endif
  21102. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21103. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21104. // BodyReader
  21105. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21106. // Test that read timeout during streaming is detected
  21107. // Use a large content-length response where server delays mid-stream
  21108. Server svr;
  21109. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21110. // Send a large response with delay in the middle
  21111. res.set_content_provider(
  21112. 1000, // content_length
  21113. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21114. if (offset < 100) {
  21115. // Send first 100 bytes immediately
  21116. std::string data(100, 'A');
  21117. sink.write(data.c_str(), data.size());
  21118. return true;
  21119. }
  21120. // Then delay longer than client timeout
  21121. std::this_thread::sleep_for(std::chrono::seconds(3));
  21122. std::string data(900, 'B');
  21123. sink.write(data.c_str(), data.size());
  21124. return true;
  21125. });
  21126. });
  21127. auto port = 8091;
  21128. std::thread t([&]() { svr.listen("localhost", port); });
  21129. svr.wait_until_ready();
  21130. Client cli("localhost", port);
  21131. cli.set_read_timeout(1, 0); // 1 second timeout
  21132. auto handle = cli.open_stream("GET", "/slow-stream");
  21133. ASSERT_TRUE(handle.is_valid());
  21134. char buf[256];
  21135. ssize_t total = 0;
  21136. ssize_t n;
  21137. bool got_error = false;
  21138. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21139. total += n;
  21140. }
  21141. if (n < 0) {
  21142. got_error = true;
  21143. // Should be timeout or read error
  21144. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21145. handle.get_read_error() == Error::Read)
  21146. << "Actual error: " << to_string(handle.get_read_error());
  21147. }
  21148. // Either we got an error, or we got less data than expected
  21149. EXPECT_TRUE(got_error || total < 1000)
  21150. << "Expected timeout but got all " << total << " bytes";
  21151. svr.stop();
  21152. t.join();
  21153. }
  21154. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21155. // Test connection closed detection via BodyReader
  21156. Server svr;
  21157. std::atomic<bool> close_now{false};
  21158. svr.Get("/will-close", [&](const Request &, Response &res) {
  21159. res.set_content_provider(
  21160. 10000, // Large content_length that we won't fully send
  21161. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21162. if (offset < 100) {
  21163. std::string data(100, 'X');
  21164. sink.write(data.c_str(), data.size());
  21165. return true;
  21166. }
  21167. // Wait for signal then abort
  21168. while (!close_now) {
  21169. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21170. }
  21171. return false; // Abort - server will close connection
  21172. });
  21173. });
  21174. auto port = 8092;
  21175. std::thread t([&]() { svr.listen("localhost", port); });
  21176. svr.wait_until_ready();
  21177. Client cli("localhost", port);
  21178. auto handle = cli.open_stream("GET", "/will-close");
  21179. ASSERT_TRUE(handle.is_valid());
  21180. char buf[256];
  21181. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21182. EXPECT_GT(n, 0) << "First read should succeed";
  21183. // Signal server to close
  21184. close_now = true;
  21185. // Keep reading until error or EOF
  21186. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21187. // Keep reading
  21188. }
  21189. // Should get an error since content_length wasn't satisfied
  21190. if (n < 0) {
  21191. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21192. handle.get_read_error() == Error::Read)
  21193. << "Actual error: " << to_string(handle.get_read_error());
  21194. }
  21195. svr.stop();
  21196. t.join();
  21197. }
  21198. #ifdef CPPHTTPLIB_SSL_ENABLED
  21199. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21200. // Test that read timeout during SSL streaming is detected
  21201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21202. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21203. res.set_content_provider(
  21204. 1000, "text/plain",
  21205. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21206. if (offset < 100) {
  21207. std::string data(100, 'A');
  21208. sink.write(data.c_str(), data.size());
  21209. return true;
  21210. }
  21211. std::this_thread::sleep_for(std::chrono::seconds(3));
  21212. std::string data(900, 'B');
  21213. sink.write(data.c_str(), data.size());
  21214. return true;
  21215. });
  21216. });
  21217. auto port = 8093;
  21218. std::thread t([&]() { svr.listen("localhost", port); });
  21219. svr.wait_until_ready();
  21220. SSLClient cli("localhost", port);
  21221. cli.enable_server_certificate_verification(false);
  21222. cli.set_read_timeout(1, 0); // 1 second timeout
  21223. auto handle = cli.open_stream("GET", "/slow-stream");
  21224. ASSERT_TRUE(handle.is_valid());
  21225. char buf[256];
  21226. ssize_t total = 0;
  21227. ssize_t n;
  21228. bool got_error = false;
  21229. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21230. total += n;
  21231. }
  21232. if (n < 0) {
  21233. got_error = true;
  21234. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21235. handle.get_read_error() == Error::Read)
  21236. << "Actual error: " << to_string(handle.get_read_error());
  21237. }
  21238. EXPECT_TRUE(got_error || total < 1000)
  21239. << "Expected timeout but got all " << total << " bytes";
  21240. svr.stop();
  21241. t.join();
  21242. }
  21243. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21244. // Test SSL connection closed detection
  21245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21246. std::atomic<bool> close_now{false};
  21247. svr.Get("/will-close", [&](const Request &, Response &res) {
  21248. res.set_content_provider(
  21249. 10000, "text/plain",
  21250. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21251. if (offset < 100) {
  21252. std::string data(100, 'X');
  21253. sink.write(data.c_str(), data.size());
  21254. return true;
  21255. }
  21256. while (!close_now) {
  21257. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21258. }
  21259. return false;
  21260. });
  21261. });
  21262. auto port = 8094;
  21263. std::thread t([&]() { svr.listen("localhost", port); });
  21264. svr.wait_until_ready();
  21265. SSLClient cli("localhost", port);
  21266. cli.enable_server_certificate_verification(false);
  21267. auto handle = cli.open_stream("GET", "/will-close");
  21268. ASSERT_TRUE(handle.is_valid());
  21269. char buf[256];
  21270. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21271. EXPECT_GT(n, 0);
  21272. // Signal server to close
  21273. close_now = true;
  21274. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21275. // Keep reading
  21276. }
  21277. if (n < 0) {
  21278. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21279. handle.get_read_error() == Error::Read)
  21280. << "Actual error: " << to_string(handle.get_read_error());
  21281. }
  21282. svr.stop();
  21283. t.join();
  21284. }
  21285. #endif
  21286. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21287. using namespace httplib;
  21288. // Create a test file
  21289. const char *fname = "etag_testfile.txt";
  21290. const char *content = "etag-content";
  21291. {
  21292. std::ofstream ofs(fname);
  21293. ofs << content;
  21294. ASSERT_TRUE(ofs.good());
  21295. }
  21296. Server svr;
  21297. svr.set_mount_point("/static", ".");
  21298. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21299. svr.wait_until_ready();
  21300. Client cli(HOST, PORT);
  21301. // First request: should get 200 with ETag header
  21302. auto res1 = cli.Get("/static/etag_testfile.txt");
  21303. ASSERT_TRUE(res1);
  21304. ASSERT_EQ(200, res1->status);
  21305. ASSERT_TRUE(res1->has_header("ETag"));
  21306. std::string etag = res1->get_header_value("ETag");
  21307. EXPECT_FALSE(etag.empty());
  21308. // Verify ETag format: W/"hex-hex"
  21309. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21310. EXPECT_EQ('W', etag[0]);
  21311. EXPECT_EQ('/', etag[1]);
  21312. EXPECT_EQ('"', etag[2]);
  21313. EXPECT_EQ('"', etag.back());
  21314. // Exact match: expect 304 Not Modified
  21315. Headers h2 = {{"If-None-Match", etag}};
  21316. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21317. ASSERT_TRUE(res2);
  21318. EXPECT_EQ(304, res2->status);
  21319. // Wildcard match: expect 304 Not Modified
  21320. Headers h3 = {{"If-None-Match", "*"}};
  21321. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21322. ASSERT_TRUE(res3);
  21323. EXPECT_EQ(304, res3->status);
  21324. // Non-matching ETag: expect 200
  21325. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21326. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21327. ASSERT_TRUE(res4);
  21328. EXPECT_EQ(200, res4->status);
  21329. // Multiple ETags with one matching: expect 304
  21330. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21331. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21332. ASSERT_TRUE(res5);
  21333. EXPECT_EQ(304, res5->status);
  21334. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21335. // that equivalent to the single comma-separated list above, so the match on
  21336. // the second line must still be found.
  21337. Headers h6;
  21338. h6.emplace("If-None-Match", "W/\"other\"");
  21339. h6.emplace("If-None-Match", etag);
  21340. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21341. ASSERT_TRUE(res6);
  21342. EXPECT_EQ(304, res6->status);
  21343. svr.stop();
  21344. t.join();
  21345. std::remove(fname);
  21346. }
  21347. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21348. using namespace httplib;
  21349. Server svr;
  21350. svr.set_mount_point("/static", ".");
  21351. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21352. svr.wait_until_ready();
  21353. Client cli(HOST, PORT);
  21354. // Send If-None-Match: * to a non-existent file
  21355. Headers h = {{"If-None-Match", "*"}};
  21356. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21358. EXPECT_EQ(404, res->status);
  21359. svr.stop();
  21360. t.join();
  21361. }
  21362. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21363. using namespace httplib;
  21364. // Create a test file
  21365. const char *fname = "etag_boundary_testfile.txt";
  21366. const char *content = "boundary-test";
  21367. {
  21368. std::ofstream ofs(fname);
  21369. ofs << content;
  21370. ASSERT_TRUE(ofs.good());
  21371. }
  21372. Server svr;
  21373. svr.set_mount_point("/static", ".");
  21374. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21375. svr.wait_until_ready();
  21376. Client cli(HOST, PORT);
  21377. // Get the actual ETag
  21378. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21379. ASSERT_TRUE(res1);
  21380. ASSERT_EQ(200, res1->status);
  21381. ASSERT_TRUE(res1->has_header("ETag"));
  21382. std::string etag = res1->get_header_value("ETag");
  21383. // Test 1: Very long ETag value (longer than actual ETag)
  21384. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21385. Headers h1 = {{"If-None-Match", "W/"
  21386. "\"very-long-etag-value-that-is-much-longer-"
  21387. "than-the-actual-etag-value\""}};
  21388. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21389. ASSERT_TRUE(res2);
  21390. EXPECT_EQ(200, res2->status); // Should not match
  21391. // Test 2: Long string followed by wildcard
  21392. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21393. // string)
  21394. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21395. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21396. ASSERT_TRUE(res3);
  21397. EXPECT_EQ(304, res3->status); // Should match on "*"
  21398. // Test 3: Wildcard followed by long string
  21399. // Should match on "*" immediately and return 304
  21400. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21401. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21402. ASSERT_TRUE(res4);
  21403. EXPECT_EQ(304, res4->status); // Should match on "*"
  21404. // Test 4: Multiple long non-matching values
  21405. // Should NOT match and return 200 (test that all comparisons are safe)
  21406. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21407. "W/\"second-long-non-matching-value\", "
  21408. "W/\"third-long-non-matching-value\""}};
  21409. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21410. ASSERT_TRUE(res5);
  21411. EXPECT_EQ(200, res5->status); // Should not match
  21412. // Test 5: Single character that is not "*" (edge case)
  21413. Headers h5 = {{"If-None-Match", "X"}};
  21414. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21415. ASSERT_TRUE(res6);
  21416. EXPECT_EQ(200, res6->status); // Should not match
  21417. svr.stop();
  21418. t.join();
  21419. std::remove(fname);
  21420. }
  21421. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21422. using namespace httplib;
  21423. // Create a test file
  21424. const char *fname = "ims_testfile.txt";
  21425. const char *content = "if-modified-since-test";
  21426. {
  21427. std::ofstream ofs(fname);
  21428. ofs << content;
  21429. ASSERT_TRUE(ofs.good());
  21430. }
  21431. Server svr;
  21432. svr.set_mount_point("/static", ".");
  21433. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21434. svr.wait_until_ready();
  21435. Client cli(HOST, PORT);
  21436. // First request: should get 200 with Last-Modified header
  21437. auto res1 = cli.Get("/static/ims_testfile.txt");
  21438. ASSERT_TRUE(res1);
  21439. ASSERT_EQ(200, res1->status);
  21440. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21441. std::string last_modified = res1->get_header_value("Last-Modified");
  21442. EXPECT_FALSE(last_modified.empty());
  21443. // If-Modified-Since with same time: expect 304
  21444. Headers h2 = {{"If-Modified-Since", last_modified}};
  21445. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21446. ASSERT_TRUE(res2);
  21447. EXPECT_EQ(304, res2->status);
  21448. // If-Modified-Since with future time: expect 304
  21449. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21450. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21451. ASSERT_TRUE(res3);
  21452. EXPECT_EQ(304, res3->status);
  21453. // If-Modified-Since with past time: expect 200
  21454. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21455. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21456. ASSERT_TRUE(res4);
  21457. EXPECT_EQ(200, res4->status);
  21458. // If-None-Match takes precedence over If-Modified-Since
  21459. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21460. ASSERT_TRUE(res1->has_header("ETag"));
  21461. std::string etag = res1->get_header_value("ETag");
  21462. Headers h5 = {{"If-None-Match", etag},
  21463. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21464. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21465. ASSERT_TRUE(res5);
  21466. EXPECT_EQ(304, res5->status);
  21467. svr.stop();
  21468. t.join();
  21469. std::remove(fname);
  21470. }
  21471. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21472. using namespace httplib;
  21473. Server svr;
  21474. // Endpoint that returns compressible content
  21475. svr.Get("/compressible", [](const Request &, Response &res) {
  21476. // Return a large enough body to trigger compression
  21477. std::string body(1000, 'a');
  21478. res.set_content(body, "text/plain");
  21479. });
  21480. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21481. svr.wait_until_ready();
  21482. Client cli(HOST, PORT);
  21483. // Request with gzip support: should get Vary header when compressed
  21484. cli.set_compress(true);
  21485. auto res1 = cli.Get("/compressible");
  21486. ASSERT_TRUE(res1);
  21487. EXPECT_EQ(200, res1->status);
  21488. // If Content-Encoding is set, Vary should also be set
  21489. if (res1->has_header("Content-Encoding")) {
  21490. EXPECT_TRUE(res1->has_header("Vary"));
  21491. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21492. }
  21493. // Request without Accept-Encoding header: should not have compression
  21494. Headers h_no_compress;
  21495. auto res2 = cli.Get("/compressible", h_no_compress);
  21496. ASSERT_TRUE(res2);
  21497. EXPECT_EQ(200, res2->status);
  21498. // Verify Vary header is present when compression is applied
  21499. // (the exact behavior depends on server configuration)
  21500. svr.stop();
  21501. t.join();
  21502. }
  21503. TEST(ETagTest, IfRangeWithETag) {
  21504. using namespace httplib;
  21505. // Create a test file with known content
  21506. const char *fname = "if_range_testfile.txt";
  21507. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21508. {
  21509. std::ofstream ofs(fname);
  21510. ofs << content;
  21511. ASSERT_TRUE(ofs.good());
  21512. }
  21513. Server svr;
  21514. svr.set_mount_point("/static", ".");
  21515. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21516. svr.wait_until_ready();
  21517. Client cli(HOST, PORT);
  21518. // First request: get ETag
  21519. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21520. ASSERT_TRUE(res1);
  21521. ASSERT_EQ(200, res1->status);
  21522. ASSERT_TRUE(res1->has_header("ETag"));
  21523. std::string etag = res1->get_header_value("ETag");
  21524. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21525. // Since our server generates weak ETags (W/"..."), If-Range with our
  21526. // ETag should NOT result in partial content - it should return full content.
  21527. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21528. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21529. ASSERT_TRUE(res2);
  21530. // Weak ETag in If-Range -> full content (200), not partial (206)
  21531. EXPECT_EQ(200, res2->status);
  21532. EXPECT_EQ(content, res2->body);
  21533. EXPECT_FALSE(res2->has_header("Content-Range"));
  21534. // Range request with non-matching If-Range (ETag): should get 200 (full
  21535. // content)
  21536. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21537. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21538. ASSERT_TRUE(res3);
  21539. EXPECT_EQ(200, res3->status);
  21540. EXPECT_EQ(content, res3->body);
  21541. EXPECT_FALSE(res3->has_header("Content-Range"));
  21542. // Range request with strong ETag (hypothetical - our server doesn't generate
  21543. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21544. // should return full content)
  21545. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21546. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21547. ASSERT_TRUE(res4);
  21548. EXPECT_EQ(200, res4->status);
  21549. EXPECT_EQ(content, res4->body);
  21550. EXPECT_FALSE(res4->has_header("Content-Range"));
  21551. svr.stop();
  21552. t.join();
  21553. std::remove(fname);
  21554. }
  21555. TEST(ETagTest, IfRangeWithDate) {
  21556. using namespace httplib;
  21557. // Create a test file
  21558. const char *fname = "if_range_date_testfile.txt";
  21559. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21560. {
  21561. std::ofstream ofs(fname);
  21562. ofs << content;
  21563. ASSERT_TRUE(ofs.good());
  21564. }
  21565. Server svr;
  21566. svr.set_mount_point("/static", ".");
  21567. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21568. svr.wait_until_ready();
  21569. Client cli(HOST, PORT);
  21570. // First request: get Last-Modified
  21571. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21572. ASSERT_TRUE(res1);
  21573. ASSERT_EQ(200, res1->status);
  21574. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21575. std::string last_modified = res1->get_header_value("Last-Modified");
  21576. // Range request with matching If-Range (date): should get 206
  21577. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21578. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21579. ASSERT_TRUE(res2);
  21580. EXPECT_EQ(206, res2->status);
  21581. EXPECT_EQ("FGHIJ", res2->body);
  21582. // Range request with old If-Range date: should get 200 (full content)
  21583. Headers h3 = {{"Range", "bytes=5-9"},
  21584. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21585. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21586. ASSERT_TRUE(res3);
  21587. EXPECT_EQ(200, res3->status);
  21588. EXPECT_EQ(content, res3->body);
  21589. // Range request with future If-Range date: should get 206
  21590. Headers h4 = {{"Range", "bytes=0-4"},
  21591. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21592. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21593. ASSERT_TRUE(res4);
  21594. EXPECT_EQ(206, res4->status);
  21595. EXPECT_EQ("ABCDE", res4->body);
  21596. svr.stop();
  21597. t.join();
  21598. std::remove(fname);
  21599. }
  21600. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21601. using namespace httplib;
  21602. const char *fname = "etag_malformed.txt";
  21603. const char *content = "malformed-etag";
  21604. {
  21605. std::ofstream ofs(fname);
  21606. ofs << content;
  21607. ASSERT_TRUE(ofs.good());
  21608. }
  21609. Server svr;
  21610. svr.set_mount_point("/static", ".");
  21611. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21612. svr.wait_until_ready();
  21613. Client cli(HOST, PORT);
  21614. // baseline: should get 200 and an ETag
  21615. auto res1 = cli.Get("/static/etag_malformed.txt");
  21616. ASSERT_TRUE(res1);
  21617. ASSERT_EQ(200, res1->status);
  21618. ASSERT_TRUE(res1->has_header("ETag"));
  21619. // Malformed ETag value (missing quotes) should be treated as non-matching
  21620. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21621. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21622. ASSERT_TRUE(res_bad);
  21623. EXPECT_EQ(200, res_bad->status);
  21624. // Whitespace-only header value should be considered invalid / non-matching
  21625. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21626. "Host: localhost\r\n"
  21627. "If-None-Match: \r\n"
  21628. "Connection: close\r\n"
  21629. "\r\n";
  21630. std::string out;
  21631. ASSERT_TRUE(send_request(5, raw_req, &out));
  21632. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21633. svr.stop();
  21634. t.join();
  21635. std::remove(fname);
  21636. }
  21637. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21638. using namespace httplib;
  21639. const char *fname = "ims_invalid_format.txt";
  21640. const char *content = "ims-bad-format";
  21641. {
  21642. std::ofstream ofs(fname);
  21643. ofs << content;
  21644. ASSERT_TRUE(ofs.good());
  21645. }
  21646. Server svr;
  21647. svr.set_mount_point("/static", ".");
  21648. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21649. svr.wait_until_ready();
  21650. Client cli(HOST, PORT);
  21651. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21652. ASSERT_TRUE(res1);
  21653. ASSERT_EQ(200, res1->status);
  21654. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21655. // If-Modified-Since with invalid format should not result in 304
  21656. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21657. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21658. ASSERT_TRUE(res_bad);
  21659. EXPECT_EQ(200, res_bad->status);
  21660. // If-Range with invalid date format should be treated as mismatch -> full
  21661. // content (200)
  21662. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21663. {"If-Range", "invalid-date"}};
  21664. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21665. ASSERT_TRUE(res_ifrange);
  21666. EXPECT_EQ(200, res_ifrange->status);
  21667. svr.stop();
  21668. t.join();
  21669. std::remove(fname);
  21670. }
  21671. TEST(ETagTest, IfRangeWithMalformedETag) {
  21672. using namespace httplib;
  21673. const char *fname = "ifrange_malformed.txt";
  21674. const std::string content = "0123456789";
  21675. {
  21676. std::ofstream ofs(fname);
  21677. ofs << content;
  21678. ASSERT_TRUE(ofs.good());
  21679. }
  21680. Server svr;
  21681. svr.set_mount_point("/static", ".");
  21682. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21683. svr.wait_until_ready();
  21684. Client cli(HOST, PORT);
  21685. // First request: get ETag
  21686. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21687. ASSERT_TRUE(res1);
  21688. ASSERT_EQ(200, res1->status);
  21689. ASSERT_TRUE(res1->has_header("ETag"));
  21690. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21691. // full content (200)
  21692. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21693. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21694. ASSERT_TRUE(res2);
  21695. EXPECT_EQ(200, res2->status);
  21696. EXPECT_EQ(content, res2->body);
  21697. svr.stop();
  21698. t.join();
  21699. std::remove(fname);
  21700. }
  21701. TEST(ETagTest, ExtremeLargeDateValues) {
  21702. using namespace httplib;
  21703. const char *fname = "ims_extreme_date.txt";
  21704. const char *content = "ims-extreme-date";
  21705. {
  21706. std::ofstream ofs(fname);
  21707. ofs << content;
  21708. ASSERT_TRUE(ofs.good());
  21709. }
  21710. Server svr;
  21711. svr.set_mount_point("/static", ".");
  21712. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21713. svr.wait_until_ready();
  21714. Client cli(HOST, PORT);
  21715. auto res1 = cli.Get(std::string("/static/") + fname);
  21716. ASSERT_TRUE(res1);
  21717. ASSERT_EQ(200, res1->status);
  21718. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21719. // Extremely large year that may overflow date parsing routines.
  21720. Headers h_large_date = {
  21721. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21722. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21723. ASSERT_TRUE(res_bad);
  21724. // Expect server to treat this as invalid/mismatch and return full content
  21725. EXPECT_EQ(200, res_bad->status);
  21726. // If-Range with extremely large date should be treated as mismatch -> full
  21727. // content (200)
  21728. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21729. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21730. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21731. ASSERT_TRUE(res_ifrange);
  21732. EXPECT_EQ(200, res_ifrange->status);
  21733. svr.stop();
  21734. t.join();
  21735. std::remove(fname);
  21736. }
  21737. TEST(ETagTest, NegativeFileModificationTime) {
  21738. using namespace httplib;
  21739. const char *fname = "ims_negative_mtime.txt";
  21740. const std::string content = "negative-mtime";
  21741. {
  21742. std::ofstream ofs(fname);
  21743. ofs << content;
  21744. ASSERT_TRUE(ofs.good());
  21745. }
  21746. // Try to set file mtime to a negative value. This may fail on some
  21747. // platforms/filesystems; if it fails, the test will still verify server
  21748. // behaves safely by performing a regular conditional request.
  21749. #if defined(__APPLE__) || defined(__linux__)
  21750. bool set_negative = false;
  21751. do {
  21752. struct timeval times[2];
  21753. // access time: now
  21754. times[0].tv_sec = time(nullptr);
  21755. times[0].tv_usec = 0;
  21756. // modification time: negative (e.g., -1)
  21757. times[1].tv_sec = -1;
  21758. times[1].tv_usec = 0;
  21759. if (utimes(fname, times) == 0) { set_negative = true; }
  21760. } while (0);
  21761. #else
  21762. bool set_negative = false;
  21763. #endif
  21764. Server svr;
  21765. svr.set_mount_point("/static", ".");
  21766. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21767. svr.wait_until_ready();
  21768. Client cli(HOST, PORT);
  21769. auto res1 = cli.Get(std::string("/static/") + fname);
  21770. ASSERT_TRUE(res1);
  21771. ASSERT_EQ(200, res1->status);
  21772. bool has_last_modified = res1->has_header("Last-Modified");
  21773. std::string last_modified;
  21774. if (has_last_modified) {
  21775. last_modified = res1->get_header_value("Last-Modified");
  21776. }
  21777. if (set_negative) {
  21778. // If we successfully set a negative mtime, ensure server returns a
  21779. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21780. // with an old date and ensure server handles it without crash.
  21781. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21782. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21783. ASSERT_TRUE(res2);
  21784. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21785. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21786. } else {
  21787. // Could not set negative mtime on this platform; fall back to verifying
  21788. // that normal invalid/malformed dates are treated safely (non-304).
  21789. Headers h_bad_date = {
  21790. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21791. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21792. ASSERT_TRUE(res_bad);
  21793. EXPECT_EQ(200, res_bad->status);
  21794. }
  21795. svr.stop();
  21796. t.join();
  21797. std::remove(fname);
  21798. }
  21799. //==============================================================================
  21800. // Integration Tests with Server
  21801. //==============================================================================
  21802. class SSEIntegrationTest : public ::testing::Test {
  21803. protected:
  21804. void SetUp() override {
  21805. stop_server_.store(false);
  21806. events_.clear();
  21807. server_ = httplib::detail::make_unique<Server>();
  21808. setup_server();
  21809. start_server();
  21810. }
  21811. void TearDown() override {
  21812. stop_server_.store(true);
  21813. event_cv_.notify_all();
  21814. server_->stop();
  21815. if (server_thread_.joinable()) { server_thread_.join(); }
  21816. }
  21817. void setup_server() {
  21818. // Simple SSE endpoint
  21819. server_->Get("/events", [this](const Request &req, Response &res) {
  21820. auto last_id = req.get_header_value("Last-Event-ID");
  21821. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21822. res.set_chunked_content_provider(
  21823. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21824. std::unique_lock<std::mutex> lock(event_mutex_);
  21825. if (event_cv_.wait_for(
  21826. lock, std::chrono::milliseconds(200), [this] {
  21827. return !events_.empty() || stop_server_.load();
  21828. })) {
  21829. if (stop_server_.load()) { return false; }
  21830. if (!events_.empty()) {
  21831. std::string event = events_.front();
  21832. events_.erase(events_.begin());
  21833. sink.write(event.data(), event.size());
  21834. return true;
  21835. }
  21836. }
  21837. return !stop_server_.load();
  21838. });
  21839. });
  21840. // Endpoint that returns error
  21841. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21842. res.status = 500;
  21843. res.set_content("Internal Server Error", "text/plain");
  21844. });
  21845. // Endpoint for custom event types
  21846. server_->Get("/custom-events", [](const Request &, Response &res) {
  21847. res.set_chunked_content_provider(
  21848. "text/event-stream", [](size_t offset, DataSink &sink) {
  21849. if (offset == 0) {
  21850. std::string event = "event: update\ndata: updated\n\n"
  21851. "event: delete\ndata: deleted\n\n";
  21852. sink.write(event.data(), event.size());
  21853. }
  21854. return false; // End stream after sending
  21855. });
  21856. });
  21857. }
  21858. void start_server() {
  21859. port_ = server_->bind_to_any_port(HOST);
  21860. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21861. // Wait for server to start
  21862. while (!server_->is_running()) {
  21863. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21864. }
  21865. }
  21866. int get_port() const { return port_; }
  21867. void send_event(const std::string &event) {
  21868. std::lock_guard<std::mutex> lock(event_mutex_);
  21869. events_.push_back(event);
  21870. event_cv_.notify_all();
  21871. }
  21872. std::unique_ptr<Server> server_;
  21873. std::thread server_thread_;
  21874. std::mutex event_mutex_;
  21875. std::condition_variable event_cv_;
  21876. std::vector<std::string> events_;
  21877. std::atomic<bool> stop_server_{false};
  21878. std::string last_received_event_id_;
  21879. int port_ = 0;
  21880. };
  21881. //==============================================================================
  21882. // SSE Parsing Tests
  21883. //==============================================================================
  21884. class SSEParsingTest : public SSEIntegrationTest {
  21885. protected:
  21886. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21887. // A trailing sentinel event tells when the whole stream has been parsed.
  21888. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21889. auto body = stream + "event: end\ndata: end\n\n";
  21890. server_->Get("/parse", [body](const Request &, Response &res) {
  21891. res.set_content(body, "text/event-stream");
  21892. });
  21893. return collect("/parse");
  21894. }
  21895. // Runs SSEClient against path until an "end" event arrives and returns the
  21896. // messages dispatched before it
  21897. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21898. Client client(HOST, get_port());
  21899. sse::SSEClient sse(client, path);
  21900. std::mutex mutex;
  21901. std::condition_variable cv;
  21902. std::vector<sse::SSEMessage> messages;
  21903. auto done = false;
  21904. sse.on_message([&](const sse::SSEMessage &msg) {
  21905. std::lock_guard<std::mutex> lock(mutex);
  21906. // Ignore a replay from a reconnect that races with stop()
  21907. if (!done) { messages.push_back(msg); }
  21908. });
  21909. sse.on_event("end", [&](const sse::SSEMessage &) {
  21910. std::lock_guard<std::mutex> lock(mutex);
  21911. done = true;
  21912. cv.notify_all();
  21913. });
  21914. sse.set_reconnect_interval(100);
  21915. sse.start_async();
  21916. {
  21917. std::unique_lock<std::mutex> lock(mutex);
  21918. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21919. }
  21920. sse.stop();
  21921. EXPECT_TRUE(done);
  21922. return messages;
  21923. }
  21924. };
  21925. TEST_F(SSEParsingTest, SingleLineData) {
  21926. auto msgs = parse("data: hello\n\n");
  21927. ASSERT_EQ(msgs.size(), 1u);
  21928. EXPECT_EQ(msgs[0].data, "hello");
  21929. EXPECT_EQ(msgs[0].event, "message");
  21930. }
  21931. TEST_F(SSEParsingTest, MultiLineData) {
  21932. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21933. ASSERT_EQ(msgs.size(), 1u);
  21934. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21935. }
  21936. TEST_F(SSEParsingTest, CustomEventType) {
  21937. auto msgs = parse("event: update\ndata: payload\n\n");
  21938. ASSERT_EQ(msgs.size(), 1u);
  21939. EXPECT_EQ(msgs[0].event, "update");
  21940. EXPECT_EQ(msgs[0].data, "payload");
  21941. }
  21942. TEST_F(SSEParsingTest, EventIdHandling) {
  21943. auto msgs = parse("id: 12345\ndata: test\n\n");
  21944. ASSERT_EQ(msgs.size(), 1u);
  21945. EXPECT_EQ(msgs[0].id, "12345");
  21946. }
  21947. TEST_F(SSEParsingTest, EmptyEventId) {
  21948. auto msgs = parse("id:\ndata: test\n\n");
  21949. ASSERT_EQ(msgs.size(), 1u);
  21950. EXPECT_EQ(msgs[0].id, "");
  21951. }
  21952. TEST_F(SSEParsingTest, CommentsIgnored) {
  21953. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21954. ASSERT_EQ(msgs.size(), 1u);
  21955. EXPECT_EQ(msgs[0].data, "hello");
  21956. EXPECT_EQ(msgs[0].event, "message");
  21957. }
  21958. TEST_F(SSEParsingTest, ColonInValue) {
  21959. auto msgs = parse("data: hello:world:test\n\n");
  21960. ASSERT_EQ(msgs.size(), 1u);
  21961. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21962. }
  21963. TEST_F(SSEParsingTest, FieldNameOnly) {
  21964. // A line without a colon is a field name with an empty value
  21965. auto msgs = parse("data\n\n");
  21966. ASSERT_EQ(msgs.size(), 1u);
  21967. EXPECT_EQ(msgs[0].data, "");
  21968. }
  21969. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21970. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21971. ASSERT_EQ(msgs.size(), 1u);
  21972. EXPECT_EQ(msgs[0].event, "update");
  21973. EXPECT_EQ(msgs[0].data, "hello");
  21974. }
  21975. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21976. auto msgs = parse("data\r\n\r\n");
  21977. ASSERT_EQ(msgs.size(), 1u);
  21978. EXPECT_EQ(msgs[0].data, "");
  21979. }
  21980. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21981. auto msgs = parse("event: update\rdata: hello\r\r");
  21982. ASSERT_EQ(msgs.size(), 1u);
  21983. EXPECT_EQ(msgs[0].event, "update");
  21984. EXPECT_EQ(msgs[0].data, "hello");
  21985. }
  21986. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21987. // Chunk boundaries fall inside every \r\n and right before the first one
  21988. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21989. "\n\r", "\nevent: end\ndata: end\n\n"};
  21990. server_->Get("/split", [chunks](const Request &, Response &res) {
  21991. auto i = std::make_shared<size_t>(0);
  21992. res.set_chunked_content_provider(
  21993. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21994. if (*i == chunks.size()) {
  21995. sink.done();
  21996. } else {
  21997. sink.write(chunks[*i].data(), chunks[*i].size());
  21998. (*i)++;
  21999. }
  22000. return true;
  22001. });
  22002. });
  22003. auto msgs = collect("/split");
  22004. ASSERT_EQ(msgs.size(), 1u);
  22005. EXPECT_EQ(msgs[0].event, "update");
  22006. EXPECT_EQ(msgs[0].data, "hello");
  22007. }
  22008. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22009. // Only a BOM at the start of the stream is ignored
  22010. auto msgs = parse("\xEF\xBB\xBF"
  22011. "data: first\n\n"
  22012. "\xEF\xBB\xBF"
  22013. "data: second\n\n");
  22014. ASSERT_EQ(msgs.size(), 1u);
  22015. EXPECT_EQ(msgs[0].data, "first");
  22016. }
  22017. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22018. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22019. ASSERT_EQ(msgs.size(), 1u);
  22020. EXPECT_EQ(msgs[0].data, "hello");
  22021. EXPECT_EQ(msgs[0].event, "message");
  22022. }
  22023. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22024. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22025. ASSERT_EQ(msgs.size(), 2u);
  22026. EXPECT_EQ(msgs[0].data, "hello");
  22027. EXPECT_EQ(msgs[1].data, "hello");
  22028. }
  22029. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22030. // An event without data is not dispatched, and its type must not leak
  22031. // into the next event
  22032. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22033. ASSERT_EQ(msgs.size(), 1u);
  22034. EXPECT_EQ(msgs[0].event, "message");
  22035. EXPECT_EQ(msgs[0].data, "hello");
  22036. }
  22037. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22038. // Also when the empty field replaces an earlier type
  22039. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22040. ASSERT_EQ(msgs.size(), 2u);
  22041. EXPECT_EQ(msgs[0].event, "message");
  22042. EXPECT_EQ(msgs[1].event, "message");
  22043. }
  22044. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22045. // The first connection sends only an id; the second echoes back the
  22046. // Last-Event-ID it was reconnected with
  22047. std::atomic<int> connection_count{0};
  22048. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22049. if (connection_count++ == 0) {
  22050. res.set_content("id: 42\n\n", "text/event-stream");
  22051. } else {
  22052. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22053. "\n\nevent: end\ndata: end\n\n",
  22054. "text/event-stream");
  22055. }
  22056. });
  22057. auto msgs = collect("/id-only");
  22058. ASSERT_EQ(msgs.size(), 1u);
  22059. EXPECT_EQ(msgs[0].data, "42");
  22060. }
  22061. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22062. // The first connection sets an id and then clears it with an empty one; the
  22063. // second reports whether it was reconnected with a Last-Event-ID
  22064. std::atomic<int> connection_count{0};
  22065. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22066. if (connection_count++ == 0) {
  22067. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22068. "text/event-stream");
  22069. } else {
  22070. res.set_content(
  22071. std::string("data: ") +
  22072. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22073. "\n\nevent: end\ndata: end\n\n",
  22074. "text/event-stream");
  22075. }
  22076. });
  22077. auto msgs = collect("/id-clear");
  22078. ASSERT_EQ(msgs.size(), 3u);
  22079. EXPECT_EQ(msgs[0].id, "1");
  22080. EXPECT_EQ(msgs[1].id, "");
  22081. EXPECT_EQ(msgs[2].data, "not sent");
  22082. }
  22083. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22084. // The first connection sets an id and then sends ids that cannot be carried
  22085. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22086. // with
  22087. std::atomic<int> connection_count{0};
  22088. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22089. if (connection_count++ == 0) {
  22090. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22091. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22092. "text/event-stream");
  22093. } else {
  22094. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22095. "\n\nevent: end\ndata: end\n\n",
  22096. "text/event-stream");
  22097. }
  22098. });
  22099. auto msgs = collect("/id-unsendable");
  22100. ASSERT_EQ(msgs.size(), 1u);
  22101. EXPECT_EQ(msgs[0].data, "42");
  22102. }
  22103. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22104. auto msgs = parse("event: notification\nid: evt-42\n"
  22105. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22106. ASSERT_EQ(msgs.size(), 1u);
  22107. EXPECT_EQ(msgs[0].event, "notification");
  22108. EXPECT_EQ(msgs[0].id, "evt-42");
  22109. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22110. }
  22111. TEST(SSEMessageTest, Clear) {
  22112. sse::SSEMessage msg;
  22113. msg.event = "custom";
  22114. msg.data = "some data";
  22115. msg.id = "123";
  22116. msg.clear();
  22117. EXPECT_EQ(msg.event, "message");
  22118. EXPECT_EQ(msg.data, "");
  22119. EXPECT_EQ(msg.id, "");
  22120. }
  22121. //==============================================================================
  22122. // SSE Integration Tests
  22123. //==============================================================================
  22124. // Test: Successful connection and on_open callback
  22125. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22126. // Add a simple endpoint that sends one event and closes
  22127. server_->Get("/simple-event", [](const Request &, Response &res) {
  22128. res.set_chunked_content_provider(
  22129. "text/event-stream", [](size_t offset, DataSink &sink) {
  22130. if (offset == 0) {
  22131. std::string event = "data: hello\n\n";
  22132. sink.write(event.data(), event.size());
  22133. }
  22134. return false; // Close stream after sending
  22135. });
  22136. });
  22137. Client client("localhost", get_port());
  22138. sse::SSEClient sse(client, "/simple-event");
  22139. std::atomic<bool> open_called{false};
  22140. std::atomic<bool> message_received{false};
  22141. sse.on_open([&open_called]() { open_called.store(true); });
  22142. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22143. if (msg.data == "hello") { message_received.store(true); }
  22144. });
  22145. sse.set_reconnect_interval(100);
  22146. sse.set_max_reconnect_attempts(1);
  22147. // Start async
  22148. sse.start_async();
  22149. // Wait for message to be processed
  22150. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22151. sse.stop();
  22152. EXPECT_TRUE(open_called.load());
  22153. EXPECT_TRUE(message_received.load());
  22154. }
  22155. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22156. // A data line that never ends.
  22157. server_->Get("/endless-line", [](const Request &, Response &res) {
  22158. res.set_chunked_content_provider(
  22159. "text/event-stream", [](size_t offset, DataSink &sink) {
  22160. if (offset == 0) { sink.write("data: ", 6); }
  22161. std::string chunk(64 * 1024, 'A');
  22162. return sink.write(chunk.data(), chunk.size());
  22163. });
  22164. });
  22165. Client client("localhost", get_port());
  22166. sse::SSEClient sse(client, "/endless-line");
  22167. std::atomic<bool> too_long{false};
  22168. sse.on_error([&](Error err) {
  22169. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22170. });
  22171. sse.set_max_reconnect_attempts(1);
  22172. sse.start_async();
  22173. for (int i = 0; i < 500 && !too_long; i++) {
  22174. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22175. }
  22176. sse.stop();
  22177. EXPECT_TRUE(too_long);
  22178. }
  22179. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22180. // Far more in all than the client's payload limit below.
  22181. server_->Get("/many-events", [](const Request &, Response &res) {
  22182. res.set_chunked_content_provider(
  22183. "text/event-stream", [](size_t offset, DataSink &sink) {
  22184. if (offset == 0) {
  22185. std::string events;
  22186. for (int i = 0; i < 1000; i++) {
  22187. events += "data: message\n\n";
  22188. }
  22189. sink.write(events.data(), events.size());
  22190. }
  22191. return false;
  22192. });
  22193. });
  22194. Client client("localhost", get_port());
  22195. client.set_payload_max_length(1024);
  22196. sse::SSEClient sse(client, "/many-events");
  22197. std::atomic<int> messages{0};
  22198. std::atomic<bool> too_large{false};
  22199. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22200. sse.on_error([&](Error err) {
  22201. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22202. });
  22203. sse.set_max_reconnect_attempts(1);
  22204. sse.start_async();
  22205. for (int i = 0; i < 500 && messages < 1000; i++) {
  22206. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22207. }
  22208. sse.stop();
  22209. EXPECT_GE(messages.load(), 1000);
  22210. EXPECT_FALSE(too_large);
  22211. }
  22212. // Test: on_message callback
  22213. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22214. // Endpoint that sends multiple events then closes
  22215. server_->Get("/multi-event", [](const Request &, Response &res) {
  22216. res.set_chunked_content_provider(
  22217. "text/event-stream", [](size_t offset, DataSink &sink) {
  22218. if (offset == 0) {
  22219. std::string events = "data: message1\n\ndata: message2\n\n";
  22220. sink.write(events.data(), events.size());
  22221. }
  22222. return false;
  22223. });
  22224. });
  22225. Client client("localhost", get_port());
  22226. sse::SSEClient sse(client, "/multi-event");
  22227. std::vector<std::string> received_messages;
  22228. std::mutex messages_mutex;
  22229. sse.on_message([&](const sse::SSEMessage &msg) {
  22230. std::lock_guard<std::mutex> lock(messages_mutex);
  22231. received_messages.push_back(msg.data);
  22232. });
  22233. sse.set_reconnect_interval(100);
  22234. sse.set_max_reconnect_attempts(1);
  22235. sse.start_async();
  22236. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22237. sse.stop();
  22238. std::lock_guard<std::mutex> lock(messages_mutex);
  22239. EXPECT_GE(received_messages.size(), 2u);
  22240. if (received_messages.size() >= 2) {
  22241. EXPECT_EQ(received_messages[0], "message1");
  22242. EXPECT_EQ(received_messages[1], "message2");
  22243. }
  22244. }
  22245. // Test: on_event for specific types
  22246. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22247. Client client("localhost", get_port());
  22248. sse::SSEClient sse(client, "/custom-events");
  22249. std::atomic<bool> update_received{false};
  22250. std::atomic<bool> delete_received{false};
  22251. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22252. if (msg.data == "updated") { update_received.store(true); }
  22253. });
  22254. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22255. if (msg.data == "deleted") { delete_received.store(true); }
  22256. });
  22257. sse.set_max_reconnect_attempts(1);
  22258. sse.start_async();
  22259. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22260. sse.stop();
  22261. EXPECT_TRUE(update_received.load());
  22262. EXPECT_TRUE(delete_received.load());
  22263. }
  22264. // Test: on_error callback on connection failure
  22265. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22266. // Connect to a non-existent port
  22267. Client client("localhost", 59999);
  22268. sse::SSEClient sse(client, "/events");
  22269. std::atomic<bool> error_called{false};
  22270. Error received_error = Error::Success;
  22271. sse.on_error([&](Error err) {
  22272. error_called.store(true);
  22273. received_error = err;
  22274. });
  22275. sse.set_reconnect_interval(50);
  22276. sse.set_max_reconnect_attempts(1);
  22277. sse.start_async();
  22278. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22279. sse.stop();
  22280. EXPECT_TRUE(error_called.load());
  22281. EXPECT_NE(received_error, Error::Success);
  22282. }
  22283. // Test: Last-Event-ID header sent on reconnect
  22284. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22285. // Endpoint that sends event with ID
  22286. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22287. res.set_chunked_content_provider(
  22288. "text/event-stream", [](size_t offset, DataSink &sink) {
  22289. if (offset == 0) {
  22290. std::string event = "id: evt-123\ndata: test\n\n";
  22291. sink.write(event.data(), event.size());
  22292. }
  22293. return false;
  22294. });
  22295. });
  22296. Client client("localhost", get_port());
  22297. sse::SSEClient sse(client, "/event-with-id");
  22298. std::atomic<bool> id_received{false};
  22299. sse.on_message([&](const sse::SSEMessage &msg) {
  22300. if (!msg.id.empty()) { id_received.store(true); }
  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. EXPECT_TRUE(id_received.load());
  22308. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22309. }
  22310. // Test: Manual stop
  22311. TEST_F(SSEIntegrationTest, ManualStop) {
  22312. // Endpoint that sends one event and stays open briefly. The server outlives
  22313. // this test body, so the provider uses the fixture's flag, not a local.
  22314. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22315. res.set_chunked_content_provider(
  22316. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22317. if (offset == 0) {
  22318. std::string event = "data: connected\n\n";
  22319. sink.write(event.data(), event.size());
  22320. }
  22321. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22322. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22323. }
  22324. return false;
  22325. });
  22326. });
  22327. Client client("localhost", get_port());
  22328. sse::SSEClient sse(client, "/stay-open");
  22329. std::atomic<bool> connected{false};
  22330. sse.on_open([&connected]() { connected.store(true); });
  22331. sse.set_reconnect_interval(100);
  22332. sse.set_max_reconnect_attempts(1);
  22333. sse.start_async();
  22334. // Wait for connection to establish
  22335. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22336. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22337. }
  22338. EXPECT_TRUE(connected.load());
  22339. EXPECT_TRUE(sse.is_connected());
  22340. // Signal handler to stop
  22341. stop_server_.store(true);
  22342. // Stop SSE client
  22343. sse.stop();
  22344. EXPECT_FALSE(sse.is_connected());
  22345. }
  22346. // Sends one event, then nothing until stop is set
  22347. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22348. return [&stop](const Request &, Response &res) {
  22349. res.set_chunked_content_provider(
  22350. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22351. if (offset == 0) {
  22352. std::string event = "data: hello\n\n";
  22353. sink.write(event.data(), event.size());
  22354. }
  22355. while (!stop.load()) {
  22356. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22357. }
  22358. return false;
  22359. });
  22360. };
  22361. }
  22362. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22363. static void check_stop_interrupts_blocked_read(Client &client) {
  22364. client.set_read_timeout(30, 0);
  22365. for (auto by_destructor : {false, true}) {
  22366. std::atomic<bool> received{false};
  22367. std::chrono::steady_clock::time_point start;
  22368. {
  22369. sse::SSEClient sse(client, "/idle-stream");
  22370. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22371. sse.start_async();
  22372. for (int i = 0; i < 500 && !received.load(); ++i) {
  22373. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22374. }
  22375. ASSERT_TRUE(received.load());
  22376. // Let the client block in the next read
  22377. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22378. start = std::chrono::steady_clock::now();
  22379. if (!by_destructor) { sse.stop(); }
  22380. }
  22381. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22382. std::chrono::seconds(2));
  22383. }
  22384. }
  22385. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22386. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22387. Client client("localhost", get_port());
  22388. check_stop_interrupts_blocked_read(client);
  22389. }
  22390. #ifdef CPPHTTPLIB_SSL_ENABLED
  22391. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22392. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22393. std::atomic<bool> done{false};
  22394. svr.Get("/idle-stream", idle_event_stream(done));
  22395. auto port = svr.bind_to_any_port(HOST);
  22396. std::thread t([&] { svr.listen_after_bind(); });
  22397. auto se = detail::scope_exit([&] {
  22398. done.store(true);
  22399. svr.stop();
  22400. t.join();
  22401. });
  22402. svr.wait_until_ready();
  22403. Client client("https://localhost:" + std::to_string(port));
  22404. client.enable_server_certificate_verification(false);
  22405. check_stop_interrupts_blocked_read(client);
  22406. }
  22407. #endif
  22408. // Test: SSEClient with custom headers
  22409. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22410. // Setup a server endpoint that checks for custom header
  22411. std::atomic<bool> header_received{false};
  22412. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22413. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22414. header_received.store(true);
  22415. }
  22416. res.set_chunked_content_provider("text/event-stream",
  22417. [](size_t, DataSink &) { return false; });
  22418. });
  22419. Client client("localhost", get_port());
  22420. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22421. sse::SSEClient sse(client, "/header-check", headers);
  22422. sse.set_max_reconnect_attempts(1);
  22423. sse.start_async();
  22424. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22425. sse.stop();
  22426. EXPECT_TRUE(header_received.load());
  22427. }
  22428. // Test: Reconnect interval configuration
  22429. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22430. Client client("localhost", get_port());
  22431. sse::SSEClient sse(client, "/events");
  22432. auto &result = sse.set_reconnect_interval(500);
  22433. // Builder pattern should return reference to self
  22434. EXPECT_EQ(&result, &sse);
  22435. }
  22436. // Test: Max reconnect attempts
  22437. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22438. // Connect to non-existent port to force reconnects
  22439. Client client("localhost", 59998);
  22440. sse::SSEClient sse(client, "/events");
  22441. std::atomic<int> error_count{0};
  22442. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22443. sse.set_reconnect_interval(50);
  22444. sse.set_max_reconnect_attempts(2);
  22445. auto start = std::chrono::steady_clock::now();
  22446. sse.start(); // Blocking call
  22447. auto end = std::chrono::steady_clock::now();
  22448. // Should have stopped after 2 failed attempts
  22449. EXPECT_GE(error_count.load(), 2);
  22450. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22451. auto duration =
  22452. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22453. #ifdef _WIN32
  22454. // Windows is much slower for socket connection failures
  22455. EXPECT_LT(duration.count(), 7000);
  22456. #else
  22457. EXPECT_LT(duration.count(), 1000);
  22458. #endif
  22459. }
  22460. // Test: Multi-line data in integration
  22461. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22462. // Endpoint with multi-line data
  22463. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22464. res.set_chunked_content_provider(
  22465. "text/event-stream", [](size_t offset, DataSink &sink) {
  22466. if (offset == 0) {
  22467. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22468. sink.write(event.data(), event.size());
  22469. }
  22470. return false;
  22471. });
  22472. });
  22473. Client client("localhost", get_port());
  22474. sse::SSEClient sse(client, "/multiline-data");
  22475. std::string received_data;
  22476. std::mutex data_mutex;
  22477. sse.on_message([&](const sse::SSEMessage &msg) {
  22478. std::lock_guard<std::mutex> lock(data_mutex);
  22479. received_data = msg.data;
  22480. });
  22481. sse.set_reconnect_interval(100);
  22482. sse.set_max_reconnect_attempts(1);
  22483. sse.start_async();
  22484. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22485. sse.stop();
  22486. std::lock_guard<std::mutex> lock(data_mutex);
  22487. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22488. }
  22489. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22490. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22491. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22492. DataSink &sink) {
  22493. if (offset == 0) {
  22494. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22495. sink.write(events.data(), events.size());
  22496. }
  22497. return false;
  22498. });
  22499. });
  22500. Client client("localhost", get_port());
  22501. sse::SSEClient sse(client, "/empty-data-lines");
  22502. std::mutex mutex;
  22503. std::condition_variable cv;
  22504. std::vector<std::string> received;
  22505. sse.on_message([&](const sse::SSEMessage &msg) {
  22506. std::lock_guard<std::mutex> lock(mutex);
  22507. received.push_back(msg.data);
  22508. cv.notify_all();
  22509. });
  22510. sse.set_max_reconnect_attempts(1);
  22511. sse.start_async();
  22512. {
  22513. std::unique_lock<std::mutex> lock(mutex);
  22514. cv.wait_for(lock, std::chrono::seconds(2),
  22515. [&] { return received.size() >= 3; });
  22516. }
  22517. sse.stop();
  22518. ASSERT_GE(received.size(), 3u);
  22519. EXPECT_EQ(received[0], "");
  22520. EXPECT_EQ(received[1], "\nhello");
  22521. EXPECT_EQ(received[2], "");
  22522. }
  22523. // Test: Auto-reconnect after server disconnection
  22524. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22525. std::atomic<int> connection_count{0};
  22526. std::atomic<int> message_count{0};
  22527. // Endpoint that sends one event and closes, forcing reconnect
  22528. server_->Get("/reconnect-test",
  22529. [&connection_count](const Request &, Response &res) {
  22530. connection_count.fetch_add(1);
  22531. res.set_chunked_content_provider(
  22532. "text/event-stream", [](size_t offset, DataSink &sink) {
  22533. if (offset == 0) {
  22534. std::string event = "data: hello\n\n";
  22535. sink.write(event.data(), event.size());
  22536. }
  22537. return false; // Close connection after sending
  22538. });
  22539. });
  22540. Client client("localhost", get_port());
  22541. sse::SSEClient sse(client, "/reconnect-test");
  22542. sse.on_message([&message_count](const sse::SSEMessage &) {
  22543. message_count.fetch_add(1);
  22544. });
  22545. sse.set_reconnect_interval(100);
  22546. sse.set_max_reconnect_attempts(3);
  22547. sse.start_async();
  22548. // Wait long enough for multiple reconnects
  22549. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22550. sse.stop();
  22551. // Should have connected multiple times (initial + reconnects)
  22552. EXPECT_GE(connection_count.load(), 2);
  22553. // Should have received messages from multiple connections
  22554. EXPECT_GE(message_count.load(), 2);
  22555. }
  22556. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22557. std::atomic<int> connection_count{0};
  22558. // Neither Content-Length nor chunked: the close ends the stream
  22559. server_->Get("/close-delimited",
  22560. [&connection_count](const Request &, Response &res) {
  22561. connection_count.fetch_add(1);
  22562. res.set_content_provider(
  22563. "text/event-stream", [](size_t offset, DataSink &sink) {
  22564. if (offset == 0) {
  22565. std::string event = "data: hello\n\n";
  22566. sink.write(event.data(), event.size());
  22567. } else {
  22568. sink.done();
  22569. }
  22570. return true;
  22571. });
  22572. });
  22573. Client client("localhost", get_port());
  22574. sse::SSEClient sse(client, "/close-delimited");
  22575. std::atomic<int> error_count{0};
  22576. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22577. sse.set_reconnect_interval(100);
  22578. sse.start_async();
  22579. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22580. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22581. }
  22582. sse.stop();
  22583. // Reconnects as after any end of the stream, but reports no error
  22584. EXPECT_GE(connection_count.load(), 2);
  22585. EXPECT_EQ(0, error_count.load());
  22586. }
  22587. // Test: A retry field that is not all ASCII digits is ignored
  22588. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22589. std::atomic<int> connection_count{0};
  22590. server_->Get("/bad-retry",
  22591. [&connection_count](const Request &, Response &res) {
  22592. connection_count.fetch_add(1);
  22593. res.set_chunked_content_provider(
  22594. "text/event-stream", [](size_t offset, DataSink &sink) {
  22595. if (offset == 0) {
  22596. std::string event = "retry: -1\ndata: hello\n\n";
  22597. sink.write(event.data(), event.size());
  22598. }
  22599. return false;
  22600. });
  22601. });
  22602. Client client("localhost", get_port());
  22603. sse::SSEClient sse(client, "/bad-retry");
  22604. sse.set_reconnect_interval(10000);
  22605. sse.start_async();
  22606. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22607. sse.stop();
  22608. EXPECT_EQ(connection_count.load(), 1);
  22609. }
  22610. // Test: A retry field of all ASCII digits sets the reconnection time
  22611. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22612. std::mutex mutex;
  22613. std::condition_variable cv;
  22614. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22615. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22616. {
  22617. std::lock_guard<std::mutex> lock(mutex);
  22618. connected_at.push_back(std::chrono::steady_clock::now());
  22619. cv.notify_all();
  22620. }
  22621. res.set_chunked_content_provider(
  22622. "text/event-stream", [](size_t offset, DataSink &sink) {
  22623. if (offset == 0) {
  22624. std::string event = "retry: 0\ndata: hello\n\n";
  22625. sink.write(event.data(), event.size());
  22626. }
  22627. return false;
  22628. });
  22629. });
  22630. Client client("localhost", get_port());
  22631. sse::SSEClient sse(client, "/zero-retry");
  22632. sse.set_reconnect_interval(10000);
  22633. sse.start_async();
  22634. {
  22635. std::unique_lock<std::mutex> lock(mutex);
  22636. cv.wait_for(lock, std::chrono::seconds(5),
  22637. [&] { return connected_at.size() >= 2; });
  22638. }
  22639. sse.stop();
  22640. // The server-supplied interval is applied, but never below 100ms, so
  22641. // "retry: 0" does not cause a busy reconnect loop
  22642. std::lock_guard<std::mutex> lock(mutex);
  22643. ASSERT_GE(connected_at.size(), 2u);
  22644. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22645. connected_at[1] - connected_at[0])
  22646. .count();
  22647. EXPECT_GE(interval_ms, 100);
  22648. }
  22649. // Test: Last-Event-ID sent on reconnect
  22650. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22651. std::atomic<int> connection_count{0};
  22652. std::vector<std::string> received_last_event_ids;
  22653. std::mutex id_mutex;
  22654. // Endpoint that checks Last-Event-ID header and sends event with ID
  22655. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22656. int conn = connection_count.fetch_add(1);
  22657. // Capture the Last-Event-ID header from each connection
  22658. {
  22659. std::lock_guard<std::mutex> lock(id_mutex);
  22660. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22661. }
  22662. res.set_chunked_content_provider(
  22663. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22664. if (offset == 0) {
  22665. std::string event =
  22666. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22667. sink.write(event.data(), event.size());
  22668. }
  22669. return false;
  22670. });
  22671. });
  22672. Client client("localhost", get_port());
  22673. sse::SSEClient sse(client, "/reconnect-with-id");
  22674. sse.set_reconnect_interval(100);
  22675. sse.set_max_reconnect_attempts(3);
  22676. sse.start_async();
  22677. // Wait for at least 2 connections
  22678. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22679. sse.stop();
  22680. // Verify behavior
  22681. std::lock_guard<std::mutex> lock(id_mutex);
  22682. EXPECT_GE(received_last_event_ids.size(), 2u);
  22683. // First connection should have no Last-Event-ID
  22684. if (!received_last_event_ids.empty()) {
  22685. EXPECT_EQ(received_last_event_ids[0], "");
  22686. }
  22687. // Second connection should have Last-Event-ID from first connection
  22688. if (received_last_event_ids.size() >= 2) {
  22689. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22690. }
  22691. }
  22692. // Test: set_headers updates headers used on reconnect
  22693. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22694. std::vector<std::string> received_tokens;
  22695. std::mutex token_mutex;
  22696. // Endpoint that captures Authorization header
  22697. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22698. {
  22699. std::lock_guard<std::mutex> lock(token_mutex);
  22700. received_tokens.push_back(req.get_header_value("Authorization"));
  22701. }
  22702. res.set_chunked_content_provider(
  22703. "text/event-stream", [](size_t offset, DataSink &sink) {
  22704. if (offset == 0) {
  22705. std::string event = "data: hello\n\n";
  22706. sink.write(event.data(), event.size());
  22707. }
  22708. return false; // Close connection to trigger reconnect
  22709. });
  22710. });
  22711. Client client("localhost", get_port());
  22712. Headers headers = {{"Authorization", "Bearer old-token"}};
  22713. sse::SSEClient sse(client, "/auth-check", headers);
  22714. // Update headers on each successful connection
  22715. sse.on_open(
  22716. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22717. sse.set_reconnect_interval(100);
  22718. sse.set_max_reconnect_attempts(3);
  22719. sse.start_async();
  22720. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22721. sse.stop();
  22722. std::lock_guard<std::mutex> lock(token_mutex);
  22723. ASSERT_GE(received_tokens.size(), 2u);
  22724. // First connection uses original header
  22725. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22726. // Second connection uses updated header from set_headers
  22727. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22728. }
  22729. // Test: 401 allows reconnection (so on_error can refresh headers)
  22730. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22731. std::atomic<int> connection_count{0};
  22732. // Endpoint: returns 401 on first attempt, 200 on second
  22733. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22734. int conn = connection_count.fetch_add(1);
  22735. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22736. res.status = StatusCode::Unauthorized_401;
  22737. res.set_content("Unauthorized", "text/plain");
  22738. return;
  22739. }
  22740. res.set_chunked_content_provider(
  22741. "text/event-stream", [](size_t offset, DataSink &sink) {
  22742. if (offset == 0) {
  22743. std::string event = "data: authenticated\n\n";
  22744. sink.write(event.data(), event.size());
  22745. }
  22746. return false;
  22747. });
  22748. });
  22749. Client client("localhost", get_port());
  22750. Headers headers = {{"Authorization", "Bearer expired"}};
  22751. sse::SSEClient sse(client, "/auth-retry", headers);
  22752. std::atomic<bool> message_received{false};
  22753. // Refresh token on error
  22754. sse.on_error(
  22755. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22756. sse.on_message([&](const sse::SSEMessage &msg) {
  22757. if (msg.data == "authenticated") { message_received.store(true); }
  22758. });
  22759. sse.set_reconnect_interval(100);
  22760. sse.set_max_reconnect_attempts(3);
  22761. sse.start_async();
  22762. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22763. sse.stop();
  22764. // Should have reconnected after 401 and succeeded with new token
  22765. EXPECT_GE(connection_count.load(), 2);
  22766. EXPECT_TRUE(message_received.load());
  22767. }
  22768. TEST(Issue2318Test, EmptyHostString) {
  22769. {
  22770. httplib::Client cli_empty("", PORT);
  22771. auto res = cli_empty.Get("/");
  22772. ASSERT_FALSE(res);
  22773. EXPECT_EQ(httplib::Error::Connection, res.error());
  22774. }
  22775. {
  22776. httplib::Client cli(" ", PORT);
  22777. auto res = cli.Get("/");
  22778. ASSERT_FALSE(res);
  22779. EXPECT_EQ(httplib::Error::Connection, res.error());
  22780. }
  22781. }
  22782. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22783. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22784. Server svr;
  22785. // Set a small payload limit (1KB)
  22786. svr.set_payload_max_length(1024);
  22787. svr.Post("/test", [&](const Request &req, Response &res) {
  22788. res.set_content("Body size: " + std::to_string(req.body.size()),
  22789. "text/plain");
  22790. });
  22791. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22792. auto se = detail::scope_exit([&] {
  22793. svr.stop();
  22794. listen_thread.join();
  22795. });
  22796. svr.wait_until_ready();
  22797. // Create data that compresses well but exceeds limit when decompressed
  22798. // 8KB of repeated null bytes compresses to a very small size
  22799. std::string original_data(8 * 1024, '\0');
  22800. // Compress the data using gzip
  22801. std::string compressed_data;
  22802. detail::gzip_compressor compressor;
  22803. compressor.compress(original_data.data(), original_data.size(), true,
  22804. [&](const char *data, size_t size) {
  22805. compressed_data.append(data, size);
  22806. return true;
  22807. });
  22808. // Verify compression worked (compressed should be much smaller)
  22809. ASSERT_LT(compressed_data.size(), original_data.size());
  22810. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22811. // Send compressed data with Content-Encoding: gzip
  22812. Client cli(HOST, PORT);
  22813. Headers headers = {{"Content-Encoding", "gzip"}};
  22814. auto res =
  22815. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22816. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22818. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22819. }
  22820. #endif
  22821. // ============================================================================
  22822. // OpenSSL-Specific Tests
  22823. // ============================================================================
  22824. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22825. X509 *readCertificate(const std::string &strFileName) {
  22826. std::ifstream inStream(strFileName);
  22827. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22828. std::istreambuf_iterator<char>());
  22829. if (strCertPEM.empty()) return (nullptr);
  22830. BIO *pbCert = BIO_new(BIO_s_mem());
  22831. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22832. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22833. BIO_free(pbCert);
  22834. return (pCert);
  22835. }
  22836. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22837. std::ifstream inStream(strFileName);
  22838. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22839. std::istreambuf_iterator<char>());
  22840. if (strPrivateKeyPEM.empty()) return (nullptr);
  22841. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22842. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22843. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22844. BIO_free(pbPrivKey);
  22845. return (pPrivateKey);
  22846. }
  22847. TEST(BindServerTest, UpdateCerts) {
  22848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22849. int port = svr.bind_to_any_port("0.0.0.0");
  22850. ASSERT_TRUE(svr.is_valid());
  22851. ASSERT_TRUE(port > 0);
  22852. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22853. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22854. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22855. ASSERT_TRUE(cert != nullptr);
  22856. ASSERT_TRUE(ca_cert != nullptr);
  22857. ASSERT_TRUE(key != nullptr);
  22858. X509_STORE *cert_store = X509_STORE_new();
  22859. X509_STORE_add_cert(cert_store, ca_cert);
  22860. // svr.update_certs(cert, key, cert_store); // deprecated
  22861. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22862. CLIENT_CA_CERT_FILE);
  22863. ASSERT_TRUE(svr.is_valid());
  22864. svr.stop();
  22865. X509_STORE_free(cert_store);
  22866. X509_free(cert);
  22867. X509_free(ca_cert);
  22868. EVP_PKEY_free(key);
  22869. }
  22870. // Test that update_certs() updates client CA list correctly
  22871. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22872. // Start with file-based constructor
  22873. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22874. ASSERT_TRUE(svr.is_valid());
  22875. // Initially no client CA list should be set
  22876. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22877. ASSERT_TRUE(ssl_ctx != nullptr);
  22878. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22879. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22880. // Now update with client CA (PEM string)
  22881. std::string cert_pem, key_pem, ca_pem;
  22882. read_file(SERVER_CERT_FILE, cert_pem);
  22883. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22884. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22885. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22886. ASSERT_TRUE(svr.is_valid());
  22887. // Now client CA list should be set
  22888. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22889. ASSERT_TRUE(ca_list_after != nullptr);
  22890. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22891. }
  22892. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22893. // Test that the file-path SSLServer constructor properly sets the client CA
  22894. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22895. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22896. ASSERT_TRUE(svr.is_valid());
  22897. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22898. ASSERT_TRUE(ssl_ctx != nullptr);
  22899. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22900. ASSERT_TRUE(ca_list != nullptr);
  22901. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22902. }
  22903. #endif
  22904. // ============================================================================
  22905. // MbedTLS-Specific Tests
  22906. // ============================================================================
  22907. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22908. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22909. using namespace httplib::tls;
  22910. // Track if callback was invoked
  22911. bool callback_invoked = false;
  22912. // The callback receives void* ctx which is actually MbedTlsContext*
  22913. // We can access the mbedtls_ssl_config via the context
  22914. auto setup_callback = [&callback_invoked](void *ctx) {
  22915. callback_invoked = true;
  22916. // Cast to MbedTlsContext* to access the ssl config
  22917. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22918. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22919. // Use static variables to hold certificate data (simplified for test)
  22920. static mbedtls_x509_crt own_cert;
  22921. static mbedtls_pk_context own_key;
  22922. static mbedtls_x509_crt ca_chain;
  22923. static bool initialized = false;
  22924. if (!initialized) {
  22925. mbedtls_x509_crt_init(&own_cert);
  22926. mbedtls_pk_init(&own_key);
  22927. mbedtls_x509_crt_init(&ca_chain);
  22928. // Load server certificate
  22929. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22930. return false;
  22931. }
  22932. // Load server private key.
  22933. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22934. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22935. #if MBEDTLS_VERSION_MAJOR == 3
  22936. ,
  22937. mbedtls_ctr_drbg_random, nullptr
  22938. #endif
  22939. ) != 0) {
  22940. return false;
  22941. }
  22942. // Load CA chain for client verification
  22943. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22944. return false;
  22945. }
  22946. initialized = true;
  22947. }
  22948. // Configure the SSL config
  22949. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22950. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22951. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22952. // Set minimum TLS version using mbedTLS native API
  22953. #if MBEDTLS_VERSION_MAJOR >= 3
  22954. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22955. #else
  22956. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22957. MBEDTLS_SSL_MINOR_VERSION_3);
  22958. #endif
  22959. return true;
  22960. };
  22961. SSLServer svr(setup_callback);
  22962. ASSERT_TRUE(svr.is_valid());
  22963. ASSERT_TRUE(callback_invoked);
  22964. svr.Get("/test", [&](const Request &req, Response &res) {
  22965. res.set_content("test", "text/plain");
  22966. auto cert = req.peer_cert();
  22967. ASSERT_TRUE(static_cast<bool>(cert));
  22968. auto common_name = cert.subject_cn();
  22969. EXPECT_EQ("Common Name", common_name);
  22970. });
  22971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22972. auto se = detail::scope_exit([&] {
  22973. svr.stop();
  22974. t.join();
  22975. ASSERT_FALSE(svr.is_running());
  22976. });
  22977. svr.wait_until_ready();
  22978. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22979. cli.enable_server_certificate_verification(false);
  22980. cli.set_connection_timeout(30);
  22981. auto res = cli.Get("/test");
  22982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22983. ASSERT_EQ(StatusCode::OK_200, res->status);
  22984. }
  22985. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22986. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22987. // keep-alive SSL session, which reads through that config in
  22988. // mbedtls_ssl_close_notify.
  22989. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22990. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22991. ASSERT_TRUE(svr.is_valid());
  22992. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22993. res.set_content("test", "text/plain");
  22994. });
  22995. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22996. auto se = detail::scope_exit([&] {
  22997. svr.stop();
  22998. t.join();
  22999. ASSERT_FALSE(svr.is_running());
  23000. });
  23001. svr.wait_until_ready();
  23002. {
  23003. SSLClient cli(HOST, PORT);
  23004. cli.enable_server_certificate_verification(false);
  23005. cli.set_keep_alive(true);
  23006. auto res = cli.Get("/test");
  23007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23008. ASSERT_EQ(StatusCode::OK_200, res->status);
  23009. // cli is destructed here with the keep-alive SSL session still open.
  23010. }
  23011. }
  23012. #endif
  23013. // WebSocket Tests
  23014. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23015. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23016. // defining the meaning of these bits has been negotiated.
  23017. auto make_frame = [](uint8_t first_byte) {
  23018. std::string frame;
  23019. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23020. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23021. frame += "Hello";
  23022. return frame;
  23023. };
  23024. // RSV1 set (0x40)
  23025. {
  23026. detail::BufferStream strm;
  23027. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23028. ws::Opcode opcode;
  23029. std::string payload;
  23030. bool fin;
  23031. EXPECT_EQ(
  23032. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23033. ws::impl::FrameRead::Fail);
  23034. }
  23035. // RSV2 set (0x20)
  23036. {
  23037. detail::BufferStream strm;
  23038. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23039. ws::Opcode opcode;
  23040. std::string payload;
  23041. bool fin;
  23042. EXPECT_EQ(
  23043. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23044. ws::impl::FrameRead::Fail);
  23045. }
  23046. // RSV3 set (0x10)
  23047. {
  23048. detail::BufferStream strm;
  23049. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23050. ws::Opcode opcode;
  23051. std::string payload;
  23052. bool fin;
  23053. EXPECT_EQ(
  23054. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23055. ws::impl::FrameRead::Fail);
  23056. }
  23057. // No RSV bits set - should succeed
  23058. {
  23059. detail::BufferStream strm;
  23060. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23061. ws::Opcode opcode;
  23062. std::string payload;
  23063. bool fin;
  23064. EXPECT_EQ(
  23065. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23066. ws::impl::FrameRead::Ok);
  23067. EXPECT_EQ(ws::Opcode::Text, opcode);
  23068. EXPECT_EQ("Hello", payload);
  23069. EXPECT_TRUE(fin);
  23070. }
  23071. }
  23072. TEST(WebSocketTest, ControlFrameValidation) {
  23073. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23074. // payload length <= 125.
  23075. // Ping with FIN=0 - must be rejected
  23076. {
  23077. detail::BufferStream strm;
  23078. std::string frame;
  23079. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23080. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23081. strm.write(frame.data(), frame.size());
  23082. ws::Opcode opcode;
  23083. std::string payload;
  23084. bool fin;
  23085. EXPECT_EQ(
  23086. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23087. ws::impl::FrameRead::Fail);
  23088. }
  23089. // Close with FIN=0 - must be rejected
  23090. {
  23091. detail::BufferStream strm;
  23092. std::string frame;
  23093. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23094. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23095. strm.write(frame.data(), frame.size());
  23096. ws::Opcode opcode;
  23097. std::string payload;
  23098. bool fin;
  23099. EXPECT_EQ(
  23100. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23101. ws::impl::FrameRead::Fail);
  23102. }
  23103. // Ping with payload_len=126 (extended length) - must be rejected
  23104. {
  23105. detail::BufferStream strm;
  23106. std::string frame;
  23107. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23108. frame += static_cast<char>(126); // payload_len=126 (>125)
  23109. frame += static_cast<char>(0x00); // extended length high byte
  23110. frame += static_cast<char>(126); // extended length low byte
  23111. frame += std::string(126, 'x');
  23112. strm.write(frame.data(), frame.size());
  23113. ws::Opcode opcode;
  23114. std::string payload;
  23115. bool fin;
  23116. EXPECT_EQ(
  23117. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23118. ws::impl::FrameRead::Fail);
  23119. }
  23120. // Ping with FIN=1 and payload_len=125 - should succeed
  23121. {
  23122. detail::BufferStream strm;
  23123. std::string frame;
  23124. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23125. frame += static_cast<char>(125); // payload_len=125
  23126. frame += std::string(125, 'x');
  23127. strm.write(frame.data(), frame.size());
  23128. ws::Opcode opcode;
  23129. std::string payload;
  23130. bool fin;
  23131. EXPECT_EQ(
  23132. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23133. ws::impl::FrameRead::Ok);
  23134. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23135. EXPECT_EQ(125u, payload.size());
  23136. EXPECT_TRUE(fin);
  23137. }
  23138. }
  23139. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23140. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23141. // length MUST be 0.
  23142. // MSB set - must be rejected
  23143. {
  23144. detail::BufferStream strm;
  23145. std::string frame;
  23146. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23147. frame += static_cast<char>(127); // 64-bit extended length
  23148. frame += static_cast<char>(0x80); // MSB set (invalid)
  23149. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23150. strm.write(frame.data(), frame.size());
  23151. ws::Opcode opcode;
  23152. std::string payload;
  23153. bool fin;
  23154. EXPECT_EQ(
  23155. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23156. ws::impl::FrameRead::Fail);
  23157. }
  23158. // MSB clear - should pass length parsing (will be rejected by max_len,
  23159. // but that's a different check; use a small length to verify)
  23160. {
  23161. detail::BufferStream strm;
  23162. std::string frame;
  23163. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23164. frame += static_cast<char>(127); // 64-bit extended length
  23165. frame += std::string(7, '\0'); // high bytes = 0
  23166. frame += static_cast<char>(0x03); // length = 3
  23167. frame += "abc";
  23168. strm.write(frame.data(), frame.size());
  23169. ws::Opcode opcode;
  23170. std::string payload;
  23171. bool fin;
  23172. EXPECT_EQ(
  23173. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23174. ws::impl::FrameRead::Ok);
  23175. EXPECT_EQ(ws::Opcode::Text, opcode);
  23176. EXPECT_EQ("abc", payload);
  23177. }
  23178. }
  23179. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23180. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23181. // Valid UTF-8
  23182. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23183. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23184. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23185. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23186. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23187. // Invalid UTF-8
  23188. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23189. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23190. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23191. EXPECT_FALSE(
  23192. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23193. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23194. }
  23195. TEST(WebSocketTest, ConnectAndDisconnect) {
  23196. Server svr;
  23197. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23198. std::string msg;
  23199. while (ws.read(msg)) {}
  23200. });
  23201. auto port = svr.bind_to_any_port(HOST);
  23202. std::thread t([&]() { svr.listen_after_bind(); });
  23203. svr.wait_until_ready();
  23204. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23205. auto res = client.connect();
  23206. ASSERT_TRUE(res);
  23207. EXPECT_EQ(Error::Success, res.error());
  23208. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23209. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23210. EXPECT_TRUE(client.is_open());
  23211. client.close();
  23212. EXPECT_FALSE(client.is_open());
  23213. svr.stop();
  23214. t.join();
  23215. }
  23216. TEST(WebSocketTest, ValidURL) {
  23217. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23218. EXPECT_TRUE(ws1.is_valid());
  23219. ws::WebSocketClient ws2("ws://example.com/path");
  23220. EXPECT_TRUE(ws2.is_valid());
  23221. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23222. EXPECT_TRUE(ws3.is_valid());
  23223. #ifdef CPPHTTPLIB_SSL_ENABLED
  23224. ws::WebSocketClient wss1("wss://example.com/path");
  23225. EXPECT_TRUE(wss1.is_valid());
  23226. ws::WebSocketClient wss2("wss://example.com:443/path");
  23227. EXPECT_TRUE(wss2.is_valid());
  23228. #endif
  23229. }
  23230. TEST(WebSocketTest, InvalidURL) {
  23231. // No scheme
  23232. ws::WebSocketClient ws1("localhost:8080/path");
  23233. EXPECT_FALSE(ws1.is_valid());
  23234. // No path
  23235. ws::WebSocketClient ws2("ws://localhost:8080");
  23236. EXPECT_FALSE(ws2.is_valid());
  23237. // Empty string
  23238. ws::WebSocketClient ws3("");
  23239. EXPECT_FALSE(ws3.is_valid());
  23240. // Missing host
  23241. ws::WebSocketClient ws4("ws://:8080/path");
  23242. EXPECT_FALSE(ws4.is_valid());
  23243. // Port number overflow — should not crash
  23244. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23245. EXPECT_FALSE(ws5.is_valid());
  23246. // Port out of range
  23247. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23248. EXPECT_FALSE(ws6.is_valid());
  23249. }
  23250. TEST(WebSocketTest, UnsupportedScheme) {
  23251. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23252. ws::WebSocketClient ws1("http://localhost:8080/path");
  23253. EXPECT_FALSE(ws1.is_valid());
  23254. ws::WebSocketClient ws2("https://localhost:8080/path");
  23255. EXPECT_FALSE(ws2.is_valid());
  23256. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23257. EXPECT_FALSE(ws3.is_valid());
  23258. #else
  23259. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23260. std::invalid_argument);
  23261. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23262. std::invalid_argument);
  23263. #endif
  23264. }
  23265. TEST(WebSocketTest, ConnectWhenInvalid) {
  23266. ws::WebSocketClient ws("not a valid url");
  23267. EXPECT_FALSE(ws.is_valid());
  23268. auto res = ws.connect();
  23269. EXPECT_FALSE(res);
  23270. EXPECT_EQ(Error::Connection, res.error());
  23271. EXPECT_EQ(-1, res.status());
  23272. }
  23273. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23274. // Grab a port that is free, then close it again so nothing listens there
  23275. Server svr;
  23276. auto port = svr.bind_to_any_port(HOST);
  23277. svr.stop();
  23278. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23279. auto res = client.connect();
  23280. ASSERT_FALSE(res);
  23281. EXPECT_EQ(Error::Connection, res.error());
  23282. EXPECT_EQ(-1, res.status());
  23283. }
  23284. TEST(WebSocketTest, DefaultPort) {
  23285. ws::WebSocketClient ws1("ws://example.com/path");
  23286. EXPECT_TRUE(ws1.is_valid());
  23287. // ws:// defaults to port 80 (verified by successful parse)
  23288. #ifdef CPPHTTPLIB_SSL_ENABLED
  23289. ws::WebSocketClient ws2("wss://example.com/path");
  23290. EXPECT_TRUE(ws2.is_valid());
  23291. // wss:// defaults to port 443 (verified by successful parse)
  23292. #endif
  23293. }
  23294. TEST(WebSocketTest, IPv6LiteralAddress) {
  23295. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23296. EXPECT_TRUE(ws1.is_valid());
  23297. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23298. EXPECT_TRUE(ws2.is_valid());
  23299. }
  23300. TEST(WebSocketTest, ComplexPath) {
  23301. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23302. EXPECT_TRUE(ws1.is_valid());
  23303. ws::WebSocketClient ws2("ws://localhost:8080/");
  23304. EXPECT_TRUE(ws2.is_valid());
  23305. }
  23306. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23307. Server svr;
  23308. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23309. std::string msg;
  23310. while (ws.read(msg)) {}
  23311. });
  23312. auto port = svr.bind_to_any_port(HOST);
  23313. std::thread t([&]() { svr.listen_after_bind(); });
  23314. svr.wait_until_ready();
  23315. auto another_host = "example.com";
  23316. auto wrong_ip = "192.0.2.1";
  23317. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23318. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23319. ASSERT_TRUE(client.connect());
  23320. EXPECT_TRUE(client.is_open());
  23321. client.close();
  23322. svr.stop();
  23323. t.join();
  23324. }
  23325. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23326. Server svr;
  23327. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23328. std::string msg;
  23329. while (ws.read(msg)) {}
  23330. });
  23331. auto port = svr.bind_to_any_port(HOST);
  23332. std::thread t([&]() { svr.listen_after_bind(); });
  23333. svr.wait_until_ready();
  23334. auto wrong_ip = "192.0.2.1";
  23335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23336. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23337. client.set_connection_timeout(1);
  23338. client.set_read_timeout(1);
  23339. client.set_write_timeout(1);
  23340. EXPECT_FALSE(client.connect());
  23341. EXPECT_FALSE(client.is_open());
  23342. svr.stop();
  23343. t.join();
  23344. }
  23345. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23346. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23347. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23348. // (RFC 6761) is only a map key and the Host header value.
  23349. auto host = "target.invalid";
  23350. Server svr;
  23351. std::string received_host;
  23352. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23353. received_host = req.get_header_value("Host");
  23354. std::string msg;
  23355. while (ws.read(msg)) {}
  23356. });
  23357. auto port = svr.bind_to_any_port(HOST);
  23358. std::thread t([&]() { svr.listen_after_bind(); });
  23359. // ASSERT_* below returns from the test body, which would leave t joinable
  23360. // and make ~thread call std::terminate.
  23361. auto se = detail::scope_exit([&] {
  23362. svr.stop();
  23363. if (t.joinable()) { t.join(); }
  23364. });
  23365. svr.wait_until_ready();
  23366. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23367. std::to_string(port) + "/ws");
  23368. client.set_hostname_addr_map({{host, HOST}});
  23369. ASSERT_TRUE(client.connect());
  23370. EXPECT_TRUE(client.is_open());
  23371. client.close();
  23372. svr.stop();
  23373. t.join();
  23374. // The mapping only redirects the connection; the identity stays host_.
  23375. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23376. }
  23377. class WebSocketIntegrationTest : public ::testing::Test {
  23378. protected:
  23379. void SetUp() override {
  23380. server_ = httplib::detail::make_unique<Server>();
  23381. setup_server();
  23382. start_server();
  23383. }
  23384. void TearDown() override {
  23385. server_->stop();
  23386. if (server_thread_.joinable()) { server_thread_.join(); }
  23387. }
  23388. void setup_server() {
  23389. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23390. std::string msg;
  23391. ws::ReadResult ret;
  23392. while ((ret = ws.read(msg))) {
  23393. if (ret == ws::Binary) {
  23394. ws.send(msg.data(), msg.size());
  23395. } else {
  23396. ws.send(msg);
  23397. }
  23398. }
  23399. });
  23400. server_->WebSocket("/ws-echo-string",
  23401. [](const Request &, ws::WebSocket &ws) {
  23402. std::string msg;
  23403. while (ws.read(msg)) {
  23404. ws.send("echo: " + msg);
  23405. }
  23406. });
  23407. server_->WebSocket(
  23408. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23409. // Echo back request metadata
  23410. ws.send("path:" + req.path);
  23411. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23412. std::string msg;
  23413. while (ws.read(msg)) {}
  23414. });
  23415. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23416. std::string msg;
  23417. ws.read(msg); // wait for a message
  23418. ws.close();
  23419. });
  23420. server_->WebSocket("/ws-close-status",
  23421. [](const Request &, ws::WebSocket &ws) {
  23422. std::string msg;
  23423. ws.read(msg); // wait for a message
  23424. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23425. });
  23426. server_->WebSocket(
  23427. "/ws-subprotocol",
  23428. [](const Request &, ws::WebSocket &ws) {
  23429. std::string msg;
  23430. while (ws.read(msg)) {
  23431. ws.send(msg);
  23432. }
  23433. },
  23434. [](const std::vector<std::string> &protocols) -> std::string {
  23435. for (const auto &p : protocols) {
  23436. if (p == "graphql-ws") { return p; }
  23437. }
  23438. return "";
  23439. });
  23440. server_->WebSocket(
  23441. "/ws-subprotocol-unoffered",
  23442. [](const Request &, ws::WebSocket &ws) {
  23443. std::string msg;
  23444. while (ws.read(msg)) {
  23445. ws.send(msg);
  23446. }
  23447. },
  23448. [](const std::vector<std::string> &) -> std::string {
  23449. return "admin";
  23450. });
  23451. }
  23452. void start_server() {
  23453. port_ = server_->bind_to_any_port(HOST);
  23454. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23455. server_->wait_until_ready();
  23456. }
  23457. std::unique_ptr<Server> server_;
  23458. std::thread server_thread_;
  23459. int port_ = 0;
  23460. };
  23461. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23462. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23463. "/ws-echo");
  23464. ASSERT_TRUE(client.connect());
  23465. ASSERT_TRUE(client.is_open());
  23466. ASSERT_TRUE(client.send("Hello WebSocket"));
  23467. std::string msg;
  23468. EXPECT_EQ(ws::Text, client.read(msg));
  23469. EXPECT_EQ("Hello WebSocket", msg);
  23470. client.close();
  23471. }
  23472. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23473. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23474. "/ws-echo");
  23475. ASSERT_TRUE(client.connect());
  23476. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23477. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23478. std::string msg;
  23479. EXPECT_EQ(ws::Binary, client.read(msg));
  23480. EXPECT_EQ(binary_data, msg);
  23481. client.close();
  23482. }
  23483. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23484. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23485. "/ws-echo");
  23486. ASSERT_TRUE(client.connect());
  23487. for (int i = 0; i < 10; i++) {
  23488. auto text = "message " + std::to_string(i);
  23489. ASSERT_TRUE(client.send(text));
  23490. std::string msg;
  23491. ASSERT_TRUE(client.read(msg));
  23492. EXPECT_EQ(text, msg);
  23493. }
  23494. client.close();
  23495. }
  23496. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23497. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23498. "/ws-close");
  23499. ASSERT_TRUE(client.connect());
  23500. // Send a message to trigger the server to close
  23501. ASSERT_TRUE(client.send("trigger close"));
  23502. // The server will close, so read should return false
  23503. std::string msg;
  23504. EXPECT_FALSE(client.read(msg));
  23505. EXPECT_FALSE(client.is_open());
  23506. }
  23507. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23508. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23509. "/ws-echo");
  23510. ASSERT_TRUE(client.connect());
  23511. // 128KB message
  23512. std::string large_data(128 * 1024, 'X');
  23513. ASSERT_TRUE(client.send(large_data));
  23514. std::string msg;
  23515. ASSERT_TRUE(client.read(msg));
  23516. EXPECT_EQ(large_data, msg);
  23517. client.close();
  23518. }
  23519. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23520. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23521. "/ws-echo");
  23522. ASSERT_TRUE(client.connect());
  23523. const int num_threads = 4;
  23524. std::vector<std::thread> threads;
  23525. std::atomic<int> send_count{0};
  23526. for (int t = 0; t < num_threads; t++) {
  23527. threads.emplace_back([&client, &send_count, t]() {
  23528. for (int i = 0; i < 5; i++) {
  23529. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23530. if (client.send(text)) { send_count++; }
  23531. }
  23532. });
  23533. }
  23534. for (auto &th : threads) {
  23535. th.join();
  23536. }
  23537. int received = 0;
  23538. std::string msg;
  23539. while (received < send_count.load()) {
  23540. if (!client.read(msg)) { break; }
  23541. received++;
  23542. }
  23543. EXPECT_EQ(send_count.load(), received);
  23544. client.close();
  23545. }
  23546. TEST_F(WebSocketIntegrationTest, ReadString) {
  23547. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23548. "/ws-echo-string");
  23549. ASSERT_TRUE(client.connect());
  23550. ASSERT_TRUE(client.send("hello"));
  23551. std::string msg;
  23552. ASSERT_TRUE(client.read(msg));
  23553. EXPECT_EQ("echo: hello", msg);
  23554. ASSERT_TRUE(client.send("world"));
  23555. ASSERT_TRUE(client.read(msg));
  23556. EXPECT_EQ("echo: world", msg);
  23557. client.close();
  23558. }
  23559. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23560. Headers headers = {{"X-Test-Header", "test-value"}};
  23561. ws::WebSocketClient client(
  23562. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23563. ASSERT_TRUE(client.connect());
  23564. std::string msg;
  23565. ASSERT_TRUE(client.read(msg));
  23566. EXPECT_EQ("path:/ws-request-info", msg);
  23567. ASSERT_TRUE(client.read(msg));
  23568. EXPECT_EQ("header:test-value", msg);
  23569. client.close();
  23570. }
  23571. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23572. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23573. "/ws-echo");
  23574. client.set_read_timeout(1, 0); // 1 second
  23575. ASSERT_TRUE(client.connect());
  23576. // Don't send anything — server echo handler waits for a message, so read()
  23577. // should time out. The connection survives it: nothing was consumed.
  23578. std::string msg;
  23579. EXPECT_EQ(client.read(msg), ws::Timeout);
  23580. EXPECT_TRUE(client.is_open());
  23581. // And it is still usable afterwards.
  23582. EXPECT_TRUE(client.send("after timeout"));
  23583. EXPECT_EQ(client.read(msg), ws::Text);
  23584. EXPECT_EQ(msg, "after timeout");
  23585. }
  23586. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23587. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23588. "/ws-echo");
  23589. client.set_read_timeout(1, 0);
  23590. ASSERT_TRUE(client.connect());
  23591. ASSERT_TRUE(client.send("first"));
  23592. std::string msg;
  23593. ASSERT_EQ(client.read(msg), ws::Text);
  23594. ASSERT_EQ(msg, "first");
  23595. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23596. // not be used with a read timeout: it would reprocess the previous message.
  23597. EXPECT_EQ(client.read(msg), ws::Timeout);
  23598. EXPECT_EQ(msg, "first");
  23599. }
  23600. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23601. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23602. "/ws-echo");
  23603. ASSERT_TRUE(client.connect());
  23604. // Setting it once the connection is open reaches the live stream, not just
  23605. // the seed for the next connect().
  23606. client.set_read_timeout(1, 0);
  23607. std::string msg;
  23608. EXPECT_EQ(client.read(msg), ws::Timeout);
  23609. EXPECT_TRUE(client.is_open());
  23610. }
  23611. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23612. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23613. "/ws-echo");
  23614. client.set_read_timeout(5, 0);
  23615. ASSERT_TRUE(client.connect());
  23616. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23617. // The server should reject it and close the connection.
  23618. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23619. client.send(oversized);
  23620. // The server's read() should have failed due to payload limit,
  23621. // so our read() should return false (connection closed).
  23622. std::string msg;
  23623. EXPECT_FALSE(client.read(msg));
  23624. }
  23625. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23626. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23627. "/ws-echo");
  23628. client.set_read_timeout(10, 0);
  23629. ASSERT_TRUE(client.connect());
  23630. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23631. // This should succeed.
  23632. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23633. ASSERT_TRUE(client.send(at_limit));
  23634. std::string msg;
  23635. ASSERT_TRUE(client.read(msg));
  23636. EXPECT_EQ(at_limit.size(), msg.size());
  23637. client.close();
  23638. }
  23639. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23640. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23641. "/nonexistent");
  23642. auto res = client.connect();
  23643. EXPECT_FALSE(res);
  23644. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23645. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23646. EXPECT_FALSE(client.is_open());
  23647. }
  23648. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23649. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23650. "/ws-echo");
  23651. ASSERT_TRUE(client.connect());
  23652. ASSERT_TRUE(client.send(""));
  23653. std::string msg;
  23654. EXPECT_EQ(ws::Text, client.read(msg));
  23655. EXPECT_EQ("", msg);
  23656. client.close();
  23657. }
  23658. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23660. "/ws-echo");
  23661. // First connection
  23662. ASSERT_TRUE(client.connect());
  23663. ASSERT_TRUE(client.send("first"));
  23664. std::string msg;
  23665. ASSERT_TRUE(client.read(msg));
  23666. EXPECT_EQ("first", msg);
  23667. client.close();
  23668. EXPECT_FALSE(client.is_open());
  23669. // Reconnect using the same client object
  23670. ASSERT_TRUE(client.connect());
  23671. ASSERT_TRUE(client.is_open());
  23672. ASSERT_TRUE(client.send("second"));
  23673. ASSERT_TRUE(client.read(msg));
  23674. EXPECT_EQ("second", msg);
  23675. client.close();
  23676. }
  23677. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23678. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23679. "/ws-close-status");
  23680. ASSERT_TRUE(client.connect());
  23681. // Trigger the server to close with GoingAway status
  23682. ASSERT_TRUE(client.send("trigger"));
  23683. // read() should return false after receiving the close frame
  23684. std::string msg;
  23685. EXPECT_FALSE(client.read(msg));
  23686. EXPECT_FALSE(client.is_open());
  23687. }
  23688. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23689. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23690. "/ws-echo");
  23691. ASSERT_TRUE(client.connect());
  23692. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23693. EXPECT_FALSE(client.is_open());
  23694. }
  23695. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23696. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23697. ws::WebSocketClient client(
  23698. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23699. ASSERT_TRUE(client.connect());
  23700. // Server should have selected graphql-ws
  23701. EXPECT_EQ("graphql-ws", client.subprotocol());
  23702. client.close();
  23703. }
  23704. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23705. Headers headers;
  23706. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23707. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23708. ws::WebSocketClient client(
  23709. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23710. ASSERT_TRUE(client.connect());
  23711. // The offer on the second field line counts too, so graphql-ws is selected
  23712. EXPECT_EQ("graphql-ws", client.subprotocol());
  23713. client.close();
  23714. }
  23715. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23716. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23717. ws::WebSocketClient client(
  23718. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23719. ASSERT_TRUE(client.connect());
  23720. // Server should not have selected any subprotocol
  23721. EXPECT_TRUE(client.subprotocol().empty());
  23722. client.close();
  23723. }
  23724. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23725. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23726. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23727. "/ws-subprotocol-unoffered",
  23728. headers);
  23729. ASSERT_TRUE(client.connect());
  23730. EXPECT_TRUE(client.subprotocol().empty());
  23731. client.close();
  23732. }
  23733. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23734. // Connect without requesting any subprotocol
  23735. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23736. "/ws-subprotocol");
  23737. ASSERT_TRUE(client.connect());
  23738. EXPECT_TRUE(client.subprotocol().empty());
  23739. client.close();
  23740. }
  23741. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23742. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23743. "/ws-echo");
  23744. client.set_tcp_nodelay(true);
  23745. client.set_connection_timeout(3, 0);
  23746. bool socket_options_called = false;
  23747. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23748. ASSERT_TRUE(client.connect());
  23749. ASSERT_TRUE(client.is_open());
  23750. EXPECT_TRUE(socket_options_called);
  23751. ASSERT_TRUE(client.send("hello"));
  23752. std::string msg;
  23753. auto result = client.read(msg);
  23754. EXPECT_EQ(result, ws::ReadResult::Text);
  23755. EXPECT_EQ(msg, "hello");
  23756. client.close();
  23757. }
  23758. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23760. "/ws-echo");
  23761. client.set_connection_timeout(std::chrono::seconds(3));
  23762. client.set_write_timeout(std::chrono::seconds(3));
  23763. // A sub-second remainder exercises the seconds/microseconds split.
  23764. client.set_read_timeout(std::chrono::milliseconds(1500));
  23765. ASSERT_TRUE(client.connect());
  23766. auto start = std::chrono::steady_clock::now();
  23767. std::string msg;
  23768. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23769. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23770. std::chrono::steady_clock::now() - start)
  23771. .count();
  23772. // Above 1s so that dropping the microseconds half of the split fails here.
  23773. // Ignoring the setter altogether would not reach this line at all: a client
  23774. // waits forever by default.
  23775. EXPECT_GE(elapsed, 1400);
  23776. EXPECT_LT(elapsed, 30000);
  23777. }
  23778. #ifndef _WIN32
  23779. // A send() that times out after part of the data went out returns the count
  23780. // written so far. Every byte of the frame must still be sent, or the peer reads
  23781. // the next frame's header and payload as the rest of this one.
  23782. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  23783. signal(SIGPIPE, SIG_IGN);
  23784. const std::string large(4 * 1024 * 1024, 'A');
  23785. std::atomic<bool> large_sent{false};
  23786. std::atomic<bool> small_sent{false};
  23787. Server svr;
  23788. svr.set_write_timeout(0, 500000);
  23789. svr.set_socket_options([](socket_t sock) {
  23790. int size = 8192;
  23791. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  23792. reinterpret_cast<const char *>(&size), sizeof(size));
  23793. });
  23794. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23795. large_sent = ws.send(large.data(), large.size());
  23796. small_sent = ws.send("after");
  23797. std::string msg;
  23798. while (ws.read(msg)) {}
  23799. });
  23800. auto port = svr.bind_to_any_port(HOST);
  23801. std::thread t([&]() { svr.listen_after_bind(); });
  23802. auto se = detail::scope_exit([&] {
  23803. svr.stop();
  23804. t.join();
  23805. });
  23806. svr.wait_until_ready();
  23807. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  23808. std::to_string(port) + "/ws");
  23809. client.set_read_timeout(5);
  23810. client.set_socket_options([](socket_t sock) {
  23811. int size = 8192;
  23812. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  23813. reinterpret_cast<const char *>(&size), sizeof(size));
  23814. });
  23815. ASSERT_TRUE(client.connect());
  23816. // Outlast the server's write timeout, then drain.
  23817. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  23818. std::string msg;
  23819. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  23820. EXPECT_TRUE(msg == large);
  23821. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  23822. EXPECT_EQ("after", msg);
  23823. EXPECT_TRUE(large_sent);
  23824. EXPECT_TRUE(small_sent);
  23825. client.close();
  23826. }
  23827. #endif
  23828. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23829. Server svr;
  23830. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23831. if (!req.has_header("Authorization")) {
  23832. res.status = StatusCode::Unauthorized_401;
  23833. res.set_content("Unauthorized", "text/plain");
  23834. return Server::HandlerResponse::Handled;
  23835. }
  23836. return Server::HandlerResponse::Unhandled;
  23837. });
  23838. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23839. std::string msg;
  23840. while (ws.read(msg)) {
  23841. ws.send(msg);
  23842. }
  23843. });
  23844. auto port = svr.bind_to_any_port("localhost");
  23845. std::thread t([&]() { svr.listen_after_bind(); });
  23846. svr.wait_until_ready();
  23847. // Without Authorization header - should be rejected before upgrade
  23848. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23849. EXPECT_FALSE(client1.connect());
  23850. // The rejection is framed like any other HTTP response
  23851. {
  23852. Client cli("localhost", port);
  23853. Headers headers = {{"Upgrade", "websocket"},
  23854. {"Connection", "Upgrade"},
  23855. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23856. {"Sec-WebSocket-Version", "13"}};
  23857. auto res = cli.Get("/ws", headers);
  23858. ASSERT_TRUE(res);
  23859. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23860. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23861. EXPECT_EQ("Unauthorized", res->body);
  23862. }
  23863. // With Authorization header - should succeed
  23864. Headers headers = {{"Authorization", "Bearer token123"}};
  23865. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23866. headers);
  23867. ASSERT_TRUE(client2.connect());
  23868. ASSERT_TRUE(client2.send("hello"));
  23869. std::string msg;
  23870. ASSERT_TRUE(client2.read(msg));
  23871. EXPECT_EQ("hello", msg);
  23872. client2.close();
  23873. svr.stop();
  23874. t.join();
  23875. }
  23876. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23877. Server svr;
  23878. std::atomic<int> pre_routing_calls{0};
  23879. std::atomic<int> pre_request_calls{0};
  23880. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23881. pre_routing_calls++;
  23882. if (req.path == "/handled") {
  23883. res.set_content("handled", "text/plain");
  23884. return Server::HandlerResponse::Handled;
  23885. }
  23886. return Server::HandlerResponse::Unhandled;
  23887. });
  23888. svr.set_pre_request_handler([&](const Request &, Response &) {
  23889. pre_request_calls++;
  23890. return Server::HandlerResponse::Unhandled;
  23891. });
  23892. svr.Get("/http", [](const Request &, Response &res) {
  23893. res.set_content("http", "text/plain");
  23894. });
  23895. svr.WebSocket("/ws",
  23896. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23897. auto port = svr.bind_to_any_port("localhost");
  23898. std::thread t([&]() { svr.listen_after_bind(); });
  23899. auto se = detail::scope_exit([&] {
  23900. svr.stop();
  23901. t.join();
  23902. });
  23903. svr.wait_until_ready();
  23904. Headers upgrade = {{"Upgrade", "websocket"},
  23905. {"Connection", "Upgrade"},
  23906. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23907. {"Sec-WebSocket-Version", "13"}};
  23908. auto get = [&](const char *path) {
  23909. pre_routing_calls = 0;
  23910. return Client("localhost", port).Get(path, upgrade);
  23911. };
  23912. // No WebSocket route, but an HTTP one
  23913. auto res = get("/http");
  23914. ASSERT_TRUE(res);
  23915. EXPECT_EQ(StatusCode::OK_200, res->status);
  23916. EXPECT_EQ("http", res->body);
  23917. EXPECT_EQ(1, pre_routing_calls);
  23918. EXPECT_EQ(1, pre_request_calls);
  23919. // No route at all
  23920. res = get("/none");
  23921. ASSERT_TRUE(res);
  23922. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23923. EXPECT_EQ(1, pre_routing_calls);
  23924. // Answered by the pre-routing handler
  23925. res = get("/handled");
  23926. ASSERT_TRUE(res);
  23927. EXPECT_EQ(StatusCode::OK_200, res->status);
  23928. EXPECT_EQ("handled", res->body);
  23929. EXPECT_EQ(1, pre_routing_calls);
  23930. // A WebSocket route
  23931. pre_routing_calls = 0;
  23932. pre_request_calls = 0;
  23933. {
  23934. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23935. "/ws");
  23936. ASSERT_TRUE(client.connect());
  23937. std::string msg;
  23938. ASSERT_TRUE(client.read(msg));
  23939. EXPECT_EQ("ws", msg);
  23940. client.close();
  23941. }
  23942. EXPECT_EQ(1, pre_routing_calls);
  23943. EXPECT_EQ(1, pre_request_calls);
  23944. }
  23945. // An upgrade request answered by a hook leaves its body unread, so that body
  23946. // must not be served as the next request on the connection.
  23947. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23948. Server svr;
  23949. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23950. if (req.path == "/pre-routing") {
  23951. res.set_content("pre-routing", "text/plain");
  23952. return Server::HandlerResponse::Handled;
  23953. }
  23954. return Server::HandlerResponse::Unhandled;
  23955. });
  23956. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23957. if (req.matched_route == "/pre-request") {
  23958. res.set_content("pre-request", "text/plain");
  23959. return Server::HandlerResponse::Handled;
  23960. }
  23961. return Server::HandlerResponse::Unhandled;
  23962. });
  23963. svr.Get("/smuggled", [](const Request &, Response &res) {
  23964. res.set_content("smuggled", "text/plain");
  23965. });
  23966. svr.WebSocket("/pre-request",
  23967. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23968. auto port = svr.bind_to_any_port(HOST);
  23969. std::thread t([&]() { svr.listen_after_bind(); });
  23970. auto se = detail::scope_exit([&] {
  23971. svr.stop();
  23972. t.join();
  23973. });
  23974. svr.wait_until_ready();
  23975. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23976. for (auto path : {"/pre-routing", "/pre-request"}) {
  23977. std::string req = std::string("GET ") + path +
  23978. " HTTP/1.1\r\n"
  23979. "Host: localhost\r\n"
  23980. "Upgrade: websocket\r\n"
  23981. "Connection: Upgrade\r\n"
  23982. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23983. "Sec-WebSocket-Version: 13\r\n"
  23984. "Content-Length: " +
  23985. std::to_string(body.size()) + "\r\n\r\n" + body;
  23986. std::string res;
  23987. ASSERT_TRUE(send_request(5, req, &res, port));
  23988. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23989. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23990. // Only one response, and the body was not served as a request
  23991. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23992. }
  23993. }
  23994. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23995. Server svr;
  23996. std::atomic<int> pre_request_calls{0};
  23997. std::atomic<bool> route_matched{false};
  23998. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23999. pre_request_calls++;
  24000. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24001. if (req.get_header_value("Authorization") != "Bearer token123") {
  24002. res.status = StatusCode::Unauthorized_401;
  24003. res.set_content("Unauthorized", "text/plain");
  24004. return Server::HandlerResponse::Handled;
  24005. }
  24006. return Server::HandlerResponse::Unhandled;
  24007. });
  24008. std::atomic<bool> handler_called{false};
  24009. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24010. handler_called = true;
  24011. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24012. });
  24013. auto port = svr.bind_to_any_port("localhost");
  24014. std::thread t([&]() { svr.listen_after_bind(); });
  24015. svr.wait_until_ready();
  24016. // Without Authorization header - should be rejected before upgrade
  24017. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24018. "/ws/1");
  24019. EXPECT_FALSE(client1.connect());
  24020. EXPECT_FALSE(handler_called);
  24021. EXPECT_EQ(1, pre_request_calls);
  24022. EXPECT_TRUE(route_matched);
  24023. // The rejection is an ordinary HTTP response, not a protocol switch
  24024. {
  24025. Client cli("localhost", port);
  24026. Headers headers = {{"Upgrade", "websocket"},
  24027. {"Connection", "Upgrade"},
  24028. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24029. {"Sec-WebSocket-Version", "13"}};
  24030. auto res = cli.Get("/ws/1", headers);
  24031. ASSERT_TRUE(res);
  24032. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24033. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24034. EXPECT_EQ("Unauthorized", res->body);
  24035. }
  24036. EXPECT_FALSE(handler_called);
  24037. // With Authorization header - should succeed
  24038. Headers headers = {{"Authorization", "Bearer token123"}};
  24039. ws::WebSocketClient client2(
  24040. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24041. ASSERT_TRUE(client2.connect());
  24042. std::string msg;
  24043. ASSERT_TRUE(client2.read(msg));
  24044. EXPECT_EQ("/ws/:id 2", msg);
  24045. EXPECT_TRUE(handler_called);
  24046. client2.close();
  24047. svr.stop();
  24048. t.join();
  24049. }
  24050. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24051. static Headers websocket_upgrade_headers() {
  24052. return {{"Upgrade", "websocket"},
  24053. {"Connection", "Upgrade"},
  24054. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24055. {"Sec-WebSocket-Version", "13"},
  24056. {"Sec-WebSocket-Protocol", "chat"}};
  24057. }
  24058. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24059. Server svr;
  24060. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24061. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24062. return Server::HandlerResponse::Unhandled;
  24063. });
  24064. svr.set_pre_request_handler([](const Request &req, Response &) {
  24065. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24066. return Server::HandlerResponse::Unhandled;
  24067. });
  24068. svr.set_exception_handler(
  24069. [](const Request &, Response &res, std::exception_ptr ep) {
  24070. try {
  24071. std::rethrow_exception(ep);
  24072. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24073. });
  24074. auto handler = [](const Request &, ws::WebSocket &) {};
  24075. svr.WebSocket("/pre-routing", handler);
  24076. svr.WebSocket("/pre-request", handler);
  24077. svr.WebSocket("/sub-protocol", handler,
  24078. [](const std::vector<std::string> &) -> std::string {
  24079. throw std::runtime_error("/sub-protocol");
  24080. });
  24081. auto port = svr.bind_to_any_port(HOST);
  24082. ASSERT_GT(port, 0);
  24083. thread t = thread([&] { svr.listen_after_bind(); });
  24084. auto se = detail::scope_exit([&] {
  24085. svr.stop();
  24086. t.join();
  24087. ASSERT_FALSE(svr.is_running());
  24088. });
  24089. svr.wait_until_ready();
  24090. Client cli(HOST, port);
  24091. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24092. auto res = cli.Get(path, websocket_upgrade_headers());
  24093. if (!res) {
  24094. ADD_FAILURE() << path << ": " << to_string(res.error());
  24095. continue;
  24096. }
  24097. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24098. EXPECT_EQ(path, res->body);
  24099. }
  24100. }
  24101. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24102. Server svr;
  24103. svr.set_pre_routing_handler(
  24104. [](const Request &, Response &) -> Server::HandlerResponse {
  24105. throw std::runtime_error("pre-routing");
  24106. });
  24107. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24108. auto port = svr.bind_to_any_port(HOST);
  24109. ASSERT_GT(port, 0);
  24110. thread t = thread([&] { svr.listen_after_bind(); });
  24111. auto se = detail::scope_exit([&] {
  24112. svr.stop();
  24113. t.join();
  24114. ASSERT_FALSE(svr.is_running());
  24115. });
  24116. svr.wait_until_ready();
  24117. Client cli(HOST, port);
  24118. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24119. ASSERT_TRUE(res) << to_string(res.error());
  24120. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24121. }
  24122. #endif
  24123. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24124. Server svr;
  24125. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24126. // A read timeout is how a handler gets control back. Without it, a handler
  24127. // parked in read() can never write on the connection it is reading.
  24128. ws.set_read_timeout(std::chrono::milliseconds(100));
  24129. std::string msg;
  24130. while (ws.is_open()) {
  24131. auto r = ws.read(msg);
  24132. if (r == httplib::ws::Timeout) {
  24133. ws.send("tick");
  24134. continue;
  24135. }
  24136. if (r == httplib::ws::Fail) { break; }
  24137. ws.send(msg);
  24138. }
  24139. });
  24140. auto port = svr.bind_to_any_port("localhost");
  24141. std::thread t([&]() { svr.listen_after_bind(); });
  24142. svr.wait_until_ready();
  24143. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24144. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24145. ASSERT_TRUE(client.connect());
  24146. // The client sends nothing, so anything it receives came out of the
  24147. // handler's timeout path.
  24148. std::string msg;
  24149. ASSERT_EQ(client.read(msg), ws::Text);
  24150. EXPECT_EQ("tick", msg);
  24151. client.close();
  24152. svr.stop();
  24153. t.join();
  24154. }
  24155. // Stream::read may return fewer bytes than asked for. This is that contract at
  24156. // its worst -- one byte per call -- which is what a frame header straddling a
  24157. // read buffer's boundary looks like to the frame parser.
  24158. class WsByteAtATimeStream : public Stream {
  24159. public:
  24160. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24161. bool is_readable() const override { return true; }
  24162. bool wait_readable() const override { return true; }
  24163. bool wait_writable() const override { return true; }
  24164. ssize_t read(char *ptr, size_t size) override {
  24165. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24166. *ptr = data_[pos_++];
  24167. return 1;
  24168. }
  24169. ssize_t write(const char *, size_t size) override {
  24170. return static_cast<ssize_t>(size);
  24171. }
  24172. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24173. ip = "127.0.0.1";
  24174. port = 0;
  24175. }
  24176. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24177. ip = "127.0.0.1";
  24178. port = 0;
  24179. }
  24180. socket_t socket() const override { return INVALID_SOCKET; }
  24181. time_t duration() const override { return 0; }
  24182. private:
  24183. std::string data_;
  24184. size_t pos_ = 0;
  24185. };
  24186. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24187. // The payload uses the 16-bit extended length, so the header, the length
  24188. // and the mask key are all multi-byte fields here. Each used to be read
  24189. // with a single read() call, which fails as soon as one is split. The
  24190. // payload is also a little over one read chunk, so it is read in two.
  24191. std::string body;
  24192. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24193. body += static_cast<char>(i % 251);
  24194. }
  24195. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24196. std::string frame;
  24197. frame += static_cast<char>(0x81); // FIN + Text
  24198. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24199. frame += static_cast<char>(body.size() >> 8);
  24200. frame += static_cast<char>(body.size() & 0xff);
  24201. for (size_t i = 0; i < 4; i++) {
  24202. frame += static_cast<char>(mask[i]);
  24203. }
  24204. for (size_t i = 0; i < body.size(); i++) {
  24205. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24206. }
  24207. WsByteAtATimeStream strm(frame);
  24208. ws::Opcode opcode;
  24209. std::string payload;
  24210. bool fin = false;
  24211. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24212. /*expect_masked=*/true, body.size()),
  24213. ws::impl::FrameRead::Ok);
  24214. EXPECT_TRUE(fin);
  24215. EXPECT_EQ(opcode, ws::Opcode::Text);
  24216. EXPECT_EQ(payload, body);
  24217. }
  24218. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24219. std::string body(2000, 'x');
  24220. std::string frame;
  24221. frame += static_cast<char>(0x82); // FIN + Binary
  24222. frame += static_cast<char>(126); // 16-bit length follows
  24223. frame += static_cast<char>(body.size() >> 8);
  24224. frame += static_cast<char>(body.size() & 0xff);
  24225. frame += body;
  24226. detail::BufferStream strm;
  24227. strm.write(frame.data(), frame.size());
  24228. ws::Opcode opcode;
  24229. std::string payload;
  24230. bool fin;
  24231. EXPECT_EQ(
  24232. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24233. ws::impl::FrameRead::Ok);
  24234. EXPECT_EQ(body, payload);
  24235. }
  24236. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24237. // The header announces the largest payload allowed, and only 3 bytes of it
  24238. // ever arrive.
  24239. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24240. std::string frame;
  24241. frame += static_cast<char>(0x82); // FIN + Binary
  24242. frame += static_cast<char>(127); // 64-bit length follows
  24243. for (int shift = 56; shift >= 0; shift -= 8) {
  24244. frame += static_cast<char>((len >> shift) & 0xff);
  24245. }
  24246. frame += "abc";
  24247. detail::BufferStream strm;
  24248. strm.write(frame.data(), frame.size());
  24249. ws::Opcode opcode;
  24250. std::string payload;
  24251. bool fin;
  24252. EXPECT_EQ(
  24253. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24254. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24255. ws::impl::FrameRead::Fail);
  24256. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24257. }
  24258. TEST(WebSocketTest, QueryStringInHandshake) {
  24259. Server svr;
  24260. std::mutex mtx;
  24261. std::string received_target;
  24262. std::string received_token;
  24263. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24264. {
  24265. std::lock_guard<std::mutex> lock(mtx);
  24266. received_target = req.target;
  24267. if (req.has_param("token")) {
  24268. received_token = req.get_param_value("token");
  24269. }
  24270. }
  24271. std::string msg;
  24272. while (ws.read(msg)) {
  24273. ws.send(msg);
  24274. }
  24275. });
  24276. auto port = svr.bind_to_any_port("localhost");
  24277. std::thread t([&]() { svr.listen_after_bind(); });
  24278. svr.wait_until_ready();
  24279. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24280. "/ws?token=ABC&session=123");
  24281. ASSERT_TRUE(client.connect());
  24282. // Round-trip ensures the handler has run and captured the request.
  24283. ASSERT_TRUE(client.send("hello"));
  24284. std::string msg;
  24285. ASSERT_TRUE(client.read(msg));
  24286. EXPECT_EQ("hello", msg);
  24287. client.close();
  24288. {
  24289. std::lock_guard<std::mutex> lock(mtx);
  24290. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24291. EXPECT_EQ("ABC", received_token);
  24292. }
  24293. svr.stop();
  24294. t.join();
  24295. }
  24296. // Run a handshake against a throwaway server and hand the request the server
  24297. // received back to the caller, so tests can assert on the headers the client
  24298. // actually put on the wire.
  24299. static void capture_websocket_handshake_request(
  24300. const Headers &client_headers,
  24301. std::function<void(const Request &, int port)> verify) {
  24302. Server svr;
  24303. std::mutex mtx;
  24304. Request received;
  24305. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24306. {
  24307. std::lock_guard<std::mutex> lock(mtx);
  24308. received = req;
  24309. }
  24310. std::string msg;
  24311. while (ws.read(msg)) {
  24312. ws.send(msg);
  24313. }
  24314. });
  24315. auto port = svr.bind_to_any_port("localhost");
  24316. std::thread t([&]() { svr.listen_after_bind(); });
  24317. auto se = detail::scope_exit([&] {
  24318. svr.stop();
  24319. t.join();
  24320. });
  24321. svr.wait_until_ready();
  24322. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24323. client_headers);
  24324. ASSERT_TRUE(client.connect());
  24325. ASSERT_TRUE(client.send("hello"));
  24326. std::string msg;
  24327. ASSERT_TRUE(client.read(msg));
  24328. client.close();
  24329. {
  24330. std::lock_guard<std::mutex> lock(mtx);
  24331. verify(received, port);
  24332. }
  24333. }
  24334. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24335. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24336. // Non-default port must be present in the Host header. Default ports
  24337. // (80/443) are omitted; that logic is covered by
  24338. // MakeHostAndPortStringTest.
  24339. EXPECT_EQ("localhost:" + std::to_string(port),
  24340. req.get_header_value("Host"));
  24341. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24342. req.get_header_value("User-Agent"));
  24343. EXPECT_FALSE(req.has_header("Accept"));
  24344. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24345. EXPECT_FALSE(req.has_header("Content-Length"));
  24346. });
  24347. }
  24348. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24349. capture_websocket_handshake_request(
  24350. {{"Host", "example.com"},
  24351. {"User-Agent", "custom-agent"},
  24352. {"X-Custom", "value"}},
  24353. [](const Request &req, int) {
  24354. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24355. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24356. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24357. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24358. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24359. });
  24360. }
  24361. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24362. capture_websocket_handshake_request(
  24363. {{"Upgrade", "bogus"},
  24364. {"Connection", "close"},
  24365. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24366. {"Sec-WebSocket-Version", "8"}},
  24367. [](const Request &req, int) {
  24368. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24369. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24370. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24371. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24372. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24373. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24374. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24375. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24376. req.get_header_value("Sec-WebSocket-Key"));
  24377. });
  24378. }
  24379. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24380. // A header the client refuses to send must abort the handshake before any
  24381. // part of it reaches the wire; a lone request line would otherwise sit in
  24382. // the peer's buffer as a truncated request.
  24383. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24384. ASSERT_NE(INVALID_SOCKET, srv);
  24385. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24386. sockaddr_in addr{};
  24387. addr.sin_family = AF_INET;
  24388. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24389. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24390. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24391. ASSERT_EQ(0, ::listen(srv, 1));
  24392. sockaddr_in bound{};
  24393. socklen_t bound_len = sizeof(bound);
  24394. ASSERT_EQ(
  24395. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24396. auto port = ntohs(bound.sin_port);
  24397. ssize_t received = -1;
  24398. std::thread t([&] {
  24399. // Bound every blocking call so a regression fails the test with a bad
  24400. // value instead of hanging the suite.
  24401. fd_set rfds;
  24402. FD_ZERO(&rfds);
  24403. FD_SET(srv, &rfds);
  24404. timeval tv{5, 0};
  24405. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24406. 0) {
  24407. return;
  24408. }
  24409. sockaddr_in cli_addr{};
  24410. socklen_t cli_len = sizeof(cli_addr);
  24411. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24412. if (cli == INVALID_SOCKET) { return; }
  24413. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24414. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24415. char buf[4096];
  24416. received = ::recv(cli, buf, sizeof(buf), 0);
  24417. });
  24418. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24419. // connect() has already shut the socket down by the time it returns false,
  24420. // so the peer sees EOF without waiting for the client to be destroyed.
  24421. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24422. {{"X-Bad", "a\r\nInjected: 1"}});
  24423. EXPECT_FALSE(client.connect());
  24424. t.join();
  24425. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24426. EXPECT_EQ(0, received);
  24427. }
  24428. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24429. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24430. // contains "upgrade" as a substring is a different token and must not
  24431. // start a WebSocket handshake.
  24432. auto make_request = [](const std::vector<std::string> &connection_values) {
  24433. Request req;
  24434. req.method = "GET";
  24435. req.headers.emplace("Upgrade", "websocket");
  24436. for (const auto &value : connection_values) {
  24437. req.headers.emplace("Connection", value);
  24438. }
  24439. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24440. req.headers.emplace("Sec-WebSocket-Version", "13");
  24441. return req;
  24442. };
  24443. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24444. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24445. EXPECT_TRUE(
  24446. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24447. EXPECT_TRUE(
  24448. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24449. EXPECT_TRUE(
  24450. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24451. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24452. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24453. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24454. EXPECT_FALSE(
  24455. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24456. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24457. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24458. }
  24459. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24460. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24461. // asks recipients to match each protocol-name case-insensitively, and RFC
  24462. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24463. // client naming websocket alongside another protocol, or on a second field
  24464. // line, is offering websocket; a value that merely contains "websocket" as a
  24465. // substring is a different protocol name and is not.
  24466. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24467. Request req;
  24468. req.method = "GET";
  24469. for (const auto &value : upgrade_values) {
  24470. req.headers.emplace("Upgrade", value);
  24471. }
  24472. req.headers.emplace("Connection", "Upgrade");
  24473. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24474. req.headers.emplace("Sec-WebSocket-Version", "13");
  24475. return req;
  24476. };
  24477. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24478. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24479. EXPECT_TRUE(
  24480. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24481. EXPECT_TRUE(
  24482. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24483. EXPECT_TRUE(
  24484. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24485. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24486. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24487. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24488. EXPECT_FALSE(
  24489. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24490. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24491. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24492. }
  24493. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24494. Server svr;
  24495. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24496. auto port = svr.bind_to_any_port("localhost");
  24497. std::thread t([&]() { svr.listen_after_bind(); });
  24498. auto se = detail::scope_exit([&] {
  24499. svr.stop();
  24500. t.join();
  24501. });
  24502. svr.wait_until_ready();
  24503. Headers headers = {{"Upgrade", "websocket"},
  24504. {"Connection", "notupgrade"},
  24505. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24506. {"Sec-WebSocket-Version", "13"}};
  24507. Client cli("localhost", port);
  24508. auto res = cli.Get("/ws", headers);
  24509. // The route exists only as a WebSocket route, so a request that fails the
  24510. // handshake check falls through to ordinary routing.
  24511. ASSERT_TRUE(res);
  24512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24513. }
  24514. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24515. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24516. // Connection value is the only thing left for the client to reject.
  24517. Server svr;
  24518. svr.Get("/ws", [](const Request &req, Response &res) {
  24519. res.status = StatusCode::SwitchingProtocol_101;
  24520. res.set_header("Upgrade", "websocket");
  24521. res.set_header("Connection", "notupgrade");
  24522. res.set_header("Sec-WebSocket-Accept",
  24523. detail::websocket_accept_key(
  24524. req.get_header_value("Sec-WebSocket-Key")));
  24525. });
  24526. auto port = svr.bind_to_any_port("localhost");
  24527. std::thread t([&]() { svr.listen_after_bind(); });
  24528. auto se = detail::scope_exit([&] {
  24529. svr.stop();
  24530. t.join();
  24531. });
  24532. svr.wait_until_ready();
  24533. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24534. auto res = client.connect();
  24535. EXPECT_FALSE(res);
  24536. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24537. EXPECT_FALSE(client.is_open());
  24538. }
  24539. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24540. Server svr;
  24541. svr.Get("/ws", [](const Request &req, Response &res) {
  24542. res.status = StatusCode::SwitchingProtocol_101;
  24543. res.set_header("Upgrade", "websocket");
  24544. res.set_header("Connection", "Upgrade");
  24545. res.set_header("Sec-WebSocket-Accept",
  24546. detail::websocket_accept_key(
  24547. req.get_header_value("Sec-WebSocket-Key")));
  24548. res.set_header("Sec-WebSocket-Protocol", "admin");
  24549. });
  24550. auto port = svr.bind_to_any_port("localhost");
  24551. std::thread t([&]() { svr.listen_after_bind(); });
  24552. auto se = detail::scope_exit([&] {
  24553. svr.stop();
  24554. t.join();
  24555. });
  24556. svr.wait_until_ready();
  24557. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24558. // Server selects a subprotocol the client never offered
  24559. {
  24560. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24561. ws::WebSocketClient client(url, headers);
  24562. auto res = client.connect();
  24563. EXPECT_FALSE(res);
  24564. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24565. EXPECT_FALSE(client.is_open());
  24566. EXPECT_TRUE(client.subprotocol().empty());
  24567. }
  24568. // Client offered none but the server named one anyway
  24569. {
  24570. ws::WebSocketClient client(url);
  24571. auto res = client.connect();
  24572. EXPECT_FALSE(res);
  24573. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24574. EXPECT_FALSE(client.is_open());
  24575. EXPECT_TRUE(client.subprotocol().empty());
  24576. }
  24577. }
  24578. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24579. // The socket path doubles as the URL host, so it must not contain '/'.
  24580. const char *shard = getenv("GTEST_SHARD_INDEX");
  24581. const std::string sock_path =
  24582. shard ? std::string("httplib-ws-") + shard + ".sock"
  24583. : std::string("httplib-ws.sock");
  24584. std::remove(sock_path.c_str());
  24585. Server svr;
  24586. std::mutex mtx;
  24587. std::string received_host;
  24588. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24589. {
  24590. std::lock_guard<std::mutex> lock(mtx);
  24591. received_host = req.get_header_value("Host");
  24592. }
  24593. std::string msg;
  24594. while (ws.read(msg)) {
  24595. ws.send(msg);
  24596. }
  24597. });
  24598. svr.set_address_family(AF_UNIX);
  24599. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24600. auto se = detail::scope_exit([&] {
  24601. svr.stop();
  24602. t.join();
  24603. std::remove(sock_path.c_str());
  24604. });
  24605. svr.wait_until_ready();
  24606. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24607. client.set_address_family(AF_UNIX);
  24608. ASSERT_TRUE(client.connect());
  24609. ASSERT_TRUE(client.send("hello"));
  24610. std::string msg;
  24611. ASSERT_TRUE(client.read(msg));
  24612. client.close();
  24613. {
  24614. std::lock_guard<std::mutex> lock(mtx);
  24615. // There is no host:port for a Unix socket, so the same "localhost"
  24616. // placeholder the HTTP client uses is expected.
  24617. EXPECT_EQ("localhost", received_host);
  24618. }
  24619. }
  24620. // Two threads must never parse WebSocket frames from the same stream.
  24621. // close() used to read the peer's Close reply with its own frame read, so it
  24622. // raced a reader thread that was in the middle of a payload: the payload loop
  24623. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24624. // so bytes taken by close() were replaced with bytes from further along the
  24625. // stream. The message kept its length and silently changed content.
  24626. //
  24627. // The raw peer below sends a frame header plus part of the payload, waits for
  24628. // the handler to call close(), and only then sends the rest. Whichever thread
  24629. // would win the race for those bytes, the message must arrive intact, because
  24630. // close() must not touch the stream while read() owns it.
  24631. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24632. #ifndef _WIN32
  24633. signal(SIGPIPE, SIG_IGN);
  24634. #endif
  24635. const size_t payload_len = 120; // fits the 7-bit length field
  24636. const size_t prefix_len = 8;
  24637. const int attempts = 8;
  24638. std::string expected(payload_len, '\0');
  24639. for (size_t i = 0; i < payload_len; i++) {
  24640. expected[i] = static_cast<char>('a' + i % 26);
  24641. }
  24642. std::atomic<bool> peer_stalled{false};
  24643. std::atomic<bool> handler_done{false};
  24644. std::mutex received_mutex;
  24645. std::vector<std::string> received;
  24646. // Bound every wait, so a regression fails the test instead of hanging the
  24647. // suite.
  24648. auto wait_for = [](const std::atomic<bool> &flag) {
  24649. for (int i = 0; i < 500 && !flag; i++) {
  24650. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24651. }
  24652. };
  24653. Server svr;
  24654. svr.set_websocket_ping_interval(0);
  24655. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24656. std::thread reader([&]() {
  24657. std::string msg;
  24658. while (ws.read(msg)) {
  24659. std::lock_guard<std::mutex> guard(received_mutex);
  24660. received.push_back(msg);
  24661. }
  24662. });
  24663. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24664. // inside read_websocket_frame() when close() runs.
  24665. wait_for(peer_stalled);
  24666. ws.close();
  24667. reader.join();
  24668. handler_done = true;
  24669. });
  24670. auto port = svr.bind_to_any_port("127.0.0.1");
  24671. std::thread t([&]() { svr.listen_after_bind(); });
  24672. auto se = detail::scope_exit([&] {
  24673. svr.stop();
  24674. t.join();
  24675. });
  24676. svr.wait_until_ready();
  24677. auto send_bytes = [](socket_t s, const std::string &data) {
  24678. #ifdef _WIN32
  24679. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24680. #else
  24681. auto n = ::send(s, data.data(), data.size(), 0);
  24682. #endif
  24683. return n == static_cast<decltype(n)>(data.size());
  24684. };
  24685. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24686. // Every length used here fits the 7-bit length field.
  24687. auto masked_header = [](uint8_t first_byte, size_t len) {
  24688. std::string h;
  24689. h += static_cast<char>(first_byte);
  24690. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24691. h.append(4, '\0'); // mask key
  24692. return h;
  24693. };
  24694. for (int attempt = 0; attempt < attempts; attempt++) {
  24695. peer_stalled = false;
  24696. handler_done = false;
  24697. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24698. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24699. auto se_sock = detail::scope_exit([&] {
  24700. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24701. });
  24702. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24703. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24704. sockaddr_in addr{};
  24705. addr.sin_family = AF_INET;
  24706. addr.sin_port = htons(static_cast<uint16_t>(port));
  24707. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24708. ASSERT_EQ(
  24709. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24710. << "attempt " << attempt;
  24711. ASSERT_TRUE(send_bytes(sock,
  24712. "GET /ws HTTP/1.1\r\n"
  24713. "Host: 127.0.0.1\r\n"
  24714. "Upgrade: websocket\r\n"
  24715. "Connection: Upgrade\r\n"
  24716. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24717. "Sec-WebSocket-Version: 13\r\n"
  24718. "\r\n"))
  24719. << "attempt " << attempt;
  24720. std::string response;
  24721. while (response.find("\r\n\r\n") == std::string::npos) {
  24722. char buf[512];
  24723. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24724. if (n <= 0) { break; }
  24725. response.append(buf, static_cast<size_t>(n));
  24726. }
  24727. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24728. << "attempt " << attempt;
  24729. // Send the header of a Binary message but only the first prefix_len bytes
  24730. // of its payload, leaving the reader thread stalled inside the payload.
  24731. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24732. expected.substr(0, prefix_len)))
  24733. << "attempt " << attempt;
  24734. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24735. peer_stalled = true;
  24736. // Let close() send its Close frame and park in its own read before the
  24737. // rest of the payload arrives, so both threads are waiting for it.
  24738. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24739. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24740. close_frame += static_cast<char>(0x03); // status 1000
  24741. close_frame += static_cast<char>(0xE8);
  24742. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24743. << "attempt " << attempt;
  24744. // Closing the peer releases the reader thread even on the buggy path,
  24745. // where it waits for bytes another thread already consumed.
  24746. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24747. detail::close_socket(sock);
  24748. sock = INVALID_SOCKET;
  24749. wait_for(handler_done);
  24750. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24751. }
  24752. std::lock_guard<std::mutex> guard(received_mutex);
  24753. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24754. << "a message in flight when close() ran was dropped";
  24755. for (size_t i = 0; i < received.size(); i++) {
  24756. EXPECT_EQ(expected, received[i]) << "message " << i;
  24757. }
  24758. }
  24759. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24760. // returning the socket, or INVALID_SOCKET.
  24761. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24762. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24763. if (sock == INVALID_SOCKET) { return sock; }
  24764. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24765. sockaddr_in addr{};
  24766. addr.sin_family = AF_INET;
  24767. addr.sin_port = htons(static_cast<uint16_t>(port));
  24768. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24769. std::string req = "GET " + path +
  24770. " HTTP/1.1\r\n"
  24771. "Host: 127.0.0.1\r\n"
  24772. "Upgrade: websocket\r\n"
  24773. "Connection: Upgrade\r\n"
  24774. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24775. "Sec-WebSocket-Version: 13\r\n"
  24776. "\r\n";
  24777. std::string res;
  24778. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24779. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24780. static_cast<ssize_t>(req.size())) {
  24781. char c;
  24782. while (res.find("\r\n\r\n") == std::string::npos &&
  24783. ::recv(sock, &c, 1, 0) == 1) {
  24784. res += c;
  24785. }
  24786. }
  24787. if (res.find(" 101 ") == std::string::npos) {
  24788. detail::close_socket(sock);
  24789. return INVALID_SOCKET;
  24790. }
  24791. return sock;
  24792. }
  24793. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24794. // The payload must fit the 7-bit length field.
  24795. static std::string masked_frame(uint8_t first_byte,
  24796. const std::string &payload) {
  24797. std::string f;
  24798. f += static_cast<char>(first_byte);
  24799. f += static_cast<char>(0x80 | payload.size());
  24800. f.append(4, '\0');
  24801. return f + payload;
  24802. }
  24803. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24804. std::atomic<bool> done{false};
  24805. std::string received;
  24806. Server svr;
  24807. svr.set_websocket_ping_interval(0);
  24808. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24809. std::string msg;
  24810. if (ws.read(msg) == ws::Binary) { received = msg; }
  24811. done = true;
  24812. });
  24813. auto port = svr.bind_to_any_port("127.0.0.1");
  24814. std::thread t([&]() { svr.listen_after_bind(); });
  24815. auto se = detail::scope_exit([&] {
  24816. svr.stop();
  24817. t.join();
  24818. });
  24819. svr.wait_until_ready();
  24820. auto sock = connect_raw_websocket(port, "/ws");
  24821. ASSERT_NE(INVALID_SOCKET, sock);
  24822. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24823. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24824. masked_frame(0x89, "p") + // FIN + Ping
  24825. masked_frame(0x80, "lo"); // FIN + Continuation
  24826. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24827. for (int i = 0; i < 500 && !done; i++) {
  24828. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24829. }
  24830. ASSERT_TRUE(done);
  24831. EXPECT_EQ("Hello", received);
  24832. // The Ping between the fragments is answered with a Pong.
  24833. char pong[3];
  24834. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24835. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24836. }
  24837. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24838. Server svr;
  24839. svr.set_websocket_ping_interval(-1);
  24840. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24841. std::string msg;
  24842. while (ws.read(msg)) {}
  24843. });
  24844. auto port = svr.bind_to_any_port("127.0.0.1");
  24845. std::thread t([&]() { svr.listen_after_bind(); });
  24846. auto se = detail::scope_exit([&] {
  24847. svr.stop();
  24848. t.join();
  24849. });
  24850. svr.wait_until_ready();
  24851. auto sock = connect_raw_websocket(port, "/ws");
  24852. ASSERT_NE(INVALID_SOCKET, sock);
  24853. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24854. // Nothing comes while the client stays quiet.
  24855. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24856. char c;
  24857. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24858. }
  24859. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24860. // and that has to end a read() already waiting on the peer, on every platform.
  24861. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24862. // The peer sends no pings, and its handler never calls read(), which is
  24863. // where pongs are written.
  24864. std::mutex mutex;
  24865. std::condition_variable cv;
  24866. auto release = false;
  24867. svr.set_websocket_ping_interval(0);
  24868. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24869. std::unique_lock<std::mutex> lock(mutex);
  24870. cv.wait(lock, [&] { return release; });
  24871. });
  24872. auto port = svr.bind_to_any_port(HOST);
  24873. std::thread t([&]() { svr.listen_after_bind(); });
  24874. auto se = detail::scope_exit([&] {
  24875. {
  24876. std::lock_guard<std::mutex> lock(mutex);
  24877. release = true;
  24878. }
  24879. cv.notify_all();
  24880. svr.stop();
  24881. t.join();
  24882. });
  24883. svr.wait_until_ready();
  24884. ws::WebSocketClient client(std::string(scheme) +
  24885. "://localhost:" + std::to_string(port) + "/ws");
  24886. #ifdef CPPHTTPLIB_SSL_ENABLED
  24887. client.enable_server_certificate_verification(false);
  24888. #endif
  24889. // A ping a second, given up on after two go unanswered: about 3s
  24890. client.set_websocket_ping_interval(1);
  24891. client.set_websocket_max_missed_pongs(2);
  24892. // Well past that, so that a read the timeout ends instead stands out
  24893. client.set_read_timeout(10);
  24894. ASSERT_TRUE(client.connect());
  24895. auto start = std::chrono::steady_clock::now();
  24896. std::string msg;
  24897. EXPECT_EQ(ws::Fail, client.read(msg));
  24898. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24899. std::chrono::steady_clock::now() - start)
  24900. .count(),
  24901. 6000);
  24902. EXPECT_FALSE(client.is_open());
  24903. }
  24904. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24905. Server svr;
  24906. check_pong_timeout_ends_read(svr, "ws");
  24907. }
  24908. #ifdef CPPHTTPLIB_SSL_ENABLED
  24909. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24911. ASSERT_TRUE(svr.is_valid());
  24912. check_pong_timeout_ends_read(svr, "wss");
  24913. }
  24914. #endif
  24915. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24916. Server svr;
  24917. svr.set_websocket_ping_interval(0);
  24918. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24919. std::string msg;
  24920. while (ws.read(msg)) {}
  24921. });
  24922. auto port = svr.bind_to_any_port("127.0.0.1");
  24923. std::thread t([&]() { svr.listen_after_bind(); });
  24924. auto se = detail::scope_exit([&] {
  24925. svr.stop();
  24926. t.join();
  24927. });
  24928. svr.wait_until_ready();
  24929. // Each Close payload and the reply it should get: an echo when valid, 1002
  24930. // otherwise.
  24931. std::vector<std::pair<std::string, std::string>> cases = {
  24932. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24933. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24934. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24935. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24936. };
  24937. // Also between the fragments of a message.
  24938. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24939. for (const auto &c : cases) {
  24940. auto sock = connect_raw_websocket(port, "/ws");
  24941. ASSERT_NE(INVALID_SOCKET, sock);
  24942. auto frames = prefix + masked_frame(0x88, c.first);
  24943. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24944. std::string reply;
  24945. char buf[256];
  24946. while (reply.size() < 2 + c.second.size()) {
  24947. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24948. if (n <= 0) { break; }
  24949. reply.append(buf, static_cast<size_t>(n));
  24950. }
  24951. detail::close_socket(sock);
  24952. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24953. c.second,
  24954. reply);
  24955. }
  24956. }
  24957. }
  24958. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24959. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24960. protected:
  24961. void SetUp() override {
  24962. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24963. SERVER_PRIVATE_KEY_FILE);
  24964. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24965. std::string msg;
  24966. ws::ReadResult ret;
  24967. while ((ret = ws.read(msg))) {
  24968. if (ret == ws::Binary) {
  24969. ws.send(msg.data(), msg.size());
  24970. } else {
  24971. ws.send(msg);
  24972. }
  24973. }
  24974. });
  24975. port_ = server_->bind_to_any_port(HOST);
  24976. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24977. server_->wait_until_ready();
  24978. }
  24979. void TearDown() override {
  24980. server_->stop();
  24981. if (server_thread_.joinable()) { server_thread_.join(); }
  24982. }
  24983. std::unique_ptr<SSLServer> server_;
  24984. std::thread server_thread_;
  24985. int port_ = 0;
  24986. };
  24987. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24988. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24989. {
  24990. ws::WebSocketClient client(url);
  24991. client.enable_server_certificate_verification(false);
  24992. auto calls = 0;
  24993. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24994. calls++;
  24995. return false;
  24996. });
  24997. EXPECT_FALSE(client.connect());
  24998. EXPECT_GT(calls, 0);
  24999. }
  25000. {
  25001. ws::WebSocketClient client(url);
  25002. client.enable_server_certificate_verification(false);
  25003. client.set_session_verifier([](tls::session_t) {
  25004. return SSLVerifierResponse::CertificateRejected;
  25005. });
  25006. EXPECT_FALSE(client.connect());
  25007. }
  25008. {
  25009. ws::WebSocketClient client(url);
  25010. client.enable_server_certificate_verification(false);
  25011. client.set_session_verifier([](tls::session_t) {
  25012. return SSLVerifierResponse::CertificateAccepted;
  25013. });
  25014. EXPECT_TRUE(client.connect());
  25015. }
  25016. }
  25017. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25018. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25019. "/ws-echo");
  25020. client.enable_server_certificate_verification(false);
  25021. ASSERT_TRUE(client.connect());
  25022. ASSERT_TRUE(client.is_open());
  25023. ASSERT_TRUE(client.send("Hello WSS"));
  25024. std::string msg;
  25025. EXPECT_EQ(ws::Text, client.read(msg));
  25026. EXPECT_EQ("Hello WSS", msg);
  25027. client.close();
  25028. }
  25029. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25030. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25031. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25032. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25033. // client (without calling close() first) is the only path that runs
  25034. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25035. // bug exactly.
  25036. //
  25037. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25038. // when linked against an instrumented libssl; run under Valgrind to catch it
  25039. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25040. // suite (the freed session otherwise stalls on the close handshake) — this test
  25041. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25042. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25043. {
  25044. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25045. "/ws-echo");
  25046. client.enable_server_certificate_verification(false);
  25047. client.set_read_timeout(2, 0);
  25048. client.set_write_timeout(2, 0);
  25049. ASSERT_TRUE(client.connect());
  25050. ASSERT_TRUE(client.is_open());
  25051. ASSERT_TRUE(client.send("still open"));
  25052. // Intentionally do NOT call client.close(): leaving scope runs
  25053. // shutdown_and_close() with the WebSocket still open, which must send the
  25054. // close frame while the TLS session is still alive.
  25055. }
  25056. }
  25057. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25058. // shutdown_and_close() at the start of connect(), reproducing the same
  25059. // use-after-free within the test body rather than at scope exit. The second
  25060. // connect must succeed and echo, proving the close handshake ran over a live
  25061. // session. See the note above about memory-tool requirements.
  25062. TEST_F(WebSocketSSLIntegrationTest,
  25063. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25064. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25065. "/ws-echo");
  25066. client.enable_server_certificate_verification(false);
  25067. client.set_read_timeout(2, 0);
  25068. client.set_write_timeout(2, 0);
  25069. ASSERT_TRUE(client.connect());
  25070. ASSERT_TRUE(client.is_open());
  25071. ASSERT_TRUE(client.send("still open"));
  25072. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25073. // the still-open connection, which must not touch a freed TLS session.
  25074. ASSERT_TRUE(client.connect());
  25075. ASSERT_TRUE(client.is_open());
  25076. ASSERT_TRUE(client.send("after reconnect"));
  25077. std::string msg;
  25078. EXPECT_EQ(ws::Text, client.read(msg));
  25079. EXPECT_EQ("after reconnect", msg);
  25080. client.close();
  25081. }
  25082. #endif
  25083. #ifdef CPPHTTPLIB_SSL_ENABLED
  25084. class WebSocketSSLCATest : public ::testing::Test {
  25085. protected:
  25086. void SetUp() override {
  25087. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25088. SERVER_PRIVATE_KEY_FILE);
  25089. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25090. std::string msg;
  25091. while (ws.read(msg)) {
  25092. ws.send(msg);
  25093. }
  25094. });
  25095. port_ = server_->bind_to_any_port("127.0.0.1");
  25096. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25097. server_->wait_until_ready();
  25098. }
  25099. void TearDown() override {
  25100. server_->stop();
  25101. if (server_thread_.joinable()) { server_thread_.join(); }
  25102. }
  25103. std::string url() const {
  25104. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25105. }
  25106. std::unique_ptr<SSLServer> server_;
  25107. std::thread server_thread_;
  25108. int port_ = 0;
  25109. };
  25110. // A custom CA loaded as PEM verifies the server with full certificate
  25111. // verification enabled
  25112. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25113. ws::WebSocketClient client(url());
  25114. std::string cert;
  25115. read_file(SERVER_CERT2_FILE, cert);
  25116. client.load_ca_cert_store(cert.c_str(), cert.size());
  25117. ASSERT_TRUE(client.connect());
  25118. ASSERT_TRUE(client.send("hello"));
  25119. std::string msg;
  25120. EXPECT_EQ(ws::Text, client.read(msg));
  25121. EXPECT_EQ("hello", msg);
  25122. client.close();
  25123. }
  25124. // A custom CA that does not cover the server must fail verification (the
  25125. // custom CA is exclusive; system certs are not loaded alongside it)
  25126. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25127. ws::WebSocketClient client(url());
  25128. std::string cert;
  25129. read_file(CLIENT_CA_CERT_FILE, cert);
  25130. client.load_ca_cert_store(cert.c_str(), cert.size());
  25131. auto res = client.connect();
  25132. ASSERT_FALSE(res);
  25133. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25134. EXPECT_EQ(-1, res.status());
  25135. EXPECT_NE(0u, res.ssl_backend_error());
  25136. }
  25137. // The same CA as a file path rather than PEM in memory
  25138. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25139. ws::WebSocketClient client(url());
  25140. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25141. ASSERT_TRUE(client.connect());
  25142. ASSERT_TRUE(client.send("hello"));
  25143. std::string msg;
  25144. EXPECT_EQ(ws::Text, client.read(msg));
  25145. EXPECT_EQ("hello", msg);
  25146. client.close();
  25147. }
  25148. // ...and a CA file that does not cover the server still fails, so it is the
  25149. // path above that decides the outcome
  25150. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25151. ws::WebSocketClient client(url());
  25152. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25153. ASSERT_FALSE(client.connect());
  25154. }
  25155. // Regression test: reconnecting with a native custom CA store used to reuse
  25156. // a store handle the previous TLS context had already freed (use-after-free
  25157. // under the OpenSSL backend). The context now lives as long as the client.
  25158. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25159. ws::WebSocketClient client(url());
  25160. std::string cert;
  25161. read_file(SERVER_CERT2_FILE, cert);
  25162. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25163. ASSERT_TRUE(client.connect());
  25164. client.close();
  25165. ASSERT_TRUE(client.connect());
  25166. ASSERT_TRUE(client.send("again"));
  25167. std::string msg;
  25168. EXPECT_EQ(ws::Text, client.read(msg));
  25169. EXPECT_EQ("again", msg);
  25170. client.close();
  25171. }
  25172. // Regression test: a certificate with a trusted chain but no identity match
  25173. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25174. // verification entirely for IP hosts, so this connection succeeded there.
  25175. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25176. // chain verification while the identity check must still fail.
  25177. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25178. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25179. ASSERT_TRUE(svr.is_valid());
  25180. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25181. std::string msg;
  25182. while (ws.read(msg)) {
  25183. ws.send(msg);
  25184. }
  25185. });
  25186. auto port = svr.bind_to_any_port("127.0.0.1");
  25187. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25188. auto se = detail::scope_exit([&] {
  25189. svr.stop();
  25190. t.join();
  25191. });
  25192. svr.wait_until_ready();
  25193. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25194. "/echo");
  25195. std::string cert;
  25196. read_file(SERVER_CERT_FILE, cert);
  25197. client.load_ca_cert_store(cert.c_str(), cert.size());
  25198. ASSERT_FALSE(client.connect());
  25199. }
  25200. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25201. // SNI, so nothing binds the host name to the TLS session. These bind the
  25202. // server to "localhost" instead, the only shape that exercises the SNI and
  25203. // hostname-verification path with certificate verification left enabled.
  25204. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25205. protected:
  25206. void Start(const char *cert_file) {
  25207. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25208. SERVER_PRIVATE_KEY_FILE);
  25209. ASSERT_TRUE(server_->is_valid());
  25210. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25211. std::string msg;
  25212. while (ws.read(msg)) {
  25213. ws.send(msg);
  25214. }
  25215. });
  25216. port_ = server_->bind_to_any_port("localhost");
  25217. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25218. server_->wait_until_ready();
  25219. }
  25220. void TearDown() override {
  25221. if (server_) { server_->stop(); }
  25222. if (server_thread_.joinable()) { server_thread_.join(); }
  25223. }
  25224. std::string url() const {
  25225. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25226. }
  25227. std::unique_ptr<SSLServer> server_;
  25228. std::thread server_thread_;
  25229. int port_ = 0;
  25230. };
  25231. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25232. // out and the connection is usable
  25233. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25234. Start(SERVER_CERT2_FILE);
  25235. ws::WebSocketClient client(url());
  25236. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25237. ASSERT_TRUE(client.connect());
  25238. ASSERT_TRUE(client.send("hello"));
  25239. std::string msg;
  25240. EXPECT_EQ(ws::Text, client.read(msg));
  25241. EXPECT_EQ("hello", msg);
  25242. client.close();
  25243. }
  25244. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25245. // while the identity check must still reject "localhost"
  25246. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25247. Start(SERVER_CERT_FILE);
  25248. ws::WebSocketClient client(url());
  25249. client.set_ca_cert_path(SERVER_CERT_FILE);
  25250. auto res = client.connect();
  25251. ASSERT_FALSE(res);
  25252. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25253. EXPECT_EQ(-1, res.status());
  25254. }
  25255. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25256. // disabled: the chain is still checked, only the identity check is skipped
  25257. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25258. Start(SERVER_CERT_FILE);
  25259. ws::WebSocketClient client(url());
  25260. client.set_ca_cert_path(SERVER_CERT_FILE);
  25261. client.enable_server_hostname_verification(false);
  25262. ASSERT_TRUE(client.connect());
  25263. ASSERT_TRUE(client.send("hello"));
  25264. std::string msg;
  25265. EXPECT_EQ(ws::Text, client.read(msg));
  25266. EXPECT_EQ("hello", msg);
  25267. client.close();
  25268. }
  25269. // A CA that did not sign the server certificate fails the chain, even though
  25270. // the name would match
  25271. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25272. Start(SERVER_CERT2_FILE);
  25273. ws::WebSocketClient client(url());
  25274. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25275. ASSERT_FALSE(client.connect());
  25276. }
  25277. // With verification disabled, neither the chain nor the name is checked
  25278. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25279. Start(SERVER_CERT_FILE);
  25280. ws::WebSocketClient client(url());
  25281. client.enable_server_certificate_verification(false);
  25282. ASSERT_TRUE(client.connect());
  25283. ASSERT_TRUE(client.send("hello"));
  25284. std::string msg;
  25285. EXPECT_EQ(ws::Text, client.read(msg));
  25286. EXPECT_EQ("hello", msg);
  25287. client.close();
  25288. }
  25289. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25290. protected:
  25291. void SetUp() override {
  25292. server_ = httplib::detail::make_unique<SSLServer>(
  25293. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25294. ASSERT_TRUE(server_->is_valid());
  25295. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25296. std::string msg;
  25297. while (ws.read(msg)) {
  25298. ws.send(msg);
  25299. }
  25300. });
  25301. port_ = server_->bind_to_any_port("localhost");
  25302. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25303. server_->wait_until_ready();
  25304. }
  25305. void TearDown() override {
  25306. server_->stop();
  25307. if (server_thread_.joinable()) { server_thread_.join(); }
  25308. }
  25309. std::string url() const {
  25310. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25311. }
  25312. void ConnectWithClientCert(const std::string &client_cert_file,
  25313. const std::string &client_private_key_file,
  25314. const char *private_key_password) {
  25315. std::string cert_pem, key_pem;
  25316. read_file(client_cert_file, cert_pem);
  25317. read_file(client_private_key_file, key_pem);
  25318. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25319. key_pem.c_str(), key_pem.size(),
  25320. private_key_password};
  25321. ConnectWithPem(pem);
  25322. }
  25323. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25324. ws::WebSocketClient client(url(), pem);
  25325. ASSERT_TRUE(client.is_valid());
  25326. client.enable_server_certificate_verification(false);
  25327. ASSERT_TRUE(client.connect());
  25328. ASSERT_TRUE(client.send("hello"));
  25329. std::string msg;
  25330. EXPECT_EQ(ws::Text, client.read(msg));
  25331. EXPECT_EQ("hello", msg);
  25332. client.close();
  25333. }
  25334. std::unique_ptr<SSLServer> server_;
  25335. std::thread server_thread_;
  25336. int port_ = 0;
  25337. };
  25338. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25339. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25340. }
  25341. // Control for the tests above: the fixture's server really does require a
  25342. // client certificate, so it is the PEM the constructor installed that decides
  25343. // the outcome.
  25344. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25345. ws::WebSocketClient client(url());
  25346. ASSERT_TRUE(client.is_valid());
  25347. client.enable_server_certificate_verification(false);
  25348. EXPECT_FALSE(client.connect());
  25349. }
  25350. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25351. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25352. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25353. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25354. }
  25355. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25356. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25357. std::string cert_pem, key_pem;
  25358. read_file(CLIENT_CERT_FILE, cert_pem);
  25359. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25360. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25361. std::vector<char> key(key_pem.begin(), key_pem.end());
  25362. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25363. key.size(), nullptr};
  25364. ConnectWithPem(pem);
  25365. }
  25366. #endif
  25367. #if !defined(_WIN32)
  25368. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25369. auto secret_dir = std::string("./symlink_test_secret");
  25370. auto served_dir = std::string("./symlink_test_served");
  25371. auto secret_file = secret_dir + "/secret.txt";
  25372. auto symlink_path = served_dir + "/escape";
  25373. // Setup: create directories and files
  25374. mkdir(secret_dir.c_str(), 0755);
  25375. mkdir(served_dir.c_str(), 0755);
  25376. {
  25377. std::ofstream ofs(secret_file);
  25378. ofs << "SECRET_DATA";
  25379. }
  25380. // Create symlink using absolute path so it resolves correctly
  25381. #ifdef PATH_MAX
  25382. char abs_secret[PATH_MAX];
  25383. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25384. #else
  25385. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25386. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25387. ASSERT_NE(nullptr, abs_secret);
  25388. #endif
  25389. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25390. auto se = detail::scope_exit([&] {
  25391. unlink(symlink_path.c_str());
  25392. unlink(secret_file.c_str());
  25393. rmdir(served_dir.c_str());
  25394. rmdir(secret_dir.c_str());
  25395. });
  25396. Server svr;
  25397. svr.set_mount_point("/", served_dir);
  25398. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25399. auto se2 = detail::scope_exit([&] {
  25400. svr.stop();
  25401. listen_thread.join();
  25402. });
  25403. svr.wait_until_ready();
  25404. Client cli("localhost", PORT);
  25405. // Symlink pointing outside base dir should be blocked
  25406. auto res = cli.Get("/escape/secret.txt");
  25407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25408. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25409. }
  25410. #endif
  25411. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25412. // "GET /smuggled" request), reads the first response, and only then sends the
  25413. // embedded request as the body. Returns how many times /smuggled ran.
  25414. //
  25415. // The body is sent AFTER receiving the first response (as in the original
  25416. // PoC) so that the stream_line_reader cannot buffer it together with the
  25417. // headers of the first request.
  25418. static int count_smuggled_requests(const std::string &outer_head,
  25419. std::string &first_response) {
  25420. Server svr;
  25421. svr.set_mount_point("/", "./www");
  25422. std::atomic<int> smuggled_count(0);
  25423. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25424. smuggled_count++;
  25425. res.set_content("oops", "text/plain");
  25426. });
  25427. svr.Post("/post", [&](const Request &req, Response &res) {
  25428. res.set_content(req.body, "text/plain");
  25429. });
  25430. auto port = svr.bind_to_any_port("localhost");
  25431. thread t = thread([&] { svr.listen_after_bind(); });
  25432. auto se = detail::scope_exit([&] {
  25433. svr.stop();
  25434. t.join();
  25435. });
  25436. svr.wait_until_ready();
  25437. auto error = Error::Success;
  25438. auto sock = detail::create_client_socket(
  25439. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25440. /*connection_timeout_sec=*/2, 0,
  25441. /*read_timeout_sec=*/2, 0,
  25442. /*write_timeout_sec=*/2, 0, std::string(), error);
  25443. EXPECT_NE(INVALID_SOCKET, sock);
  25444. if (sock == INVALID_SOCKET) { return -1; }
  25445. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25446. // The "smuggled" request will be sent as the body of the outer request
  25447. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25448. "Host: localhost\r\n"
  25449. "Connection: close\r\n"
  25450. "\r\n";
  25451. auto head = outer_head;
  25452. auto len = std::to_string(smuggled.size());
  25453. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25454. pos = head.find("{len}", pos + len.size())) {
  25455. head.replace(pos, 5, len);
  25456. }
  25457. // Step 1: Send only the outer request headers (no body yet)
  25458. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25459. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25460. // Step 2: Read the first response
  25461. char buf[4096];
  25462. for (;;) {
  25463. auto n = recv(sock, buf, sizeof(buf), 0);
  25464. if (n <= 0) break;
  25465. first_response.append(buf, static_cast<size_t>(n));
  25466. // Stop once we have a complete response (headers + body)
  25467. auto hdr_end = first_response.find("\r\n\r\n");
  25468. if (hdr_end != std::string::npos) {
  25469. // Check for Content-Length to know when the body is complete
  25470. auto cl_pos = first_response.find("Content-Length:");
  25471. if (cl_pos != std::string::npos) {
  25472. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25473. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25474. auto cl = std::stoul(
  25475. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25476. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25477. } else {
  25478. break; // No Content-Length, assume headers-only response
  25479. }
  25480. }
  25481. }
  25482. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25483. // vulnerable server the keep-alive loop reads this as a second request. The
  25484. // server may already have closed the connection, so the result is ignored.
  25485. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25486. // Half-close so that a server which drained the body sees EOF and closes,
  25487. // instead of the read below waiting for the read timeout.
  25488. #ifdef _WIN32
  25489. ::shutdown(sock, SD_SEND);
  25490. #else
  25491. ::shutdown(sock, SHUT_WR);
  25492. #endif
  25493. // Step 4: Read until the server closes the connection
  25494. for (;;) {
  25495. auto n = recv(sock, buf, sizeof(buf), 0);
  25496. if (n <= 0) break;
  25497. }
  25498. return smuggled_count.load();
  25499. }
  25500. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25501. // A GET request with Content-Length to a static file handler must have its
  25502. // body drained before the keep-alive connection is reused. Otherwise the
  25503. // unread body bytes are interpreted as the next HTTP request.
  25504. std::string first_response;
  25505. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25506. "Host: localhost\r\n"
  25507. "Content-Length: {len}\r\n"
  25508. "\r\n",
  25509. first_response));
  25510. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25511. }
  25512. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25513. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25514. // be answered with 400 and the connection closed. Treating it as "no body"
  25515. // leaves the body to be parsed as the next request.
  25516. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25517. const char *targets[] = {
  25518. "GET /file", // handler that never reads the body
  25519. "GET /not-found", // no handler matches (404)
  25520. "POST /post", // handler that reads the body
  25521. };
  25522. for (auto target : targets) {
  25523. for (auto value : values) {
  25524. std::string first_response;
  25525. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25526. " HTTP/1.1\r\n"
  25527. "Host: localhost\r\n"
  25528. "Content-Length: " +
  25529. value + "\r\n\r\n",
  25530. first_response))
  25531. << target << " with Content-Length: " << value;
  25532. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25533. << target << " with Content-Length: " << value;
  25534. }
  25535. }
  25536. }
  25537. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25538. // A 400 for an unparseable request line leaves the rest of the message
  25539. // unread, so the connection must be closed rather than reused.
  25540. std::string first_response;
  25541. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25542. "Host: localhost\r\n"
  25543. "Content-Length: {len}\r\n"
  25544. "\r\n",
  25545. first_response));
  25546. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25547. }
  25548. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25549. // Same as above for a header block that fails to parse.
  25550. std::string first_response;
  25551. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25552. "Host: localhost\r\n"
  25553. "Bad Header\r\n"
  25554. "Content-Length: {len}\r\n"
  25555. "\r\n",
  25556. first_response));
  25557. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25558. }
  25559. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25560. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25561. // server must not read another request on that connection, even when the
  25562. // request had no body to drain.
  25563. std::string first_response;
  25564. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25565. "Host: localhost\r\n"
  25566. "\r\n",
  25567. first_response));
  25568. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25569. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25570. }
  25571. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25572. // A content reader that stops early leaves the stream inside the body.
  25573. // Draining the whole Content-Length from there, or reading the body again,
  25574. // reads into the next request, and whatever follows is parsed as a request
  25575. // of its own.
  25576. Server svr;
  25577. std::atomic<int> smuggled_count(0);
  25578. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25579. svr.Post("/upload", [](const Request &req, Response &res,
  25580. const ContentReader &content_reader) {
  25581. // Stop at the last chunk, so the whole body has been read however it
  25582. // arrives.
  25583. auto length = req.get_header_value_u64("Content-Length");
  25584. size_t total = 0;
  25585. auto consumed = content_reader([&](const char *, size_t n) {
  25586. total += n;
  25587. return total < length;
  25588. });
  25589. EXPECT_FALSE(consumed);
  25590. if (req.has_param("retry")) {
  25591. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25592. }
  25593. // Replace the 400 the aborted read set, which would close the connection.
  25594. res.set_redirect("/done");
  25595. });
  25596. auto port = svr.bind_to_any_port(HOST);
  25597. thread t = thread([&] { svr.listen_after_bind(); });
  25598. auto se = detail::scope_exit([&] {
  25599. svr.stop();
  25600. t.join();
  25601. });
  25602. svr.wait_until_ready();
  25603. // A front end sees the second request as a POST whose body is the GET. The
  25604. // first body is as long as the POST's headers, so draining it again reads
  25605. // exactly those and leaves the GET to be parsed next.
  25606. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25607. "Host: localhost\r\n"
  25608. "\r\n";
  25609. std::string second_head = "POST /post HTTP/1.1\r\n"
  25610. "Host: localhost\r\n"
  25611. "Content-Length: " +
  25612. std::to_string(inner.size()) +
  25613. "\r\n"
  25614. "\r\n";
  25615. for (auto target : {"/upload", "/upload?retry"}) {
  25616. smuggled_count = 0;
  25617. std::string request = "POST " + std::string(target) +
  25618. " HTTP/1.1\r\n"
  25619. "Host: localhost\r\n"
  25620. "Content-Length: " +
  25621. std::to_string(second_head.size()) +
  25622. "\r\n"
  25623. "\r\n" +
  25624. std::string(second_head.size(), 'A') + second_head +
  25625. inner;
  25626. std::string response;
  25627. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25628. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25629. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25630. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25631. EXPECT_EQ(0, smuggled_count.load()) << target;
  25632. }
  25633. }
  25634. // An error response closes the connection anyway, so the body is left unread
  25635. // with a redirect, such as one to a login page.
  25636. static void serve_redirects(Server &svr,
  25637. const std::function<void(int)> &client) {
  25638. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25639. res.set_redirect("/login");
  25640. return Server::HandlerResponse::Handled;
  25641. });
  25642. auto port = svr.bind_to_any_port(HOST);
  25643. ASSERT_GT(port, 0);
  25644. thread t = thread([&] { svr.listen_after_bind(); });
  25645. auto se = detail::scope_exit([&] {
  25646. svr.stop();
  25647. t.join();
  25648. ASSERT_FALSE(svr.is_running());
  25649. });
  25650. svr.wait_until_ready();
  25651. client(port);
  25652. }
  25653. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25654. Server svr;
  25655. serve_redirects(svr, [](int port) {
  25656. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25657. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25658. std::to_string(body.size()) + "\r\n\r\n" + body +
  25659. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25660. std::string resp;
  25661. ASSERT_TRUE(send_request(1, req, &resp, port));
  25662. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25663. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25664. });
  25665. }
  25666. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25667. Server svr;
  25668. svr.set_read_timeout(0, 200000);
  25669. serve_redirects(svr, [](int port) {
  25670. // A byte every 100 ms keeps each read within the read timeout, but not the
  25671. // body as a whole, so the server closes and the bytes sent after that fail.
  25672. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25673. "Content-Length: 10\r\n\r\n"};
  25674. parts.resize(11, "x");
  25675. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25676. });
  25677. }
  25678. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25679. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25680. // must be rejected with 400 Bad Request.
  25681. Server svr;
  25682. svr.Post("/test", [&](const Request &, Response &res) {
  25683. res.set_content("ok", "text/plain");
  25684. });
  25685. thread t = thread([&] { svr.listen(HOST, PORT); });
  25686. auto se = detail::scope_exit([&] {
  25687. svr.stop();
  25688. t.join();
  25689. ASSERT_FALSE(svr.is_running());
  25690. });
  25691. svr.wait_until_ready();
  25692. // Exact "chunked"
  25693. {
  25694. auto req = "POST /test HTTP/1.1\r\n"
  25695. "Host: localhost\r\n"
  25696. "Content-Length: 5\r\n"
  25697. "Transfer-Encoding: chunked\r\n"
  25698. "Connection: close\r\n"
  25699. "\r\n"
  25700. "hello";
  25701. std::string response;
  25702. ASSERT_TRUE(send_request(1, req, &response));
  25703. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25704. response.substr(0, response.find("\r\n")));
  25705. }
  25706. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25707. {
  25708. auto req = "POST /test HTTP/1.1\r\n"
  25709. "Host: localhost\r\n"
  25710. "Content-Length: 5\r\n"
  25711. "Transfer-Encoding: gzip, chunked\r\n"
  25712. "Connection: close\r\n"
  25713. "\r\n"
  25714. "hello";
  25715. std::string response;
  25716. ASSERT_TRUE(send_request(1, req, &response));
  25717. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25718. response.substr(0, response.find("\r\n")));
  25719. }
  25720. }
  25721. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25722. Server svr;
  25723. svr.Post("/test", [&](const Request &, Response &res) {
  25724. res.set_content("ok", "text/plain");
  25725. });
  25726. thread t = thread([&] { svr.listen(HOST, PORT); });
  25727. auto se = detail::scope_exit([&] {
  25728. svr.stop();
  25729. t.join();
  25730. ASSERT_FALSE(svr.is_running());
  25731. });
  25732. svr.wait_until_ready();
  25733. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25734. // length cannot be determined, so the server must answer 400 and close
  25735. // rather than treat the request as bodyless and leave the body in the
  25736. // socket for the next request to pick up.
  25737. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25738. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25739. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25740. std::string response;
  25741. ASSERT_TRUE(send_request(1, req, &response));
  25742. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25743. response.substr(0, response.find("\r\n")))
  25744. << transfer_encoding;
  25745. }
  25746. // RFC 9110 5.3: the codings may also be split across several
  25747. // Transfer-Encoding lines, which combine in the order they were received.
  25748. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25749. // just like the single-line "chunked, gzip" above.
  25750. {
  25751. auto req = "POST /test HTTP/1.1\r\n"
  25752. "Host: localhost\r\n"
  25753. "Transfer-Encoding: chunked\r\n"
  25754. "Transfer-Encoding: gzip\r\n"
  25755. "\r\n"
  25756. "0\r\n\r\n";
  25757. std::string response;
  25758. ASSERT_TRUE(send_request(1, req, &response));
  25759. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25760. response.substr(0, response.find("\r\n")));
  25761. }
  25762. }
  25763. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25764. Server svr;
  25765. svr.Post("/test", [&](const Request &, Response &res) {
  25766. res.set_content("ok", "text/plain");
  25767. });
  25768. auto port = svr.bind_to_any_port(HOST);
  25769. ASSERT_GT(port, 0);
  25770. thread t = thread([&] { svr.listen_after_bind(); });
  25771. auto se = detail::scope_exit([&] {
  25772. svr.stop();
  25773. t.join();
  25774. ASSERT_FALSE(svr.is_running());
  25775. });
  25776. svr.wait_until_ready();
  25777. for (auto transfer_encoding :
  25778. {"Transfer-Encoding: gzip, chunked\r\n",
  25779. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25780. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25781. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25782. transfer_encoding + "\r\n0\r\n\r\n";
  25783. std::string response;
  25784. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25785. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25786. response.substr(0, response.find("\r\n")))
  25787. << transfer_encoding;
  25788. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25789. << transfer_encoding;
  25790. }
  25791. }
  25792. // Regression for issue #2450: a DELETE without Content-Length on a
  25793. // keep-alive connection must not let the post-response drain consume the
  25794. // next request's bytes.
  25795. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25796. Server svr;
  25797. std::atomic<int> delete_count(0);
  25798. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25799. delete_count++;
  25800. res.status = StatusCode::NoContent_204;
  25801. });
  25802. auto port = svr.bind_to_any_port(HOST);
  25803. thread t = thread([&] { svr.listen_after_bind(); });
  25804. auto se = detail::scope_exit([&] {
  25805. svr.stop();
  25806. t.join();
  25807. });
  25808. svr.wait_until_ready();
  25809. auto error = Error::Success;
  25810. auto sock = detail::create_client_socket(
  25811. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25812. /*connection_timeout_sec=*/2, 0,
  25813. /*read_timeout_sec=*/2, 0,
  25814. /*write_timeout_sec=*/2, 0, std::string(), error);
  25815. ASSERT_NE(INVALID_SOCKET, sock);
  25816. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25817. auto send_request_and_read_response = [&](const std::string &req,
  25818. std::string &out) -> bool {
  25819. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25820. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25821. char buf[4096];
  25822. for (;;) {
  25823. auto n = recv(sock, buf, sizeof(buf), 0);
  25824. if (n <= 0) { return !out.empty(); }
  25825. out.append(buf, static_cast<size_t>(n));
  25826. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25827. }
  25828. };
  25829. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25830. "Host: localhost\r\n"
  25831. "\r\n";
  25832. std::string resp1;
  25833. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25834. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25835. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25836. "Host: localhost\r\n"
  25837. "Connection: close\r\n"
  25838. "\r\n";
  25839. std::string resp2;
  25840. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25841. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25842. EXPECT_EQ(2, delete_count.load());
  25843. }
  25844. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25845. Server svr;
  25846. svr.Post("/ingest", [&](const Request &, Response &res,
  25847. const ContentReader &content_reader) {
  25848. auto consumed = content_reader([](const char *, size_t) { return false; });
  25849. EXPECT_FALSE(consumed);
  25850. res.status = StatusCode::Conflict_409;
  25851. res.set_header("Connection", "close");
  25852. });
  25853. auto port = svr.bind_to_any_port(HOST);
  25854. thread t = thread([&] { svr.listen_after_bind(); });
  25855. auto se = detail::scope_exit([&] {
  25856. svr.stop();
  25857. t.join();
  25858. });
  25859. svr.wait_until_ready();
  25860. auto error = Error::Success;
  25861. auto sock = detail::create_client_socket(
  25862. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25863. /*connection_timeout_sec=*/2, 0,
  25864. /*read_timeout_sec=*/1, 0,
  25865. /*write_timeout_sec=*/2, 0, std::string(), error);
  25866. ASSERT_NE(INVALID_SOCKET, sock);
  25867. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25868. std::string request = "POST /ingest HTTP/1.1\r\n"
  25869. "Host: localhost\r\n"
  25870. "Transfer-Encoding: chunked\r\n"
  25871. "\r\n"
  25872. "4\r\n"
  25873. "data\r\n";
  25874. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25875. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25876. std::string response;
  25877. ssize_t received = 0;
  25878. do {
  25879. char buf[4096];
  25880. received = recv(sock, buf, sizeof(buf), 0);
  25881. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25882. } while (received > 0);
  25883. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25884. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25885. EXPECT_EQ(0, received);
  25886. }
  25887. namespace no_proxy_test {
  25888. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25889. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25890. // calling listen().
  25891. class ScopedServer {
  25892. public:
  25893. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25894. ~ScopedServer() {
  25895. svr_.stop();
  25896. if (th_.joinable()) { th_.join(); }
  25897. }
  25898. Server &svr() { return svr_; }
  25899. int port() const { return port_; }
  25900. void listen() {
  25901. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25902. svr_.wait_until_ready();
  25903. }
  25904. private:
  25905. Server svr_;
  25906. std::thread th_;
  25907. int port_ = 0;
  25908. };
  25909. class ProxyAndTargetServers {
  25910. public:
  25911. ProxyAndTargetServers() {
  25912. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25913. proxy_hits_++;
  25914. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25915. res.set_content("via-proxy", "text/plain");
  25916. });
  25917. target_.Get(".*", [this](const Request &req, Response &res) {
  25918. target_hits_++;
  25919. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25920. res.set_content("direct", "text/plain");
  25921. });
  25922. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25923. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25924. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25925. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25926. proxy_mock_.wait_until_ready();
  25927. target_.wait_until_ready();
  25928. }
  25929. ~ProxyAndTargetServers() {
  25930. proxy_mock_.stop();
  25931. target_.stop();
  25932. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25933. if (target_thread_.joinable()) { target_thread_.join(); }
  25934. }
  25935. Server &proxy_mock() { return proxy_mock_; }
  25936. Server &target() { return target_; }
  25937. int proxy_port() const { return proxy_port_; }
  25938. int target_port() const { return target_port_; }
  25939. int proxy_hits() const { return proxy_hits_.load(); }
  25940. int target_hits() const { return target_hits_.load(); }
  25941. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25942. void reset_counters() {
  25943. proxy_hits_ = 0;
  25944. target_hits_ = 0;
  25945. last_had_proxy_authz_ = false;
  25946. }
  25947. private:
  25948. Server proxy_mock_;
  25949. Server target_;
  25950. std::thread proxy_thread_;
  25951. std::thread target_thread_;
  25952. int proxy_port_ = 0;
  25953. int target_port_ = 0;
  25954. std::atomic<int> proxy_hits_{0};
  25955. std::atomic<int> target_hits_{0};
  25956. std::atomic<bool> last_had_proxy_authz_{false};
  25957. };
  25958. inline std::unique_ptr<Client> make_client(const std::string &host,
  25959. ProxyAndTargetServers &s) {
  25960. auto cli = detail::make_unique<Client>(host, s.target_port());
  25961. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25962. cli->set_proxy("127.0.0.1", s.proxy_port());
  25963. return cli;
  25964. }
  25965. } // namespace no_proxy_test
  25966. using no_proxy_test::make_client;
  25967. using no_proxy_test::ProxyAndTargetServers;
  25968. // A stream request carries the credentials a buffered request does
  25969. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25970. no_proxy_test::ScopedServer origin;
  25971. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25972. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25973. });
  25974. origin.listen();
  25975. Client cli("127.0.0.1", origin.port());
  25976. cli.set_basic_auth("user", "pass");
  25977. auto handle = cli.open_stream("GET", "/x");
  25978. ASSERT_TRUE(handle.is_valid());
  25979. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25980. Client bearer("127.0.0.1", origin.port());
  25981. bearer.set_bearer_token_auth("tok");
  25982. auto handle2 = bearer.open_stream("GET", "/x");
  25983. ASSERT_TRUE(handle2.is_valid());
  25984. EXPECT_EQ("Bearer tok", read_all(handle2));
  25985. }
  25986. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25987. // takes its own credentials, as for a buffered request
  25988. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25989. std::string target, authz, proxy_authz;
  25990. no_proxy_test::ScopedServer proxy;
  25991. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25992. target = req.target;
  25993. authz = req.get_header_value("Authorization");
  25994. proxy_authz = req.get_header_value("Proxy-Authorization");
  25995. res.set_content("ok", "text/plain");
  25996. });
  25997. proxy.listen();
  25998. Client cli("origin.example", 8080);
  25999. cli.set_proxy("127.0.0.1", proxy.port());
  26000. cli.set_proxy_basic_auth("puser", "ppass");
  26001. cli.set_basic_auth("user", "pass");
  26002. auto handle = cli.open_stream("GET", "/x");
  26003. ASSERT_TRUE(handle.is_valid());
  26004. EXPECT_EQ("ok", read_all(handle));
  26005. EXPECT_EQ("http://origin.example:8080/x", target);
  26006. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26007. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26008. }
  26009. // In absolute-form the path follows the authority, so a path that does not
  26010. // begin with '/' would make the proxy connect to another host
  26011. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26012. std::vector<std::string> targets;
  26013. no_proxy_test::ScopedServer proxy;
  26014. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26015. targets.push_back(req.target);
  26016. res.set_content("ok", "text/plain");
  26017. });
  26018. proxy.listen();
  26019. Client cli("origin.example", 8080);
  26020. cli.set_proxy("127.0.0.1", proxy.port());
  26021. cli.set_basic_auth("user", "pass");
  26022. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26023. auto res = cli.Get(path);
  26024. EXPECT_FALSE(res) << path;
  26025. auto handle = cli.open_stream("GET", path);
  26026. EXPECT_FALSE(handle.is_valid()) << path;
  26027. }
  26028. EXPECT_TRUE(targets.empty());
  26029. auto res = cli.Get("/x");
  26030. ASSERT_TRUE(res);
  26031. ASSERT_EQ(1u, targets.size());
  26032. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26033. }
  26034. TEST(NoProxyTest, ExactHostnameBypasses) {
  26035. ProxyAndTargetServers s;
  26036. auto cli = make_client("example.com", s);
  26037. cli->set_no_proxy({"example.com"});
  26038. auto res = cli->Get("/");
  26039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26040. EXPECT_EQ(0, s.proxy_hits());
  26041. EXPECT_EQ(1, s.target_hits());
  26042. }
  26043. TEST(NoProxyTest, SubdomainBypasses) {
  26044. ProxyAndTargetServers s;
  26045. auto cli = make_client("foo.example.com", s);
  26046. cli->set_no_proxy({"example.com"});
  26047. auto res = cli->Get("/");
  26048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26049. EXPECT_EQ(0, s.proxy_hits());
  26050. EXPECT_EQ(1, s.target_hits());
  26051. }
  26052. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26053. // Regression guard: "evilexample.com" must not be considered a subdomain
  26054. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26055. // check would let traffic bypass the proxy and leak credentials direct
  26056. // to the attacker host.
  26057. ProxyAndTargetServers s;
  26058. auto cli = make_client("evilexample.com", s);
  26059. cli->set_no_proxy({"example.com"});
  26060. auto res = cli->Get("/");
  26061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26062. EXPECT_GE(s.proxy_hits(), 1);
  26063. EXPECT_EQ(0, s.target_hits());
  26064. }
  26065. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26066. ProxyAndTargetServers s;
  26067. auto cli = make_client("example.com.evil.com", s);
  26068. cli->set_no_proxy({"example.com"});
  26069. auto res = cli->Get("/");
  26070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26071. EXPECT_GE(s.proxy_hits(), 1);
  26072. EXPECT_EQ(0, s.target_hits());
  26073. }
  26074. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26075. ProxyAndTargetServers s;
  26076. auto cli = make_client("example.com", s);
  26077. cli->set_no_proxy({".example.com"});
  26078. auto res = cli->Get("/");
  26079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26080. EXPECT_EQ(0, s.proxy_hits());
  26081. EXPECT_EQ(1, s.target_hits());
  26082. }
  26083. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26084. ProxyAndTargetServers s;
  26085. auto cli = make_client("Example.COM", s);
  26086. cli->set_no_proxy({"EXAMPLE.com"});
  26087. auto res = cli->Get("/");
  26088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26089. EXPECT_EQ(0, s.proxy_hits());
  26090. EXPECT_EQ(1, s.target_hits());
  26091. }
  26092. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26093. ProxyAndTargetServers s;
  26094. auto cli = make_client("example.com.", s);
  26095. cli->set_no_proxy({"example.com"});
  26096. auto res = cli->Get("/");
  26097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26098. EXPECT_EQ(0, s.proxy_hits());
  26099. EXPECT_EQ(1, s.target_hits());
  26100. }
  26101. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26102. // Trailing dots must be normalized on BOTH sides — host and entry.
  26103. // An implementation that only strips the host-side trailing dot would
  26104. // fail to match host "example.com" against entry "example.com." because
  26105. // a literal substring search would compare 11 chars against 12.
  26106. ProxyAndTargetServers s;
  26107. auto cli = make_client("example.com", s);
  26108. cli->set_no_proxy({"example.com."});
  26109. auto res = cli->Get("/");
  26110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26111. EXPECT_EQ(0, s.proxy_hits());
  26112. EXPECT_EQ(1, s.target_hits());
  26113. }
  26114. TEST(NoProxyTest, WildcardBypassesEverything) {
  26115. ProxyAndTargetServers s;
  26116. auto cli = make_client("anything.invalid.test", s);
  26117. cli->set_no_proxy({"*"});
  26118. auto res = cli->Get("/");
  26119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26120. EXPECT_EQ(0, s.proxy_hits());
  26121. EXPECT_EQ(1, s.target_hits());
  26122. }
  26123. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26124. ProxyAndTargetServers s;
  26125. Client cli("127.0.0.1", s.target_port());
  26126. cli.set_proxy("127.0.0.1", s.proxy_port());
  26127. cli.set_no_proxy({"127.0.0.1"});
  26128. auto res = cli.Get("/");
  26129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26130. EXPECT_EQ(0, s.proxy_hits());
  26131. EXPECT_EQ(1, s.target_hits());
  26132. }
  26133. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26134. ProxyAndTargetServers s;
  26135. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26136. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26137. cli.set_proxy("127.0.0.1", s.proxy_port());
  26138. cli.set_no_proxy({"::1"});
  26139. auto res = cli.Get("/");
  26140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26141. EXPECT_EQ(0, s.proxy_hits());
  26142. EXPECT_EQ(1, s.target_hits());
  26143. }
  26144. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26145. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26146. // must still be recognized as IPv6 for CIDR matching. Implementations
  26147. // that detect IPv6 only when the host begins with '[' would parse the
  26148. // host as a hostname and miss the match.
  26149. ProxyAndTargetServers s;
  26150. Client cli("fe80::1", s.target_port());
  26151. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26152. cli.set_proxy("127.0.0.1", s.proxy_port());
  26153. cli.set_no_proxy({"fe80::/10"});
  26154. auto res = cli.Get("/");
  26155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26156. EXPECT_EQ(0, s.proxy_hits());
  26157. EXPECT_EQ(1, s.target_hits());
  26158. }
  26159. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26160. ProxyAndTargetServers s;
  26161. Client cli("::1", s.target_port());
  26162. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  26163. cli.set_proxy("127.0.0.1", s.proxy_port());
  26164. cli.set_no_proxy({"[::1]"});
  26165. auto res = cli.Get("/");
  26166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26167. EXPECT_EQ(0, s.proxy_hits());
  26168. EXPECT_EQ(1, s.target_hits());
  26169. }
  26170. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26171. ProxyAndTargetServers s;
  26172. Client cli("fe80::1", s.target_port());
  26173. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26174. cli.set_proxy("127.0.0.1", s.proxy_port());
  26175. cli.set_no_proxy({"[fe80::]/10"});
  26176. auto res = cli.Get("/");
  26177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26178. EXPECT_EQ(0, s.proxy_hits());
  26179. EXPECT_EQ(1, s.target_hits());
  26180. }
  26181. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26182. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26183. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26184. // tricks via address-family conversion.
  26185. ProxyAndTargetServers s;
  26186. Client cli("::ffff:127.0.0.1", s.target_port());
  26187. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26188. cli.set_proxy("127.0.0.1", s.proxy_port());
  26189. cli.set_no_proxy({"127.0.0.1"});
  26190. auto res = cli.Get("/");
  26191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26192. EXPECT_GE(s.proxy_hits(), 1);
  26193. EXPECT_EQ(0, s.target_hits());
  26194. }
  26195. TEST(NoProxyTest, IPv4CidrMatch) {
  26196. ProxyAndTargetServers s;
  26197. Client cli("127.0.0.1", s.target_port());
  26198. cli.set_proxy("127.0.0.1", s.proxy_port());
  26199. cli.set_no_proxy({"127.0.0.0/8"});
  26200. auto res = cli.Get("/");
  26201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26202. EXPECT_EQ(0, s.proxy_hits());
  26203. EXPECT_EQ(1, s.target_hits());
  26204. }
  26205. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26206. ProxyAndTargetServers s;
  26207. Client cli("127.0.0.1", s.target_port());
  26208. cli.set_proxy("127.0.0.1", s.proxy_port());
  26209. cli.set_no_proxy({"10.0.0.0/8"});
  26210. auto res = cli.Get("/");
  26211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26212. EXPECT_GE(s.proxy_hits(), 1);
  26213. EXPECT_EQ(0, s.target_hits());
  26214. }
  26215. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26216. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26217. // IPv4 target matches.
  26218. ProxyAndTargetServers s;
  26219. Client cli("127.0.0.1", s.target_port());
  26220. cli.set_proxy("127.0.0.1", s.proxy_port());
  26221. cli.set_no_proxy({"0.0.0.0/0"});
  26222. auto res = cli.Get("/");
  26223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26224. EXPECT_EQ(0, s.proxy_hits());
  26225. EXPECT_EQ(1, s.target_hits());
  26226. }
  26227. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26228. ProxyAndTargetServers s;
  26229. Client cli("127.0.0.1", s.target_port());
  26230. cli.set_proxy("127.0.0.1", s.proxy_port());
  26231. cli.set_no_proxy({"127.0.0.1"});
  26232. auto res = cli.Get("/");
  26233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26234. EXPECT_EQ(0, s.proxy_hits());
  26235. EXPECT_EQ(1, s.target_hits());
  26236. }
  26237. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26238. ProxyAndTargetServers s;
  26239. Client cli("127.0.0.1", s.target_port());
  26240. cli.set_proxy("127.0.0.1", s.proxy_port());
  26241. cli.set_no_proxy({"127.0.0.0/33"});
  26242. auto res = cli.Get("/");
  26243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26244. EXPECT_GE(s.proxy_hits(), 1);
  26245. EXPECT_EQ(0, s.target_hits());
  26246. }
  26247. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26248. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26249. ProxyAndTargetServers s;
  26250. Client cli("127.0.0.1", s.target_port());
  26251. cli.set_proxy("127.0.0.1", s.proxy_port());
  26252. cli.set_no_proxy({"127.0.0.1/"});
  26253. auto res = cli.Get("/");
  26254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26255. EXPECT_GE(s.proxy_hits(), 1);
  26256. EXPECT_EQ(0, s.target_hits());
  26257. }
  26258. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26259. ProxyAndTargetServers s;
  26260. auto cli = make_client("internal.corp", s);
  26261. cli->set_proxy_basic_auth("u", "p");
  26262. cli->set_no_proxy({"internal.corp"});
  26263. auto res = cli->Get("/");
  26264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26265. EXPECT_EQ(1, s.target_hits());
  26266. EXPECT_EQ(0, s.proxy_hits());
  26267. EXPECT_FALSE(s.last_had_proxy_authz())
  26268. << "Proxy-Authorization must not be sent direct to the target";
  26269. }
  26270. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26271. ProxyAndTargetServers s;
  26272. auto cli = make_client("public.example", s);
  26273. cli->set_proxy_basic_auth("u", "p");
  26274. cli->set_no_proxy({"internal.corp"}); // does not match
  26275. auto res = cli->Get("/");
  26276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26277. EXPECT_GE(s.proxy_hits(), 1);
  26278. EXPECT_TRUE(s.last_had_proxy_authz());
  26279. }
  26280. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26281. std::atomic<int> hits{0};
  26282. std::atomic<int> hits_with_authz{0};
  26283. no_proxy_test::ScopedServer proxy_mock;
  26284. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26285. hits++;
  26286. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26287. if (req.target.find("/redir") != std::string::npos) {
  26288. res.set_redirect("http://other.example/landed");
  26289. } else {
  26290. res.set_content("via-proxy", "text/plain");
  26291. }
  26292. });
  26293. proxy_mock.listen();
  26294. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26295. hits = 0;
  26296. hits_with_authz = 0;
  26297. Client cli("public.example", 80);
  26298. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26299. cli.set_proxy_basic_auth(c.first, c.second);
  26300. cli.set_follow_location(true);
  26301. // The redirect to another host goes through the proxy as well
  26302. auto res = cli.Get("/redir");
  26303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26304. EXPECT_EQ(2, hits.load());
  26305. EXPECT_EQ(2, hits_with_authz.load());
  26306. }
  26307. }
  26308. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26309. ProxyAndTargetServers s;
  26310. auto cli = make_client("anything.test", s);
  26311. auto res = cli->Get("/");
  26312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26313. EXPECT_GE(s.proxy_hits(), 1);
  26314. EXPECT_EQ(0, s.target_hits());
  26315. }
  26316. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26317. ProxyAndTargetServers s;
  26318. auto cli = make_client("example.com", s);
  26319. cli->set_no_proxy({"example.com:8080"});
  26320. auto res = cli->Get("/");
  26321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26322. EXPECT_GE(s.proxy_hits(), 1);
  26323. EXPECT_EQ(0, s.target_hits());
  26324. }
  26325. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26326. ProxyAndTargetServers s;
  26327. auto cli = make_client("anything.test", s);
  26328. cli->set_no_proxy({"", " ", "\t"});
  26329. auto res = cli->Get("/");
  26330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26331. EXPECT_GE(s.proxy_hits(), 1);
  26332. EXPECT_EQ(0, s.target_hits());
  26333. }
  26334. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26335. // An entry with leading/trailing whitespace must still match — env-style
  26336. // values are commonly pasted with stray spaces and an implementation
  26337. // that feeds the raw token directly to inet_pton would fail to match
  26338. // valid CIDRs because of the spaces.
  26339. ProxyAndTargetServers s;
  26340. Client cli("127.0.0.1", s.target_port());
  26341. cli.set_proxy("127.0.0.1", s.proxy_port());
  26342. cli.set_no_proxy({" 127.0.0.0/8 "});
  26343. auto res = cli.Get("/");
  26344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26345. EXPECT_EQ(0, s.proxy_hits());
  26346. EXPECT_EQ(1, s.target_hits());
  26347. }
  26348. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26349. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26350. // go direct and must NOT carry Proxy-Authorization.
  26351. std::atomic<int> proxy_hits{0};
  26352. std::atomic<int> target_hits{0};
  26353. std::atomic<bool> target_saw_authz{false};
  26354. no_proxy_test::ScopedServer proxy_mock, target;
  26355. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26356. proxy_hits++;
  26357. res.status = 302;
  26358. res.set_header("Location", "http://127.0.0.1:" +
  26359. std::to_string(target.port()) + "/landed");
  26360. });
  26361. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26362. target_hits++;
  26363. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26364. res.set_content("direct", "text/plain");
  26365. });
  26366. proxy_mock.listen();
  26367. target.listen();
  26368. Client cli("public.example", target.port());
  26369. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26370. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26371. cli.set_proxy_basic_auth("u", "p");
  26372. cli.set_no_proxy({"127.0.0.1"});
  26373. cli.set_follow_location(true);
  26374. auto res = cli.Get("/redir");
  26375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26376. EXPECT_GE(proxy_hits.load(), 1);
  26377. EXPECT_GE(target_hits.load(), 1);
  26378. EXPECT_FALSE(target_saw_authz.load());
  26379. }
  26380. #ifdef CPPHTTPLIB_SSL_ENABLED
  26381. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26382. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26383. // proxy creds would be sent to the (possibly hostile) origin.
  26384. std::atomic<int> target_hits{0};
  26385. std::atomic<bool> target_saw_proxy_authz{false};
  26386. no_proxy_test::ScopedServer target;
  26387. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26388. target_hits++;
  26389. if (req.has_header("Proxy-Authorization")) {
  26390. target_saw_proxy_authz = true;
  26391. }
  26392. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26393. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26394. "nonce=\"abc\", algorithm=MD5");
  26395. });
  26396. target.listen();
  26397. // The proxy address is set to the target's port: the bypass MUST kick in;
  26398. // if it doesn't, the test still routes "via proxy" to the same server and
  26399. // the Proxy-Authorization assertion below catches the leak.
  26400. Client cli("evil.example", target.port());
  26401. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26402. cli.set_proxy("127.0.0.1", target.port());
  26403. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26404. cli.set_no_proxy({"evil.example"});
  26405. auto res = cli.Get("/x");
  26406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26407. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26408. EXPECT_EQ(1, target_hits.load());
  26409. EXPECT_FALSE(target_saw_proxy_authz.load());
  26410. }
  26411. #endif
  26412. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26413. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26414. std::atomic<int> proxy_hits{0};
  26415. std::atomic<int> bypass_hits{0};
  26416. std::atomic<bool> proxy_saw_c_url{false};
  26417. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26418. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26419. proxy_hits++;
  26420. if (req.path.find("/start") != std::string::npos) {
  26421. res.status = 302;
  26422. res.set_header("Location", "http://127.0.0.1:" +
  26423. std::to_string(bypass_server.port()) +
  26424. "/middle");
  26425. return;
  26426. }
  26427. if (req.path.find("/end") != std::string::npos) {
  26428. proxy_saw_c_url = true;
  26429. res.set_content("c-via-proxy", "text/plain");
  26430. return;
  26431. }
  26432. res.set_content("unexpected", "text/plain");
  26433. });
  26434. // public.example's "advertised" port is arbitrary (the request never lands
  26435. // there — it goes through the proxy), but use a dynamic value to stay
  26436. // friendly with sharded parallel runs.
  26437. int public_port = bypass_server.port();
  26438. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26439. bypass_hits++;
  26440. res.status = 302;
  26441. res.set_header("Location", "http://public.example:" +
  26442. std::to_string(public_port) + "/end");
  26443. });
  26444. proxy_mock.listen();
  26445. bypass_server.listen();
  26446. Client cli("public.example", public_port);
  26447. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26448. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26449. cli.set_no_proxy({"127.0.0.1"});
  26450. cli.set_follow_location(true);
  26451. auto res = cli.Get("/start");
  26452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26453. EXPECT_EQ(StatusCode::OK_200, res->status);
  26454. EXPECT_EQ("c-via-proxy", res->body);
  26455. EXPECT_GE(proxy_hits.load(), 2);
  26456. EXPECT_GE(bypass_hits.load(), 1);
  26457. EXPECT_TRUE(proxy_saw_c_url.load());
  26458. }
  26459. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26460. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26461. // request reconnects to the correct endpoint.
  26462. std::atomic<int> proxy_hits{0};
  26463. std::atomic<int> target_hits{0};
  26464. no_proxy_test::ScopedServer proxy_mock, target;
  26465. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26466. proxy_hits++;
  26467. res.set_content("via-proxy", "text/plain");
  26468. });
  26469. target.svr().Get(".*", [&](const Request &, Response &res) {
  26470. target_hits++;
  26471. res.set_content("direct", "text/plain");
  26472. });
  26473. proxy_mock.listen();
  26474. target.listen();
  26475. Client cli("public.example", target.port());
  26476. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26477. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26478. cli.set_keep_alive(true);
  26479. auto res1 = cli.Get("/a");
  26480. ASSERT_TRUE(res1);
  26481. EXPECT_EQ("via-proxy", res1->body);
  26482. EXPECT_EQ(1, proxy_hits.load());
  26483. EXPECT_EQ(0, target_hits.load());
  26484. cli.set_no_proxy({"public.example"});
  26485. auto res2 = cli.Get("/b");
  26486. ASSERT_TRUE(res2);
  26487. EXPECT_EQ("direct", res2->body);
  26488. EXPECT_EQ(1, proxy_hits.load());
  26489. EXPECT_EQ(1, target_hits.load());
  26490. }
  26491. // Forward declarations (see the base64_encode note).
  26492. namespace httplib {
  26493. namespace detail {
  26494. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26495. int shutdown_socket(socket_t sock) noexcept;
  26496. } // namespace detail
  26497. } // namespace httplib
  26498. namespace proxy_tunnel_test {
  26499. const char *const kTunnelEstablished =
  26500. "HTTP/1.1 200 Connection established\r\n\r\n";
  26501. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26502. using ConnectReply = std::function<std::string(const std::string &head)>;
  26503. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26504. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26505. class ScopedConnectProxy {
  26506. public:
  26507. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26508. : forward_port_(forward_port), reply_(std::move(reply)) {
  26509. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26510. if (listen_sock_ == INVALID_SOCKET) { return; }
  26511. auto a = loopback(0);
  26512. auto addr = reinterpret_cast<sockaddr *>(&a);
  26513. socklen_t alen = sizeof(a);
  26514. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26515. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26516. ::listen(listen_sock_, 4) != 0) {
  26517. return;
  26518. }
  26519. port_ = ntohs(a.sin_port);
  26520. th_ = std::thread([this] { run(); });
  26521. }
  26522. ~ScopedConnectProxy() {
  26523. if (th_.joinable()) {
  26524. stop_ = true;
  26525. auto wake = connect_to(port_);
  26526. th_.join();
  26527. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26528. }
  26529. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26530. }
  26531. int port() const { return port_; }
  26532. int connect_hits() const { return connect_hits_.load(); }
  26533. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26534. std::string connect_request() const {
  26535. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26536. return connect_request_;
  26537. }
  26538. private:
  26539. static sockaddr_in loopback(int port) {
  26540. sockaddr_in a{};
  26541. a.sin_family = AF_INET;
  26542. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26543. a.sin_port = htons(static_cast<unsigned short>(port));
  26544. return a;
  26545. }
  26546. static socket_t connect_to(int port) {
  26547. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26548. if (sock == INVALID_SOCKET) { return sock; }
  26549. auto a = loopback(port);
  26550. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26551. detail::close_socket(sock);
  26552. return INVALID_SOCKET;
  26553. }
  26554. return sock;
  26555. }
  26556. static bool send_all(socket_t sock, const char *data, size_t size) {
  26557. while (size > 0) {
  26558. auto n = detail::send_socket(sock, data, size, 0);
  26559. if (n <= 0) { return false; }
  26560. data += n;
  26561. size -= static_cast<size_t>(n);
  26562. }
  26563. return true;
  26564. }
  26565. void run() {
  26566. for (;;) {
  26567. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26568. if (stop_) {
  26569. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26570. return;
  26571. }
  26572. if (client == INVALID_SOCKET) { continue; }
  26573. serve(client);
  26574. detail::close_socket(client);
  26575. }
  26576. }
  26577. void serve(socket_t client) {
  26578. std::string head;
  26579. char buf[2048];
  26580. while (head.find("\r\n\r\n") == std::string::npos) {
  26581. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26582. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26583. if (n <= 0) { return; }
  26584. head.append(buf, static_cast<size_t>(n));
  26585. }
  26586. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26587. connect_hits_++;
  26588. {
  26589. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26590. connect_request_ = head;
  26591. }
  26592. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26593. if (!send_all(client, res.data(), res.size()) ||
  26594. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26595. return;
  26596. }
  26597. auto origin = connect_to(forward_port_);
  26598. if (origin == INVALID_SOCKET) { return; }
  26599. // When either side stops, shut both down so the other pump returns too.
  26600. auto pump = [&](socket_t from, socket_t to) {
  26601. char b[8192];
  26602. for (;;) {
  26603. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26604. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26605. }
  26606. detail::shutdown_socket(client);
  26607. detail::shutdown_socket(origin);
  26608. };
  26609. std::thread up([&] { pump(client, origin); });
  26610. pump(origin, client);
  26611. up.join();
  26612. detail::close_socket(origin);
  26613. }
  26614. int forward_port_;
  26615. ConnectReply reply_;
  26616. socket_t listen_sock_ = INVALID_SOCKET;
  26617. int port_ = 0;
  26618. std::thread th_;
  26619. std::atomic<bool> stop_{false};
  26620. std::atomic<int> connect_hits_{0};
  26621. mutable std::mutex connect_request_mutex_;
  26622. std::string connect_request_;
  26623. };
  26624. } // namespace proxy_tunnel_test
  26625. #ifdef CPPHTTPLIB_SSL_ENABLED
  26626. namespace proxy_tunnel_test {
  26627. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26628. class ScopedSSLServer {
  26629. public:
  26630. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26631. port_ = svr_.bind_to_any_port("127.0.0.1");
  26632. }
  26633. ~ScopedSSLServer() {
  26634. svr_.stop();
  26635. if (th_.joinable()) { th_.join(); }
  26636. }
  26637. SSLServer &svr() { return svr_; }
  26638. int port() const { return port_; }
  26639. void listen() {
  26640. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26641. svr_.wait_until_ready();
  26642. }
  26643. private:
  26644. SSLServer svr_;
  26645. std::thread th_;
  26646. int port_ = 0;
  26647. };
  26648. // Sends one request through the CONNECT proxy to the TLS origin with a
  26649. // credential configured for each hop, and checks that each credential reaches
  26650. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26651. // origin's (every header in origin_headers) on the tunnelled request.
  26652. void CredentialsStayWithTheirHop(
  26653. const std::function<void(SSLClient &)> &set_credentials,
  26654. const std::string &scheme,
  26655. const std::vector<std::string> &origin_headers = {"Authorization"},
  26656. bool stream = false) {
  26657. std::atomic<int> origin_hits{0};
  26658. std::atomic<bool> origin_saw_proxy_authz{false};
  26659. std::atomic<bool> origin_saw_headers{false};
  26660. ScopedSSLServer origin;
  26661. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26662. origin_hits++;
  26663. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26664. origin_saw_headers =
  26665. std::all_of(origin_headers.begin(), origin_headers.end(),
  26666. [&](const std::string &h) { return req.has_header(h); });
  26667. res.set_content("ok", "text/plain");
  26668. });
  26669. origin.listen();
  26670. ScopedConnectProxy proxy(origin.port());
  26671. ASSERT_NE(0, proxy.port());
  26672. // Pinned to 127.0.0.1 for the same reason as the test below.
  26673. SSLClient cli("127.0.0.1", origin.port());
  26674. cli.enable_server_certificate_verification(false);
  26675. cli.set_proxy("127.0.0.1", proxy.port());
  26676. set_credentials(cli);
  26677. if (stream) {
  26678. auto handle = cli.open_stream("GET", "/x");
  26679. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26680. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26681. } else {
  26682. auto res = cli.Get("/x");
  26683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26684. EXPECT_EQ(StatusCode::OK_200, res->status);
  26685. }
  26686. EXPECT_EQ(1, origin_hits.load());
  26687. EXPECT_EQ(1, proxy.connect_hits());
  26688. EXPECT_TRUE(origin_saw_headers.load());
  26689. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26690. << "Proxy-Authorization must not be sent inside the tunnel";
  26691. auto connect_req = proxy.connect_request();
  26692. EXPECT_NE(std::string::npos,
  26693. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26694. for (const auto &h : origin_headers) {
  26695. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26696. << h << " must not be sent to the proxy on CONNECT";
  26697. }
  26698. }
  26699. } // namespace proxy_tunnel_test
  26700. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26701. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26702. [](SSLClient &cli) {
  26703. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26704. cli.set_basic_auth("origin-user", "origin-pass");
  26705. },
  26706. "Basic");
  26707. }
  26708. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26709. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26710. [](SSLClient &cli) {
  26711. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26712. cli.set_basic_auth("origin-user", "origin-pass");
  26713. },
  26714. "Basic", {"Authorization"}, true);
  26715. }
  26716. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26717. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26718. [](SSLClient &cli) {
  26719. cli.set_proxy_bearer_token_auth("proxy-token");
  26720. cli.set_bearer_token_auth("origin-token");
  26721. },
  26722. "Bearer");
  26723. }
  26724. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26725. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26726. [](SSLClient &cli) {
  26727. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26728. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26729. {"Cookie", "sid=origin-session"},
  26730. {"X-Api-Key", "origin-key"}});
  26731. },
  26732. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26733. }
  26734. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26735. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26736. // retry; otherwise proxy creds would be sent to the origin.
  26737. std::atomic<int> origin_hits{0};
  26738. std::atomic<bool> origin_saw_proxy_authz{false};
  26739. proxy_tunnel_test::ScopedSSLServer origin;
  26740. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26741. origin_hits++;
  26742. if (req.has_header("Proxy-Authorization")) {
  26743. origin_saw_proxy_authz = true;
  26744. }
  26745. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26746. res.set_header("Proxy-Authenticate",
  26747. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26748. "algorithm=MD5");
  26749. });
  26750. origin.listen();
  26751. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26752. ASSERT_NE(0, proxy.port());
  26753. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26754. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26755. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26756. // and answer with its own status, making this test flaky.
  26757. SSLClient cli("127.0.0.1", origin.port());
  26758. cli.enable_server_certificate_verification(false);
  26759. cli.set_proxy("127.0.0.1", proxy.port());
  26760. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26761. auto res = cli.Get("/x");
  26762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26763. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26764. EXPECT_EQ(1, origin_hits.load());
  26765. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26766. EXPECT_EQ(1, proxy.connect_hits());
  26767. }
  26768. #endif
  26769. namespace proxy_tunnel_test {
  26770. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26771. // anything else gets a 407 with `challenge`.
  26772. ConnectReply require_proxy_auth(const std::string &expected,
  26773. const std::string &challenge) {
  26774. return [=](const std::string &head) -> std::string {
  26775. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26776. std::string::npos) {
  26777. return kTunnelEstablished;
  26778. }
  26779. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26780. "Proxy-Authenticate: " +
  26781. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26782. };
  26783. }
  26784. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26785. // request, then echoes.
  26786. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26787. ws.send(
  26788. "authorization:" + req.get_header_value("Authorization") +
  26789. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26790. std::string msg;
  26791. while (ws.read(msg)) {
  26792. ws.send(msg);
  26793. }
  26794. }
  26795. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26796. class ScopedWebSocketOrigin {
  26797. public:
  26798. ScopedWebSocketOrigin() {
  26799. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26800. server_.listen();
  26801. }
  26802. int port() const { return server_.port(); }
  26803. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26804. std::string url() const {
  26805. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26806. }
  26807. private:
  26808. no_proxy_test::ScopedServer server_;
  26809. };
  26810. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26811. // passed as a constructor header, and checks that each reaches only its hop.
  26812. void WebSocketCredentialsStayWithTheirHop(
  26813. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26814. const std::string &proxy_authz, const std::string &origin_authz) {
  26815. ScopedWebSocketOrigin origin;
  26816. ScopedConnectProxy proxy(
  26817. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26818. ASSERT_NE(0, proxy.port());
  26819. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26820. client.set_proxy("127.0.0.1", proxy.port());
  26821. set_proxy_credentials(client);
  26822. auto res = client.connect();
  26823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26824. std::string msg;
  26825. ASSERT_TRUE(client.read(msg));
  26826. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26827. client.close();
  26828. EXPECT_EQ(1, proxy.connect_hits());
  26829. EXPECT_EQ(std::string::npos,
  26830. proxy.connect_request().find("\r\nAuthorization: "))
  26831. << "origin credentials must not be sent to the proxy";
  26832. }
  26833. } // namespace proxy_tunnel_test
  26834. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26835. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26836. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26837. ASSERT_NE(0, proxy.port());
  26838. ws::WebSocketClient client(origin.url());
  26839. client.set_proxy("127.0.0.1", proxy.port());
  26840. auto res = client.connect();
  26841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26842. std::string msg;
  26843. ASSERT_TRUE(client.read(msg));
  26844. ASSERT_TRUE(client.send("hello"));
  26845. ASSERT_TRUE(client.read(msg));
  26846. EXPECT_EQ("hello", msg);
  26847. client.close();
  26848. EXPECT_EQ(1, proxy.connect_hits());
  26849. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26850. auto connect_req = proxy.connect_request();
  26851. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26852. EXPECT_NE(std::string::npos,
  26853. connect_req.find("\r\nHost: " + target + "\r\n"));
  26854. }
  26855. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26856. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26857. [](ws::WebSocketClient &cli) {
  26858. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26859. },
  26860. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26861. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26862. }
  26863. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26864. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26865. [](ws::WebSocketClient &cli) {
  26866. cli.set_proxy_bearer_token_auth("proxy-token");
  26867. },
  26868. "Bearer proxy-token", "Bearer origin-token");
  26869. }
  26870. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26871. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26872. proxy_tunnel_test::ScopedConnectProxy proxy(
  26873. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26874. "Basic " + detail::base64_encode("proxy-user:"),
  26875. "Basic realm=\"proxy\""));
  26876. ASSERT_NE(0, proxy.port());
  26877. ws::WebSocketClient client(origin.url());
  26878. client.set_proxy("127.0.0.1", proxy.port());
  26879. client.set_proxy_basic_auth("proxy-user", "");
  26880. auto res = client.connect();
  26881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26882. client.close();
  26883. EXPECT_EQ(1, proxy.connect_hits());
  26884. }
  26885. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26886. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26887. proxy_tunnel_test::ScopedConnectProxy proxy(
  26888. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26889. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26890. ASSERT_NE(0, proxy.port());
  26891. ws::WebSocketClient client(origin.url());
  26892. client.set_proxy("127.0.0.1", proxy.port());
  26893. auto res = client.connect();
  26894. EXPECT_FALSE(res);
  26895. EXPECT_EQ(Error::ProxyConnection, res.error());
  26896. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26897. EXPECT_EQ("Basic realm=\"proxy\"",
  26898. res.get_header_value("Proxy-Authenticate"));
  26899. EXPECT_FALSE(client.is_open());
  26900. }
  26901. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26902. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26903. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26904. ASSERT_NE(0, proxy.port());
  26905. ws::WebSocketClient client(origin.url());
  26906. client.set_proxy("127.0.0.1", proxy.port());
  26907. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26908. client.set_no_proxy({"127.0.0.1"});
  26909. auto res = client.connect();
  26910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26911. std::string msg;
  26912. ASSERT_TRUE(client.read(msg));
  26913. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26914. << "proxy credentials must not reach a bypassed origin";
  26915. client.close();
  26916. EXPECT_EQ(0, proxy.connect_hits());
  26917. }
  26918. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26919. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26920. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26921. ASSERT_NE(0, proxy.port());
  26922. ws::WebSocketClient client(origin.url());
  26923. client.set_proxy("127.0.0.1", proxy.port());
  26924. ASSERT_TRUE(client.connect());
  26925. ASSERT_TRUE(client.connect());
  26926. client.close();
  26927. EXPECT_EQ(2, proxy.connect_hits());
  26928. }
  26929. #ifdef CPPHTTPLIB_SSL_ENABLED
  26930. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26931. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26932. proxy_tunnel_test::ScopedConnectProxy proxy(
  26933. origin.port(), [](const std::string &head) -> std::string {
  26934. if (head.find(
  26935. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26936. std::string::npos) {
  26937. return proxy_tunnel_test::kTunnelEstablished;
  26938. }
  26939. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26940. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26941. "nonce=\"abc\", algorithm=MD5\r\n"
  26942. "Content-Length: 0\r\n\r\n";
  26943. });
  26944. ASSERT_NE(0, proxy.port());
  26945. ws::WebSocketClient client(origin.url());
  26946. client.set_proxy("127.0.0.1", proxy.port());
  26947. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26948. auto res = client.connect();
  26949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26950. std::string msg;
  26951. ASSERT_TRUE(client.read(msg));
  26952. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26953. client.close();
  26954. EXPECT_EQ(2, proxy.connect_hits());
  26955. }
  26956. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26957. proxy_tunnel_test::ScopedSSLServer origin;
  26958. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26959. origin.listen();
  26960. proxy_tunnel_test::ScopedConnectProxy proxy(
  26961. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26962. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26963. ASSERT_NE(0, proxy.port());
  26964. ws::WebSocketClient client(
  26965. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26966. client.enable_server_certificate_verification(false);
  26967. client.set_proxy("127.0.0.1", proxy.port());
  26968. client.set_proxy_bearer_token_auth("proxy-token");
  26969. auto res = client.connect();
  26970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26971. std::string msg;
  26972. ASSERT_TRUE(client.read(msg));
  26973. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26974. << "Proxy-Authorization must not be sent inside the tunnel";
  26975. client.close();
  26976. EXPECT_EQ(1, proxy.connect_hits());
  26977. }
  26978. #endif