test.cc 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029
  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. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  442. // before it is dropped; anywhere else it is an ordinary file name character.
  443. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  444. #ifdef _WIN32
  445. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  446. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  447. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  448. #else
  449. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  450. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  451. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  452. #endif
  453. }
  454. // Forward declaration (see the base64_encode note below): split builds move the
  455. // definition into httplib.cc, so re-declaring it here lets the test link.
  456. namespace httplib {
  457. namespace detail {
  458. bool is_chunked_transfer_encoding(const Headers &headers);
  459. } // namespace detail
  460. } // namespace httplib
  461. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  462. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  463. auto make = [](std::initializer_list<const char *> lines) {
  464. Headers h;
  465. for (auto te : lines) {
  466. if (te) { h.emplace("Transfer-Encoding", te); }
  467. }
  468. return h;
  469. };
  470. // Sole coding, matched case-insensitively.
  471. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  472. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  473. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  474. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  475. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  476. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  477. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  478. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  479. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  480. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  481. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  482. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  483. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  484. // were received, into one list. Headers preserves that order, so the answer
  485. // is decided by the last coding of the last line and the order the lines
  486. // arrived in is significant.
  487. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  488. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  489. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  490. // The split can fall anywhere in the list.
  491. EXPECT_TRUE(
  492. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  493. EXPECT_FALSE(
  494. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  495. // A trailing line naming no coding leaves the list ending in nothing, so it
  496. // must not inherit the chunked from the line before it.
  497. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  498. }
  499. // Forward declarations (see the base64_encode note below).
  500. namespace httplib {
  501. namespace detail {
  502. bool parse_status_line(const char *line, std::string &version, int &status,
  503. std::string &reason);
  504. std::string file_extension(const std::string &path);
  505. std::string
  506. find_content_type(const std::string &path,
  507. const std::map<std::string, std::string> &user_data,
  508. const std::string &default_content_type);
  509. bool can_compress_content_type(const std::string &content_type);
  510. bool is_prohibited_header_name(const std::string &name);
  511. bool is_valid_path(const std::string &path);
  512. #ifdef CPPHTTPLIB_SSL_ENABLED
  513. bool match_hostname(const std::string &pattern, const std::string &hostname);
  514. #endif
  515. } // namespace detail
  516. } // namespace httplib
  517. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  518. struct {
  519. const char *line;
  520. const char *version;
  521. int status;
  522. const char *reason;
  523. } cases[] = {
  524. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  525. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  526. // The reason phrase may be empty, or left out along with its space.
  527. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  528. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  529. };
  530. for (const auto &c : cases) {
  531. std::string version;
  532. int status = 0;
  533. std::string reason = "unset";
  534. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  535. << c.line;
  536. EXPECT_EQ(c.version, version);
  537. EXPECT_EQ(c.status, status);
  538. EXPECT_EQ(c.reason, reason);
  539. }
  540. }
  541. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  542. const char *lines[] = {
  543. "HTTP/2 200 OK\r\n",
  544. "HTTP/1.2 200 OK\r\n",
  545. "HTTP/1.1 20 OK\r\n",
  546. "HTTP/1.1 2000 OK\r\n",
  547. "HTTP/1.1 2x0 OK\r\n",
  548. "HTTP/1.1 200 OK\r\n",
  549. "HTTP/1.1 200OK\r\n",
  550. "HTTP/1.1 200 O\rK\r\n",
  551. "HTTP/1.1 200 OK",
  552. "HTTP/1.1 200 OK\r\nX",
  553. "",
  554. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  555. "HTTP/1.1 200 OK\n",
  556. #endif
  557. };
  558. for (auto line : lines) {
  559. std::string version;
  560. int status = 0;
  561. std::string reason;
  562. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  563. << line;
  564. }
  565. }
  566. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  567. // Long enough to overflow the stack when matched with std::regex.
  568. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  569. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  570. std::string version;
  571. int status = 0;
  572. std::string reason;
  573. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  574. EXPECT_EQ(200, status);
  575. EXPECT_EQ(long_reason, reason);
  576. }
  577. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  578. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  579. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  580. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  581. EXPECT_EQ("", detail::file_extension("noext"));
  582. EXPECT_EQ("", detail::file_extension("a."));
  583. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  584. EXPECT_EQ("", detail::file_extension("a.b-c"));
  585. // Long enough to overflow the stack when matched with std::regex.
  586. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  587. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  588. }
  589. #ifdef CPPHTTPLIB_SSL_ENABLED
  590. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  591. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  592. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  593. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  594. // A wildcard needs two labels after it, in the leftmost label only
  595. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  596. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  597. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  598. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  599. EXPECT_FALSE(
  600. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  601. // No name may have an empty label
  602. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  603. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  604. }
  605. #endif
  606. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  607. detail::case_ignore::hash hash;
  608. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  609. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  610. // Long enough to overflow the stack if hashed one call per character.
  611. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  612. }
  613. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  614. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  615. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  616. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  617. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  618. // Same 26-bit hash as html, svg and js.
  619. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  620. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  621. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  622. }
  623. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  624. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  625. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  626. }
  627. }
  628. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  629. // name anywhere else.
  630. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  631. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  632. #ifdef _WIN32
  633. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  634. #else
  635. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  636. #endif
  637. }
  638. }
  639. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  640. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  641. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  642. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  643. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  644. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  645. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  646. // Same 26-bit hash as application/json.
  647. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  648. }
  649. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  650. Request req;
  651. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  652. EXPECT_TRUE(req.is_multipart_form_data());
  653. std::string boundary;
  654. EXPECT_TRUE(detail::parse_multipart_boundary(
  655. req.get_header_value("Content-Type"), boundary));
  656. EXPECT_EQ("x", boundary);
  657. }
  658. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  659. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  660. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  661. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  662. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  663. // Same 26-bit hash as REMOTE_ADDR.
  664. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  665. }
  666. // Forward declaration: in split builds split.py strips `inline` and moves the
  667. // definition into httplib.cc, so detail::base64_encode is not visible from the
  668. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  669. // in both header-only and split builds.
  670. namespace httplib {
  671. namespace detail {
  672. std::string base64_encode(const std::string &in);
  673. } // namespace detail
  674. } // namespace httplib
  675. TEST(Base64EncodeTest, KnownAnswers) {
  676. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  677. // where the accumulator's top bit is already set before the next shift.
  678. EXPECT_EQ("", detail::base64_encode(""));
  679. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  680. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  681. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  682. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  683. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  684. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  685. // High bytes keep the top bit set across several rounds.
  686. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  687. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  688. }
  689. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  690. string unescapedCharacters = "-_.!~*'()";
  691. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  692. }
  693. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  694. string reservedCharacters = ";,/?:@&=+$";
  695. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  696. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  697. }
  698. TEST(ClientQueryOrder, PreserveOrder) {
  699. // This test reproduces Issue #2259: client may reorder query parameters
  700. // when sending a GET request. The expected behavior is that the client
  701. // preserves the original query string order when the caller supplied it
  702. // as part of the path.
  703. Server svr;
  704. svr.Get("/", [&](const Request &req, Response &res) {
  705. // Echo back the raw target so the test can assert ordering
  706. res.set_content(req.target, "text/plain");
  707. });
  708. std::thread t{[&] { svr.listen(HOST, PORT); }};
  709. auto se = detail::scope_exit([&] {
  710. svr.stop();
  711. t.join();
  712. ASSERT_FALSE(svr.is_running());
  713. });
  714. svr.wait_until_ready();
  715. Client cli(HOST, PORT);
  716. ASSERT_TRUE(cli.is_valid());
  717. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  718. auto res = cli.Get(original);
  719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  720. // Expect the echoed target to exactly match the original path (order
  721. // preserved)
  722. EXPECT_EQ(res->body, original);
  723. }
  724. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  725. string chineseCharacters = U8("中国語");
  726. string russianCharacters = U8("дом");
  727. string brazilianCharacters = U8("óculos");
  728. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  729. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  730. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  731. "%D0%B4%D0%BE%D0%BC");
  732. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  733. }
  734. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  735. string unescapedCharacters = "-_.!~*'()";
  736. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  737. }
  738. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  739. string reservedCharacters = ";,/?:@&=+$";
  740. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  741. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  742. }
  743. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  744. string chineseCharacters = U8("中国語");
  745. string russianCharacters = U8("дом");
  746. string brazilianCharacters = U8("óculos");
  747. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  748. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  749. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  750. "%D0%B4%D0%BE%D0%BC");
  751. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  752. }
  753. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  754. // Issue #2082 use case: encoding path component with ampersand
  755. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  756. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  757. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  758. }
  759. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  760. string unescapedCharacters = "-_.!~*'()";
  761. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  762. }
  763. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  764. string reservedCharacters = ";,/?:@&=+$#";
  765. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  766. }
  767. TEST(EncodeUriTest, TestUTF8Characters) {
  768. string chineseCharacters = U8("中国語");
  769. string russianCharacters = U8("дом");
  770. string brazilianCharacters = U8("óculos");
  771. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  772. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  773. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  774. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  775. }
  776. TEST(EncodeUriTest, TestCompleteUri) {
  777. string uri =
  778. "https://example.com/path/to/resource?query=value&param=test#fragment";
  779. EXPECT_EQ(
  780. httplib::encode_uri(uri),
  781. "https://example.com/path/to/resource?query=value&param=test#fragment");
  782. }
  783. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  784. string uri =
  785. "https://example.com/path with spaces/file name.html?q=hello world";
  786. EXPECT_EQ(httplib::encode_uri(uri),
  787. "https://example.com/path%20with%20spaces/"
  788. "file%20name.html?q=hello%20world");
  789. }
  790. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  791. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  792. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  793. }
  794. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  795. string unescapedCharacters = "-_.!~*'()";
  796. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  797. }
  798. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  799. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  800. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  801. string encodedBrazilian = "%C3%B3culos";
  802. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  803. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  804. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  805. }
  806. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  807. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  808. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  809. "Piri Tommy Villiers - on & on");
  810. }
  811. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  812. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  813. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  814. }
  815. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  816. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  817. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  818. }
  819. TEST(DecodeUriTest, TestUTF8Characters) {
  820. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  821. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  822. string encodedBrazilian = "%C3%B3culos";
  823. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  824. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  825. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  826. }
  827. TEST(DecodeUriTest, TestCompleteUri) {
  828. string encodedUri = "https://example.com/path%20with%20spaces/"
  829. "file%20name.html?q=hello%20world";
  830. EXPECT_EQ(
  831. httplib::decode_uri(encodedUri),
  832. "https://example.com/path with spaces/file name.html?q=hello world");
  833. }
  834. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  835. string original =
  836. "https://example.com/path with spaces/file name.html?q=hello world";
  837. string encoded = httplib::encode_uri(original);
  838. string decoded = httplib::decode_uri(encoded);
  839. EXPECT_EQ(decoded, original);
  840. }
  841. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  842. // decode_uri is the inverse of encode_uri: an escaped reserved character
  843. // stays encoded so it is not promoted into a real delimiter, while
  844. // non-reserved escapes still decode (like JS decodeURI).
  845. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  846. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  847. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  848. "%3F%3A%40%26%3D%2B%24%2C%3B");
  849. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  850. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  851. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  852. "http://example.com/a%2Fb");
  853. // decode_uri_component still decodes the reserved character.
  854. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  855. }
  856. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  857. string original = "Piri Tommy Villiers - on & on";
  858. string encoded = httplib::encode_uri_component(original);
  859. string decoded = httplib::decode_uri_component(encoded);
  860. EXPECT_EQ(decoded, original);
  861. }
  862. TEST(TrimTests, TrimStringTests) {
  863. EXPECT_EQ("abc", detail::trim_copy("abc"));
  864. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  865. EXPECT_TRUE(detail::trim_copy("").empty());
  866. }
  867. TEST(AsciiTest, LocaleIndependentClassification) {
  868. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  869. // which consult the global C locale: std::isalnum(0xC5) can return true
  870. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  871. // helpers must classify every byte by the ASCII grammar alone.
  872. for (int i = 0; i < 256; i++) {
  873. auto c = static_cast<char>(i);
  874. auto is_digit = i >= '0' && i <= '9';
  875. auto is_upper = i >= 'A' && i <= 'Z';
  876. auto is_lower = i >= 'a' && i <= 'z';
  877. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  878. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  879. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  880. << "byte " << i;
  881. }
  882. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  883. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  884. // Non-ASCII bytes must be percent-encoded, never passed through as
  885. // alphanumeric.
  886. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  887. }
  888. TEST(FromCharsTest, Double) {
  889. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  890. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  891. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  892. auto parse = [](const std::string &s, double &v) {
  893. return detail::from_chars(s.data(), s.data() + s.size(), v);
  894. };
  895. double v = -1.0;
  896. // Representative quality values.
  897. EXPECT_EQ(parse("0", v).ec, std::errc{});
  898. EXPECT_DOUBLE_EQ(v, 0.0);
  899. EXPECT_EQ(parse("1", v).ec, std::errc{});
  900. EXPECT_DOUBLE_EQ(v, 1.0);
  901. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  902. EXPECT_DOUBLE_EQ(v, 0.8);
  903. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  904. EXPECT_DOUBLE_EQ(v, 0.001);
  905. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  906. EXPECT_DOUBLE_EQ(v, 1.0);
  907. // A missing integer or fractional part is tolerated.
  908. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  909. EXPECT_DOUBLE_EQ(v, 0.5);
  910. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  911. EXPECT_DOUBLE_EQ(v, 5.0);
  912. // Values outside [0, 1] still parse; the caller range-checks them.
  913. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  914. EXPECT_DOUBLE_EQ(v, 123.456);
  915. // Stops at the first byte that is not part of the number and reports where.
  916. std::string trailing = "0.9, text/html";
  917. auto r = parse(trailing, v);
  918. EXPECT_EQ(r.ec, std::errc{});
  919. EXPECT_DOUBLE_EQ(v, 0.9);
  920. EXPECT_EQ(*r.ptr, ',');
  921. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  922. // outright, and an 'e'/'E' simply ends the number.
  923. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  924. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  925. std::string exp_input = "1.5e3";
  926. r = parse(exp_input, v);
  927. EXPECT_EQ(r.ec, std::errc{});
  928. EXPECT_DOUBLE_EQ(v, 1.5);
  929. EXPECT_EQ(*r.ptr, 'e');
  930. // Invalid inputs.
  931. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  932. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  933. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  934. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  935. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  936. // Pathological but well-formed inputs must stay bounded (no overflow, no
  937. // out-of-bounds table access) and stay within [0, 1] for the caller.
  938. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  939. std::errc{});
  940. EXPECT_DOUBLE_EQ(v, 0.0);
  941. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  942. std::errc{});
  943. EXPECT_GE(v, 0.0);
  944. EXPECT_LE(v, 1.0);
  945. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  946. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  947. }
  948. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  949. // Simple case without quality values
  950. std::vector<std::string> result1;
  951. EXPECT_TRUE(detail::parse_accept_header(
  952. "text/html,application/json,text/plain", result1));
  953. EXPECT_EQ(result1.size(), 3U);
  954. EXPECT_EQ(result1[0], "text/html");
  955. EXPECT_EQ(result1[1], "application/json");
  956. EXPECT_EQ(result1[2], "text/plain");
  957. // With quality values
  958. std::vector<std::string> result2;
  959. EXPECT_TRUE(detail::parse_accept_header(
  960. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  961. EXPECT_EQ(result2.size(), 3U);
  962. EXPECT_EQ(result2[0], "application/json"); // highest q value
  963. EXPECT_EQ(result2[1], "text/html");
  964. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  965. }
  966. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  967. // Mixed with and without quality values
  968. std::vector<std::string> result;
  969. EXPECT_TRUE(detail::parse_accept_header(
  970. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  971. EXPECT_EQ(result.size(), 3U);
  972. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  973. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  974. EXPECT_EQ(result[2], "application/json"); // q=0.5
  975. }
  976. TEST(ParseAcceptHeaderTest, EdgeCases) {
  977. // Empty header
  978. std::vector<std::string> empty_result;
  979. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  980. EXPECT_TRUE(empty_result.empty());
  981. // Single type
  982. std::vector<std::string> single_result;
  983. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  984. EXPECT_EQ(single_result.size(), 1U);
  985. EXPECT_EQ(single_result[0], "application/json");
  986. // Wildcard types
  987. std::vector<std::string> wildcard_result;
  988. EXPECT_TRUE(detail::parse_accept_header(
  989. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  990. EXPECT_EQ(wildcard_result.size(), 3U);
  991. EXPECT_EQ(wildcard_result[0], "application/json");
  992. EXPECT_EQ(wildcard_result[1], "text/*");
  993. EXPECT_EQ(wildcard_result[2], "*/*");
  994. }
  995. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  996. // Common browser Accept header
  997. std::vector<std::string> browser_result;
  998. EXPECT_TRUE(
  999. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1000. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1001. browser_result));
  1002. EXPECT_EQ(browser_result.size(), 6U);
  1003. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1004. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1005. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1006. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1007. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1008. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1009. // API client header
  1010. std::vector<std::string> api_result;
  1011. EXPECT_TRUE(detail::parse_accept_header(
  1012. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1013. api_result));
  1014. EXPECT_EQ(api_result.size(), 3U);
  1015. EXPECT_EQ(api_result[0], "application/json");
  1016. EXPECT_EQ(api_result[1], "application/xml");
  1017. EXPECT_EQ(api_result[2], "text/plain");
  1018. }
  1019. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1020. // Quality value with 3 decimal places
  1021. std::vector<std::string> decimal_result;
  1022. EXPECT_TRUE(detail::parse_accept_header(
  1023. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1024. EXPECT_EQ(decimal_result.size(), 2U);
  1025. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1026. EXPECT_EQ(decimal_result[1], "text/html");
  1027. // Zero quality (should still be included but with lowest priority)
  1028. std::vector<std::string> zero_q_result;
  1029. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1030. zero_q_result));
  1031. EXPECT_EQ(zero_q_result.size(), 2U);
  1032. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1033. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1034. // No spaces around commas
  1035. std::vector<std::string> no_space_result;
  1036. EXPECT_TRUE(detail::parse_accept_header(
  1037. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1038. no_space_result));
  1039. EXPECT_EQ(no_space_result.size(), 3U);
  1040. EXPECT_EQ(no_space_result[0], "text/html");
  1041. EXPECT_EQ(no_space_result[1], "application/json");
  1042. EXPECT_EQ(no_space_result[2], "text/plain");
  1043. }
  1044. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1045. // Quality values always use '.' as the decimal separator, so parsing must
  1046. // not depend on the process locale. An embedding application may have
  1047. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1048. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1049. std::string saved = cur ? cur : "C";
  1050. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1051. "fr_FR.UTF-8"};
  1052. bool switched = false;
  1053. for (const auto loc : comma_locales) {
  1054. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1055. std::localeconv()->decimal_point[0] == ',') {
  1056. switched = true;
  1057. break;
  1058. }
  1059. }
  1060. if (!switched) {
  1061. std::setlocale(LC_NUMERIC, saved.c_str());
  1062. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1063. }
  1064. // The higher-weighted type appears later in the list, so a correct parse
  1065. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1066. // sensitive parse reads both weights as 0 and leaves the original order.
  1067. std::vector<std::string> result;
  1068. EXPECT_TRUE(detail::parse_accept_header(
  1069. "application/json;q=0.1,text/html;q=0.9", result));
  1070. ASSERT_EQ(result.size(), 2U);
  1071. EXPECT_EQ(result[0], "text/html");
  1072. EXPECT_EQ(result[1], "application/json");
  1073. std::setlocale(LC_NUMERIC, saved.c_str());
  1074. }
  1075. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1076. std::vector<std::string> result;
  1077. // Invalid quality value (> 1.0)
  1078. EXPECT_FALSE(
  1079. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1080. // Invalid quality value (< 0.0)
  1081. EXPECT_FALSE(
  1082. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1083. // Invalid quality value (not a number)
  1084. EXPECT_FALSE(detail::parse_accept_header(
  1085. "text/html;q=invalid,application/json", result));
  1086. // A valid numeric prefix does not make the entire quality value valid.
  1087. EXPECT_FALSE(detail::parse_accept_header(
  1088. "text/html;q=0.5junk,application/json", result));
  1089. // Empty quality value
  1090. EXPECT_FALSE(
  1091. detail::parse_accept_header("text/html;q=,application/json", result));
  1092. // Invalid media type format (no slash and not wildcard)
  1093. EXPECT_FALSE(
  1094. detail::parse_accept_header("invalidtype,application/json", result));
  1095. // Valid cases should still work
  1096. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1097. EXPECT_EQ(result.size(), 1U);
  1098. EXPECT_EQ(result[0], "*/*");
  1099. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1100. EXPECT_EQ(result.size(), 1U);
  1101. EXPECT_EQ(result[0], "*");
  1102. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1103. EXPECT_EQ(result.size(), 1U);
  1104. EXPECT_EQ(result[0], "text/*");
  1105. }
  1106. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1107. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1108. // and must not be answered with 400 Bad Request.
  1109. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1110. struct {
  1111. const char *value;
  1112. std::vector<std::string> expected;
  1113. } cases[] = {
  1114. {",application/json", {"application/json"}},
  1115. {"text/html,", {"text/html"}},
  1116. {"text/html,,*/*", {"text/html", "*/*"}},
  1117. // An empty element may be spelled with whitespace in it
  1118. {"text/html, , application/json", {"text/html", "application/json"}},
  1119. // Nothing but empty elements is an empty list, which means the same
  1120. // thing as no Accept header at all
  1121. {",,,", {}},
  1122. // Quality values still apply across ignored empty elements
  1123. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1124. };
  1125. for (const auto &c : cases) {
  1126. std::vector<std::string> result;
  1127. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1128. << "value: " << c.value;
  1129. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1130. }
  1131. // An invalid entry is still rejected when empty elements surround it
  1132. std::vector<std::string> result;
  1133. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1134. }
  1135. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1136. // or ';' inside one does not end the list element or the parameter. Section
  1137. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1138. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1139. struct {
  1140. const char *value;
  1141. std::vector<std::string> expected;
  1142. } cases[] = {
  1143. {"text/html;profile=\"a,b\",application/json",
  1144. {"text/html", "application/json"}},
  1145. // A "q=" inside a quoted value is not the weight
  1146. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1147. {"text/html", "application/json"}},
  1148. // The weight after a quoted value still applies
  1149. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1150. {"application/json", "text/html"}},
  1151. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1152. {"application/json", "text/html"}},
  1153. {"text/html;profile=\"a\\\"b\",application/json",
  1154. {"text/html", "application/json"}},
  1155. // An escaped backslash does not escape the '"' after it
  1156. {"text/html;profile=\"a\\\\\",application/json",
  1157. {"text/html", "application/json"}},
  1158. };
  1159. for (const auto &c : cases) {
  1160. std::vector<std::string> result;
  1161. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1162. << "value: " << c.value;
  1163. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1164. }
  1165. }
  1166. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1167. Server svr;
  1168. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1169. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1170. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1171. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1172. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1173. res.set_content("ok", "text/plain");
  1174. });
  1175. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1176. EXPECT_TRUE(false);
  1177. res.set_content("bad request", "text/plain");
  1178. });
  1179. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1180. auto se = detail::scope_exit([&] {
  1181. svr.stop();
  1182. listen_thread.join();
  1183. ASSERT_FALSE(svr.is_running());
  1184. });
  1185. svr.wait_until_ready();
  1186. Client cli("localhost", PORT);
  1187. {
  1188. auto res = cli.Get(
  1189. "/accept_ok",
  1190. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1192. EXPECT_EQ(StatusCode::OK_200, res->status);
  1193. }
  1194. {
  1195. auto res = cli.Get("/accept_bad_request",
  1196. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1198. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1199. }
  1200. }
  1201. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1202. Server svr;
  1203. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1204. res.set_content("ok", "text/plain");
  1205. });
  1206. std::atomic<int> start_count{0};
  1207. std::atomic<bool> running_when_called{false};
  1208. svr.set_start_handler([&]() {
  1209. running_when_called = svr.is_running();
  1210. start_count++;
  1211. });
  1212. auto port = svr.bind_to_any_port(HOST);
  1213. std::thread t([&]() { svr.listen_after_bind(); });
  1214. auto se = detail::scope_exit([&] {
  1215. svr.stop();
  1216. t.join();
  1217. ASSERT_FALSE(svr.is_running());
  1218. });
  1219. svr.wait_until_ready();
  1220. // A successful request proves the accept loop is running, which the start
  1221. // handler precedes; so by now the handler must have run exactly once.
  1222. Client cli(HOST, port);
  1223. cli.set_connection_timeout(std::chrono::seconds(5));
  1224. auto res = cli.Get("/");
  1225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1226. EXPECT_EQ(StatusCode::OK_200, res->status);
  1227. EXPECT_EQ(1, start_count.load());
  1228. EXPECT_TRUE(running_when_called.load());
  1229. }
  1230. TEST(DivideTest, DivideStringTests) {
  1231. auto divide = [](const std::string &str, char d) {
  1232. std::string lhs;
  1233. std::string rhs;
  1234. detail::divide(str, d,
  1235. [&](const char *lhs_data, std::size_t lhs_size,
  1236. const char *rhs_data, std::size_t rhs_size) {
  1237. lhs.assign(lhs_data, lhs_size);
  1238. rhs.assign(rhs_data, rhs_size);
  1239. });
  1240. return std::make_pair(std::move(lhs), std::move(rhs));
  1241. };
  1242. {
  1243. const auto res = divide("", '=');
  1244. EXPECT_EQ(res.first, "");
  1245. EXPECT_EQ(res.second, "");
  1246. }
  1247. {
  1248. const auto res = divide("=", '=');
  1249. EXPECT_EQ(res.first, "");
  1250. EXPECT_EQ(res.second, "");
  1251. }
  1252. {
  1253. const auto res = divide(" ", '=');
  1254. EXPECT_EQ(res.first, " ");
  1255. EXPECT_EQ(res.second, "");
  1256. }
  1257. {
  1258. const auto res = divide("a", '=');
  1259. EXPECT_EQ(res.first, "a");
  1260. EXPECT_EQ(res.second, "");
  1261. }
  1262. {
  1263. const auto res = divide("a=", '=');
  1264. EXPECT_EQ(res.first, "a");
  1265. EXPECT_EQ(res.second, "");
  1266. }
  1267. {
  1268. const auto res = divide("=b", '=');
  1269. EXPECT_EQ(res.first, "");
  1270. EXPECT_EQ(res.second, "b");
  1271. }
  1272. {
  1273. const auto res = divide("a=b", '=');
  1274. EXPECT_EQ(res.first, "a");
  1275. EXPECT_EQ(res.second, "b");
  1276. }
  1277. {
  1278. const auto res = divide("a=b=", '=');
  1279. EXPECT_EQ(res.first, "a");
  1280. EXPECT_EQ(res.second, "b=");
  1281. }
  1282. {
  1283. const auto res = divide("a=b=c", '=');
  1284. EXPECT_EQ(res.first, "a");
  1285. EXPECT_EQ(res.second, "b=c");
  1286. }
  1287. }
  1288. TEST(SplitTest, ParseQueryString) {
  1289. string s = "key1=val1&key2=val2&key3=val3";
  1290. Params dic;
  1291. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1292. [&](const char *b, const char *e) {
  1293. string key, val;
  1294. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1295. if (key.empty()) {
  1296. key.assign(b2, e2);
  1297. } else {
  1298. val.assign(b2, e2);
  1299. }
  1300. });
  1301. dic.emplace(key, val);
  1302. });
  1303. EXPECT_EQ("val1", dic.find("key1")->second);
  1304. EXPECT_EQ("val2", dic.find("key2")->second);
  1305. EXPECT_EQ("val3", dic.find("key3")->second);
  1306. }
  1307. TEST(SplitTest, ParseInvalidQueryTests) {
  1308. {
  1309. string s = " ";
  1310. Params dict;
  1311. detail::parse_query_text(s, dict);
  1312. EXPECT_TRUE(dict.empty());
  1313. }
  1314. {
  1315. string s = " = =";
  1316. Params dict;
  1317. detail::parse_query_text(s, dict);
  1318. EXPECT_TRUE(dict.empty());
  1319. }
  1320. }
  1321. TEST(ParseQueryTest, ParseQueryString) {
  1322. {
  1323. std::string s = "key1=val1&key2=val2&key3=val3";
  1324. Params dic;
  1325. detail::parse_query_text(s, dic);
  1326. EXPECT_EQ("val1", dic.find("key1")->second);
  1327. EXPECT_EQ("val2", dic.find("key2")->second);
  1328. EXPECT_EQ("val3", dic.find("key3")->second);
  1329. }
  1330. {
  1331. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1332. Params dic;
  1333. detail::parse_query_text(s, dic);
  1334. EXPECT_EQ("", dic.find("key1")->second);
  1335. EXPECT_EQ("val1", dic.find("key2")->second);
  1336. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1337. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1338. }
  1339. }
  1340. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1341. Params dic;
  1342. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1343. dic.emplace("key1", "val1");
  1344. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1345. dic.emplace("key2", "val2");
  1346. dic.emplace("key3", "val3");
  1347. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1348. }
  1349. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1350. Params params;
  1351. params.emplace("a", "1");
  1352. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1353. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1354. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1355. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1356. // Long enough to overflow the stack when matched with std::regex.
  1357. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1358. EXPECT_EQ("/p?" + long_query + "&a=1",
  1359. append_query_params("/p?" + long_query, params));
  1360. }
  1361. // Joins every entry of a Headers or Params into "key=value " so a whole
  1362. // traversal can be compared in one assertion. Both are instantiations of the
  1363. // same insertion-ordered container, so one helper serves both.
  1364. template <typename Map> static std::string entries_to_string(const Map &m) {
  1365. std::string s;
  1366. for (const auto &entry : m) {
  1367. s += entry.first + "=" + entry.second + " ";
  1368. }
  1369. return s;
  1370. }
  1371. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1372. // Params used to be a std::multimap, which sorted by name and handed the
  1373. // caller's query back alphabetised. A client signing its query string could
  1374. // not reproduce the order it asked for.
  1375. Params dic;
  1376. dic.emplace("zulu", "1");
  1377. dic.emplace("alpha", "2");
  1378. dic.emplace("mike", "3");
  1379. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1380. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1381. }
  1382. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1383. Params dic;
  1384. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1385. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1386. }
  1387. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1388. Request req;
  1389. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1390. req.params);
  1391. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1392. EXPECT_EQ("first", req.get_param_value("tag"));
  1393. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1394. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1395. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1396. EXPECT_EQ("", req.get_param_value("tag", 3));
  1397. }
  1398. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1399. // Params shares its container with Headers, which matches field names
  1400. // case-insensitively. Parameter names must not pick that up.
  1401. Params dic;
  1402. dic.emplace("Key", "upper");
  1403. dic.emplace("key", "lower");
  1404. EXPECT_EQ(2U, dic.size());
  1405. EXPECT_EQ(1U, dic.count("Key"));
  1406. EXPECT_EQ(1U, dic.count("key"));
  1407. EXPECT_EQ("upper", dic.find("Key")->second);
  1408. EXPECT_EQ("lower", dic.find("key")->second);
  1409. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1410. }
  1411. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1412. Server svr;
  1413. std::string order;
  1414. svr.Get("/order", [&](const Request &req, Response &res) {
  1415. order = entries_to_string(req.params);
  1416. res.set_content("ok", "text/plain");
  1417. });
  1418. auto port = svr.bind_to_any_port(HOST);
  1419. thread t = thread([&] { svr.listen_after_bind(); });
  1420. auto se = detail::scope_exit([&] {
  1421. svr.stop();
  1422. t.join();
  1423. ASSERT_FALSE(svr.is_running());
  1424. });
  1425. svr.wait_until_ready();
  1426. Client cli(HOST, port);
  1427. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1430. }
  1431. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1432. Server svr;
  1433. std::string field_order, file_order;
  1434. svr.Post("/order", [&](const Request &req, Response &res) {
  1435. for (const auto &field : req.form.fields) {
  1436. field_order += field.first + "=" + field.second.content + " ";
  1437. }
  1438. for (const auto &file : req.form.files) {
  1439. file_order += file.first + "=" + file.second.filename + " ";
  1440. }
  1441. res.set_content("ok", "text/plain");
  1442. });
  1443. auto port = svr.bind_to_any_port(HOST);
  1444. thread t = thread([&] { svr.listen_after_bind(); });
  1445. auto se = detail::scope_exit([&] {
  1446. svr.stop();
  1447. t.join();
  1448. ASSERT_FALSE(svr.is_running());
  1449. });
  1450. svr.wait_until_ready();
  1451. UploadFormDataItems items = {
  1452. {"zulu", "1", "", ""},
  1453. {"alpha", "2", "", ""},
  1454. {"mike", "3", "", ""},
  1455. {"zebra", "z", "z.txt", "text/plain"},
  1456. {"apple", "a", "a.txt", "text/plain"},
  1457. };
  1458. Client cli(HOST, port);
  1459. auto res = cli.Post("/order", items);
  1460. ASSERT_TRUE(res);
  1461. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1462. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1463. }
  1464. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1465. Server svr;
  1466. std::vector<std::string> values;
  1467. std::string first, second, out_of_range, order;
  1468. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1469. values = req.form.get_fields("tag");
  1470. first = req.form.get_field("tag", 0);
  1471. second = req.form.get_field("tag", 1);
  1472. out_of_range = req.form.get_field("tag", 2);
  1473. for (const auto &field : req.form.fields) {
  1474. order += field.first + "=" + field.second.content + " ";
  1475. }
  1476. res.set_content("ok", "text/plain");
  1477. });
  1478. auto port = svr.bind_to_any_port(HOST);
  1479. thread t = thread([&] { svr.listen_after_bind(); });
  1480. auto se = detail::scope_exit([&] {
  1481. svr.stop();
  1482. t.join();
  1483. ASSERT_FALSE(svr.is_running());
  1484. });
  1485. svr.wait_until_ready();
  1486. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1487. // not adjacent in the container.
  1488. UploadFormDataItems items = {
  1489. {"tag", "first", "", ""},
  1490. {"other", "x", "", ""},
  1491. {"tag", "second", "", ""},
  1492. };
  1493. Client cli(HOST, port);
  1494. auto res = cli.Post("/repeated", items);
  1495. ASSERT_TRUE(res);
  1496. ASSERT_EQ(2U, values.size());
  1497. EXPECT_EQ("first", values[0]);
  1498. EXPECT_EQ("second", values[1]);
  1499. EXPECT_EQ("first", first);
  1500. EXPECT_EQ("second", second);
  1501. // std::multimap already kept entries sharing a name in insertion order, so
  1502. // everything above passes without this change too. The whole traversal is
  1503. // what tells the two apart: sorting by name would hoist "other" to the front
  1504. // and the two "tag" parts would end up adjacent.
  1505. EXPECT_EQ("tag=first other=x tag=second ", order);
  1506. // Advancing past the last entry of a name used to run off the container;
  1507. // the container's saturating increment makes it return the default instead.
  1508. EXPECT_EQ("", out_of_range);
  1509. }
  1510. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1511. Server svr;
  1512. std::string file_names;
  1513. svr.Post("/upload", [&](const Request &req, Response &res) {
  1514. for (const auto &file : req.form.files) {
  1515. file_names += file.first + "|" + file.second.filename + " ";
  1516. }
  1517. res.set_content("ok", "text/plain");
  1518. });
  1519. auto port = svr.bind_to_any_port(HOST);
  1520. thread t = thread([&] { svr.listen_after_bind(); });
  1521. auto se = detail::scope_exit([&] {
  1522. svr.stop();
  1523. t.join();
  1524. ASSERT_FALSE(svr.is_running());
  1525. });
  1526. svr.wait_until_ready();
  1527. // A trailing backslash would otherwise escape the closing quote.
  1528. UploadFormDataItems items = {
  1529. {"dir\\", "x", "a.txt", "text/plain"},
  1530. {"b", "y", "a\\\\b.txt", "text/plain"},
  1531. };
  1532. Client cli(HOST, port);
  1533. auto res = cli.Post("/upload", items);
  1534. ASSERT_TRUE(res);
  1535. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1536. }
  1537. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1538. // Server::read_content() keeps a FormFields::iterator alive across the
  1539. // content callbacks that fill the part it points at. The container is
  1540. // vector-backed, so a later emplace can reallocate and invalidate an older
  1541. // iterator; 64 parts grow the vector through seven reallocations, which
  1542. // checks that every part's content still lands in its own entry.
  1543. const size_t part_count = 64;
  1544. // One formula for both the parts sent and the values expected back, so the
  1545. // two cannot drift apart.
  1546. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1547. auto content_of = [](size_t i) {
  1548. return std::string(64, static_cast<char>('a' + (i % 26)));
  1549. };
  1550. Server svr;
  1551. std::vector<std::pair<std::string, std::string>> received;
  1552. svr.Post("/many", [&](const Request &req, Response &res) {
  1553. for (const auto &field : req.form.fields) {
  1554. received.emplace_back(field.first, field.second.content);
  1555. }
  1556. res.set_content("ok", "text/plain");
  1557. });
  1558. auto port = svr.bind_to_any_port(HOST);
  1559. thread t = thread([&] { svr.listen_after_bind(); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. t.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. UploadFormDataItems items;
  1567. for (size_t i = 0; i < part_count; i++) {
  1568. items.push_back({name_of(i), content_of(i), "", ""});
  1569. }
  1570. Client cli(HOST, port);
  1571. auto res = cli.Post("/many", items);
  1572. ASSERT_TRUE(res);
  1573. ASSERT_EQ(part_count, received.size());
  1574. for (size_t i = 0; i < part_count; i++) {
  1575. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1576. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1577. }
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1580. string content_type = "multipart/form-data; boundary=something";
  1581. string boundary;
  1582. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1583. EXPECT_TRUE(ret);
  1584. EXPECT_EQ(boundary, "something");
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1587. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1588. string boundary;
  1589. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1590. EXPECT_TRUE(ret);
  1591. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1592. }
  1593. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1594. string content_type =
  1595. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1596. string boundary;
  1597. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1598. EXPECT_TRUE(ret);
  1599. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1600. }
  1601. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1602. string content_type =
  1603. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1604. string boundary;
  1605. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1606. EXPECT_TRUE(ret);
  1607. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1608. }
  1609. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1610. const string boundary(70, 'a');
  1611. string content_type = "multipart/form-data; boundary=" + boundary;
  1612. string parsed;
  1613. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1614. EXPECT_TRUE(ret);
  1615. EXPECT_EQ(parsed, boundary);
  1616. }
  1617. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1618. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1619. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1620. string parsed;
  1621. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1622. EXPECT_FALSE(ret);
  1623. }
  1624. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1625. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1626. // is 72 characters on the wire and still valid.
  1627. const string boundary(70, 'a');
  1628. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1629. string parsed;
  1630. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1631. EXPECT_EQ(parsed, boundary);
  1632. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1633. parsed.clear();
  1634. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1635. }
  1636. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1637. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1638. // The parameter parser must not treat that '=' as the key/value separator.
  1639. string content_type =
  1640. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1641. "charset=UTF-8";
  1642. string parsed;
  1643. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1644. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1645. }
  1646. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1647. // A ';' inside the quoted-string is part of the value, not a parameter
  1648. // separator, so it must not truncate the boundary.
  1649. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1650. string parsed;
  1651. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1652. EXPECT_EQ(parsed, "a;b");
  1653. }
  1654. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1655. string parsed;
  1656. EXPECT_TRUE(detail::parse_multipart_boundary(
  1657. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1658. EXPECT_EQ("a\\b", parsed);
  1659. EXPECT_TRUE(detail::parse_multipart_boundary(
  1660. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1661. EXPECT_EQ("a\"b", parsed);
  1662. }
  1663. TEST(ParseDispositionParamsTest, QuotedValues) {
  1664. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1665. // ';' and '=' are ordinary characters inside one.
  1666. struct {
  1667. const char *value;
  1668. std::vector<std::pair<const char *, const char *>> expected;
  1669. } cases[] = {
  1670. {"name=\"file1\"; filename=\"a.txt\"",
  1671. {{"name", "file1"}, {"filename", "a.txt"}}},
  1672. // Whitespace around '=' and ';' is still trimmed
  1673. {"name=\"file2\" ;filename = \"a.html\"",
  1674. {{"name", "file2"}, {"filename", "a.html"}}},
  1675. // '=' inside the value used to leave only the text after the last one
  1676. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1677. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1678. {"name=\"x=y\"", {{"name", "x=y"}}},
  1679. // ';' inside the value used to truncate the pair and leave a bogus one
  1680. {"name=\"file3\"; filename=\"a;b.txt\"",
  1681. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1682. // An unquoted value keeps working, and so does filename*
  1683. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1684. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1685. // A parameter with no key is dropped rather than turned into one whose
  1686. // key is the value
  1687. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1688. // An escaped quote does not end the value
  1689. {"name=\"a\\\"; filename=evil.php\"",
  1690. {{"name", "a\"; filename=evil.php"}}},
  1691. // Other backslashes, as in a Windows path, are kept
  1692. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1693. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1694. };
  1695. for (const auto &c : cases) {
  1696. Params params;
  1697. detail::parse_disposition_params(c.value, params);
  1698. for (const auto &kv : c.expected) {
  1699. auto it = params.find(kv.first);
  1700. ASSERT_NE(it, params.end())
  1701. << "value: " << c.value << ", key: " << kv.first;
  1702. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1703. }
  1704. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1705. }
  1706. }
  1707. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1708. Server svr;
  1709. std::string filename;
  1710. std::string content;
  1711. svr.Post("/upload", [&](const Request &req, Response &) {
  1712. const auto &file = req.form.get_file("file");
  1713. filename = file.filename;
  1714. content = file.content;
  1715. });
  1716. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1717. auto se = detail::scope_exit([&] {
  1718. svr.stop();
  1719. thread.join();
  1720. ASSERT_FALSE(svr.is_running());
  1721. });
  1722. svr.wait_until_ready();
  1723. std::string body = "--B\r\n"
  1724. "Content-Disposition: form-data; name=\"file\"; "
  1725. "filename=\"a.txt\"\r\n"
  1726. "Content-Type: text/plain\r\n"
  1727. "\r\n"
  1728. "hello\r\n"
  1729. "--B--\r\n";
  1730. Client cli(HOST, PORT);
  1731. auto res = cli.Post(
  1732. "/upload",
  1733. [&](size_t offset, DataSink &sink) {
  1734. if (offset < body.size()) {
  1735. sink.write(&body[offset], 1);
  1736. } else {
  1737. sink.done();
  1738. }
  1739. return true;
  1740. },
  1741. "multipart/form-data; boundary=B");
  1742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1743. EXPECT_EQ(StatusCode::OK_200, res->status);
  1744. EXPECT_EQ("a.txt", filename);
  1745. EXPECT_EQ("hello", content);
  1746. }
  1747. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1748. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1749. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1750. Server svr;
  1751. std::string field_value, file_name, file_filename;
  1752. bool has_field = false, has_file = false;
  1753. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1754. has_field = req.form.has_field("x=y");
  1755. field_value = req.form.get_field("x=y");
  1756. has_file = req.form.has_file("file1");
  1757. const auto &file = req.form.get_file("file1");
  1758. file_name = file.name;
  1759. file_filename = file.filename;
  1760. res.set_content("ok", "text/plain");
  1761. });
  1762. auto port = svr.bind_to_any_port(HOST);
  1763. thread t = thread([&] { svr.listen_after_bind(); });
  1764. auto se = detail::scope_exit([&] {
  1765. svr.stop();
  1766. t.join();
  1767. ASSERT_FALSE(svr.is_running());
  1768. });
  1769. svr.wait_until_ready();
  1770. UploadFormDataItems items = {
  1771. {"x=y", "field-value", "", ""},
  1772. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1773. };
  1774. Client cli(HOST, port);
  1775. auto res = cli.Post("/quoted", items);
  1776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1777. ASSERT_EQ(StatusCode::OK_200, res->status);
  1778. EXPECT_TRUE(has_field);
  1779. EXPECT_EQ("field-value", field_value);
  1780. EXPECT_TRUE(has_file);
  1781. EXPECT_EQ("file1", file_name);
  1782. EXPECT_EQ("a;b=report.pdf", file_filename);
  1783. }
  1784. TEST(GetHeaderValueTest, DefaultValue) {
  1785. Headers headers = {{"Dummy", "Dummy"}};
  1786. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1787. EXPECT_STREQ("text/plain", val);
  1788. }
  1789. TEST(GetHeaderValueTest, DefaultValueInt) {
  1790. Headers headers = {{"Dummy", "Dummy"}};
  1791. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1792. EXPECT_EQ(100ull, val);
  1793. }
  1794. TEST(GetHeaderValueTest, RegularValue) {
  1795. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1796. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1797. EXPECT_STREQ("text/html", val);
  1798. }
  1799. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1800. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1801. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1802. EXPECT_STREQ("text/html", val);
  1803. }
  1804. TEST(GetHeaderValueTest, SetContent) {
  1805. Response res;
  1806. res.set_content("html", "text/html");
  1807. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1808. res.set_content("text", "text/plain");
  1809. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1810. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1811. }
  1812. TEST(GetHeaderValueTest, RegularValueInt) {
  1813. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1814. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1815. EXPECT_EQ(100ull, val);
  1816. }
  1817. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1818. Headers headers = {{"Content-Length", "x"}};
  1819. auto is_invalid_value = false;
  1820. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1821. is_invalid_value);
  1822. EXPECT_EQ(0ull, val);
  1823. EXPECT_TRUE(is_invalid_value);
  1824. }
  1825. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1826. // An all-digit value that overflows size_t must be reported as invalid, not
  1827. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1828. // a large length to a small one on 32-bit builds, leaving the framing length
  1829. // wrong while is_invalid_value stayed false.
  1830. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1831. auto is_invalid_value = false;
  1832. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1833. is_invalid_value);
  1834. EXPECT_TRUE(is_invalid_value);
  1835. // A well-formed length is unaffected.
  1836. Headers ok = {{"Content-Length", "1234"}};
  1837. is_invalid_value = false;
  1838. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1839. is_invalid_value);
  1840. EXPECT_EQ(1234ull, val);
  1841. EXPECT_FALSE(is_invalid_value);
  1842. }
  1843. TEST(GetHeaderValueTest, Range) {
  1844. {
  1845. Headers headers = {make_range_header({{1, -1}})};
  1846. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1847. EXPECT_STREQ("bytes=1-", val);
  1848. }
  1849. {
  1850. Headers headers = {make_range_header({{-1, 1}})};
  1851. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1852. EXPECT_STREQ("bytes=-1", val);
  1853. }
  1854. {
  1855. Headers headers = {make_range_header({{1, 10}})};
  1856. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1857. EXPECT_STREQ("bytes=1-10", val);
  1858. }
  1859. {
  1860. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1861. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1862. EXPECT_STREQ("bytes=1-10, 100-", val);
  1863. }
  1864. {
  1865. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1866. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1867. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1868. }
  1869. {
  1870. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1871. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1872. EXPECT_STREQ("bytes=0-0, -1", val);
  1873. }
  1874. }
  1875. TEST(BearerTokenAuthTest, SchemeValidation) {
  1876. // A value shorter than "Bearer " must not throw from the fixed-length
  1877. // substr, and a non-Bearer scheme must not be reported as a token.
  1878. struct {
  1879. const char *value;
  1880. const char *expected;
  1881. } cases[] = {
  1882. {"x", ""},
  1883. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1884. {"Bearer abc123", "abc123"},
  1885. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1886. };
  1887. for (const auto &c : cases) {
  1888. Request req;
  1889. req.set_header("Authorization", c.value);
  1890. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1891. }
  1892. }
  1893. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1894. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1895. // to depend on the standard library (libstdc++ handed back duplicates in
  1896. // reverse insertion order, libc++ in insertion order).
  1897. Request req;
  1898. req.set_header("Accept-Encoding", "gzip");
  1899. req.set_header("Accept-Encoding", "deflate");
  1900. req.set_header("Accept-Encoding", "br");
  1901. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1902. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1903. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1904. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1905. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1906. }
  1907. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1908. Request req;
  1909. req.set_header("X-Test", "only");
  1910. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1911. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1912. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1913. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1914. }
  1915. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1916. Request req;
  1917. req.set_header("X-First", "1");
  1918. req.set_header("X-Test", "2");
  1919. req.params.emplace("first", "1");
  1920. req.params.emplace("test", "2");
  1921. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1922. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1923. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1924. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1925. // The second one is negative when read as a signed value
  1926. const auto max_id = (std::numeric_limits<size_t>::max)();
  1927. for (auto id : {max_id / 2, max_id}) {
  1928. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1929. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1930. EXPECT_EQ("", req.get_param_value("test", id));
  1931. EXPECT_EQ("", req.form.get_field("test", id));
  1932. EXPECT_EQ("", req.form.get_file("test", id).content);
  1933. }
  1934. }
  1935. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1936. Headers headers;
  1937. headers.emplace("Host", "example.com");
  1938. headers.emplace("Accept-Encoding", "gzip");
  1939. headers.emplace("User-Agent", "test");
  1940. headers.emplace("Accept-Encoding", "deflate");
  1941. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1942. "Accept-Encoding=deflate ",
  1943. entries_to_string(headers));
  1944. }
  1945. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1946. Headers headers = {{"Content-Type", "text/html"},
  1947. {"CONTENT-TYPE", "text/xml"}};
  1948. EXPECT_EQ(2U, headers.count("content-type"));
  1949. auto it = headers.find("content-type");
  1950. ASSERT_TRUE(it != headers.end());
  1951. EXPECT_EQ("text/html", it->second);
  1952. }
  1953. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1954. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1955. // drop only those fields and leave everything positioned between them.
  1956. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1957. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1958. auto rng = headers.equal_range("a");
  1959. headers.erase(rng.first, rng.second);
  1960. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1961. }
  1962. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1963. Headers headers = {
  1964. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1965. EXPECT_EQ(3U, headers.erase("A"));
  1966. EXPECT_EQ(0U, headers.count("A"));
  1967. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1968. }
  1969. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1970. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1971. headers.emplace_front("Host", "example.com");
  1972. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1973. entries_to_string(headers));
  1974. }
  1975. TEST(ParseHeaderValueTest, Range) {
  1976. {
  1977. Ranges ranges;
  1978. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1979. EXPECT_TRUE(ret);
  1980. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1981. }
  1982. {
  1983. Ranges ranges;
  1984. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1985. EXPECT_TRUE(ret);
  1986. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1987. }
  1988. {
  1989. Ranges ranges;
  1990. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1991. EXPECT_TRUE(ret);
  1992. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1993. }
  1994. {
  1995. Ranges ranges;
  1996. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1997. EXPECT_FALSE(ret);
  1998. }
  1999. {
  2000. Ranges ranges;
  2001. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2002. EXPECT_TRUE(ret);
  2003. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2004. }
  2005. {
  2006. Ranges ranges;
  2007. auto ret =
  2008. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2009. EXPECT_TRUE(ret);
  2010. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2011. }
  2012. {
  2013. Ranges ranges;
  2014. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2015. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2016. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2017. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2018. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2019. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2020. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2021. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2022. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2023. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2024. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2025. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2026. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2027. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2028. EXPECT_FALSE(
  2029. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2030. EXPECT_TRUE(ranges.empty());
  2031. }
  2032. {
  2033. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2034. // remainder of the representation, so it stays accepted.
  2035. Ranges ranges;
  2036. auto ret =
  2037. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2038. EXPECT_TRUE(ret);
  2039. ASSERT_EQ(1u, ranges.size());
  2040. EXPECT_EQ(0, ranges[0].first);
  2041. EXPECT_EQ(-1, ranges[0].second);
  2042. }
  2043. // RFC 9110 14.1: range unit names are case-insensitive.
  2044. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2045. Ranges ranges;
  2046. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2047. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2048. }
  2049. }
  2050. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2051. Request req;
  2052. req.set_header("Accept-Encoding", "gzip");
  2053. Response res;
  2054. res.set_header("Content-Type", "text/plain");
  2055. auto ret = detail::encoding_type(req, res);
  2056. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2058. #else
  2059. EXPECT_TRUE(ret == detail::EncodingType::None);
  2060. #endif
  2061. }
  2062. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2063. Request req;
  2064. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2065. Response res;
  2066. res.set_header("Content-Type", "text/plain");
  2067. auto ret = detail::encoding_type(req, res);
  2068. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2069. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2070. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2071. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2072. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2073. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2074. #else
  2075. EXPECT_TRUE(ret == detail::EncodingType::None);
  2076. #endif
  2077. }
  2078. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2079. Request req;
  2080. req.set_header("Accept-Encoding",
  2081. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2082. Response res;
  2083. res.set_header("Content-Type", "text/plain");
  2084. auto ret = detail::encoding_type(req, res);
  2085. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2086. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2087. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2088. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2089. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2090. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2091. #else
  2092. EXPECT_TRUE(ret == detail::EncodingType::None);
  2093. #endif
  2094. }
  2095. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2096. // All supported encodings rejected with q=0 should return None
  2097. Request req;
  2098. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2099. Response res;
  2100. res.set_header("Content-Type", "text/plain");
  2101. auto ret = detail::encoding_type(req, res);
  2102. EXPECT_TRUE(ret == detail::EncodingType::None);
  2103. }
  2104. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2105. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2106. Request req;
  2107. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2108. Response res;
  2109. res.set_header("Content-Type", "text/plain");
  2110. auto ret = detail::encoding_type(req, res);
  2111. EXPECT_TRUE(ret == detail::EncodingType::None);
  2112. }
  2113. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2114. Request req;
  2115. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2116. Response res;
  2117. res.set_header("Content-Type", "text/plain");
  2118. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2119. }
  2120. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2121. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2122. Request req;
  2123. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2124. Response res;
  2125. res.set_header("Content-Type", "text/plain");
  2126. auto ret = detail::encoding_type(req, res);
  2127. EXPECT_TRUE(ret == detail::EncodingType::None);
  2128. }
  2129. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2130. // RFC 7231: Accept-Encoding values are case-insensitive
  2131. Request req;
  2132. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2133. Response res;
  2134. res.set_header("Content-Type", "text/plain");
  2135. auto ret = detail::encoding_type(req, res);
  2136. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2137. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2138. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2139. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2140. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2141. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2142. #else
  2143. EXPECT_TRUE(ret == detail::EncodingType::None);
  2144. #endif
  2145. }
  2146. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2147. // q value should determine priority, not hardcoded order
  2148. Request req;
  2149. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2150. Response res;
  2151. res.set_header("Content-Type", "text/plain");
  2152. auto ret = detail::encoding_type(req, res);
  2153. // gzip has highest q=1.0, so it should be selected even though
  2154. // br and zstd are also supported
  2155. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2156. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2157. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2158. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2159. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2160. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2161. #else
  2162. EXPECT_TRUE(ret == detail::EncodingType::None);
  2163. #endif
  2164. }
  2165. TEST(BufferStreamTest, read) {
  2166. detail::BufferStream strm1;
  2167. Stream &strm = strm1;
  2168. EXPECT_EQ(5, strm.write("hello"));
  2169. char buf[512];
  2170. EXPECT_EQ(2, strm.read(buf, 2));
  2171. EXPECT_EQ('h', buf[0]);
  2172. EXPECT_EQ('e', buf[1]);
  2173. EXPECT_EQ(2, strm.read(buf, 2));
  2174. EXPECT_EQ('l', buf[0]);
  2175. EXPECT_EQ('l', buf[1]);
  2176. EXPECT_EQ(1, strm.read(buf, 1));
  2177. EXPECT_EQ('o', buf[0]);
  2178. EXPECT_EQ(0, strm.read(buf, 1));
  2179. }
  2180. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2181. auto host = "www.httpwatch.com";
  2182. auto ip = hosted_at(host);
  2183. EXPECT_EQ("23.96.13.243", ip);
  2184. std::vector<std::string> addrs;
  2185. hosted_at(host, addrs);
  2186. EXPECT_EQ(1u, addrs.size());
  2187. }
  2188. #if 0 // It depends on each test environment...
  2189. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2190. auto host = "www.youtube.com";
  2191. std::vector<std::string> addrs;
  2192. hosted_at(host, addrs);
  2193. EXPECT_EQ(20u, addrs.size());
  2194. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2195. EXPECT_TRUE(it != addrs.end());
  2196. }
  2197. #endif
  2198. class ChunkedEncodingTest : public ::testing::Test {
  2199. protected:
  2200. ChunkedEncodingTest()
  2201. : cli_(HOST, PORT)
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. ,
  2204. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2205. #endif
  2206. {
  2207. cli_.set_connection_timeout(2);
  2208. #ifdef CPPHTTPLIB_SSL_ENABLED
  2209. cli_.enable_server_certificate_verification(false);
  2210. #endif
  2211. }
  2212. virtual void SetUp() {
  2213. read_file("./image.jpg", image_data_);
  2214. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2215. res.set_content("Hello World!", "text/plain");
  2216. });
  2217. svr_.Get(
  2218. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2219. res.set_chunked_content_provider(
  2220. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2221. size_t remaining = image_data_.size() - offset;
  2222. if (remaining == 0) {
  2223. sink.done();
  2224. } else {
  2225. constexpr size_t CHUNK_SIZE = 1024;
  2226. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2227. sink.write(&image_data_[offset], send_size);
  2228. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2229. }
  2230. return true;
  2231. });
  2232. });
  2233. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2234. svr_.wait_until_ready();
  2235. }
  2236. virtual void TearDown() {
  2237. svr_.stop();
  2238. if (!request_threads_.empty()) {
  2239. std::this_thread::sleep_for(std::chrono::seconds(1));
  2240. for (auto &t : request_threads_) {
  2241. t.join();
  2242. }
  2243. }
  2244. t_.join();
  2245. }
  2246. #ifdef CPPHTTPLIB_SSL_ENABLED
  2247. SSLClient cli_;
  2248. SSLServer svr_;
  2249. #else
  2250. Client cli_;
  2251. Server svr_;
  2252. #endif
  2253. thread t_;
  2254. std::vector<thread> request_threads_;
  2255. std::string image_data_;
  2256. };
  2257. TEST_F(ChunkedEncodingTest, NormalGet) {
  2258. auto res = cli_.Get("/chunked");
  2259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2260. std::string out;
  2261. read_file("./image.jpg", out);
  2262. EXPECT_EQ(StatusCode::OK_200, res->status);
  2263. EXPECT_EQ(out, res->body);
  2264. }
  2265. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2266. std::string body;
  2267. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2268. body.append(data, data_length);
  2269. return true;
  2270. });
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. std::string out;
  2273. read_file("./image.jpg", out);
  2274. EXPECT_EQ(StatusCode::OK_200, res->status);
  2275. EXPECT_EQ(out, body);
  2276. }
  2277. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2278. std::string body;
  2279. auto res = cli_.Get(
  2280. "/chunked",
  2281. [&](const Response &response) {
  2282. EXPECT_EQ(StatusCode::OK_200, response.status);
  2283. return true;
  2284. },
  2285. [&](const char *data, size_t data_length) {
  2286. body.append(data, data_length);
  2287. return true;
  2288. });
  2289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2290. std::string out;
  2291. read_file("./image.jpg", out);
  2292. EXPECT_EQ(StatusCode::OK_200, res->status);
  2293. EXPECT_EQ(out, body);
  2294. }
  2295. TEST(RangeTest, FromHTTPBin_Online) {
  2296. auto host = "httpbingo.org";
  2297. auto path = std::string{"/range/32"};
  2298. #ifdef CPPHTTPLIB_SSL_ENABLED
  2299. auto port = 443;
  2300. SSLClient cli(host, port);
  2301. #else
  2302. auto port = 80;
  2303. Client cli(host, port);
  2304. #endif
  2305. cli.set_connection_timeout(5);
  2306. {
  2307. auto res = cli.Get(path);
  2308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2309. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2310. EXPECT_EQ(StatusCode::OK_200, res->status);
  2311. }
  2312. {
  2313. Headers headers = {make_range_header({{1, -1}})};
  2314. auto res = cli.Get(path, headers);
  2315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2316. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2317. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2318. }
  2319. {
  2320. Headers headers = {make_range_header({{1, 10}})};
  2321. auto res = cli.Get(path, headers);
  2322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2323. EXPECT_EQ("bcdefghijk", res->body);
  2324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2325. }
  2326. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2327. // entire resource, while the original httpbin returned 200. Both are
  2328. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2329. {
  2330. Headers headers = {make_range_header({{0, 31}})};
  2331. auto res = cli.Get(path, headers);
  2332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2333. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2334. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2335. res->status == StatusCode::PartialContent_206);
  2336. }
  2337. {
  2338. Headers headers = {make_range_header({{0, -1}})};
  2339. auto res = cli.Get(path, headers);
  2340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2341. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2342. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2343. res->status == StatusCode::PartialContent_206);
  2344. }
  2345. // go-httpbin returns 206 with clamped range for over-range requests,
  2346. // while the original httpbin returned 416. Both behaviors are observed
  2347. // in real servers, so we only verify the request succeeds.
  2348. {
  2349. Headers headers = {make_range_header({{0, 32}})};
  2350. auto res = cli.Get(path, headers);
  2351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2352. }
  2353. }
  2354. TEST(RangeTest, IgnoredForPost) {
  2355. Server svr;
  2356. svr.Post("/", [](const Request &, Response &res) {
  2357. res.set_content("abcdefg", "text/plain");
  2358. });
  2359. auto port = svr.bind_to_any_port(HOST);
  2360. ASSERT_GT(port, 0);
  2361. thread t = thread([&] { svr.listen_after_bind(); });
  2362. auto se = detail::scope_exit([&] {
  2363. svr.stop();
  2364. t.join();
  2365. ASSERT_FALSE(svr.is_running());
  2366. });
  2367. svr.wait_until_ready();
  2368. Client cli(HOST, port);
  2369. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2370. auto res = cli.Post("/", Headers{{"Range", range}});
  2371. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2372. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2373. EXPECT_EQ("abcdefg", res->body) << range;
  2374. }
  2375. }
  2376. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2377. auto host = "unresolvableaddress.local";
  2378. auto path = std::string{"/"};
  2379. #ifdef CPPHTTPLIB_SSL_ENABLED
  2380. auto port = 443;
  2381. SSLClient cli(host, port);
  2382. #else
  2383. auto port = 80;
  2384. Client cli(host, port);
  2385. #endif
  2386. cli.set_connection_timeout(1);
  2387. {
  2388. auto res = cli.Get(path);
  2389. ASSERT_FALSE(res);
  2390. }
  2391. std::this_thread::sleep_for(std::chrono::seconds(8));
  2392. }
  2393. #if defined(__linux__) && defined(__GLIBC__) && \
  2394. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2395. // Forward declaration: in split builds split.py strips `inline` and moves the
  2396. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2397. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2398. // against the symbol in both header-only and split builds.
  2399. namespace httplib {
  2400. namespace detail {
  2401. int getaddrinfo_with_timeout(const char *node, const char *service,
  2402. const struct addrinfo *hints,
  2403. struct addrinfo **res, time_t timeout_sec);
  2404. } // namespace detail
  2405. } // namespace httplib
  2406. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2407. //
  2408. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2409. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2410. // gai_suspend() call hits the connection timeout the function calls
  2411. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2412. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2413. // still alive and still references the now-destroyed stack frame.
  2414. //
  2415. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2416. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2417. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2418. // and runs them in a container.
  2419. namespace {
  2420. bool should_run_issue_2431_tests() {
  2421. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2422. return v && *v && std::string(v) != "0";
  2423. }
  2424. std::string unique_unresolvable_host(int n) {
  2425. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2426. // glibc still asks the configured nameserver — which is exactly the path
  2427. // we want to exercise. A unique label per call avoids the resolver cache.
  2428. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2429. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2430. std::to_string(n) + ".invalid";
  2431. }
  2432. } // namespace
  2433. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2434. if (!should_run_issue_2431_tests()) {
  2435. GTEST_SKIP()
  2436. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2437. }
  2438. for (int i = 0; i < 8; ++i) {
  2439. struct addrinfo hints;
  2440. memset(&hints, 0, sizeof(hints));
  2441. hints.ai_family = AF_UNSPEC;
  2442. hints.ai_socktype = SOCK_STREAM;
  2443. auto host = unique_unresolvable_host(i);
  2444. struct addrinfo *result = nullptr;
  2445. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2446. &result, /*timeout_sec=*/1);
  2447. if (rc == 0 && result) { freeaddrinfo(result); }
  2448. }
  2449. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2450. // stack region they still believe holds their gaicb.
  2451. std::this_thread::sleep_for(std::chrono::seconds(3));
  2452. }
  2453. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2454. if (!should_run_issue_2431_tests()) {
  2455. GTEST_SKIP()
  2456. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2457. }
  2458. std::atomic<bool> stop{false};
  2459. std::vector<std::thread> threads;
  2460. for (int t = 0; t < 8; ++t) {
  2461. threads.emplace_back([t, &stop] {
  2462. int i = 0;
  2463. while (!stop.load(std::memory_order_relaxed)) {
  2464. struct addrinfo hints;
  2465. memset(&hints, 0, sizeof(hints));
  2466. hints.ai_family = AF_UNSPEC;
  2467. hints.ai_socktype = SOCK_STREAM;
  2468. auto host = unique_unresolvable_host(t * 100000 + i++);
  2469. struct addrinfo *result = nullptr;
  2470. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2471. &result, /*timeout_sec=*/1);
  2472. if (rc == 0 && result) { freeaddrinfo(result); }
  2473. }
  2474. });
  2475. }
  2476. std::this_thread::sleep_for(std::chrono::seconds(8));
  2477. stop.store(true, std::memory_order_relaxed);
  2478. for (auto &th : threads) {
  2479. th.join();
  2480. }
  2481. std::this_thread::sleep_for(std::chrono::seconds(3));
  2482. }
  2483. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2484. if (!should_run_issue_2431_tests()) {
  2485. GTEST_SKIP()
  2486. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2487. }
  2488. std::atomic<bool> stop{false};
  2489. std::vector<std::thread> threads;
  2490. for (int t = 0; t < 8; ++t) {
  2491. threads.emplace_back([t, &stop] {
  2492. int i = 0;
  2493. while (!stop.load(std::memory_order_relaxed)) {
  2494. auto host = unique_unresolvable_host(t * 100000 + i++);
  2495. Client cli(host, 80);
  2496. cli.set_connection_timeout(1, 0);
  2497. cli.set_read_timeout(1, 0);
  2498. cli.set_write_timeout(1, 0);
  2499. (void)cli.Get("/");
  2500. }
  2501. });
  2502. }
  2503. std::this_thread::sleep_for(std::chrono::seconds(8));
  2504. stop.store(true, std::memory_order_relaxed);
  2505. for (auto &th : threads) {
  2506. th.join();
  2507. }
  2508. std::this_thread::sleep_for(std::chrono::seconds(3));
  2509. }
  2510. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2511. TEST(ConnectionErrorTest, InvalidHost) {
  2512. auto host = "-abcde.com";
  2513. #ifdef CPPHTTPLIB_SSL_ENABLED
  2514. auto port = 443;
  2515. SSLClient cli(host, port);
  2516. #else
  2517. auto port = 80;
  2518. Client cli(host, port);
  2519. #endif
  2520. cli.set_connection_timeout(std::chrono::seconds(2));
  2521. auto res = cli.Get("/");
  2522. ASSERT_TRUE(!res);
  2523. EXPECT_EQ(Error::Connection, res.error());
  2524. }
  2525. TEST(ConnectionErrorTest, InvalidHost2) {
  2526. auto host = "httpcan.org/";
  2527. #ifdef CPPHTTPLIB_SSL_ENABLED
  2528. SSLClient cli(host);
  2529. #else
  2530. Client cli(host);
  2531. #endif
  2532. cli.set_connection_timeout(std::chrono::seconds(2));
  2533. auto res = cli.Get("/");
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::Connection, res.error());
  2536. }
  2537. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2538. auto host = "httpcan.org/";
  2539. #ifdef CPPHTTPLIB_SSL_ENABLED
  2540. SSLClient cli(host);
  2541. #else
  2542. Client cli(host);
  2543. #endif
  2544. cli.set_connection_timeout(std::chrono::seconds(2));
  2545. auto res = cli.Get("/");
  2546. ASSERT_TRUE(!res);
  2547. stringstream s;
  2548. s << "error code: " << res.error();
  2549. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2550. }
  2551. TEST(ConnectionErrorTest, InvalidPort) {
  2552. auto host = "localhost";
  2553. auto port = 44380;
  2554. #ifdef CPPHTTPLIB_SSL_ENABLED
  2555. SSLClient cli(host, port);
  2556. #else
  2557. Client cli(host, port);
  2558. #endif
  2559. cli.set_connection_timeout(std::chrono::seconds(2));
  2560. auto res = cli.Get("/");
  2561. ASSERT_TRUE(!res);
  2562. EXPECT_TRUE(Error::Connection == res.error() ||
  2563. Error::ConnectionTimeout == res.error());
  2564. }
  2565. TEST(ConnectionErrorTest, Timeout_Online) {
  2566. auto host = "google.com";
  2567. #ifdef CPPHTTPLIB_SSL_ENABLED
  2568. auto port = 44380;
  2569. SSLClient cli(host, port);
  2570. #else
  2571. auto port = 8080;
  2572. Client cli(host, port);
  2573. #endif
  2574. cli.set_connection_timeout(std::chrono::seconds(2));
  2575. // only probe one address type so that the error reason
  2576. // correlates to the timed-out IPv4, not the unsupported
  2577. // IPv6 connection attempt
  2578. cli.set_address_family(AF_INET);
  2579. auto res = cli.Get("/");
  2580. ASSERT_TRUE(!res);
  2581. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2582. }
  2583. TEST(CancelTest, NoCancel_Online) {
  2584. auto host = "httpbingo.org";
  2585. auto path = std::string{"/range/32"};
  2586. #ifdef CPPHTTPLIB_SSL_ENABLED
  2587. auto port = 443;
  2588. SSLClient cli(host, port);
  2589. #else
  2590. auto port = 80;
  2591. Client cli(host, port);
  2592. #endif
  2593. cli.set_connection_timeout(std::chrono::seconds(5));
  2594. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2596. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2597. EXPECT_EQ(StatusCode::OK_200, res->status);
  2598. }
  2599. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2600. // Use /bytes with a large payload so that the DownloadProgress callback
  2601. // (which only fires for Content-Length responses) is invoked before the
  2602. // entire body is received, giving cancellation a chance to fire.
  2603. auto host = "httpbingo.org";
  2604. auto path = std::string{"/bytes/524288"};
  2605. #ifdef CPPHTTPLIB_SSL_ENABLED
  2606. auto port = 443;
  2607. SSLClient cli(host, port);
  2608. #else
  2609. auto port = 80;
  2610. Client cli(host, port);
  2611. #endif
  2612. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2613. cli.set_connection_timeout(std::chrono::seconds(5));
  2614. ASSERT_TRUE(!res);
  2615. EXPECT_EQ(Error::Canceled, res.error());
  2616. }
  2617. TEST(CancelTest, WithCancelLargePayload_Online) {
  2618. auto host = "httpbingo.org";
  2619. auto path = std::string{"/bytes/524288"};
  2620. #ifdef CPPHTTPLIB_SSL_ENABLED
  2621. auto port = 443;
  2622. SSLClient cli(host, port);
  2623. #else
  2624. auto port = 80;
  2625. Client cli(host, port);
  2626. #endif
  2627. cli.set_connection_timeout(std::chrono::seconds(5));
  2628. uint32_t count = 0;
  2629. auto res =
  2630. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2631. ASSERT_TRUE(!res);
  2632. EXPECT_EQ(Error::Canceled, res.error());
  2633. }
  2634. TEST(CancelTest, NoCancelPost) {
  2635. Server svr;
  2636. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2637. res.set_content("Hello World!", "text/plain");
  2638. });
  2639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2640. auto se = detail::scope_exit([&] {
  2641. svr.stop();
  2642. thread.join();
  2643. ASSERT_FALSE(svr.is_running());
  2644. });
  2645. svr.wait_until_ready();
  2646. Client cli(HOST, PORT);
  2647. cli.set_connection_timeout(std::chrono::seconds(5));
  2648. auto res =
  2649. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2650. "application/json", [](uint64_t, uint64_t) { return true; });
  2651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2652. EXPECT_EQ("Hello World!", res->body);
  2653. EXPECT_EQ(StatusCode::OK_200, res->status);
  2654. }
  2655. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2656. Server svr;
  2657. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2658. res.set_content("Hello World!", "text/plain");
  2659. });
  2660. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2661. auto se = detail::scope_exit([&] {
  2662. svr.stop();
  2663. thread.join();
  2664. ASSERT_FALSE(svr.is_running());
  2665. });
  2666. svr.wait_until_ready();
  2667. Client cli(HOST, PORT);
  2668. cli.set_connection_timeout(std::chrono::seconds(5));
  2669. auto res =
  2670. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2671. "application/json", [](uint64_t, uint64_t) { return false; });
  2672. ASSERT_TRUE(!res);
  2673. EXPECT_EQ(Error::Canceled, res.error());
  2674. }
  2675. TEST(CancelTest, WithCancelLargePayloadPost) {
  2676. Server svr;
  2677. svr.set_payload_max_length(200 * 1024 * 1024);
  2678. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2679. res.set_content(LARGE_DATA, "text/plain");
  2680. });
  2681. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2682. auto se = detail::scope_exit([&] {
  2683. svr.stop();
  2684. thread.join();
  2685. ASSERT_FALSE(svr.is_running());
  2686. });
  2687. svr.wait_until_ready();
  2688. Client cli(HOST, PORT);
  2689. cli.set_payload_max_length(200 * 1024 * 1024);
  2690. cli.set_connection_timeout(std::chrono::seconds(5));
  2691. auto res =
  2692. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2693. "application/json", [](uint64_t, uint64_t) { return false; });
  2694. ASSERT_TRUE(!res);
  2695. EXPECT_EQ(Error::Canceled, res.error());
  2696. }
  2697. TEST(CancelTest, NoCancelPut) {
  2698. Server svr;
  2699. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2700. res.set_content("Hello World!", "text/plain");
  2701. });
  2702. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2703. auto se = detail::scope_exit([&] {
  2704. svr.stop();
  2705. thread.join();
  2706. ASSERT_FALSE(svr.is_running());
  2707. });
  2708. svr.wait_until_ready();
  2709. Client cli(HOST, PORT);
  2710. cli.set_connection_timeout(std::chrono::seconds(5));
  2711. auto res =
  2712. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2713. "application/json", [](uint64_t, uint64_t) { return true; });
  2714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2715. EXPECT_EQ("Hello World!", res->body);
  2716. EXPECT_EQ(StatusCode::OK_200, res->status);
  2717. }
  2718. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2719. Server svr;
  2720. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2721. res.set_content("Hello World!", "text/plain");
  2722. });
  2723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2724. auto se = detail::scope_exit([&] {
  2725. svr.stop();
  2726. thread.join();
  2727. ASSERT_FALSE(svr.is_running());
  2728. });
  2729. svr.wait_until_ready();
  2730. Client cli(HOST, PORT);
  2731. cli.set_connection_timeout(std::chrono::seconds(5));
  2732. auto res =
  2733. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2734. "application/json", [](uint64_t, uint64_t) { return false; });
  2735. ASSERT_TRUE(!res);
  2736. EXPECT_EQ(Error::Canceled, res.error());
  2737. }
  2738. TEST(CancelTest, WithCancelLargePayloadPut) {
  2739. Server svr;
  2740. svr.set_payload_max_length(200 * 1024 * 1024);
  2741. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2742. res.set_content(LARGE_DATA, "text/plain");
  2743. });
  2744. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2745. auto se = detail::scope_exit([&] {
  2746. svr.stop();
  2747. thread.join();
  2748. ASSERT_FALSE(svr.is_running());
  2749. });
  2750. svr.wait_until_ready();
  2751. Client cli(HOST, PORT);
  2752. cli.set_payload_max_length(200 * 1024 * 1024);
  2753. cli.set_connection_timeout(std::chrono::seconds(5));
  2754. auto res =
  2755. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2756. "application/json", [](uint64_t, uint64_t) { return false; });
  2757. ASSERT_TRUE(!res);
  2758. EXPECT_EQ(Error::Canceled, res.error());
  2759. }
  2760. TEST(CancelTest, NoCancelPatch) {
  2761. Server svr;
  2762. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2763. res.set_content("Hello World!", "text/plain");
  2764. });
  2765. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2766. auto se = detail::scope_exit([&] {
  2767. svr.stop();
  2768. thread.join();
  2769. ASSERT_FALSE(svr.is_running());
  2770. });
  2771. svr.wait_until_ready();
  2772. Client cli(HOST, PORT);
  2773. cli.set_connection_timeout(std::chrono::seconds(5));
  2774. auto res =
  2775. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2776. "application/json", [](uint64_t, uint64_t) { return true; });
  2777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2778. EXPECT_EQ("Hello World!", res->body);
  2779. EXPECT_EQ(StatusCode::OK_200, res->status);
  2780. }
  2781. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2782. Server svr;
  2783. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2784. res.set_content("Hello World!", "text/plain");
  2785. });
  2786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2787. auto se = detail::scope_exit([&] {
  2788. svr.stop();
  2789. thread.join();
  2790. ASSERT_FALSE(svr.is_running());
  2791. });
  2792. svr.wait_until_ready();
  2793. Client cli(HOST, PORT);
  2794. cli.set_connection_timeout(std::chrono::seconds(5));
  2795. auto res =
  2796. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2797. "application/json", [](uint64_t, uint64_t) { return false; });
  2798. ASSERT_TRUE(!res);
  2799. EXPECT_EQ(Error::Canceled, res.error());
  2800. }
  2801. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2802. Server svr;
  2803. svr.set_payload_max_length(200 * 1024 * 1024);
  2804. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2805. res.set_content(LARGE_DATA, "text/plain");
  2806. });
  2807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2808. auto se = detail::scope_exit([&] {
  2809. svr.stop();
  2810. thread.join();
  2811. ASSERT_FALSE(svr.is_running());
  2812. });
  2813. svr.wait_until_ready();
  2814. Client cli(HOST, PORT);
  2815. cli.set_payload_max_length(200 * 1024 * 1024);
  2816. cli.set_connection_timeout(std::chrono::seconds(5));
  2817. auto res =
  2818. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2819. "application/json", [](uint64_t, uint64_t) { return false; });
  2820. ASSERT_TRUE(!res);
  2821. EXPECT_EQ(Error::Canceled, res.error());
  2822. }
  2823. TEST(CancelTest, NoCancelDelete) {
  2824. Server svr;
  2825. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2826. res.set_content("Hello World!", "text/plain");
  2827. });
  2828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2829. auto se = detail::scope_exit([&] {
  2830. svr.stop();
  2831. thread.join();
  2832. ASSERT_FALSE(svr.is_running());
  2833. });
  2834. svr.wait_until_ready();
  2835. Client cli(HOST, PORT);
  2836. cli.set_connection_timeout(std::chrono::seconds(5));
  2837. auto res =
  2838. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2839. "application/json", [](uint64_t, uint64_t) { return true; });
  2840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2841. EXPECT_EQ("Hello World!", res->body);
  2842. EXPECT_EQ(StatusCode::OK_200, res->status);
  2843. }
  2844. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2845. Server svr;
  2846. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2847. res.set_content("Hello World!", "text/plain");
  2848. });
  2849. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2850. auto se = detail::scope_exit([&] {
  2851. svr.stop();
  2852. thread.join();
  2853. ASSERT_FALSE(svr.is_running());
  2854. });
  2855. svr.wait_until_ready();
  2856. Client cli(HOST, PORT);
  2857. cli.set_connection_timeout(std::chrono::seconds(5));
  2858. auto res =
  2859. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2860. "application/json", [](uint64_t, uint64_t) { return false; });
  2861. ASSERT_TRUE(!res);
  2862. EXPECT_EQ(Error::Canceled, res.error());
  2863. }
  2864. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2865. Server svr;
  2866. svr.set_payload_max_length(200 * 1024 * 1024);
  2867. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2868. res.set_content(LARGE_DATA, "text/plain");
  2869. });
  2870. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2871. auto se = detail::scope_exit([&] {
  2872. svr.stop();
  2873. thread.join();
  2874. ASSERT_FALSE(svr.is_running());
  2875. });
  2876. svr.wait_until_ready();
  2877. Client cli(HOST, PORT);
  2878. cli.set_payload_max_length(200 * 1024 * 1024);
  2879. cli.set_connection_timeout(std::chrono::seconds(5));
  2880. auto res =
  2881. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2882. "application/json", [](uint64_t, uint64_t) { return false; });
  2883. ASSERT_TRUE(!res);
  2884. EXPECT_EQ(Error::Canceled, res.error());
  2885. }
  2886. static std::string remove_whitespace(const std::string &input) {
  2887. std::string output;
  2888. output.reserve(input.size());
  2889. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2890. [](unsigned char c) { return !std::isspace(c); });
  2891. return output;
  2892. }
  2893. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2894. auto host = "httpbingo.org";
  2895. auto path = std::string{"/basic-auth/hello/world"};
  2896. #ifdef CPPHTTPLIB_SSL_ENABLED
  2897. auto port = 443;
  2898. SSLClient cli(host, port);
  2899. #else
  2900. auto port = 80;
  2901. Client cli(host, port);
  2902. #endif
  2903. {
  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. auto res = cli.Get(
  2910. path, Headers{make_basic_authentication_header("hello", "world")});
  2911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2912. auto body = remove_whitespace(res->body);
  2913. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2914. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. }
  2917. {
  2918. cli.set_basic_auth("hello", "world");
  2919. auto res = cli.Get(path);
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. auto body = remove_whitespace(res->body);
  2922. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2923. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2924. EXPECT_EQ(StatusCode::OK_200, res->status);
  2925. }
  2926. {
  2927. cli.set_basic_auth("hello", "bad");
  2928. auto res = cli.Get(path);
  2929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2930. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2931. }
  2932. {
  2933. cli.set_basic_auth("bad", "world");
  2934. auto res = cli.Get(path);
  2935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2936. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2937. }
  2938. }
  2939. #ifdef CPPHTTPLIB_SSL_ENABLED
  2940. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2941. auto host = "httpbingo.org";
  2942. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2943. auto paths = std::vector<std::string>{
  2944. "/digest-auth/auth/hello/world/MD5",
  2945. "/digest-auth/auth/hello/world/SHA-256",
  2946. };
  2947. auto port = 443;
  2948. SSLClient cli(host, port);
  2949. {
  2950. auto res = cli.Get(unauth_path);
  2951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2952. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2953. }
  2954. {
  2955. cli.set_digest_auth("hello", "world");
  2956. for (const auto &path : paths) {
  2957. auto res = cli.Get(path.c_str());
  2958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2959. auto body = remove_whitespace(res->body);
  2960. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2961. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2962. EXPECT_EQ(StatusCode::OK_200, res->status);
  2963. }
  2964. cli.set_digest_auth("hello", "bad");
  2965. for (const auto &path : paths) {
  2966. auto res = cli.Get(path.c_str());
  2967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2968. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2969. }
  2970. }
  2971. }
  2972. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2973. // comma-separated list of challenges, and each challenge may itself carry a
  2974. // comma-separated auth-param list, so a server can legally offer Basic
  2975. // before Digest, either as two field lines or packed into one. Runs one 401
  2976. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2977. // value() joins them in receipt order) and checks that the retry carries a
  2978. // well-formed Digest Authorization header naming expected_realm.
  2979. static void
  2980. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2981. const std::string &expected_realm) {
  2982. std::atomic<int> hits{0};
  2983. Server svr;
  2984. svr.Get("/x", [&](const Request &req, Response &res) {
  2985. if (++hits == 1) {
  2986. res.status = StatusCode::Unauthorized_401;
  2987. for (const auto &challenge : challenges) {
  2988. res.set_header("WWW-Authenticate", challenge);
  2989. }
  2990. } else {
  2991. auto authorization = req.get_header_value("Authorization");
  2992. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2993. EXPECT_NE(std::string::npos,
  2994. authorization.find("realm=\"" + expected_realm + "\""));
  2995. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2996. res.set_content("ok", "text/plain");
  2997. }
  2998. });
  2999. auto port = svr.bind_to_any_port(HOST);
  3000. std::thread t([&]() { svr.listen_after_bind(); });
  3001. auto se = detail::scope_exit([&] {
  3002. svr.stop();
  3003. t.join();
  3004. });
  3005. svr.wait_until_ready();
  3006. Client cli(HOST, port);
  3007. cli.set_digest_auth("hello", "world");
  3008. auto res = cli.Get("/x");
  3009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3010. EXPECT_EQ(2, hits.load());
  3011. }
  3012. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3013. static const char *kDigestChallenge =
  3014. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3015. "algorithm=MD5";
  3016. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3017. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3018. "testrealm");
  3019. }
  3020. // Same challenge list with the schemes in the opposite order, to make sure
  3021. // the fix above didn't just special-case "Basic first".
  3022. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3023. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3024. "testrealm");
  3025. }
  3026. // A comma inside a quoted auth-param value must not be mistaken for the
  3027. // separator between two challenges (or two auth-params).
  3028. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3029. run_digest_challenge_list_test(
  3030. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3031. "algorithm=MD5"},
  3032. "test,realm");
  3033. }
  3034. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3035. // the params and leaves out the fragment.
  3036. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3037. Server svr;
  3038. std::string uri, target;
  3039. svr.Get("/a b", [&](const Request &req, Response &res) {
  3040. auto auth = req.get_header_value("Authorization");
  3041. if (auth.empty()) {
  3042. res.status = StatusCode::Unauthorized_401;
  3043. res.set_header("WWW-Authenticate",
  3044. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3045. return;
  3046. }
  3047. auto b = auth.find("uri=\"") + 5;
  3048. uri = auth.substr(b, auth.find('"', b) - b);
  3049. target = req.target;
  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("/a b#f", Params{{"x", "1"}}, Headers{});
  3061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3062. EXPECT_EQ("/a%20b?x=1", target);
  3063. EXPECT_EQ(target, uri);
  3064. }
  3065. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3066. // make_digest_authentication_header() dereferences both unconditionally, so
  3067. // a server sending a challenge missing either one must not be treated as
  3068. // usable -- doing so used to crash the client with std::out_of_range.
  3069. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3070. Server svr;
  3071. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3072. res.status = StatusCode::Unauthorized_401;
  3073. res.set_header("WWW-Authenticate", challenge);
  3074. });
  3075. auto port = svr.bind_to_any_port(HOST);
  3076. std::thread t([&]() { svr.listen_after_bind(); });
  3077. auto se = detail::scope_exit([&] {
  3078. svr.stop();
  3079. t.join();
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(HOST, port);
  3083. cli.set_digest_auth("hello", "world");
  3084. auto res = cli.Get("/x");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3087. }
  3088. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3089. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3090. }
  3091. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3092. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3093. }
  3094. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3095. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3096. }
  3097. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3098. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3099. // when storing the values, so the header builder has to re-escape them (and
  3100. // keep algorithm a bare token); otherwise the value breaks out of its
  3101. // quoted-string and injects extra auth-params into the client's Authorization.
  3102. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3103. std::atomic<int> hits{0};
  3104. std::string authorization;
  3105. Server svr;
  3106. svr.Get("/x", [&](const Request &req, Response &res) {
  3107. if (++hits == 1) {
  3108. res.status = StatusCode::Unauthorized_401;
  3109. // On the wire the quotes embedded in the values are backslash-escaped.
  3110. res.set_header("WWW-Authenticate",
  3111. "Digest realm=\"testrealm\", "
  3112. "nonce=\"n\\\"; injected=\\\"x\", "
  3113. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3114. } else {
  3115. authorization = req.get_header_value("Authorization");
  3116. res.set_content("ok", "text/plain");
  3117. }
  3118. });
  3119. auto port = svr.bind_to_any_port(HOST);
  3120. std::thread t([&]() { svr.listen_after_bind(); });
  3121. auto se = detail::scope_exit([&] {
  3122. svr.stop();
  3123. t.join();
  3124. });
  3125. svr.wait_until_ready();
  3126. Client cli(HOST, port);
  3127. cli.set_digest_auth("hello", "world");
  3128. auto res = cli.Get("/x");
  3129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3130. EXPECT_EQ(2, hits.load());
  3131. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3132. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3133. // inside its quoted-string rather than starting an "injected" auth-param.
  3134. EXPECT_NE(std::string::npos,
  3135. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3136. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3137. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3138. }
  3139. #endif
  3140. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3141. auto host = "google.com";
  3142. auto another_host = "example.com";
  3143. auto wrong_ip = "0.0.0.0";
  3144. #ifdef CPPHTTPLIB_SSL_ENABLED
  3145. SSLClient cli(host);
  3146. #else
  3147. Client cli(host);
  3148. #endif
  3149. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3150. auto res = cli.Get("/");
  3151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3152. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3153. }
  3154. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3155. auto host = "google.com";
  3156. auto wrong_ip = "0.0.0.0";
  3157. #ifdef CPPHTTPLIB_SSL_ENABLED
  3158. SSLClient cli(host);
  3159. #else
  3160. Client cli(host);
  3161. #endif
  3162. cli.set_hostname_addr_map({{host, wrong_ip}});
  3163. auto res = cli.Get("/");
  3164. ASSERT_TRUE(!res);
  3165. EXPECT_EQ(Error::Connection, res.error());
  3166. }
  3167. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3168. // A mapped value that is not an IP literal must be resolved. "localhost"
  3169. // resolves from the hosts file, so this test needs no external DNS.
  3170. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3171. auto host = "target.invalid";
  3172. Server svr;
  3173. std::string received_host;
  3174. svr.Get("/hi", [&](const Request &req, Response &res) {
  3175. received_host = req.get_header_value("Host");
  3176. res.set_content("Hello World!", "text/plain");
  3177. });
  3178. auto port = svr.bind_to_any_port(HOST);
  3179. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3180. auto se = detail::scope_exit([&] {
  3181. svr.stop();
  3182. thread.join();
  3183. ASSERT_FALSE(svr.is_running());
  3184. });
  3185. svr.wait_until_ready();
  3186. Client cli(host, port);
  3187. cli.set_hostname_addr_map({{host, HOST}});
  3188. auto res = cli.Get("/hi");
  3189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3190. EXPECT_EQ(StatusCode::OK_200, res->status);
  3191. // The mapping only redirects the connection; the identity stays host_.
  3192. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3193. }
  3194. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3195. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3196. auto host = "target.invalid";
  3197. Server svr;
  3198. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3199. res.set_content("Hello World!", "text/plain");
  3200. });
  3201. auto port = svr.bind_to_any_port("127.0.0.1");
  3202. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3203. auto se = detail::scope_exit([&] {
  3204. svr.stop();
  3205. thread.join();
  3206. ASSERT_FALSE(svr.is_running());
  3207. });
  3208. svr.wait_until_ready();
  3209. Client cli(host, port);
  3210. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3211. auto res = cli.Get("/hi");
  3212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3213. EXPECT_EQ(StatusCode::OK_200, res->status);
  3214. }
  3215. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3216. // An empty mapped value must leave host_ as the connection target. Without
  3217. // that guard the empty value would become the host argument, getaddrinfo
  3218. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3219. // loopback - silently connecting somewhere the caller never asked for.
  3220. // The server listens on loopback, so such a fallback would succeed and is
  3221. // therefore observable as a failure of this test.
  3222. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3223. Server svr;
  3224. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3225. res.set_content("Hello World!", "text/plain");
  3226. });
  3227. auto port = svr.bind_to_any_port(HOST);
  3228. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3229. auto se = detail::scope_exit([&] {
  3230. svr.stop();
  3231. thread.join();
  3232. ASSERT_FALSE(svr.is_running());
  3233. });
  3234. svr.wait_until_ready();
  3235. Client cli(blackhole, port);
  3236. cli.set_hostname_addr_map({{blackhole, ""}});
  3237. cli.set_connection_timeout(1);
  3238. auto res = cli.Get("/hi");
  3239. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3240. }
  3241. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3242. auto host = "httpbingo.org";
  3243. auto path = std::string{"/absolute-redirect/3"};
  3244. #ifdef CPPHTTPLIB_SSL_ENABLED
  3245. SSLClient cli(host);
  3246. #else
  3247. Client cli(host);
  3248. #endif
  3249. cli.set_follow_location(true);
  3250. auto res = cli.Get(path);
  3251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3252. EXPECT_EQ(StatusCode::OK_200, res->status);
  3253. }
  3254. TEST(RedirectTest, Redirect_Online) {
  3255. auto host = "httpbingo.org";
  3256. auto path = std::string{"/redirect/3"};
  3257. #ifdef CPPHTTPLIB_SSL_ENABLED
  3258. SSLClient cli(host);
  3259. #else
  3260. Client cli(host);
  3261. #endif
  3262. cli.set_follow_location(true);
  3263. auto res = cli.Get(path);
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. }
  3267. TEST(RelativeRedirectTest, Redirect_Online) {
  3268. auto host = "httpbingo.org";
  3269. auto path = std::string{"/relative-redirect/3"};
  3270. #ifdef CPPHTTPLIB_SSL_ENABLED
  3271. SSLClient cli(host);
  3272. #else
  3273. Client cli(host);
  3274. #endif
  3275. cli.set_follow_location(true);
  3276. auto res = cli.Get(path);
  3277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3278. EXPECT_EQ(StatusCode::OK_200, res->status);
  3279. }
  3280. TEST(TooManyRedirectTest, Redirect_Online) {
  3281. auto host = "httpbingo.org";
  3282. auto path = std::string{"/redirect/21"};
  3283. #ifdef CPPHTTPLIB_SSL_ENABLED
  3284. SSLClient cli(host);
  3285. #else
  3286. Client cli(host);
  3287. #endif
  3288. cli.set_follow_location(true);
  3289. auto res = cli.Get(path);
  3290. ASSERT_TRUE(!res);
  3291. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3292. }
  3293. #ifdef CPPHTTPLIB_SSL_ENABLED
  3294. TEST(YahooRedirectTest, Redirect_Online) {
  3295. Client cli("yahoo.com");
  3296. auto res = cli.Get("/");
  3297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3298. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3299. cli.set_follow_location(true);
  3300. res = cli.Get("/");
  3301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3302. EXPECT_EQ(StatusCode::OK_200, res->status);
  3303. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3304. }
  3305. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3306. #define REDIR_HOST "httpbingo.org"
  3307. #define REDIR_PATH "/redirect-to"
  3308. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3309. SSLClient cli(REDIR_HOST);
  3310. cli.set_follow_location(true);
  3311. auto res =
  3312. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::OK_200, res->status);
  3315. }
  3316. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3317. SSLClient cli(REDIR_HOST);
  3318. cli.set_follow_location(true);
  3319. Params params;
  3320. params.emplace("url", "http://example.com");
  3321. params.emplace("status_code", "302");
  3322. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3324. EXPECT_EQ(StatusCode::OK_200, res->status);
  3325. }
  3326. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3327. SSLClient cli(REDIR_HOST);
  3328. cli.set_follow_location(true);
  3329. Params params;
  3330. params.emplace("url", "http://example.com");
  3331. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3333. EXPECT_EQ(StatusCode::OK_200, res->status);
  3334. }
  3335. TEST(UrlWithSpace, Redirect_Online) {
  3336. SSLClient cli("edge.forgecdn.net");
  3337. cli.set_follow_location(true);
  3338. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3340. EXPECT_EQ(StatusCode::OK_200, res->status);
  3341. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3342. }
  3343. #endif
  3344. #if !defined(_WIN32) && !defined(_WIN64)
  3345. TEST(ReceiveSignals, Signal) {
  3346. auto setupSignalHandlers = []() {
  3347. struct sigaction act;
  3348. sigemptyset(&act.sa_mask);
  3349. act.sa_flags = SA_SIGINFO;
  3350. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3351. switch (sig) {
  3352. case SIGINT:
  3353. default: break;
  3354. }
  3355. };
  3356. ::sigaction(SIGINT, &act, nullptr);
  3357. };
  3358. Server svr;
  3359. int port = 0;
  3360. auto thread = std::thread([&]() {
  3361. setupSignalHandlers();
  3362. port = svr.bind_to_any_port(HOST);
  3363. svr.listen_after_bind();
  3364. });
  3365. auto se = detail::scope_exit([&] {
  3366. svr.stop();
  3367. thread.join();
  3368. ASSERT_FALSE(svr.is_running());
  3369. });
  3370. svr.wait_until_ready();
  3371. ASSERT_TRUE(svr.is_running());
  3372. pthread_kill(thread.native_handle(), SIGINT);
  3373. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3374. ASSERT_TRUE(svr.is_running());
  3375. }
  3376. #endif
  3377. TEST(RedirectToDifferentPort, Redirect) {
  3378. Server svr1;
  3379. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3380. res.set_content("Hello World!", "text/plain");
  3381. });
  3382. int svr1_port = 0;
  3383. auto thread1 = std::thread([&]() {
  3384. svr1_port = svr1.bind_to_any_port(HOST);
  3385. svr1.listen_after_bind();
  3386. });
  3387. Server svr2;
  3388. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3389. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3390. });
  3391. int svr2_port = 0;
  3392. auto thread2 = std::thread([&]() {
  3393. svr2_port = svr2.bind_to_any_port(HOST);
  3394. svr2.listen_after_bind();
  3395. });
  3396. auto se = detail::scope_exit([&] {
  3397. svr2.stop();
  3398. thread2.join();
  3399. svr1.stop();
  3400. thread1.join();
  3401. ASSERT_FALSE(svr2.is_running());
  3402. ASSERT_FALSE(svr1.is_running());
  3403. });
  3404. svr1.wait_until_ready();
  3405. svr2.wait_until_ready();
  3406. Client cli("localhost", svr2_port);
  3407. cli.set_follow_location(true);
  3408. auto res = cli.Get("/2");
  3409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3410. EXPECT_EQ(StatusCode::OK_200, res->status);
  3411. EXPECT_EQ("Hello World!", res->body);
  3412. }
  3413. // GET /redir on one server redirects to /target on another port, so the
  3414. // client follows it with a new client.
  3415. static Result
  3416. GetThroughRedirectToDifferentPort(Server::Handler target,
  3417. const std::function<void(Client &)> &setup,
  3418. const Headers &headers = Headers()) {
  3419. Server target_svr;
  3420. target_svr.Get("/target", target);
  3421. int target_port = 0;
  3422. auto target_thread = std::thread([&]() {
  3423. target_port = target_svr.bind_to_any_port(HOST);
  3424. target_svr.listen_after_bind();
  3425. });
  3426. Server origin_svr;
  3427. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3428. res.set_redirect(
  3429. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3430. });
  3431. int origin_port = 0;
  3432. auto origin_thread = std::thread([&]() {
  3433. origin_port = origin_svr.bind_to_any_port(HOST);
  3434. origin_svr.listen_after_bind();
  3435. });
  3436. auto se = detail::scope_exit([&] {
  3437. origin_svr.stop();
  3438. origin_thread.join();
  3439. target_svr.stop();
  3440. target_thread.join();
  3441. });
  3442. target_svr.wait_until_ready();
  3443. origin_svr.wait_until_ready();
  3444. Client cli("localhost", origin_port);
  3445. cli.set_follow_location(true);
  3446. setup(cli);
  3447. return cli.Get("/redir", headers);
  3448. }
  3449. static void
  3450. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3451. std::string captured_authorization;
  3452. auto result = GetThroughRedirectToDifferentPort(
  3453. [&](const Request &req, Response &res) {
  3454. captured_authorization = req.get_header_value("Authorization");
  3455. res.set_content("OK", "text/plain");
  3456. },
  3457. set_auth);
  3458. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3459. EXPECT_EQ(StatusCode::OK_200, result->status);
  3460. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3461. EXPECT_TRUE(captured_authorization.empty());
  3462. }
  3463. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3464. TestDoNotForwardCredentialsOnRedirect(
  3465. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3466. }
  3467. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3468. TestDoNotForwardCredentialsOnRedirect(
  3469. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3470. }
  3471. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3472. std::string captured_cookie;
  3473. auto result = GetThroughRedirectToDifferentPort(
  3474. [&](const Request &req, Response &res) {
  3475. captured_cookie = req.get_header_value("Cookie");
  3476. res.set_content("OK", "text/plain");
  3477. },
  3478. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3479. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3480. EXPECT_EQ(StatusCode::OK_200, result->status);
  3481. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3482. EXPECT_TRUE(captured_cookie.empty());
  3483. }
  3484. TEST(RedirectToSamePort, ForwardCookie) {
  3485. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3486. // header so that ordinary session flows keep working.
  3487. Server svr;
  3488. std::string captured_cookie;
  3489. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3490. res.set_redirect("/target", 302);
  3491. });
  3492. svr.Get("/target", [&](const Request &req, Response &res) {
  3493. captured_cookie = req.get_header_value("Cookie");
  3494. res.set_content("OK", "text/plain");
  3495. });
  3496. auto port = svr.bind_to_any_port(HOST);
  3497. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3498. auto se = detail::scope_exit([&] {
  3499. svr.stop();
  3500. thread.join();
  3501. ASSERT_FALSE(svr.is_running());
  3502. });
  3503. svr.wait_until_ready();
  3504. Client cli(HOST, port);
  3505. cli.set_follow_location(true);
  3506. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3507. auto res = cli.Get("/redir", headers);
  3508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3509. EXPECT_EQ(StatusCode::OK_200, res->status);
  3510. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3511. }
  3512. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3513. std::string authorization;
  3514. std::string trace_id;
  3515. auto result = GetThroughRedirectToDifferentPort(
  3516. [&](const Request &req, Response &res) {
  3517. authorization = req.get_header_value("Authorization");
  3518. trace_id = req.get_header_value("X-Trace-Id");
  3519. res.set_content("OK", "text/plain");
  3520. },
  3521. [](Client &cli) {
  3522. cli.set_default_headers(
  3523. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3524. });
  3525. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3526. EXPECT_EQ(StatusCode::OK_200, result->status);
  3527. // Like a header given with the request, a default one goes along unless it
  3528. // carries credentials (RFC 9110 15.4).
  3529. EXPECT_TRUE(authorization.empty());
  3530. EXPECT_EQ("42", trace_id);
  3531. }
  3532. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3533. auto result = GetThroughRedirectToDifferentPort(
  3534. [](const Request &, Response &res) {
  3535. res.set_content(std::string(2048, 'x'), "text/plain");
  3536. },
  3537. [](Client &cli) { cli.set_payload_max_length(1024); });
  3538. EXPECT_FALSE(result);
  3539. }
  3540. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3541. auto result = GetThroughRedirectToDifferentPort(
  3542. [](const Request &req, Response &res) {
  3543. // Answer after a second, or once the client gives up.
  3544. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3545. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3546. }
  3547. res.set_content("late", "text/plain");
  3548. },
  3549. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3550. ASSERT_FALSE(result);
  3551. EXPECT_EQ(Error::Read, result.error());
  3552. }
  3553. #ifdef CPPHTTPLIB_SSL_ENABLED
  3554. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3555. auto result = GetThroughRedirectToDifferentPort(
  3556. [](const Request &, Response &res) {
  3557. res.status = StatusCode::Unauthorized_401;
  3558. res.set_header("WWW-Authenticate",
  3559. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3560. },
  3561. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3562. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3563. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3564. }
  3565. #endif
  3566. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3567. Server svr;
  3568. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3569. // Port number that overflows int — should not crash
  3570. res.set_redirect("http://localhost:99999999999999999999/target");
  3571. });
  3572. auto port = svr.bind_to_any_port(HOST);
  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. // Should fail gracefully, not crash (no valid response due to bad port)
  3584. EXPECT_FALSE(res);
  3585. }
  3586. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3587. Server svr;
  3588. auto port = svr.bind_to_any_port(HOST);
  3589. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3590. // The server's own port followed by junk must not be followed
  3591. res.set_redirect("http://" + std::string(HOST) + ":" +
  3592. std::to_string(port) + "junk/target");
  3593. });
  3594. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3595. res.set_content("target", "text/plain");
  3596. });
  3597. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3598. auto se = detail::scope_exit([&] {
  3599. svr.stop();
  3600. thread.join();
  3601. ASSERT_FALSE(svr.is_running());
  3602. });
  3603. svr.wait_until_ready();
  3604. Client cli(HOST, port);
  3605. cli.set_follow_location(true);
  3606. auto res = cli.Get("/redir");
  3607. EXPECT_FALSE(res);
  3608. }
  3609. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3610. Server svr;
  3611. std::atomic<bool> followed{false};
  3612. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3613. res.status = StatusCode::NotModified_304;
  3614. res.set_header("Location", "/target");
  3615. });
  3616. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3617. res.status = StatusCode::UseProxy_305;
  3618. res.set_header("Location", "/target");
  3619. });
  3620. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3621. followed = true;
  3622. res.set_content("target", "text/plain");
  3623. });
  3624. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3625. auto se = detail::scope_exit([&] {
  3626. svr.stop();
  3627. th.join();
  3628. ASSERT_FALSE(svr.is_running());
  3629. });
  3630. svr.wait_until_ready();
  3631. Client cli("localhost", PORT);
  3632. cli.set_follow_location(true);
  3633. auto res = cli.Get("/304");
  3634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3635. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3636. res = cli.Get("/305");
  3637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3638. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3639. EXPECT_FALSE(followed);
  3640. }
  3641. TEST(RedirectFromPageWithContent, Redirect) {
  3642. Server svr;
  3643. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3644. res.set_content("___", "text/plain");
  3645. res.set_redirect("/2");
  3646. });
  3647. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3648. res.set_content("Hello World!", "text/plain");
  3649. });
  3650. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3651. auto se = detail::scope_exit([&] {
  3652. svr.stop();
  3653. th.join();
  3654. ASSERT_FALSE(svr.is_running());
  3655. });
  3656. svr.wait_until_ready();
  3657. {
  3658. Client cli("localhost", PORT);
  3659. cli.set_follow_location(true);
  3660. std::string body;
  3661. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3662. body.append(data, data_length);
  3663. return true;
  3664. });
  3665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3666. EXPECT_EQ(StatusCode::OK_200, res->status);
  3667. EXPECT_EQ("Hello World!", body);
  3668. }
  3669. {
  3670. Client cli("localhost", PORT);
  3671. std::string body;
  3672. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3673. body.append(data, data_length);
  3674. return true;
  3675. });
  3676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3677. EXPECT_EQ(StatusCode::Found_302, res->status);
  3678. EXPECT_EQ("___", body);
  3679. }
  3680. }
  3681. // A server can close the connection after a request with "Connection: close"
  3682. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3683. // redirected request must go out on a new connection.
  3684. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3685. #ifndef _WIN32
  3686. signal(SIGPIPE, SIG_IGN);
  3687. #endif
  3688. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3689. default_socket_options(srv);
  3690. sockaddr_in addr{};
  3691. addr.sin_family = AF_INET;
  3692. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3693. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3694. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3695. ASSERT_EQ(0, ::listen(srv, 2));
  3696. auto send_text = [](socket_t sock, const std::string &text) {
  3697. ::send(sock,
  3698. #ifdef _WIN32
  3699. static_cast<const char *>(text.c_str()),
  3700. static_cast<int>(text.size()),
  3701. #else
  3702. text.c_str(), text.size(),
  3703. #endif
  3704. 0);
  3705. };
  3706. auto reused = false;
  3707. auto server_thread = std::thread([&] {
  3708. char buf[4096];
  3709. auto first = ::accept(srv, nullptr, nullptr);
  3710. if (first == INVALID_SOCKET) { return; }
  3711. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3712. ::recv(first, buf, sizeof(buf), 0);
  3713. send_text(
  3714. first,
  3715. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3716. auto next = first;
  3717. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3718. reused = true;
  3719. } else {
  3720. detail::close_socket(first);
  3721. next = ::accept(srv, nullptr, nullptr);
  3722. if (next == INVALID_SOCKET) { return; }
  3723. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3724. ::recv(next, buf, sizeof(buf), 0);
  3725. }
  3726. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3727. "Connection: close\r\n\r\nok");
  3728. detail::close_socket(next);
  3729. });
  3730. Client cli("127.0.0.1", PORT + 2);
  3731. cli.set_follow_location(true);
  3732. cli.set_read_timeout(5, 0);
  3733. auto res = cli.Get("/1");
  3734. server_thread.join();
  3735. detail::close_socket(srv);
  3736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3737. EXPECT_EQ(StatusCode::OK_200, res->status);
  3738. EXPECT_EQ("ok", res->body);
  3739. EXPECT_FALSE(reused);
  3740. }
  3741. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3742. Server svr;
  3743. auto port_str = std::to_string(PORT);
  3744. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3745. auto expected_host = "[::1]:" + port_str;
  3746. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3747. res.set_content("___", "text/plain");
  3748. // res.set_redirect("/2");
  3749. res.set_redirect(redirect_url);
  3750. });
  3751. svr.Get("/2", [&](const Request &req, Response &res) {
  3752. auto host_header = req.headers.find("Host");
  3753. ASSERT_TRUE(host_header != req.headers.end());
  3754. EXPECT_EQ(expected_host, host_header->second);
  3755. res.set_content("Hello World!", "text/plain");
  3756. });
  3757. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3758. auto se = detail::scope_exit([&] {
  3759. svr.stop();
  3760. th.join();
  3761. ASSERT_FALSE(svr.is_running());
  3762. });
  3763. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3764. // actually starts anything, so the condition !svr.is_running() will
  3765. // always remain true, and the loop never stops.
  3766. // This basically counts how many milliseconds have passed since the
  3767. // call to svr.listen(), and if after 5 seconds nothing started yet
  3768. // aborts the test.
  3769. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3770. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3771. ASSERT_LT(milliseconds, 5000U);
  3772. }
  3773. {
  3774. Client cli("::1", PORT);
  3775. cli.set_follow_location(true);
  3776. std::string body;
  3777. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3778. body.append(data, data_length);
  3779. return true;
  3780. });
  3781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3782. EXPECT_EQ(StatusCode::OK_200, res->status);
  3783. EXPECT_EQ("Hello World!", body);
  3784. }
  3785. {
  3786. Client cli("::1", PORT);
  3787. std::string body;
  3788. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3789. body.append(data, data_length);
  3790. return true;
  3791. });
  3792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3793. EXPECT_EQ(StatusCode::Found_302, res->status);
  3794. EXPECT_EQ("___", body);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3798. Server svr;
  3799. svr.Get("/foo", [](const Request &req, Response &res) {
  3800. auto a = req.params.find("a");
  3801. if (a != req.params.end()) {
  3802. res.set_content((*a).second, "text/plain");
  3803. res.status = StatusCode::OK_200;
  3804. } else {
  3805. res.status = StatusCode::BadRequest_400;
  3806. }
  3807. });
  3808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3809. auto se = detail::scope_exit([&] {
  3810. svr.stop();
  3811. thread.join();
  3812. ASSERT_FALSE(svr.is_running());
  3813. });
  3814. svr.wait_until_ready();
  3815. {
  3816. Client cli(HOST, PORT);
  3817. cli.set_path_encode(false);
  3818. auto res = cli.Get("/foo?a=explicitly+encoded");
  3819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3820. EXPECT_EQ(StatusCode::OK_200, res->status);
  3821. // This expects it back with a space, as the `+` won't have been
  3822. // url-encoded, and server-side the params get decoded turning `+`
  3823. // into spaces.
  3824. EXPECT_EQ("explicitly encoded", res->body);
  3825. }
  3826. }
  3827. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3828. // When path encoding is disabled the client must transmit the supplied
  3829. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3830. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3831. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3832. // than a space (0x20). Assert on the raw wire target to catch this.
  3833. Server svr;
  3834. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3835. svr.Get("/foo", [&](const Request &req, Response &res) {
  3836. EXPECT_EQ(expected_target, req.target);
  3837. res.status = StatusCode::OK_200;
  3838. });
  3839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3840. auto se = detail::scope_exit([&] {
  3841. svr.stop();
  3842. thread.join();
  3843. ASSERT_FALSE(svr.is_running());
  3844. });
  3845. svr.wait_until_ready();
  3846. {
  3847. Client cli(HOST, PORT);
  3848. cli.set_path_encode(false);
  3849. auto res = cli.Get(expected_target.c_str());
  3850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3851. EXPECT_EQ(StatusCode::OK_200, res->status);
  3852. }
  3853. }
  3854. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3855. // `open_stream()` used to skip the path encoding that the buffered send
  3856. // path applies, so the same `path` produced different bytes in the request
  3857. // line depending on which API was used. Assert the two agree.
  3858. Server svr;
  3859. std::string target;
  3860. svr.Get(".*", [&](const Request &req, Response &res) {
  3861. target = req.target;
  3862. res.status = StatusCode::OK_200;
  3863. });
  3864. auto port = svr.bind_to_any_port(HOST);
  3865. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3866. auto se = detail::scope_exit([&] {
  3867. svr.stop();
  3868. thread.join();
  3869. ASSERT_FALSE(svr.is_running());
  3870. });
  3871. svr.wait_until_ready();
  3872. struct {
  3873. const char *path;
  3874. const char *expected;
  3875. } cases[] = {
  3876. {"/a b?x=1", "/a%20b?x=1"},
  3877. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3878. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3879. };
  3880. for (const auto &c : cases) {
  3881. Client cli(HOST, port);
  3882. target.clear();
  3883. auto res = cli.Get(c.path);
  3884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3885. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3886. auto buffered_target = target;
  3887. target.clear();
  3888. auto handle = cli.open_stream("GET", c.path);
  3889. EXPECT_TRUE(handle.is_valid())
  3890. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3891. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3892. }
  3893. }
  3894. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3895. // The `set_path_encode(false)` contract — transmit the supplied target
  3896. // verbatim — must hold for the streaming API too.
  3897. Server svr;
  3898. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3899. std::string target;
  3900. svr.Get("/foo", [&](const Request &req, Response &res) {
  3901. target = req.target;
  3902. res.status = StatusCode::OK_200;
  3903. });
  3904. auto port = svr.bind_to_any_port(HOST);
  3905. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3906. auto se = detail::scope_exit([&] {
  3907. svr.stop();
  3908. thread.join();
  3909. ASSERT_FALSE(svr.is_running());
  3910. });
  3911. svr.wait_until_ready();
  3912. {
  3913. Client cli(HOST, port);
  3914. cli.set_path_encode(false);
  3915. auto handle = cli.open_stream("GET", expected_target);
  3916. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3917. EXPECT_EQ(expected_target, target);
  3918. }
  3919. }
  3920. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3921. // With path encoding enabled a CR/LF in the target is percent-encoded
  3922. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3923. // write_request_line still backstops `set_path_encode(false)`, which is
  3924. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3925. Server svr;
  3926. // Captured before routing: the decoded path contains a newline, which a
  3927. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3928. std::string target;
  3929. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3930. target = req.target;
  3931. res.status = StatusCode::OK_200;
  3932. return Server::HandlerResponse::Handled;
  3933. });
  3934. auto port = svr.bind_to_any_port(HOST);
  3935. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3936. auto se = detail::scope_exit([&] {
  3937. svr.stop();
  3938. thread.join();
  3939. ASSERT_FALSE(svr.is_running());
  3940. });
  3941. svr.wait_until_ready();
  3942. {
  3943. Client cli(HOST, port);
  3944. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3945. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3946. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3947. }
  3948. }
  3949. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3950. // Every control character is percent-encoded, not just CR/LF, so the target
  3951. // passes the request-target check in write_request_line.
  3952. Server svr;
  3953. std::string target;
  3954. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3955. target = req.target;
  3956. res.status = StatusCode::OK_200;
  3957. return Server::HandlerResponse::Handled;
  3958. });
  3959. auto port = svr.bind_to_any_port(HOST);
  3960. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3961. auto se = detail::scope_exit([&] {
  3962. svr.stop();
  3963. thread.join();
  3964. ASSERT_FALSE(svr.is_running());
  3965. });
  3966. svr.wait_until_ready();
  3967. {
  3968. Client cli(HOST, port);
  3969. auto res = cli.Get("/a\tb\x1b\x7f");
  3970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3971. EXPECT_EQ("/a%09b%1B%7F", target);
  3972. }
  3973. }
  3974. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3975. // Nothing may reach the wire: a raw CR/LF target would split the request
  3976. // line and inject headers.
  3977. Server svr;
  3978. // Pre-routing so that "not called" means nothing reached the server at all,
  3979. // rather than merely failing to match a handler pattern.
  3980. auto handler_called = false;
  3981. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3982. handler_called = true;
  3983. res.status = StatusCode::OK_200;
  3984. return Server::HandlerResponse::Handled;
  3985. });
  3986. auto port = svr.bind_to_any_port(HOST);
  3987. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3988. auto se = detail::scope_exit([&] {
  3989. svr.stop();
  3990. thread.join();
  3991. ASSERT_FALSE(svr.is_running());
  3992. });
  3993. svr.wait_until_ready();
  3994. {
  3995. Client cli(HOST, port);
  3996. cli.set_path_encode(false);
  3997. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3998. EXPECT_FALSE(handle.is_valid());
  3999. EXPECT_EQ(Error::Write, handle.error);
  4000. EXPECT_FALSE(handler_called);
  4001. }
  4002. }
  4003. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4004. // Which of the two branches runs is decided by whether the query component
  4005. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4006. // an empty query and must still fall back to building one from
  4007. // `req.params`, while a non-empty query must win over `req.params`.
  4008. Server svr;
  4009. std::string target;
  4010. svr.Get("/foo", [&](const Request &req, Response &res) {
  4011. target = req.target;
  4012. res.status = StatusCode::OK_200;
  4013. });
  4014. auto port = svr.bind_to_any_port(HOST);
  4015. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4016. auto se = detail::scope_exit([&] {
  4017. svr.stop();
  4018. thread.join();
  4019. ASSERT_FALSE(svr.is_running());
  4020. });
  4021. svr.wait_until_ready();
  4022. {
  4023. // Trailing `?` -> empty query component -> `req.params` is used.
  4024. Client cli(HOST, port);
  4025. Request req;
  4026. req.method = "GET";
  4027. req.path = "/foo?";
  4028. req.params.emplace("a", "1");
  4029. target.clear();
  4030. auto res = cli.send(req);
  4031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4032. EXPECT_EQ("/foo?a=1", target);
  4033. }
  4034. {
  4035. // Non-empty query in `req.path` -> `req.params` is not appended.
  4036. Client cli(HOST, port);
  4037. Request req;
  4038. req.method = "GET";
  4039. req.path = "/foo?b=2";
  4040. req.params.emplace("a", "1");
  4041. target.clear();
  4042. auto res = cli.send(req);
  4043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4044. EXPECT_EQ("/foo?b=2", target);
  4045. }
  4046. }
  4047. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4048. Server svr;
  4049. svr.Get("/", [](const Request &req, Response &) {
  4050. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4051. });
  4052. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4053. auto se = detail::scope_exit([&] {
  4054. svr.stop();
  4055. thread.join();
  4056. ASSERT_FALSE(svr.is_running());
  4057. });
  4058. svr.wait_until_ready();
  4059. {
  4060. Client cli(HOST, PORT);
  4061. cli.set_path_encode(false);
  4062. auto res = cli.Get("/?something=%0A");
  4063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4064. EXPECT_EQ(StatusCode::OK_200, res->status);
  4065. }
  4066. }
  4067. TEST(BindServerTest, BindDualStack) {
  4068. Server svr;
  4069. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4070. res.set_content("Hello World!", "text/plain");
  4071. });
  4072. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4073. auto se = detail::scope_exit([&] {
  4074. svr.stop();
  4075. thread.join();
  4076. ASSERT_FALSE(svr.is_running());
  4077. });
  4078. svr.wait_until_ready();
  4079. {
  4080. Client cli("127.0.0.1", PORT);
  4081. auto res = cli.Get("/1");
  4082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4083. EXPECT_EQ(StatusCode::OK_200, res->status);
  4084. EXPECT_EQ("Hello World!", res->body);
  4085. }
  4086. {
  4087. Client cli("::1", PORT);
  4088. auto res = cli.Get("/1");
  4089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4090. EXPECT_EQ(StatusCode::OK_200, res->status);
  4091. EXPECT_EQ("Hello World!", res->body);
  4092. }
  4093. }
  4094. TEST(BindServerTest, BindAndListenSeparately) {
  4095. Server svr;
  4096. int port = svr.bind_to_any_port("0.0.0.0");
  4097. ASSERT_TRUE(svr.is_valid());
  4098. ASSERT_TRUE(port > 0);
  4099. svr.stop();
  4100. }
  4101. // Reports whether anything is still listening on a loopback port. A plain
  4102. // connect() is used instead of a Client request because a socket left bound by
  4103. // mistake accepts the connection into its backlog and never answers, which
  4104. // would hang the test instead of failing it.
  4105. static bool is_loopback_port_accepting(int port) {
  4106. sockaddr_in addr{};
  4107. addr.sin_family = AF_INET;
  4108. addr.sin_port = htons(static_cast<uint16_t>(port));
  4109. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4110. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4111. EXPECT_NE(sock, INVALID_SOCKET);
  4112. if (sock == INVALID_SOCKET) { return false; }
  4113. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4114. static_cast<socklen_t>(sizeof(addr)));
  4115. detail::close_socket(sock);
  4116. return ret == 0;
  4117. }
  4118. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4119. Server svr;
  4120. auto port = svr.bind_to_any_port("127.0.0.1");
  4121. ASSERT_TRUE(port > 0);
  4122. svr.stop();
  4123. // bind_to_any_port() already called listen(2), so until stop() closed the
  4124. // descriptor the port kept accepting connections into the backlog. ASSERT
  4125. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4126. // below blocks forever in the accept loop.
  4127. ASSERT_FALSE(is_loopback_port_accepting(port));
  4128. // Nothing is left to accept on, so listen_after_bind() must report failure
  4129. // instead of returning success without ever serving.
  4130. EXPECT_FALSE(svr.listen_after_bind());
  4131. // The failed listen marks the server decommissioned, so a waiter returns
  4132. // instead of spinning forever.
  4133. svr.wait_until_ready();
  4134. }
  4135. #ifdef CPPHTTPLIB_SSL_ENABLED
  4136. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4137. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4138. CLIENT_CA_CERT_DIR);
  4139. int port = svr.bind_to_any_port("0.0.0.0");
  4140. ASSERT_TRUE(svr.is_valid());
  4141. ASSERT_TRUE(port > 0);
  4142. svr.stop();
  4143. }
  4144. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4145. // or a rejected CustomRoute() registration would not stop the server binding.
  4146. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4147. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4148. CLIENT_CA_CERT_DIR);
  4149. ASSERT_TRUE(svr.is_valid());
  4150. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4151. EXPECT_FALSE(svr.is_valid());
  4152. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4153. }
  4154. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4155. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4156. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4157. int port = svr.bind_to_any_port("0.0.0.0");
  4158. ASSERT_TRUE(svr.is_valid());
  4159. ASSERT_TRUE(port > 0);
  4160. svr.stop();
  4161. }
  4162. TEST(BindServerTest, UpdateCertsPem) {
  4163. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4164. int port = svr.bind_to_any_port("0.0.0.0");
  4165. ASSERT_TRUE(svr.is_valid());
  4166. ASSERT_TRUE(port > 0);
  4167. // Read PEM files
  4168. std::string cert_pem, key_pem, ca_pem;
  4169. read_file(SERVER_CERT_FILE, cert_pem);
  4170. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4171. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4172. // Update server certificates using PEM API
  4173. ASSERT_TRUE(
  4174. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4175. ASSERT_TRUE(svr.is_valid());
  4176. svr.stop();
  4177. }
  4178. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4179. // Start server with client CA (enables client auth)
  4180. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4181. ASSERT_TRUE(svr.is_valid());
  4182. bool handler_called = false;
  4183. svr.Get("/test", [&](const Request &req, Response &res) {
  4184. handler_called = true;
  4185. // Verify client certificate is present
  4186. auto cert = req.peer_cert();
  4187. EXPECT_TRUE(static_cast<bool>(cert));
  4188. res.set_content("ok", "text/plain");
  4189. });
  4190. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4191. auto se = detail::scope_exit([&] {
  4192. svr.stop();
  4193. t.join();
  4194. ASSERT_FALSE(svr.is_running());
  4195. });
  4196. svr.wait_until_ready();
  4197. // Read PEM files
  4198. std::string cert_pem, key_pem, ca_pem;
  4199. read_file(SERVER_CERT_FILE, cert_pem);
  4200. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4201. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4202. // Update server certificates and client CA using PEM API while server running
  4203. ASSERT_TRUE(
  4204. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4205. // Connect with client certificate
  4206. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4207. cli.enable_server_certificate_verification(false);
  4208. cli.set_connection_timeout(30);
  4209. auto res = cli.Get("/test");
  4210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4211. ASSERT_EQ(StatusCode::OK_200, res->status);
  4212. ASSERT_TRUE(handler_called);
  4213. EXPECT_EQ("ok", res->body);
  4214. }
  4215. // Puts a CA that did not sign the client's certificate in the old one's place.
  4216. static bool replace_client_ca(SSLServer &svr) {
  4217. std::string cert_pem, key_pem, ca_pem;
  4218. read_file(SERVER_CERT_FILE, cert_pem);
  4219. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4220. read_file(SERVER_CERT2_FILE, ca_pem);
  4221. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4222. ca_pem.c_str());
  4223. }
  4224. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4225. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4226. ASSERT_TRUE(svr.is_valid());
  4227. svr.Get("/test", [](const Request &, Response &res) {
  4228. res.set_content("ok", "text/plain");
  4229. });
  4230. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4231. auto se = detail::scope_exit([&] {
  4232. svr.stop();
  4233. t.join();
  4234. ASSERT_FALSE(svr.is_running());
  4235. });
  4236. svr.wait_until_ready();
  4237. auto get = [] {
  4238. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4239. cli.enable_server_certificate_verification(false);
  4240. return cli.Get("/test");
  4241. };
  4242. ASSERT_TRUE(get());
  4243. ASSERT_TRUE(replace_client_ca(svr));
  4244. EXPECT_FALSE(get());
  4245. }
  4246. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4247. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4249. ASSERT_TRUE(svr.is_valid());
  4250. tls::set_verify_callback(svr.tls_context(),
  4251. [](const tls::VerifyContext &) -> bool {
  4252. throw std::runtime_error("verify");
  4253. });
  4254. svr.Get("/test", [](const Request &, Response &res) {
  4255. res.set_content("ok", "text/plain");
  4256. });
  4257. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4258. auto se = detail::scope_exit([&] {
  4259. svr.stop();
  4260. t.join();
  4261. ASSERT_FALSE(svr.is_running());
  4262. });
  4263. svr.wait_until_ready();
  4264. auto get = [] {
  4265. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4266. cli.enable_server_certificate_verification(false);
  4267. return cli.Get("/test");
  4268. };
  4269. EXPECT_FALSE(get());
  4270. // The handshake is over, so an update does not wait for it.
  4271. std::string cert_pem, key_pem;
  4272. read_file(SERVER_CERT_FILE, cert_pem);
  4273. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4274. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4275. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4276. return v.preverify_ok;
  4277. });
  4278. auto res = get();
  4279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4280. EXPECT_EQ("ok", res->body);
  4281. }
  4282. #endif
  4283. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4284. // Sends each request over a new connection with a client certificate,
  4285. // resuming the session of the one before when there is one.
  4286. class ResumingClient {
  4287. public:
  4288. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4289. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4290. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4291. SSL_FILETYPE_PEM);
  4292. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4293. // callback, not through SSL_get1_session().
  4294. SSL_CTX_set_app_data(ctx_, this);
  4295. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4296. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4297. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4298. auto self = static_cast<ResumingClient *>(
  4299. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4300. SSL_SESSION_free(self->session_);
  4301. self->session_ = session;
  4302. return 1; // Keeps the reference
  4303. });
  4304. }
  4305. ~ResumingClient() {
  4306. SSL_SESSION_free(session_);
  4307. SSL_CTX_free(ctx_);
  4308. }
  4309. // Tells whether the request was answered.
  4310. bool get() {
  4311. auto error = Error::Success;
  4312. auto sock = detail::create_client_socket(
  4313. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4314. /*connection_timeout_sec=*/5, 0,
  4315. /*read_timeout_sec=*/5, 0,
  4316. /*write_timeout_sec=*/5, 0, std::string(), error);
  4317. if (sock == INVALID_SOCKET) { return false; }
  4318. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4319. auto ssl = SSL_new(ctx_);
  4320. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4321. SSL_set_fd(ssl, static_cast<int>(sock));
  4322. if (session_) { SSL_set_session(ssl, session_); }
  4323. if (SSL_connect(ssl) != 1) { return false; }
  4324. reused_ = SSL_session_reused(ssl) == 1;
  4325. // Reading the response also takes in a TLS 1.3 session ticket.
  4326. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4327. "Connection: close\r\n\r\n";
  4328. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4329. std::string res;
  4330. char buf[256];
  4331. int n;
  4332. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4333. res.append(buf, static_cast<size_t>(n));
  4334. }
  4335. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4336. SSL_shutdown(ssl);
  4337. return res.find("200 OK") != std::string::npos;
  4338. }
  4339. // Whether the last connection resumed a session
  4340. bool reused() const { return reused_; }
  4341. private:
  4342. SSL_CTX *ctx_;
  4343. SSL_SESSION *session_ = nullptr;
  4344. bool reused_ = false;
  4345. };
  4346. // A client that resumes its session gets through, but not once the client CA
  4347. // has changed, as a resumed session does not show the certificate again.
  4348. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4349. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4350. ASSERT_TRUE(svr.is_valid());
  4351. svr.Get("/test", [](const Request &, Response &res) {
  4352. res.set_content("ok", "text/plain");
  4353. });
  4354. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4355. auto se = detail::scope_exit([&] {
  4356. svr.stop();
  4357. t.join();
  4358. ASSERT_FALSE(svr.is_running());
  4359. });
  4360. svr.wait_until_ready();
  4361. ResumingClient cli;
  4362. ASSERT_TRUE(cli.get());
  4363. ASSERT_TRUE(cli.get());
  4364. EXPECT_TRUE(cli.reused());
  4365. ASSERT_TRUE(replace_client_ca(svr));
  4366. EXPECT_FALSE(cli.get());
  4367. }
  4368. // A resumed session does not show the certificate again, so the server does
  4369. // not resume one with a verify callback to run on it.
  4370. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4372. ASSERT_TRUE(svr.is_valid());
  4373. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4374. return v.preverify_ok;
  4375. });
  4376. svr.Get("/test", [](const Request &, Response &res) {
  4377. res.set_content("ok", "text/plain");
  4378. });
  4379. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4380. auto se = detail::scope_exit([&] {
  4381. svr.stop();
  4382. t.join();
  4383. ASSERT_FALSE(svr.is_running());
  4384. });
  4385. svr.wait_until_ready();
  4386. ResumingClient cli;
  4387. ASSERT_TRUE(cli.get());
  4388. ASSERT_TRUE(cli.get());
  4389. EXPECT_FALSE(cli.reused());
  4390. }
  4391. #endif
  4392. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4393. // wolfSSL shares its session cache between contexts, so a resumed session
  4394. // could carry a client certificate checked against another server's CA, or
  4395. // against a client CA since replaced.
  4396. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4397. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4398. ASSERT_TRUE(svr.is_valid());
  4399. // Trusts a CA that did not sign the client's certificate.
  4400. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4401. ASSERT_TRUE(other.is_valid());
  4402. for (auto s : {&svr, &other}) {
  4403. s->Get("/test", [](const Request &, Response &res) {
  4404. res.set_content("ok", "text/plain");
  4405. });
  4406. }
  4407. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4408. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4409. auto se = detail::scope_exit([&] {
  4410. other.stop();
  4411. svr.stop();
  4412. t2.join();
  4413. t.join();
  4414. });
  4415. svr.wait_until_ready();
  4416. other.wait_until_ready();
  4417. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4418. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4419. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4420. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4421. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4422. ASSERT_EQ(WOLFSSL_SUCCESS,
  4423. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4424. WOLFSSL_FILETYPE_PEM));
  4425. WOLFSSL_SESSION *session = nullptr;
  4426. auto session_se = detail::scope_exit([&] {
  4427. if (session) { wolfSSL_SESSION_free(session); }
  4428. });
  4429. // A request over a new connection, resuming `session` when there is one and
  4430. // keeping the connection's own in its place. Tells whether it was answered.
  4431. auto get = [&](int port) {
  4432. auto error = Error::Success;
  4433. auto sock = detail::create_client_socket(
  4434. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4435. /*connection_timeout_sec=*/5, 0,
  4436. /*read_timeout_sec=*/5, 0,
  4437. /*write_timeout_sec=*/5, 0, std::string(), error);
  4438. if (sock == INVALID_SOCKET) { return false; }
  4439. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4440. auto ssl = wolfSSL_new(ctx);
  4441. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4442. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4443. if (session) { wolfSSL_set_session(ssl, session); }
  4444. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4445. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4446. "Connection: close\r\n\r\n";
  4447. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4448. std::string res;
  4449. char buf[256];
  4450. int n;
  4451. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4452. res.append(buf, static_cast<size_t>(n));
  4453. }
  4454. wolfSSL_shutdown(ssl);
  4455. if (session) { wolfSSL_SESSION_free(session); }
  4456. session = wolfSSL_get1_session(ssl);
  4457. return res.find("200 OK") != std::string::npos;
  4458. };
  4459. ASSERT_TRUE(get(PORT));
  4460. EXPECT_FALSE(get(PORT + 1));
  4461. ASSERT_TRUE(get(PORT));
  4462. ASSERT_TRUE(replace_client_ca(svr));
  4463. EXPECT_FALSE(get(PORT));
  4464. }
  4465. #endif
  4466. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4467. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4468. ASSERT_TRUE(svr.is_valid());
  4469. svr.Get("/test", [](const Request &, Response &res) {
  4470. res.set_content("ok", "text/plain");
  4471. });
  4472. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4473. auto se = detail::scope_exit([&] {
  4474. svr.stop();
  4475. t.join();
  4476. ASSERT_FALSE(svr.is_running());
  4477. });
  4478. svr.wait_until_ready();
  4479. // A connection that sends no ClientHello keeps its handshake in progress,
  4480. // once the server has had a moment to start it.
  4481. auto error = Error::Success;
  4482. auto sock = detail::create_client_socket(
  4483. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4484. /*connection_timeout_sec=*/5, 0,
  4485. /*read_timeout_sec=*/5, 0,
  4486. /*write_timeout_sec=*/5, 0, std::string(), error);
  4487. ASSERT_NE(INVALID_SOCKET, sock);
  4488. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4489. std::string cert_pem, key_pem;
  4490. read_file(SERVER_CERT_FILE, cert_pem);
  4491. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4492. auto update = std::async(std::launch::async, [&]() {
  4493. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4494. });
  4495. EXPECT_EQ(std::future_status::timeout,
  4496. update.wait_for(std::chrono::milliseconds(200)));
  4497. detail::close_socket(sock);
  4498. EXPECT_TRUE(update.get());
  4499. SSLClient cli(HOST, PORT);
  4500. cli.enable_server_certificate_verification(false);
  4501. auto res = cli.Get("/test");
  4502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4503. EXPECT_EQ(StatusCode::OK_200, res->status);
  4504. }
  4505. #endif
  4506. TEST(ErrorHandlerTest, ContentLength) {
  4507. Server svr;
  4508. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4509. res.status = StatusCode::OK_200;
  4510. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4511. "text/html"); // <= Content-Length still 13
  4512. });
  4513. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4514. res.set_content("Hello World!\n", "text/plain");
  4515. res.status = 524;
  4516. });
  4517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4518. auto se = detail::scope_exit([&] {
  4519. svr.stop();
  4520. thread.join();
  4521. ASSERT_FALSE(svr.is_running());
  4522. });
  4523. svr.wait_until_ready();
  4524. {
  4525. Client cli(HOST, PORT);
  4526. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4528. EXPECT_EQ(StatusCode::OK_200, res->status);
  4529. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4530. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4531. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4532. }
  4533. }
  4534. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4535. TEST(ExceptionTest, WithoutExceptionHandler) {
  4536. Server svr;
  4537. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4538. throw std::runtime_error("exception...");
  4539. });
  4540. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4541. throw std::runtime_error("exception\r\n...");
  4542. });
  4543. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4544. auto se = detail::scope_exit([&] {
  4545. svr.stop();
  4546. listen_thread.join();
  4547. ASSERT_FALSE(svr.is_running());
  4548. });
  4549. svr.wait_until_ready();
  4550. Client cli("localhost", PORT);
  4551. {
  4552. auto res = cli.Get("/exception");
  4553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4554. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4555. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4556. }
  4557. {
  4558. auto res = cli.Get("/unknown");
  4559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4560. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4561. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4562. }
  4563. }
  4564. TEST(ExceptionTest, WithExceptionHandler) {
  4565. Server svr;
  4566. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4567. std::exception_ptr ep) {
  4568. EXPECT_FALSE(ep == nullptr);
  4569. try {
  4570. std::rethrow_exception(ep);
  4571. } catch (std::exception &e) {
  4572. EXPECT_EQ("abc", std::string(e.what()));
  4573. } catch (...) {}
  4574. res.status = StatusCode::InternalServerError_500;
  4575. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4576. "text/html"); // <= Content-Length still 13 at this point
  4577. });
  4578. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4579. res.set_content("Hello World!\n", "text/plain");
  4580. throw std::runtime_error("abc");
  4581. });
  4582. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4583. auto se = detail::scope_exit([&] {
  4584. svr.stop();
  4585. thread.join();
  4586. ASSERT_FALSE(svr.is_running());
  4587. });
  4588. svr.wait_until_ready();
  4589. for (size_t i = 0; i < 10; i++) {
  4590. Client cli(HOST, PORT);
  4591. for (size_t j = 0; j < 100; j++) {
  4592. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4595. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4596. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4597. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4598. }
  4599. cli.set_keep_alive(true);
  4600. for (size_t j = 0; j < 100; j++) {
  4601. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4603. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4604. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4605. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4606. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4607. }
  4608. }
  4609. }
  4610. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4611. Server svr;
  4612. svr.set_exception_handler(
  4613. [](const Request &, Response &res, std::exception_ptr) {
  4614. res.set_content("oops", "text/plain");
  4615. });
  4616. svr.Get("/throw", [](const Request &, Response &) {
  4617. throw std::runtime_error("throw");
  4618. });
  4619. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4620. res.status = StatusCode::Created_201;
  4621. throw std::runtime_error("created-then-throw");
  4622. });
  4623. auto port = svr.bind_to_any_port(HOST);
  4624. ASSERT_GT(port, 0);
  4625. thread t = thread([&] { svr.listen_after_bind(); });
  4626. auto se = detail::scope_exit([&] {
  4627. svr.stop();
  4628. t.join();
  4629. ASSERT_FALSE(svr.is_running());
  4630. });
  4631. svr.wait_until_ready();
  4632. Client cli(HOST, port);
  4633. for (auto path : {"/throw", "/created-then-throw"}) {
  4634. auto res = cli.Get(path);
  4635. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4636. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4637. }
  4638. }
  4639. TEST(ExceptionTest, AndErrorHandler) {
  4640. Server svr;
  4641. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4642. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4643. });
  4644. svr.set_exception_handler(
  4645. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4646. EXPECT_FALSE(ep == nullptr);
  4647. try {
  4648. std::rethrow_exception(ep);
  4649. } catch (std::exception &e) {
  4650. res.set_content(e.what(), "text/html");
  4651. } catch (...) {}
  4652. res.status = StatusCode::InternalServerError_500;
  4653. });
  4654. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4655. throw std::runtime_error("EXCEPTION");
  4656. });
  4657. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4658. res.set_content("ERROR", "text/html");
  4659. res.status = StatusCode::InternalServerError_500;
  4660. });
  4661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4662. auto se = detail::scope_exit([&] {
  4663. svr.stop();
  4664. thread.join();
  4665. ASSERT_FALSE(svr.is_running());
  4666. });
  4667. svr.wait_until_ready();
  4668. Client cli(HOST, PORT);
  4669. {
  4670. auto res = cli.Get("/exception");
  4671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4672. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4673. EXPECT_EQ("EXCEPTION", res->body);
  4674. }
  4675. {
  4676. auto res = cli.Get("/error");
  4677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4678. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4679. EXPECT_EQ("ERROR", res->body);
  4680. }
  4681. {
  4682. auto res = cli.Get("/invalid");
  4683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4684. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4685. EXPECT_EQ("NOT_FOUND", res->body);
  4686. }
  4687. }
  4688. #endif
  4689. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4690. // An exception from a user callback outside process_request()'s try/catch
  4691. // used to unwind into the task queue - which does not catch - and terminate
  4692. // the process. Each test below runs the server on a single worker thread: a
  4693. // guard that catches the exception but still loses the thread would otherwise
  4694. // be hidden by a spare worker serving the follow-up request. Note that a
  4695. // regression here aborts the whole test binary rather than failing one test.
  4696. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4697. Server svr;
  4698. svr.new_task_queue = [] { return new ThreadPool(1); };
  4699. std::atomic<int> reported{0};
  4700. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4701. if (err == Error::UserCallbackException) { reported++; }
  4702. });
  4703. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4704. res.set_content_provider(
  4705. 1024, "text/plain",
  4706. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4707. sink.write("hello", 5);
  4708. throw std::runtime_error("from the content provider");
  4709. });
  4710. });
  4711. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4712. res.set_content("ok", "text/plain");
  4713. });
  4714. auto port = svr.bind_to_any_port(HOST);
  4715. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4716. auto se = detail::scope_exit([&] {
  4717. svr.stop();
  4718. listen_thread.join();
  4719. ASSERT_FALSE(svr.is_running());
  4720. });
  4721. svr.wait_until_ready();
  4722. {
  4723. Client cli(HOST, port);
  4724. cli.set_read_timeout(5, 0);
  4725. EXPECT_FALSE(cli.Get("/throw"));
  4726. }
  4727. EXPECT_TRUE(svr.is_running());
  4728. EXPECT_EQ(1, reported.load());
  4729. // A request on a fresh connection is still served.
  4730. {
  4731. Client cli(HOST, port);
  4732. auto res = cli.Get("/ok");
  4733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4734. EXPECT_EQ(StatusCode::OK_200, res->status);
  4735. EXPECT_EQ("ok", res->body);
  4736. }
  4737. }
  4738. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4739. Server svr;
  4740. svr.new_task_queue = [] { return new ThreadPool(1); };
  4741. std::atomic<bool> should_throw{true};
  4742. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4743. res.set_content("hi", "text/plain");
  4744. });
  4745. svr.set_post_routing_handler(
  4746. [&](const Request & /*req*/, Response & /*res*/) {
  4747. if (should_throw) {
  4748. throw std::runtime_error("from the post-routing handler");
  4749. }
  4750. });
  4751. auto port = svr.bind_to_any_port(HOST);
  4752. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4753. auto se = detail::scope_exit([&] {
  4754. svr.stop();
  4755. listen_thread.join();
  4756. ASSERT_FALSE(svr.is_running());
  4757. });
  4758. svr.wait_until_ready();
  4759. {
  4760. Client cli(HOST, port);
  4761. cli.set_read_timeout(5, 0);
  4762. EXPECT_FALSE(cli.Get("/hi"));
  4763. }
  4764. EXPECT_TRUE(svr.is_running());
  4765. should_throw = false;
  4766. {
  4767. Client cli(HOST, port);
  4768. auto res = cli.Get("/hi");
  4769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4770. EXPECT_EQ(StatusCode::OK_200, res->status);
  4771. EXPECT_EQ("hi", res->body);
  4772. }
  4773. }
  4774. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4775. // The guard reports the caught exception through the error logger, which is
  4776. // a user callback too. A logger that throws has to be contained as well, or
  4777. // the process would terminate from inside the catch.
  4778. Server svr;
  4779. svr.new_task_queue = [] { return new ThreadPool(1); };
  4780. std::atomic<int> reported{0};
  4781. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4782. if (err == Error::UserCallbackException) {
  4783. reported++;
  4784. throw std::runtime_error("from the error logger");
  4785. }
  4786. });
  4787. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4788. res.set_content_provider(
  4789. 1024, "text/plain",
  4790. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4791. sink.write("hello", 5);
  4792. throw std::runtime_error("from the content provider");
  4793. });
  4794. });
  4795. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4796. res.set_content("ok", "text/plain");
  4797. });
  4798. auto port = svr.bind_to_any_port(HOST);
  4799. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4800. auto se = detail::scope_exit([&] {
  4801. svr.stop();
  4802. listen_thread.join();
  4803. ASSERT_FALSE(svr.is_running());
  4804. });
  4805. svr.wait_until_ready();
  4806. {
  4807. Client cli(HOST, port);
  4808. cli.set_read_timeout(5, 0);
  4809. EXPECT_FALSE(cli.Get("/throw"));
  4810. }
  4811. EXPECT_TRUE(svr.is_running());
  4812. EXPECT_EQ(1, reported.load());
  4813. {
  4814. Client cli(HOST, port);
  4815. auto res = cli.Get("/ok");
  4816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4817. EXPECT_EQ(StatusCode::OK_200, res->status);
  4818. EXPECT_EQ("ok", res->body);
  4819. }
  4820. }
  4821. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4822. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4823. // so the exception unwinds through the ws::WebSocket object on its way to
  4824. // the guard. None of the HTTP cases above cross that.
  4825. Server svr;
  4826. svr.new_task_queue = [] { return new ThreadPool(1); };
  4827. std::atomic<int> reported{0};
  4828. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4829. if (err == Error::UserCallbackException) { reported++; }
  4830. });
  4831. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4832. throw std::runtime_error("from the WebSocket handler");
  4833. });
  4834. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4835. res.set_content("ok", "text/plain");
  4836. });
  4837. auto port = svr.bind_to_any_port(HOST);
  4838. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4839. auto se = detail::scope_exit([&] {
  4840. svr.stop();
  4841. listen_thread.join();
  4842. ASSERT_FALSE(svr.is_running());
  4843. });
  4844. svr.wait_until_ready();
  4845. {
  4846. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4847. "/ws");
  4848. auto res = client.connect();
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. // The server dropped the connection instead of dying.
  4851. std::string msg;
  4852. EXPECT_FALSE(client.read(msg));
  4853. client.close();
  4854. }
  4855. EXPECT_TRUE(svr.is_running());
  4856. EXPECT_EQ(1, reported.load());
  4857. {
  4858. Client cli(HOST, port);
  4859. auto res = cli.Get("/ok");
  4860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4861. EXPECT_EQ(StatusCode::OK_200, res->status);
  4862. EXPECT_EQ("ok", res->body);
  4863. }
  4864. }
  4865. #ifdef CPPHTTPLIB_SSL_ENABLED
  4866. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4867. // SSLServer::process_and_close_socket() is a separate overload with its own
  4868. // guard, so it is exercised on its own.
  4869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4870. ASSERT_TRUE(svr.is_valid());
  4871. svr.new_task_queue = [] { return new ThreadPool(1); };
  4872. std::atomic<int> reported{0};
  4873. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4874. if (err == Error::UserCallbackException) { reported++; }
  4875. });
  4876. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4877. res.set_content_provider(
  4878. 1024, "text/plain",
  4879. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4880. sink.write("hello", 5);
  4881. throw std::runtime_error("from the content provider");
  4882. });
  4883. });
  4884. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4885. res.set_content("ok", "text/plain");
  4886. });
  4887. auto port = svr.bind_to_any_port(HOST);
  4888. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4889. auto se = detail::scope_exit([&] {
  4890. svr.stop();
  4891. listen_thread.join();
  4892. ASSERT_FALSE(svr.is_running());
  4893. });
  4894. svr.wait_until_ready();
  4895. {
  4896. SSLClient cli(HOST, port);
  4897. cli.enable_server_certificate_verification(false);
  4898. cli.set_read_timeout(5, 0);
  4899. EXPECT_FALSE(cli.Get("/throw"));
  4900. }
  4901. EXPECT_TRUE(svr.is_running());
  4902. EXPECT_EQ(1, reported.load());
  4903. {
  4904. SSLClient cli(HOST, port);
  4905. cli.enable_server_certificate_verification(false);
  4906. auto res = cli.Get("/ok");
  4907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4908. EXPECT_EQ(StatusCode::OK_200, res->status);
  4909. EXPECT_EQ("ok", res->body);
  4910. }
  4911. }
  4912. #endif
  4913. #endif
  4914. TEST(NoContentTest, ContentLength) {
  4915. Server svr;
  4916. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4917. res.status = StatusCode::NoContent_204;
  4918. });
  4919. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4920. auto se = detail::scope_exit([&] {
  4921. svr.stop();
  4922. thread.join();
  4923. ASSERT_FALSE(svr.is_running());
  4924. });
  4925. svr.wait_until_ready();
  4926. {
  4927. Client cli(HOST, PORT);
  4928. auto res = cli.Get("/hi");
  4929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4930. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4931. // RFC 9110 8.6: none in a 204 response
  4932. EXPECT_FALSE(res->has_header("Content-Length"));
  4933. }
  4934. }
  4935. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4936. Server svr;
  4937. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4938. res.set_header("Content-Length", "5");
  4939. res.set_content("hello world", "text/plain");
  4940. });
  4941. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4942. // A body that reads as the last chunk, were it taken as chunked
  4943. res.set_header("Transfer-Encoding", "chunked");
  4944. res.set_content("0\r\n\r\n", "text/plain");
  4945. });
  4946. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4947. res.set_header("Content-Length", "2");
  4948. res.set_content_provider(5, "text/plain",
  4949. [](size_t offset, size_t length, DataSink &sink) {
  4950. sink.write(&"hello"[offset], length);
  4951. return true;
  4952. });
  4953. });
  4954. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4955. res.set_header("Content-Length", "1234");
  4956. });
  4957. thread t = thread([&] { svr.listen(HOST, PORT); });
  4958. auto se = detail::scope_exit([&] {
  4959. svr.stop();
  4960. t.join();
  4961. ASSERT_FALSE(svr.is_running());
  4962. });
  4963. svr.wait_until_ready();
  4964. Client cli(HOST, PORT);
  4965. cli.set_read_timeout(1, 0);
  4966. auto expect_body = [&](const Result &res, const std::string &body) {
  4967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4968. EXPECT_EQ(body, res->body);
  4969. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4970. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4971. };
  4972. Headers identity{{"Accept-Encoding", ""}};
  4973. expect_body(cli.Get("/body", identity), "hello world");
  4974. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4975. expect_body(cli.Get("/body",
  4976. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4977. "he");
  4978. expect_body(cli.Get("/provider", identity), "hello");
  4979. expect_body(cli.Get("/empty", identity), "");
  4980. // A HEAD response may give the length of the body a GET would get.
  4981. auto res = cli.Head("/empty");
  4982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4983. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4984. }
  4985. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4986. Server svr;
  4987. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4988. res.set_content("short", "text/plain");
  4989. });
  4990. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4991. res.body += " with a footer";
  4992. res.set_header("Transfer-Encoding", "chunked");
  4993. });
  4994. thread t = thread([&] { svr.listen(HOST, PORT); });
  4995. auto se = detail::scope_exit([&] {
  4996. svr.stop();
  4997. t.join();
  4998. ASSERT_FALSE(svr.is_running());
  4999. });
  5000. svr.wait_until_ready();
  5001. Client cli(HOST, PORT);
  5002. cli.set_read_timeout(1, 0);
  5003. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5005. EXPECT_EQ("short with a footer", res->body);
  5006. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5007. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5008. }
  5009. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5010. Server svr;
  5011. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5012. res.set_header("Content-Length", "3");
  5013. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5014. sink.write("abc", 3);
  5015. sink.done();
  5016. return true;
  5017. });
  5018. });
  5019. thread t = thread([&] { svr.listen(HOST, PORT); });
  5020. auto se = detail::scope_exit([&] {
  5021. svr.stop();
  5022. t.join();
  5023. ASSERT_FALSE(svr.is_running());
  5024. });
  5025. svr.wait_until_ready();
  5026. Client cli(HOST, PORT);
  5027. cli.set_keep_alive(true);
  5028. auto res = cli.Get("/");
  5029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5030. EXPECT_EQ("abc", res->body);
  5031. EXPECT_FALSE(res->has_header("Content-Length"));
  5032. EXPECT_EQ("close", res->get_header_value("Connection"));
  5033. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5034. // No body to delimit
  5035. auto head = cli.Head("/");
  5036. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5037. EXPECT_FALSE(head->has_header("Connection"));
  5038. }
  5039. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5040. #ifdef CPPHTTPLIB_SSL_ENABLED
  5041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5042. ASSERT_TRUE(svr.is_valid());
  5043. #else
  5044. Server svr;
  5045. #endif
  5046. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5047. if (req.path == "/routing_handler") {
  5048. res.set_header("PRE_ROUTING", "on");
  5049. res.set_content("Routing Handler", "text/plain");
  5050. return httplib::Server::HandlerResponse::Handled;
  5051. }
  5052. return httplib::Server::HandlerResponse::Unhandled;
  5053. });
  5054. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5055. res.set_content("Error", "text/html");
  5056. });
  5057. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5058. if (req.path == "/routing_handler") {
  5059. res.set_header("POST_ROUTING", "on");
  5060. }
  5061. });
  5062. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5063. res.set_content("Hello World!\n", "text/plain");
  5064. });
  5065. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5066. auto se = detail::scope_exit([&] {
  5067. svr.stop();
  5068. thread.join();
  5069. ASSERT_FALSE(svr.is_running());
  5070. });
  5071. svr.wait_until_ready();
  5072. {
  5073. #ifdef CPPHTTPLIB_SSL_ENABLED
  5074. SSLClient cli(HOST, PORT);
  5075. cli.enable_server_certificate_verification(false);
  5076. #else
  5077. Client cli(HOST, PORT);
  5078. #endif
  5079. auto res = cli.Get("/routing_handler");
  5080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5081. EXPECT_EQ(StatusCode::OK_200, res->status);
  5082. EXPECT_EQ("Routing Handler", res->body);
  5083. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5084. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5085. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5086. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5087. }
  5088. {
  5089. #ifdef CPPHTTPLIB_SSL_ENABLED
  5090. SSLClient cli(HOST, PORT);
  5091. cli.enable_server_certificate_verification(false);
  5092. #else
  5093. Client cli(HOST, PORT);
  5094. #endif
  5095. auto res = cli.Get("/hi");
  5096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ("Hello World!\n", res->body);
  5099. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5100. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5101. }
  5102. {
  5103. #ifdef CPPHTTPLIB_SSL_ENABLED
  5104. SSLClient cli(HOST, PORT);
  5105. cli.enable_server_certificate_verification(false);
  5106. #else
  5107. Client cli(HOST, PORT);
  5108. #endif
  5109. auto res = cli.Get("/aaa");
  5110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5111. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5112. EXPECT_EQ("Error", res->body);
  5113. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5114. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5115. }
  5116. }
  5117. TEST(RequestHandlerTest, PreRequestHandler) {
  5118. auto route_path = "/user/:user";
  5119. Server svr;
  5120. svr.Get("/hi", [](const Request &, Response &res) {
  5121. res.set_content("hi", "text/plain");
  5122. });
  5123. svr.Get(route_path, [](const Request &req, Response &res) {
  5124. res.set_content(req.path_params.at("user"), "text/plain");
  5125. });
  5126. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5127. if (req.matched_route == route_path) {
  5128. auto user = req.path_params.at("user");
  5129. if (user != "john") {
  5130. res.status = StatusCode::Forbidden_403;
  5131. res.set_content("error", "text/html");
  5132. return Server::HandlerResponse::Handled;
  5133. }
  5134. }
  5135. return Server::HandlerResponse::Unhandled;
  5136. });
  5137. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5138. auto se = detail::scope_exit([&] {
  5139. svr.stop();
  5140. thread.join();
  5141. ASSERT_FALSE(svr.is_running());
  5142. });
  5143. svr.wait_until_ready();
  5144. Client cli(HOST, PORT);
  5145. {
  5146. auto res = cli.Get("/hi");
  5147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. EXPECT_EQ("hi", res->body);
  5150. }
  5151. {
  5152. auto res = cli.Get("/user/john");
  5153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. EXPECT_EQ("john", res->body);
  5156. }
  5157. {
  5158. auto res = cli.Get("/user/invalid-user");
  5159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5160. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5161. EXPECT_EQ("error", res->body);
  5162. }
  5163. }
  5164. // The pre-request handler must run before the request body is read, so a
  5165. // rejected request never forces the server to buffer a (potentially large)
  5166. // body. Here the posted body is larger than the payload limit: if the body
  5167. // were read first the server would answer 413, but because the pre-request
  5168. // handler runs first it answers 403 and the body is never read.
  5169. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5170. Server svr;
  5171. svr.set_payload_max_length(8);
  5172. auto handler_ran = false;
  5173. svr.Post("/reject", [&](const Request &req, Response &res) {
  5174. handler_ran = true;
  5175. res.set_content(req.body, "text/plain");
  5176. });
  5177. svr.Post("/accept", [](const Request &req, Response &res) {
  5178. res.set_content(req.body, "text/plain");
  5179. });
  5180. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5181. if (req.matched_route == "/reject") {
  5182. res.status = StatusCode::Forbidden_403;
  5183. res.set_content("denied", "text/plain");
  5184. return Server::HandlerResponse::Handled;
  5185. }
  5186. return Server::HandlerResponse::Unhandled;
  5187. });
  5188. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5189. auto se = detail::scope_exit([&] {
  5190. svr.stop();
  5191. thread.join();
  5192. ASSERT_FALSE(svr.is_running());
  5193. });
  5194. svr.wait_until_ready();
  5195. Client cli(HOST, PORT);
  5196. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5197. // rejects with 403 before the body is read, so 413 is never reached.
  5198. {
  5199. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5201. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5202. EXPECT_EQ("denied", res->body);
  5203. EXPECT_FALSE(handler_ran);
  5204. }
  5205. // An approved route still reads the body and enforces the payload limit.
  5206. {
  5207. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5209. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5210. }
  5211. }
  5212. TEST(UserDataTest, BasicOperations) {
  5213. httplib::UserData ud;
  5214. // Initially empty
  5215. EXPECT_FALSE(ud.has("key"));
  5216. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5217. // set and get
  5218. ud.set("key", 42);
  5219. EXPECT_TRUE(ud.has("key"));
  5220. auto *p = ud.get<int>("key");
  5221. ASSERT_NE(nullptr, p);
  5222. EXPECT_EQ(42, *p);
  5223. // Type mismatch → nullptr
  5224. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5225. // Overwrite with different type
  5226. ud.set("key", std::string("hello"));
  5227. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5228. auto *s = ud.get<std::string>("key");
  5229. ASSERT_NE(nullptr, s);
  5230. EXPECT_EQ("hello", *s);
  5231. // erase
  5232. ud.erase("key");
  5233. EXPECT_FALSE(ud.has("key"));
  5234. // clear
  5235. ud.set("a", 1);
  5236. ud.set("b", 2);
  5237. ud.clear();
  5238. EXPECT_FALSE(ud.has("a"));
  5239. EXPECT_FALSE(ud.has("b"));
  5240. }
  5241. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5242. struct AuthCtx {
  5243. std::string user_id;
  5244. };
  5245. Server svr;
  5246. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5247. res.user_data.set("auth", AuthCtx{"alice"});
  5248. return Server::HandlerResponse::Unhandled;
  5249. });
  5250. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5251. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5252. ASSERT_NE(nullptr, ctx);
  5253. res.set_content("Hello " + ctx->user_id, "text/plain");
  5254. });
  5255. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5256. auto se = detail::scope_exit([&] {
  5257. svr.stop();
  5258. thread.join();
  5259. ASSERT_FALSE(svr.is_running());
  5260. });
  5261. svr.wait_until_ready();
  5262. Client cli(HOST, PORT);
  5263. auto res = cli.Get("/me");
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. EXPECT_EQ("Hello alice", res->body);
  5267. }
  5268. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5269. struct RoleCtx {
  5270. std::string role;
  5271. };
  5272. Server svr;
  5273. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5274. res.user_data.set("role", RoleCtx{"admin"});
  5275. return Server::HandlerResponse::Unhandled;
  5276. });
  5277. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5278. auto *ctx = res.user_data.get<RoleCtx>("role");
  5279. ASSERT_NE(nullptr, ctx);
  5280. res.set_content(ctx->role, "text/plain");
  5281. });
  5282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5283. auto se = detail::scope_exit([&] {
  5284. svr.stop();
  5285. thread.join();
  5286. ASSERT_FALSE(svr.is_running());
  5287. });
  5288. svr.wait_until_ready();
  5289. Client cli(HOST, PORT);
  5290. auto res = cli.Get("/role");
  5291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5292. EXPECT_EQ(StatusCode::OK_200, res->status);
  5293. EXPECT_EQ("admin", res->body);
  5294. }
  5295. TEST(InvalidFormatTest, StatusCode) {
  5296. Server svr;
  5297. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5298. res.set_content("Hello World!\n", "text/plain");
  5299. res.status = 9999; // Status should be a three-digit code...
  5300. });
  5301. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5302. auto se = detail::scope_exit([&] {
  5303. svr.stop();
  5304. thread.join();
  5305. ASSERT_FALSE(svr.is_running());
  5306. });
  5307. svr.wait_until_ready();
  5308. {
  5309. Client cli(HOST, PORT);
  5310. auto res = cli.Get("/hi");
  5311. ASSERT_FALSE(res);
  5312. }
  5313. }
  5314. TEST(URLFragmentTest, WithFragment) {
  5315. Server svr;
  5316. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5317. EXPECT_TRUE(req.target == "/hi");
  5318. });
  5319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5320. auto se = detail::scope_exit([&] {
  5321. svr.stop();
  5322. thread.join();
  5323. ASSERT_FALSE(svr.is_running());
  5324. });
  5325. svr.wait_until_ready();
  5326. {
  5327. Client cli(HOST, PORT);
  5328. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5329. EXPECT_TRUE(res);
  5330. EXPECT_EQ(StatusCode::OK_200, res->status);
  5331. res = cli.Get("/hi%23key1=val1=key2=val2");
  5332. EXPECT_TRUE(res);
  5333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5334. }
  5335. }
  5336. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5337. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5338. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5339. Server svr;
  5340. std::vector<std::string> targets;
  5341. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5342. targets.push_back(req.target);
  5343. });
  5344. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5345. auto se = detail::scope_exit([&] {
  5346. svr.stop();
  5347. thread.join();
  5348. ASSERT_FALSE(svr.is_running());
  5349. });
  5350. svr.wait_until_ready();
  5351. Client cli(HOST, PORT);
  5352. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5353. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5354. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5355. // A '?' after the '#' belongs to the fragment, not to the query.
  5356. Request req;
  5357. req.method = "GET";
  5358. req.path = "/hi#f?x=1";
  5359. req.params.emplace("a", "1");
  5360. Response res;
  5361. auto error = Error::Success;
  5362. EXPECT_TRUE(cli.send(req, res, error));
  5363. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5364. "/hi?a=1"}),
  5365. targets);
  5366. }
  5367. TEST(HeaderWriter, SetHeaderWriter) {
  5368. Server svr;
  5369. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5370. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5371. return detail::write_headers(strm, hdrs);
  5372. });
  5373. svr.Get("/hi", [](const Request &req, Response &res) {
  5374. auto it = req.headers.find("CustomClientHeader");
  5375. EXPECT_TRUE(it != req.headers.end());
  5376. EXPECT_EQ(it->second, "CustomClientValue");
  5377. res.set_content("Hello World!\n", "text/plain");
  5378. });
  5379. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5380. auto se = detail::scope_exit([&] {
  5381. svr.stop();
  5382. thread.join();
  5383. ASSERT_FALSE(svr.is_running());
  5384. });
  5385. svr.wait_until_ready();
  5386. {
  5387. Client cli(HOST, PORT);
  5388. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5389. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5390. return detail::write_headers(strm, hdrs);
  5391. });
  5392. auto res = cli.Get("/hi");
  5393. EXPECT_TRUE(res);
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. auto it = res->headers.find("CustomServerHeader");
  5396. EXPECT_TRUE(it != res->headers.end());
  5397. EXPECT_EQ(it->second, "CustomServerValue");
  5398. }
  5399. }
  5400. class ServerTest : public ::testing::Test {
  5401. protected:
  5402. ServerTest()
  5403. : cli_(HOST, PORT)
  5404. #ifdef CPPHTTPLIB_SSL_ENABLED
  5405. ,
  5406. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5407. #endif
  5408. {
  5409. #ifdef CPPHTTPLIB_SSL_ENABLED
  5410. cli_.enable_server_certificate_verification(false);
  5411. #endif
  5412. // Allow LARGE_DATA (100MB) responses
  5413. cli_.set_payload_max_length(200 * 1024 * 1024);
  5414. }
  5415. virtual void SetUp() {
  5416. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5417. svr_.set_payload_max_length(200 * 1024 * 1024);
  5418. svr_.set_mount_point("/", "./www");
  5419. svr_.set_mount_point("/mount", "./www2");
  5420. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5421. svr_.Get("/hi",
  5422. [&](const Request & /*req*/, Response &res) {
  5423. res.set_content("Hello World!", "text/plain");
  5424. })
  5425. .Get("/file_content",
  5426. [&](const Request & /*req*/, Response &res) {
  5427. res.set_file_content("./www/dir/test.html");
  5428. })
  5429. .Get("/file_content_with_content_type",
  5430. [&](const Request & /*req*/, Response &res) {
  5431. res.set_file_content("./www/file", "text/plain");
  5432. })
  5433. .Get("/invalid_file_content",
  5434. [&](const Request & /*req*/, Response &res) {
  5435. res.set_file_content("./www/dir/invalid_file_path");
  5436. })
  5437. .Get("/http_response_splitting",
  5438. [&](const Request & /*req*/, Response &res) {
  5439. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5440. EXPECT_EQ(0U, res.headers.size());
  5441. EXPECT_FALSE(res.has_header("a"));
  5442. res.set_header("a", "1\nSet-Cookie: a=1");
  5443. EXPECT_EQ(0U, res.headers.size());
  5444. EXPECT_FALSE(res.has_header("a"));
  5445. res.set_header("a", "1\rSet-Cookie: a=1");
  5446. EXPECT_EQ(0U, res.headers.size());
  5447. EXPECT_FALSE(res.has_header("a"));
  5448. res.set_header("a\r\nb", "0");
  5449. EXPECT_EQ(0U, res.headers.size());
  5450. EXPECT_FALSE(res.has_header("a"));
  5451. res.set_header("a\rb", "0");
  5452. EXPECT_EQ(0U, res.headers.size());
  5453. EXPECT_FALSE(res.has_header("a"));
  5454. res.set_header("a\nb", "0");
  5455. EXPECT_EQ(0U, res.headers.size());
  5456. EXPECT_FALSE(res.has_header("a"));
  5457. res.set_redirect("1\r\nSet-Cookie: a=1");
  5458. EXPECT_EQ(0U, res.headers.size());
  5459. EXPECT_FALSE(res.has_header("Location"));
  5460. })
  5461. .Get("/slow",
  5462. [&](const Request & /*req*/, Response &res) {
  5463. std::this_thread::sleep_for(std::chrono::seconds(4));
  5464. res.set_content("slow", "text/plain");
  5465. })
  5466. #if 0
  5467. .Post("/slowpost",
  5468. [&](const Request & /*req*/, Response &res) {
  5469. std::this_thread::sleep_for(std::chrono::seconds(2));
  5470. res.set_content("slow", "text/plain");
  5471. })
  5472. #endif
  5473. .Get("/remote_addr",
  5474. [&](const Request &req, Response &res) {
  5475. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5476. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5477. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5478. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5479. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5480. #endif
  5481. res.set_content(req.remote_addr, "text/plain");
  5482. })
  5483. .Get("/local_addr",
  5484. [&](const Request &req, Response &res) {
  5485. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5486. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5487. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5488. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5489. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5490. #endif
  5491. auto local_addr = req.local_addr;
  5492. auto local_port = std::to_string(req.local_port);
  5493. res.set_content(local_addr.append(":").append(local_port),
  5494. "text/plain");
  5495. })
  5496. .Get("/endwith%",
  5497. [&](const Request & /*req*/, Response &res) {
  5498. res.set_content("Hello World!", "text/plain");
  5499. })
  5500. .Get("/a\\+\\+b",
  5501. [&](const Request &req, Response &res) {
  5502. ASSERT_TRUE(req.has_param("a +b"));
  5503. auto val = req.get_param_value("a +b");
  5504. res.set_content(val, "text/plain");
  5505. })
  5506. .Get("/", [&](const Request & /*req*/,
  5507. Response &res) { res.set_redirect("/hi"); })
  5508. .Post("/1",
  5509. [](const Request & /*req*/, Response &res) {
  5510. res.set_redirect("/2", StatusCode::SeeOther_303);
  5511. })
  5512. .Get("/2",
  5513. [](const Request & /*req*/, Response &res) {
  5514. res.set_content("redirected.", "text/plain");
  5515. res.status = StatusCode::OK_200;
  5516. })
  5517. .Post("/person",
  5518. [&](const Request &req, Response &res) {
  5519. if (req.has_param("name") && req.has_param("note")) {
  5520. persons_[req.get_param_value("name")] =
  5521. req.get_param_value("note");
  5522. } else {
  5523. res.status = StatusCode::BadRequest_400;
  5524. }
  5525. })
  5526. .Put("/person",
  5527. [&](const Request &req, Response &res) {
  5528. if (req.has_param("name") && req.has_param("note")) {
  5529. persons_[req.get_param_value("name")] =
  5530. req.get_param_value("note");
  5531. } else {
  5532. res.status = StatusCode::BadRequest_400;
  5533. }
  5534. })
  5535. .Get("/person/(.*)",
  5536. [&](const Request &req, Response &res) {
  5537. string name = req.matches[1];
  5538. if (persons_.find(name) != persons_.end()) {
  5539. auto note = persons_[name];
  5540. res.set_content(note, "text/plain");
  5541. } else {
  5542. res.status = StatusCode::NotFound_404;
  5543. }
  5544. })
  5545. .Delete("/person",
  5546. [&](const Request &req, Response &res) {
  5547. if (req.has_param("name")) {
  5548. string name = req.get_param_value("name");
  5549. if (persons_.find(name) != persons_.end()) {
  5550. persons_.erase(name);
  5551. res.set_content("DELETED", "text/plain");
  5552. } else {
  5553. res.status = StatusCode::NotFound_404;
  5554. }
  5555. } else {
  5556. res.status = StatusCode::BadRequest_400;
  5557. }
  5558. })
  5559. .Post("/x-www-form-urlencoded-json",
  5560. [&](const Request &req, Response &res) {
  5561. auto json = req.get_param_value("json");
  5562. ASSERT_EQ(JSON_DATA, json);
  5563. res.set_content(json, "appliation/json");
  5564. res.status = StatusCode::OK_200;
  5565. })
  5566. .Get("/streamed-chunked",
  5567. [&](const Request & /*req*/, Response &res) {
  5568. res.set_chunked_content_provider(
  5569. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5570. sink.os << "123";
  5571. sink.os << "456";
  5572. sink.os << "789";
  5573. sink.done();
  5574. return true;
  5575. });
  5576. })
  5577. .Get("/streamed-chunked-with-prohibited-trailer",
  5578. [&](const Request & /*req*/, Response &res) {
  5579. auto i = new int(0);
  5580. // Declare both a prohibited trailer (Content-Length) and an
  5581. // allowed one
  5582. res.set_header("Trailer", "Content-Length, X-Allowed");
  5583. res.set_chunked_content_provider(
  5584. "text/plain",
  5585. [i](size_t /*offset*/, DataSink &sink) {
  5586. switch (*i) {
  5587. case 0: sink.os << "123"; break;
  5588. case 1: sink.os << "456"; break;
  5589. case 2: sink.os << "789"; break;
  5590. case 3: {
  5591. sink.done_with_trailer(
  5592. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5593. } break;
  5594. }
  5595. (*i)++;
  5596. return true;
  5597. },
  5598. [i](bool success) {
  5599. EXPECT_TRUE(success);
  5600. delete i;
  5601. });
  5602. })
  5603. .Get("/streamed-chunked2",
  5604. [&](const Request & /*req*/, Response &res) {
  5605. auto i = new int(0);
  5606. res.set_chunked_content_provider(
  5607. "text/plain",
  5608. [i](size_t /*offset*/, DataSink &sink) {
  5609. switch (*i) {
  5610. case 0: sink.os << "123"; break;
  5611. case 1: sink.os << "456"; break;
  5612. case 2: sink.os << "789"; break;
  5613. case 3: sink.done(); break;
  5614. }
  5615. (*i)++;
  5616. return true;
  5617. },
  5618. [i](bool success) {
  5619. EXPECT_TRUE(success);
  5620. delete i;
  5621. });
  5622. })
  5623. .Get("/streamed-chunked-with-trailer",
  5624. [&](const Request & /*req*/, Response &res) {
  5625. auto i = new int(0);
  5626. res.set_header("Trailer", "Dummy1, Dummy2");
  5627. res.set_chunked_content_provider(
  5628. "text/plain",
  5629. [i](size_t /*offset*/, DataSink &sink) {
  5630. switch (*i) {
  5631. case 0: sink.os << "123"; break;
  5632. case 1: sink.os << "456"; break;
  5633. case 2: sink.os << "789"; break;
  5634. case 3: {
  5635. sink.done_with_trailer(
  5636. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5637. } break;
  5638. }
  5639. (*i)++;
  5640. return true;
  5641. },
  5642. [i](bool success) {
  5643. EXPECT_TRUE(success);
  5644. delete i;
  5645. });
  5646. })
  5647. .Get("/streamed",
  5648. [&](const Request & /*req*/, Response &res) {
  5649. res.set_content_provider(
  5650. 6, "text/plain",
  5651. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5652. sink.os << (offset < 3 ? "a" : "b");
  5653. return true;
  5654. });
  5655. })
  5656. .Get("/streamed-without-length",
  5657. [&](const Request & /*req*/, Response &res) {
  5658. auto data = new std::string("abcdefg");
  5659. res.set_content_provider(
  5660. "text/plain",
  5661. [data](size_t offset, DataSink &sink) {
  5662. if (offset < data->size()) {
  5663. sink.os << data->substr(offset);
  5664. }
  5665. sink.done();
  5666. return true;
  5667. },
  5668. [data](bool success) {
  5669. EXPECT_TRUE(success);
  5670. delete data;
  5671. });
  5672. })
  5673. .Get("/streamed-with-range",
  5674. [&](const Request &req, Response &res) {
  5675. auto data = new std::string("abcdefg");
  5676. // An explicit status keeps the server from picking the 206 it
  5677. // would otherwise choose for a ranged request, so the response
  5678. // is not a partial representation.
  5679. auto status = req.get_param_value("status");
  5680. if (status == "200") {
  5681. res.status = StatusCode::OK_200;
  5682. } else if (status == "403") {
  5683. res.status = StatusCode::Forbidden_403;
  5684. }
  5685. res.set_content_provider(
  5686. data->size(), "text/plain",
  5687. [data](size_t offset, size_t length, DataSink &sink) {
  5688. size_t DATA_CHUNK_SIZE = 4;
  5689. const auto &d = *data;
  5690. auto out_len =
  5691. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5692. auto ret =
  5693. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5694. EXPECT_TRUE(ret);
  5695. return true;
  5696. },
  5697. [data, &req](bool success) {
  5698. EXPECT_EQ(success, !req.has_param("error"));
  5699. delete data;
  5700. });
  5701. })
  5702. .Get("/streamed-cancel",
  5703. [&](const Request & /*req*/, Response &res) {
  5704. res.set_content_provider(
  5705. size_t(-1), "text/plain",
  5706. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5707. sink.os << "data_chunk";
  5708. return true;
  5709. });
  5710. })
  5711. .Get("/regex-with-delimiter",
  5712. [&](const Request &req, Response & /*res*/) {
  5713. ASSERT_TRUE(req.has_param("key"));
  5714. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5715. })
  5716. .Get("/with-range",
  5717. [&](const Request & /*req*/, Response &res) {
  5718. res.set_content("abcdefg", "text/plain");
  5719. })
  5720. .Get("/test-start-time",
  5721. [&](const Request &req, Response & /*res*/) {
  5722. EXPECT_NE(req.start_time_,
  5723. std::chrono::steady_clock::time_point::min());
  5724. })
  5725. .Get("/with-range-customized-response",
  5726. [&](const Request & /*req*/, Response &res) {
  5727. res.status = StatusCode::BadRequest_400;
  5728. res.set_content(JSON_DATA, "application/json");
  5729. })
  5730. .Post("/chunked",
  5731. [&](const Request &req, Response & /*res*/) {
  5732. EXPECT_EQ(req.body, "dechunked post body");
  5733. })
  5734. .Post("/large-chunked",
  5735. [&](const Request &req, Response & /*res*/) {
  5736. std::string expected(6 * 30 * 1024u, 'a');
  5737. EXPECT_EQ(req.body, expected);
  5738. })
  5739. .Post("/multipart",
  5740. [&](const Request &req, Response & /*res*/) {
  5741. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5742. req.form.get_field_count("text2") +
  5743. req.form.get_field_count("file3") +
  5744. req.form.get_field_count("file4"));
  5745. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5746. req.form.get_file_count("file2"));
  5747. ASSERT_TRUE(!req.form.has_file("???"));
  5748. ASSERT_TRUE(!req.form.has_field("???"));
  5749. ASSERT_TRUE(req.body.empty());
  5750. {
  5751. const auto &text = req.form.get_field("text1");
  5752. EXPECT_EQ("text default", text);
  5753. }
  5754. {
  5755. const auto &text = req.form.get_field("text2");
  5756. EXPECT_EQ("aωb", text);
  5757. }
  5758. {
  5759. const auto &file = req.form.get_file("file1");
  5760. EXPECT_EQ("hello.txt", file.filename);
  5761. EXPECT_EQ("text/plain", file.content_type);
  5762. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5763. }
  5764. {
  5765. const auto &file = req.form.get_file("file2");
  5766. EXPECT_EQ("world.json", file.filename);
  5767. EXPECT_EQ("application/json", file.content_type);
  5768. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5769. }
  5770. {
  5771. const auto &text = req.form.get_field("file3");
  5772. EXPECT_EQ(0u, text.size());
  5773. }
  5774. {
  5775. const auto &text = req.form.get_field("file4");
  5776. EXPECT_EQ(0u, text.size());
  5777. }
  5778. })
  5779. .Post("/multipart/multi_file_values",
  5780. [&](const Request &req, Response & /*res*/) {
  5781. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5782. req.form.get_field_count("multi_text1"));
  5783. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5784. ASSERT_TRUE(!req.form.has_file("???"));
  5785. ASSERT_TRUE(!req.form.has_field("???"));
  5786. ASSERT_TRUE(req.body.empty());
  5787. {
  5788. const auto &text = req.form.get_field("text");
  5789. EXPECT_EQ("default text", text);
  5790. }
  5791. {
  5792. const auto &text1_values = req.form.get_fields("multi_text1");
  5793. EXPECT_EQ(2u, text1_values.size());
  5794. EXPECT_EQ("aaaaa", text1_values[0]);
  5795. EXPECT_EQ("bbbbb", text1_values[1]);
  5796. }
  5797. {
  5798. const auto &file1_values = req.form.get_files("multi_file1");
  5799. EXPECT_EQ(2u, file1_values.size());
  5800. auto file1 = file1_values[0];
  5801. EXPECT_EQ(file1.filename, "hello.txt");
  5802. EXPECT_EQ(file1.content_type, "text/plain");
  5803. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5804. auto file2 = file1_values[1];
  5805. EXPECT_EQ(file2.filename, "world.json");
  5806. EXPECT_EQ(file2.content_type, "application/json");
  5807. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5808. }
  5809. })
  5810. .Post("/empty",
  5811. [&](const Request &req, Response &res) {
  5812. EXPECT_EQ(req.body, "");
  5813. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5814. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5815. res.set_content("empty", "text/plain");
  5816. })
  5817. .Post("/empty-no-content-type",
  5818. [&](const Request &req, Response &res) {
  5819. EXPECT_EQ(req.body, "");
  5820. EXPECT_FALSE(req.has_header("Content-Type"));
  5821. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5822. res.set_content("empty-no-content-type", "text/plain");
  5823. })
  5824. .Post("/path-only",
  5825. [&](const Request &req, Response &res) {
  5826. EXPECT_EQ(req.body, "");
  5827. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5828. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5829. res.set_content("path-only", "text/plain");
  5830. })
  5831. .Post("/path-headers-only",
  5832. [&](const Request &req, Response &res) {
  5833. EXPECT_EQ(req.body, "");
  5834. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5835. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5836. EXPECT_EQ("world", req.get_header_value("hello"));
  5837. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5838. res.set_content("path-headers-only", "text/plain");
  5839. })
  5840. .Post("/post-large",
  5841. [&](const Request &req, Response &res) {
  5842. EXPECT_EQ(req.body, LARGE_DATA);
  5843. res.set_content(req.body, "text/plain");
  5844. })
  5845. .Post("/post-loopback",
  5846. [&](const Request &, Response &res,
  5847. ContentReader const &content_reader) {
  5848. std::string body;
  5849. content_reader([&](const char *data, size_t data_length) {
  5850. body.append(data, data_length);
  5851. return true;
  5852. });
  5853. res.set_content(body, "text/plain");
  5854. })
  5855. .Put("/put-loopback",
  5856. [&](const Request &, Response &res,
  5857. ContentReader const &content_reader) {
  5858. std::string body;
  5859. content_reader([&](const char *data, size_t data_length) {
  5860. body.append(data, data_length);
  5861. return true;
  5862. });
  5863. res.set_content(body, "text/plain");
  5864. })
  5865. .Patch("/patch-loopback",
  5866. [&](const Request &, Response &res,
  5867. ContentReader const &content_reader) {
  5868. std::string body;
  5869. content_reader([&](const char *data, size_t data_length) {
  5870. body.append(data, data_length);
  5871. return true;
  5872. });
  5873. res.set_content(body, "text/plain");
  5874. })
  5875. .Put("/empty-no-content-type",
  5876. [&](const Request &req, Response &res) {
  5877. EXPECT_EQ(req.body, "");
  5878. EXPECT_FALSE(req.has_header("Content-Type"));
  5879. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5880. res.set_content("empty-no-content-type", "text/plain");
  5881. })
  5882. .Put("/put",
  5883. [&](const Request &req, Response &res) {
  5884. EXPECT_EQ(req.body, "PUT");
  5885. res.set_content(req.body, "text/plain");
  5886. })
  5887. .Put("/put-large",
  5888. [&](const Request &req, Response &res) {
  5889. EXPECT_EQ(req.body, LARGE_DATA);
  5890. res.set_content(req.body, "text/plain");
  5891. })
  5892. .Patch("/patch",
  5893. [&](const Request &req, Response &res) {
  5894. EXPECT_EQ(req.body, "PATCH");
  5895. res.set_content(req.body, "text/plain");
  5896. })
  5897. .Delete("/delete",
  5898. [&](const Request & /*req*/, Response &res) {
  5899. res.set_content("DELETE", "text/plain");
  5900. })
  5901. .Delete("/delete-body",
  5902. [&](const Request &req, Response &res) {
  5903. EXPECT_EQ(req.body, "content");
  5904. res.set_content(req.body, "text/plain");
  5905. })
  5906. .Options(R"(\*)",
  5907. [&](const Request & /*req*/, Response &res) {
  5908. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5909. })
  5910. .CustomRoute("PROPFIND", "/dav/:id",
  5911. [&](const Request &req, Response &res) {
  5912. res.set_header("x-body-size",
  5913. std::to_string(req.body.size()));
  5914. res.set_header("x-matched-route", req.matched_route);
  5915. res.set_header("x-dav-id", req.path_params.at("id"));
  5916. res.status = StatusCode::MultiStatus_207;
  5917. res.set_content(req.body, "application/xml");
  5918. })
  5919. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5920. [&](const Request &req, Response &res) {
  5921. res.set_header("x-dav-match", req.matches[1]);
  5922. res.status = StatusCode::MultiStatus_207;
  5923. })
  5924. .CustomRoute("MKCOL", "/dav-mkcol",
  5925. [&](const Request &req, Response &res) {
  5926. EXPECT_TRUE(req.body.empty());
  5927. res.status = StatusCode::Created_201;
  5928. })
  5929. .CustomRoute(
  5930. "REPORT", "/dav-report",
  5931. [&](const Request & /*req*/, Response &res,
  5932. const ContentReader &content_reader) {
  5933. std::string body;
  5934. content_reader([&](const char *data, size_t data_length) {
  5935. body.append(data, data_length);
  5936. return true;
  5937. });
  5938. res.set_header("x-body-size", std::to_string(body.size()));
  5939. res.status = StatusCode::MultiStatus_207;
  5940. res.set_content(body, "application/xml");
  5941. })
  5942. .Get("/request-target",
  5943. [&](const Request &req, Response & /*res*/) {
  5944. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5945. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5946. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5947. })
  5948. .Get("/long-query-value",
  5949. [&](const Request &req, Response & /*res*/) {
  5950. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5951. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5952. })
  5953. .Get("/too-long-query-value",
  5954. [&](const Request &req, Response & /*res*/) {
  5955. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5956. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5957. })
  5958. .Get("/array-param",
  5959. [&](const Request &req, Response & /*res*/) {
  5960. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5961. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5962. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5963. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5964. })
  5965. .Get("/array-param-values",
  5966. [&](const Request &req, Response & /*res*/) {
  5967. auto values = req.get_param_values("array");
  5968. EXPECT_EQ(3u, values.size());
  5969. EXPECT_EQ("value1", values[0]);
  5970. EXPECT_EQ("value2", values[1]);
  5971. EXPECT_EQ("value3", values[2]);
  5972. auto empty = req.get_param_values("nonexistent");
  5973. EXPECT_TRUE(empty.empty());
  5974. })
  5975. .Post("/validate-no-multiple-headers",
  5976. [&](const Request &req, Response & /*res*/) {
  5977. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5978. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5979. })
  5980. .Post("/content_receiver",
  5981. [&](const Request &req, Response &res,
  5982. const ContentReader &content_reader) {
  5983. if (req.is_multipart_form_data()) {
  5984. std::vector<FormData> items;
  5985. content_reader(
  5986. [&](const FormData &file) {
  5987. items.push_back(file);
  5988. return true;
  5989. },
  5990. [&](const char *data, size_t data_length) {
  5991. items.back().content.append(data, data_length);
  5992. return true;
  5993. });
  5994. EXPECT_EQ(5u, items.size());
  5995. {
  5996. const auto &file = get_file_value(items, "text1");
  5997. EXPECT_TRUE(file.filename.empty());
  5998. EXPECT_EQ("text default", file.content);
  5999. }
  6000. {
  6001. const auto &file = get_file_value(items, "text2");
  6002. EXPECT_TRUE(file.filename.empty());
  6003. EXPECT_EQ("aωb", file.content);
  6004. }
  6005. {
  6006. const auto &file = get_file_value(items, "file1");
  6007. EXPECT_EQ("hello.txt", file.filename);
  6008. EXPECT_EQ("text/plain", file.content_type);
  6009. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6010. }
  6011. {
  6012. const auto &file = get_file_value(items, "file2");
  6013. EXPECT_EQ("world.json", file.filename);
  6014. EXPECT_EQ("application/json", file.content_type);
  6015. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6016. }
  6017. {
  6018. const auto &file = get_file_value(items, "file3");
  6019. EXPECT_TRUE(file.filename.empty());
  6020. EXPECT_EQ("application/octet-stream", file.content_type);
  6021. EXPECT_EQ(0u, file.content.size());
  6022. }
  6023. } else {
  6024. std::string body;
  6025. content_reader([&](const char *data, size_t data_length) {
  6026. EXPECT_EQ(7U, data_length);
  6027. body.append(data, data_length);
  6028. return true;
  6029. });
  6030. EXPECT_EQ(body, "content");
  6031. res.set_content(body, "text/plain");
  6032. }
  6033. })
  6034. .Put("/content_receiver",
  6035. [&](const Request & /*req*/, Response &res,
  6036. const ContentReader &content_reader) {
  6037. std::string body;
  6038. content_reader([&](const char *data, size_t data_length) {
  6039. body.append(data, data_length);
  6040. return true;
  6041. });
  6042. EXPECT_EQ(body, "content");
  6043. res.set_content(body, "text/plain");
  6044. })
  6045. .Patch("/content_receiver",
  6046. [&](const Request & /*req*/, Response &res,
  6047. const ContentReader &content_reader) {
  6048. std::string body;
  6049. content_reader([&](const char *data, size_t data_length) {
  6050. body.append(data, data_length);
  6051. return true;
  6052. });
  6053. EXPECT_EQ(body, "content");
  6054. res.set_content(body, "text/plain");
  6055. })
  6056. .Post("/query-string-and-body",
  6057. [&](const Request &req, Response & /*res*/) {
  6058. ASSERT_TRUE(req.has_param("key"));
  6059. EXPECT_EQ(req.get_param_value("key"), "value");
  6060. EXPECT_EQ(req.body, "content");
  6061. })
  6062. .Get("/last-request",
  6063. [&](const Request &req, Response & /*res*/) {
  6064. EXPECT_EQ("close", req.get_header_value("Connection"));
  6065. })
  6066. .Get(R"(/redirect/(\d+))",
  6067. [&](const Request &req, Response &res) {
  6068. auto num = std::stoi(req.matches[1]) + 1;
  6069. std::string url = "/redirect/" + std::to_string(num);
  6070. res.set_redirect(url);
  6071. })
  6072. .Post("/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. .Put("/binary",
  6081. [&](const Request &req, Response &res) {
  6082. EXPECT_EQ(4U, req.body.size());
  6083. EXPECT_EQ("application/octet-stream",
  6084. req.get_header_value("Content-Type"));
  6085. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6086. res.set_content(req.body, "application/octet-stream");
  6087. })
  6088. .Patch("/binary",
  6089. [&](const Request &req, Response &res) {
  6090. EXPECT_EQ(4U, req.body.size());
  6091. EXPECT_EQ("application/octet-stream",
  6092. req.get_header_value("Content-Type"));
  6093. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6094. res.set_content(req.body, "application/octet-stream");
  6095. })
  6096. .Delete("/binary",
  6097. [&](const Request &req, Response &res) {
  6098. EXPECT_EQ(4U, req.body.size());
  6099. EXPECT_EQ("application/octet-stream",
  6100. req.get_header_value("Content-Type"));
  6101. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6102. res.set_content(req.body, "application/octet-stream");
  6103. })
  6104. .Get("/issue1772",
  6105. [&](const Request & /*req*/, Response &res) {
  6106. res.status = 401;
  6107. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6108. })
  6109. .Delete("/issue609",
  6110. [](const httplib::Request &, httplib::Response &res,
  6111. const httplib::ContentReader &) {
  6112. res.set_content("ok", "text/plain");
  6113. })
  6114. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6115. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6116. .Get("/compress",
  6117. [&](const Request & /*req*/, Response &res) {
  6118. res.set_content(
  6119. "12345678901234567890123456789012345678901234567890123456789"
  6120. "01234567890123456789012345678901234567890",
  6121. "text/plain");
  6122. })
  6123. .Get("/compress-with-charset",
  6124. [&](const Request & /*req*/, Response &res) {
  6125. res.set_content(
  6126. "12345678901234567890123456789012345678901234567890123456789"
  6127. "01234567890123456789012345678901234567890",
  6128. "application/json; charset=utf-8");
  6129. })
  6130. .Get("/nocompress",
  6131. [&](const Request & /*req*/, Response &res) {
  6132. res.set_content(
  6133. "12345678901234567890123456789012345678901234567890123456789"
  6134. "01234567890123456789012345678901234567890",
  6135. "application/octet-stream");
  6136. })
  6137. .Post("/compress-multipart",
  6138. [&](const Request &req, Response & /*res*/) {
  6139. EXPECT_EQ(2u, req.form.fields.size());
  6140. ASSERT_TRUE(!req.form.has_field("???"));
  6141. {
  6142. const auto &text = req.form.get_field("key1");
  6143. EXPECT_EQ("test", text);
  6144. }
  6145. {
  6146. const auto &text = req.form.get_field("key2");
  6147. EXPECT_EQ("--abcdefg123", text);
  6148. }
  6149. })
  6150. #endif
  6151. ;
  6152. persons_["john"] = "programmer";
  6153. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6154. svr_.wait_until_ready();
  6155. }
  6156. virtual void TearDown() {
  6157. svr_.stop();
  6158. if (!request_threads_.empty()) {
  6159. std::this_thread::sleep_for(std::chrono::seconds(1));
  6160. for (auto &t : request_threads_) {
  6161. t.join();
  6162. }
  6163. }
  6164. t_.join();
  6165. }
  6166. map<string, string> persons_;
  6167. #ifdef CPPHTTPLIB_SSL_ENABLED
  6168. SSLClient cli_;
  6169. SSLServer svr_;
  6170. #else
  6171. Client cli_;
  6172. Server svr_;
  6173. #endif
  6174. thread t_;
  6175. std::vector<thread> request_threads_;
  6176. };
  6177. TEST_F(ServerTest, GetMethod200) {
  6178. auto res = cli_.Get("/hi");
  6179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6180. EXPECT_EQ("HTTP/1.1", res->version);
  6181. EXPECT_EQ(StatusCode::OK_200, res->status);
  6182. EXPECT_EQ("OK", res->reason);
  6183. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6184. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6185. EXPECT_EQ("Hello World!", res->body);
  6186. }
  6187. TEST_F(ServerTest, GetEmptyFile) {
  6188. auto res = cli_.Get("/empty_file");
  6189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6190. EXPECT_EQ(StatusCode::OK_200, res->status);
  6191. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6192. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6193. EXPECT_EQ("", res->body);
  6194. }
  6195. TEST_F(ServerTest, GetFileContent) {
  6196. auto res = cli_.Get("/file_content");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. EXPECT_EQ(StatusCode::OK_200, res->status);
  6199. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6200. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6201. EXPECT_EQ("test.html", res->body);
  6202. }
  6203. TEST_F(ServerTest, GetFileContentWithRange) {
  6204. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6206. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6207. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6208. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6209. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6210. EXPECT_EQ("est", res->body);
  6211. }
  6212. TEST_F(ServerTest, GetFileContentWithContentType) {
  6213. auto res = cli_.Get("/file_content_with_content_type");
  6214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6215. EXPECT_EQ(StatusCode::OK_200, res->status);
  6216. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6217. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6218. EXPECT_EQ("file\n", res->body);
  6219. }
  6220. TEST_F(ServerTest, GetInvalidFileContent) {
  6221. auto res = cli_.Get("/invalid_file_content");
  6222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6223. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6224. }
  6225. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6226. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6228. EXPECT_EQ("HTTP/1.1", res->version);
  6229. EXPECT_EQ(StatusCode::OK_200, res->status);
  6230. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6231. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6232. EXPECT_EQ("Hello World!", res->body);
  6233. }
  6234. TEST_F(ServerTest, GetMethod302) {
  6235. auto res = cli_.Get("/");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::Found_302, res->status);
  6238. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6239. }
  6240. TEST_F(ServerTest, GetMethod302Redirect) {
  6241. cli_.set_follow_location(true);
  6242. auto res = cli_.Get("/");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. EXPECT_EQ(StatusCode::OK_200, res->status);
  6245. EXPECT_EQ("Hello World!", res->body);
  6246. EXPECT_EQ("/hi", res->location);
  6247. }
  6248. TEST_F(ServerTest, GetMethod404) {
  6249. auto res = cli_.Get("/invalid");
  6250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6251. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6252. }
  6253. TEST_F(ServerTest, HeadMethod200) {
  6254. auto res = cli_.Head("/hi");
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. EXPECT_EQ(StatusCode::OK_200, res->status);
  6257. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6258. EXPECT_TRUE(res->body.empty());
  6259. }
  6260. TEST_F(ServerTest, HeadMethod200Static) {
  6261. auto res = cli_.Head("/mount/dir/index.html");
  6262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6263. EXPECT_EQ(StatusCode::OK_200, res->status);
  6264. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6265. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6266. EXPECT_TRUE(res->body.empty());
  6267. }
  6268. TEST_F(ServerTest, HeadMethod404) {
  6269. auto res = cli_.Head("/invalid");
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6272. EXPECT_TRUE(res->body.empty());
  6273. }
  6274. TEST_F(ServerTest, GetMethodPersonJohn) {
  6275. auto res = cli_.Get("/person/john");
  6276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6277. EXPECT_EQ(StatusCode::OK_200, res->status);
  6278. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6279. EXPECT_EQ("programmer", res->body);
  6280. }
  6281. TEST_F(ServerTest, PostMethod1) {
  6282. auto res = cli_.Get("/person/john1");
  6283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6284. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6285. res = cli_.Post("/person", "name=john1&note=coder",
  6286. "application/x-www-form-urlencoded");
  6287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6288. ASSERT_EQ(StatusCode::OK_200, res->status);
  6289. res = cli_.Get("/person/john1");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. ASSERT_EQ(StatusCode::OK_200, res->status);
  6292. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6293. ASSERT_EQ("coder", res->body);
  6294. }
  6295. TEST_F(ServerTest, PostMethod2) {
  6296. auto res = cli_.Get("/person/john2");
  6297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6298. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6299. Params params;
  6300. params.emplace("name", "john2");
  6301. params.emplace("note", "coder");
  6302. res = cli_.Post("/person", params);
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. ASSERT_EQ(StatusCode::OK_200, res->status);
  6305. res = cli_.Get("/person/john2");
  6306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6307. ASSERT_EQ(StatusCode::OK_200, res->status);
  6308. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6309. ASSERT_EQ("coder", res->body);
  6310. }
  6311. TEST_F(ServerTest, PutMethod3) {
  6312. auto res = cli_.Get("/person/john3");
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6315. Params params;
  6316. params.emplace("name", "john3");
  6317. params.emplace("note", "coder");
  6318. res = cli_.Put("/person", params);
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. ASSERT_EQ(StatusCode::OK_200, res->status);
  6321. res = cli_.Get("/person/john3");
  6322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6323. ASSERT_EQ(StatusCode::OK_200, res->status);
  6324. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6325. ASSERT_EQ("coder", res->body);
  6326. }
  6327. TEST_F(ServerTest, DeleteMethod1) {
  6328. auto res = cli_.Get("/person/john4");
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6331. Params params;
  6332. params.emplace("name", "john4");
  6333. params.emplace("note", "coder");
  6334. res = cli_.Post("/person", params);
  6335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6336. ASSERT_EQ(StatusCode::OK_200, res->status);
  6337. res = cli_.Get("/person/john4");
  6338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6339. ASSERT_EQ(StatusCode::OK_200, res->status);
  6340. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6341. ASSERT_EQ("coder", res->body);
  6342. Params delete_params;
  6343. delete_params.emplace("name", "john4");
  6344. res = cli_.Delete("/person", delete_params);
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. ASSERT_EQ(StatusCode::OK_200, res->status);
  6347. ASSERT_EQ("DELETED", res->body);
  6348. res = cli_.Get("/person/john4");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6351. }
  6352. TEST_F(ServerTest, DeleteMethod2) {
  6353. auto res = cli_.Get("/person/john5");
  6354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6356. Params params;
  6357. params.emplace("name", "john5");
  6358. params.emplace("note", "developer");
  6359. res = cli_.Post("/person", params);
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. ASSERT_EQ(StatusCode::OK_200, res->status);
  6362. res = cli_.Get("/person/john5");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. ASSERT_EQ(StatusCode::OK_200, res->status);
  6365. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6366. ASSERT_EQ("developer", res->body);
  6367. Params delete_params;
  6368. delete_params.emplace("name", "john5");
  6369. Headers headers;
  6370. headers.emplace("Custom-Header", "test-value");
  6371. res = cli_.Delete("/person", headers, delete_params);
  6372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6373. ASSERT_EQ(StatusCode::OK_200, res->status);
  6374. ASSERT_EQ("DELETED", res->body);
  6375. res = cli_.Get("/person/john5");
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6378. }
  6379. TEST_F(ServerTest, DeleteMethod3) {
  6380. auto res = cli_.Get("/person/john6");
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6383. Params params;
  6384. params.emplace("name", "john6");
  6385. params.emplace("note", "tester");
  6386. res = cli_.Post("/person", params);
  6387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6388. ASSERT_EQ(StatusCode::OK_200, res->status);
  6389. res = cli_.Get("/person/john6");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. ASSERT_EQ(StatusCode::OK_200, res->status);
  6392. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6393. ASSERT_EQ("tester", res->body);
  6394. Params delete_params;
  6395. delete_params.emplace("name", "john6");
  6396. Headers headers;
  6397. headers.emplace("Custom-Header", "test-value");
  6398. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. ASSERT_EQ(StatusCode::OK_200, res->status);
  6401. ASSERT_EQ("DELETED", res->body);
  6402. res = cli_.Get("/person/john6");
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6405. }
  6406. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6407. Params params;
  6408. params.emplace("json", JSON_DATA);
  6409. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. ASSERT_EQ(StatusCode::OK_200, res->status);
  6412. ASSERT_EQ(JSON_DATA, res->body);
  6413. }
  6414. TEST_F(ServerTest, PostEmptyContent) {
  6415. auto res = cli_.Post("/empty", "", "text/plain");
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. ASSERT_EQ(StatusCode::OK_200, res->status);
  6418. ASSERT_EQ("empty", res->body);
  6419. }
  6420. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6421. auto res = cli_.Post("/empty-no-content-type");
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. ASSERT_EQ(StatusCode::OK_200, res->status);
  6424. ASSERT_EQ("empty-no-content-type", res->body);
  6425. }
  6426. TEST_F(ServerTest, PostPathOnly) {
  6427. auto res = cli_.Post("/path-only");
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. ASSERT_EQ(StatusCode::OK_200, res->status);
  6430. ASSERT_EQ("path-only", res->body);
  6431. }
  6432. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6433. auto res = cli_.Post("/path-headers-only",
  6434. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6436. ASSERT_EQ(StatusCode::OK_200, res->status);
  6437. ASSERT_EQ("path-headers-only", res->body);
  6438. }
  6439. TEST_F(ServerTest, PostLarge) {
  6440. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. ASSERT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ(LARGE_DATA, res->body);
  6444. }
  6445. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6446. auto res = cli_.Put("/empty-no-content-type");
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. ASSERT_EQ(StatusCode::OK_200, res->status);
  6449. ASSERT_EQ("empty-no-content-type", res->body);
  6450. }
  6451. TEST_F(ServerTest, GetMethodDir) {
  6452. auto res = cli_.Get("/dir/");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6456. auto body = R"(<html>
  6457. <head>
  6458. </head>
  6459. <body>
  6460. <a href="/dir/test.html">Test</a>
  6461. <a href="/hi">hi</a>
  6462. </body>
  6463. </html>
  6464. )";
  6465. EXPECT_EQ(body, res->body);
  6466. }
  6467. TEST_F(ServerTest, GetMethodDirTest) {
  6468. auto res = cli_.Get("/dir/test.html");
  6469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6470. EXPECT_EQ(StatusCode::OK_200, res->status);
  6471. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6472. EXPECT_EQ("test.html", res->body);
  6473. }
  6474. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6475. auto res = cli_.Get("/dir/../dir/test.html");
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6478. }
  6479. TEST_F(ServerTest, GetMethodInvalidPath) {
  6480. auto res = cli_.Get("/dir/../test.html");
  6481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6483. }
  6484. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6485. auto res = cli_.Get("/../www/dir/test.html");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6488. }
  6489. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6490. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6493. }
  6494. TEST_F(ServerTest, GetMethodDirMountTest) {
  6495. auto res = cli_.Get("/mount/dir/test.html");
  6496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6499. EXPECT_EQ("test.html", res->body);
  6500. }
  6501. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6502. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6505. }
  6506. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6507. auto res = cli_.Get("/mount/dir/../test.html");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6510. }
  6511. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6512. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6514. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6515. }
  6516. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6517. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6520. }
  6521. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6522. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6525. }
  6526. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6527. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6530. }
  6531. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6532. auto res = cli_.Get("/mount/dir");
  6533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6534. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6535. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6536. }
  6537. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6538. auto res = cli_.Get("//dir");
  6539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6540. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6541. EXPECT_FALSE(res->has_header("Location"));
  6542. }
  6543. TEST_F(ServerTest, PostMethod303) {
  6544. auto res = cli_.Post("/1", "body", "text/plain");
  6545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6546. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6547. EXPECT_EQ("/2", res->get_header_value("Location"));
  6548. }
  6549. TEST_F(ServerTest, PostMethod303Redirect) {
  6550. cli_.set_follow_location(true);
  6551. auto res = cli_.Post("/1", "body", "text/plain");
  6552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6553. EXPECT_EQ(StatusCode::OK_200, res->status);
  6554. EXPECT_EQ("redirected.", res->body);
  6555. EXPECT_EQ("/2", res->location);
  6556. }
  6557. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6558. auto res = cli_.Get("/dir/test.abcde");
  6559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6560. EXPECT_EQ(StatusCode::OK_200, res->status);
  6561. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6562. EXPECT_EQ("abcde", res->body);
  6563. }
  6564. TEST_F(ServerTest, StaticFileRange) {
  6565. auto res =
  6566. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6568. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6569. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6570. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6571. EXPECT_EQ(true, res->has_header("Content-Range"));
  6572. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6573. EXPECT_EQ(std::string("cd"), res->body);
  6574. }
  6575. TEST_F(ServerTest, StaticFileRanges) {
  6576. auto res = cli_.Get("/dir/test.abcde",
  6577. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6580. EXPECT_TRUE(
  6581. res->get_header_value("Content-Type")
  6582. .find(
  6583. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6584. 0);
  6585. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6586. }
  6587. TEST_F(ServerTest, StaticFileRangeHead) {
  6588. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6590. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6591. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6592. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6593. EXPECT_EQ(true, res->has_header("Content-Range"));
  6594. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6595. }
  6596. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6597. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6599. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6601. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6602. EXPECT_EQ(true, res->has_header("Content-Range"));
  6603. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6604. res->get_header_value("Content-Range"));
  6605. EXPECT_EQ("LAST\n", res->body);
  6606. }
  6607. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6608. auto res =
  6609. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6611. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6612. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6613. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6614. EXPECT_EQ(true, res->has_header("Content-Range"));
  6615. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6616. }
  6617. TEST_F(ServerTest, StaticFileBigFile) {
  6618. auto res = cli_.Get("/dir/1MB.txt");
  6619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6620. EXPECT_EQ(StatusCode::OK_200, res->status);
  6621. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6622. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6623. }
  6624. TEST_F(ServerTest, InvalidBaseDirMount) {
  6625. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6626. }
  6627. TEST_F(ServerTest, Binary) {
  6628. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6629. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6630. "application/octet-stream");
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. ASSERT_EQ(StatusCode::OK_200, res->status);
  6633. ASSERT_EQ(4U, res->body.size());
  6634. res = cli_.Put("/binary", binary.data(), binary.size(),
  6635. "application/octet-stream");
  6636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6637. ASSERT_EQ(StatusCode::OK_200, res->status);
  6638. ASSERT_EQ(4U, res->body.size());
  6639. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6640. "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. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6645. "application/octet-stream");
  6646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6647. ASSERT_EQ(StatusCode::OK_200, res->status);
  6648. ASSERT_EQ(4U, res->body.size());
  6649. }
  6650. TEST_F(ServerTest, BinaryString) {
  6651. auto binary = std::string("\x00\x01\x02\x03", 4);
  6652. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. ASSERT_EQ(StatusCode::OK_200, res->status);
  6655. ASSERT_EQ(4U, res->body.size());
  6656. res = cli_.Put("/binary", binary, "application/octet-stream");
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. ASSERT_EQ(StatusCode::OK_200, res->status);
  6659. ASSERT_EQ(4U, res->body.size());
  6660. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. ASSERT_EQ(StatusCode::OK_200, res->status);
  6663. ASSERT_EQ(4U, res->body.size());
  6664. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6666. ASSERT_EQ(StatusCode::OK_200, res->status);
  6667. ASSERT_EQ(4U, res->body.size());
  6668. }
  6669. TEST_F(ServerTest, EmptyRequest) {
  6670. auto res = cli_.Get("");
  6671. ASSERT_TRUE(!res);
  6672. EXPECT_EQ(Error::Connection, res.error());
  6673. }
  6674. TEST_F(ServerTest, LongRequest) {
  6675. std::string request;
  6676. for (size_t i = 0; i < 545; i++) {
  6677. request += "/TooLongRequest";
  6678. }
  6679. request += "OK";
  6680. auto res = cli_.Get(request.c_str());
  6681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6682. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6683. }
  6684. TEST_F(ServerTest, TooLongRequest) {
  6685. std::string request;
  6686. for (size_t i = 0; i < 546; i++) {
  6687. request += "/TooLongRequest";
  6688. }
  6689. request += "_NG";
  6690. auto start = std::chrono::high_resolution_clock::now();
  6691. cli_.set_keep_alive(true);
  6692. auto res = cli_.Get(request.c_str());
  6693. auto end = std::chrono::high_resolution_clock::now();
  6694. auto elapsed =
  6695. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6696. .count();
  6697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6698. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6699. EXPECT_LE(elapsed, 1000);
  6700. EXPECT_EQ("close", res->get_header_value("Connection"));
  6701. EXPECT_FALSE(cli_.is_socket_open());
  6702. }
  6703. TEST_F(ServerTest, AlmostTooLongRequest) {
  6704. // test for #2046 - URI length check shouldn't include other content on req
  6705. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6706. // leading /, space, HTTP/1.1)
  6707. std::string request =
  6708. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6709. auto res = cli_.Get(request.c_str());
  6710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6711. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6712. }
  6713. TEST_F(ServerTest, LongHeader) {
  6714. Request req;
  6715. req.method = "GET";
  6716. req.path = "/hi";
  6717. std::string host_and_port;
  6718. host_and_port += HOST;
  6719. host_and_port += ":";
  6720. host_and_port += std::to_string(PORT);
  6721. req.headers.emplace("Host", host_and_port.c_str());
  6722. req.headers.emplace("Accept", "*/*");
  6723. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6724. req.headers.emplace(
  6725. "Header-Name",
  6726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6754. "@@@@@@@@@@@@@@@@");
  6755. auto res = std::make_shared<Response>();
  6756. auto error = Error::Success;
  6757. auto ret = cli_.send(req, *res, error);
  6758. ASSERT_TRUE(ret);
  6759. EXPECT_EQ(StatusCode::OK_200, res->status);
  6760. }
  6761. TEST_F(ServerTest, LongQueryValue) {
  6762. auto start = std::chrono::high_resolution_clock::now();
  6763. cli_.set_keep_alive(true);
  6764. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6765. auto end = std::chrono::high_resolution_clock::now();
  6766. auto elapsed =
  6767. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6768. .count();
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6771. EXPECT_LE(elapsed, 1000);
  6772. EXPECT_EQ("close", res->get_header_value("Connection"));
  6773. EXPECT_FALSE(cli_.is_socket_open());
  6774. }
  6775. TEST_F(ServerTest, TooLongQueryValue) {
  6776. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6777. ASSERT_FALSE(res);
  6778. EXPECT_EQ(Error::Read, res.error());
  6779. }
  6780. TEST_F(ServerTest, TooLongHeader) {
  6781. Request req;
  6782. req.method = "GET";
  6783. req.path = "/hi";
  6784. std::string host_and_port;
  6785. host_and_port += HOST;
  6786. host_and_port += ":";
  6787. host_and_port += std::to_string(PORT);
  6788. req.headers.emplace("Host", host_and_port.c_str());
  6789. req.headers.emplace("Accept", "*/*");
  6790. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6791. req.headers.emplace(
  6792. "Header-Name",
  6793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6821. "@@@@@@@@@@@@@@@@@");
  6822. auto res = std::make_shared<Response>();
  6823. auto error = Error::Success;
  6824. auto ret = cli_.send(req, *res, error);
  6825. ASSERT_TRUE(ret);
  6826. EXPECT_EQ(StatusCode::OK_200, res->status);
  6827. }
  6828. TEST_F(ServerTest, HeaderCountAtLimit) {
  6829. // Test with headers just under the 100 limit
  6830. httplib::Headers headers;
  6831. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6832. // This should keep us just under the 100 header limit
  6833. for (int i = 0; i < 95; i++) {
  6834. std::string name = "X-Test-Header-" + std::to_string(i);
  6835. std::string value = "value" + std::to_string(i);
  6836. headers.emplace(name, value);
  6837. }
  6838. // This should work fine as we're under the limit
  6839. auto res = cli_.Get("/hi", headers);
  6840. EXPECT_TRUE(res);
  6841. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6842. }
  6843. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6844. // Test with many headers to exceed the 100 limit
  6845. httplib::Headers headers;
  6846. // Add 150 headers to definitely exceed the 100 limit
  6847. for (int i = 0; i < 150; i++) {
  6848. std::string name = "X-Test-Header-" + std::to_string(i);
  6849. std::string value = "value" + std::to_string(i);
  6850. headers.emplace(name, value);
  6851. }
  6852. // This should fail due to exceeding header count limit
  6853. cli_.set_keep_alive(true);
  6854. auto res = cli_.Get("/hi", headers);
  6855. // The server should respond with 400 Bad Request
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6858. EXPECT_EQ("close", res->get_header_value("Connection"));
  6859. EXPECT_FALSE(cli_.is_socket_open());
  6860. }
  6861. TEST_F(ServerTest, PercentEncoding) {
  6862. auto res = cli_.Get("/e%6edwith%");
  6863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6864. EXPECT_EQ(StatusCode::OK_200, res->status);
  6865. }
  6866. TEST_F(ServerTest, PercentEncodingUnicode) {
  6867. auto res = cli_.Get("/e%u006edwith%");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. }
  6871. TEST_F(ServerTest, InvalidPercentEncoding) {
  6872. auto res = cli_.Get("/%endwith%");
  6873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6875. }
  6876. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6877. auto res = cli_.Get("/%uendwith%");
  6878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6880. }
  6881. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6882. auto res = cli_.Get("/hello?aaa=bbb%");
  6883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6885. }
  6886. TEST_F(ServerTest, PlusSignEncoding) {
  6887. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6889. EXPECT_EQ(StatusCode::OK_200, res->status);
  6890. EXPECT_EQ("a +b", res->body);
  6891. }
  6892. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6893. // This test simulates a potential DoS attack using many headers
  6894. // to verify our security fix prevents memory exhaustion
  6895. httplib::Headers attack_headers;
  6896. // Attempt to add many headers like an attacker would (200 headers to far
  6897. // exceed limit)
  6898. for (int i = 0; i < 200; i++) {
  6899. std::string name = "X-Attack-Header-" + std::to_string(i);
  6900. std::string value = "attack_payload_" + std::to_string(i);
  6901. attack_headers.emplace(name, value);
  6902. }
  6903. // Try to POST with excessive headers
  6904. cli_.set_keep_alive(true);
  6905. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6906. // Should either fail or return 400 Bad Request due to security limit
  6907. if (res) {
  6908. // If we get a response, it should be 400 Bad Request
  6909. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6910. EXPECT_EQ("close", res->get_header_value("Connection"));
  6911. }
  6912. EXPECT_FALSE(cli_.is_socket_open());
  6913. }
  6914. TEST_F(ServerTest, MultipartFormData) {
  6915. UploadFormDataItems items = {
  6916. {"text1", "text default", "", ""},
  6917. {"text2", "aωb", "", ""},
  6918. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6919. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6920. {"file3", "", "", "application/octet-stream"},
  6921. {"file4", "", "", " application/json tmp-string "}};
  6922. auto res = cli_.Post("/multipart", items);
  6923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6924. EXPECT_EQ(StatusCode::OK_200, res->status);
  6925. }
  6926. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6927. UploadFormDataItems items = {
  6928. {"text", "default text", "", ""},
  6929. {"multi_text1", "aaaaa", "", ""},
  6930. {"multi_text1", "bbbbb", "", ""},
  6931. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6932. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6933. "application/json"},
  6934. };
  6935. auto res = cli_.Post("/multipart/multi_file_values", items);
  6936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6937. EXPECT_EQ(StatusCode::OK_200, res->status);
  6938. }
  6939. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6940. auto res = cli_.Get("/hi");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::OK_200, res->status);
  6943. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6944. EXPECT_EQ("Hello World!", res->body);
  6945. }
  6946. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6947. Request req;
  6948. req.method = "POST";
  6949. req.path = "/chunked";
  6950. std::string host_and_port;
  6951. host_and_port += HOST;
  6952. host_and_port += ":";
  6953. host_and_port += std::to_string(PORT);
  6954. req.headers.emplace("Host", host_and_port.c_str());
  6955. req.headers.emplace("Accept", "*/*");
  6956. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6957. req.headers.emplace("Content-Type", "text/plain");
  6958. req.headers.emplace("Content-Length", "0");
  6959. req.headers.emplace(
  6960. "Transfer-Encoding",
  6961. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6962. // Client does not chunk, so make a chunked body manually.
  6963. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6964. auto res = std::make_shared<Response>();
  6965. auto error = Error::Success;
  6966. auto ret = cli_.send(req, *res, error);
  6967. ASSERT_TRUE(ret);
  6968. EXPECT_EQ(StatusCode::OK_200, res->status);
  6969. }
  6970. template <typename ClientT>
  6971. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6972. int expected_status) {
  6973. Request req;
  6974. req.method = "POST";
  6975. req.path = "/chunked";
  6976. std::string host_and_port;
  6977. host_and_port += HOST;
  6978. host_and_port += ":";
  6979. host_and_port += std::to_string(PORT);
  6980. req.headers.emplace("Host", host_and_port.c_str());
  6981. req.headers.emplace("Content-Length", "0");
  6982. req.headers.emplace("Transfer-Encoding", "chunked");
  6983. req.body = body;
  6984. auto res = std::make_shared<Response>();
  6985. auto error = Error::Success;
  6986. ASSERT_TRUE(cli.send(req, *res, error));
  6987. EXPECT_EQ(expected_status, res->status);
  6988. }
  6989. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6990. // rather than treat them as valid lengths.
  6991. template <typename ClientT>
  6992. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6993. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6994. }
  6995. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6996. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6997. }
  6998. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6999. expect_chunked_body_rejected(
  7000. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7001. }
  7002. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7003. // chunk-size line carries no CR, LF or other control character ahead of its
  7004. // terminator. Such a line must be refused rather than read as extension text.
  7005. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7006. expect_chunked_body_rejected(
  7007. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7008. }
  7009. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7010. expect_chunked_body_rejected(
  7011. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7012. }
  7013. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7014. expect_chunked_body_rejected(
  7015. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7016. }
  7017. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7018. // The literal stays split: a hex escape consumes every hex digit that
  7019. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7020. expect_chunked_body_rejected(
  7021. cli_, "4;a\x01"
  7022. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7023. }
  7024. // The bytes around chunk data are no payload, so they cannot ride on the
  7025. // payload limit
  7026. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7027. // Small enough that the whole request is sent before the server turns it
  7028. // down, yet past the limit by the last chunks
  7029. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7030. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7031. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7032. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7033. SCOPED_TRACE(size_line.substr(0, 2));
  7034. std::string body;
  7035. for (auto c : std::string("dechunked post body")) {
  7036. body += size_line + "\r\n" + c + "\r\n";
  7037. }
  7038. body += "0\r\n\r\n";
  7039. expect_chunked_body_rejected(cli_, body.c_str());
  7040. }
  7041. }
  7042. TEST_F(ServerTest, AcceptsChunkExtension) {
  7043. expect_chunked_body_status(cli_,
  7044. "4;name=value\r\ndech\r\n"
  7045. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7046. "0;last\r\n\r\n",
  7047. StatusCode::OK_200);
  7048. }
  7049. TEST_F(ServerTest, GetStreamed2) {
  7050. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7053. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7054. EXPECT_EQ(true, res->has_header("Content-Range"));
  7055. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7056. EXPECT_EQ(std::string("ab"), res->body);
  7057. }
  7058. TEST_F(ServerTest, GetStreamed) {
  7059. auto res = cli_.Get("/streamed");
  7060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7061. EXPECT_EQ(StatusCode::OK_200, res->status);
  7062. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7063. EXPECT_EQ(std::string("aaabbb"), res->body);
  7064. }
  7065. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7066. auto res = cli_.Get("/streamed-without-length",
  7067. Headers{make_range_header({{0, -1}})});
  7068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7069. EXPECT_EQ(StatusCode::OK_200, res->status);
  7070. EXPECT_EQ(false, res->has_header("Content-Length"));
  7071. EXPECT_EQ(false, res->has_header("Content-Range"));
  7072. EXPECT_EQ(std::string("abcdefg"), res->body);
  7073. }
  7074. TEST_F(ServerTest, GetStreamedWithRange1) {
  7075. auto res =
  7076. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7078. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7079. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7080. EXPECT_EQ(true, res->has_header("Content-Range"));
  7081. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7082. EXPECT_EQ(std::string("def"), res->body);
  7083. }
  7084. TEST_F(ServerTest, GetStreamedWithRange2) {
  7085. auto res =
  7086. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7089. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7090. EXPECT_EQ(true, res->has_header("Content-Range"));
  7091. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7092. EXPECT_EQ(std::string("bcdefg"), res->body);
  7093. }
  7094. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7095. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7098. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7099. EXPECT_EQ(true, res->has_header("Content-Range"));
  7100. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7101. EXPECT_EQ(std::string("efg"), res->body);
  7102. }
  7103. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7104. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7105. // the entire representation.
  7106. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7107. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7109. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7110. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7111. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7112. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7113. }
  7114. }
  7115. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7116. auto res =
  7117. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7119. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7120. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7121. EXPECT_EQ(false, res->has_header("Content-Range"));
  7122. EXPECT_EQ(0U, res->body.size());
  7123. }
  7124. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7125. // Only a 206 is served as a partial representation. Under any other status
  7126. // `apply_ranges()` reported the full content length, so the body must match
  7127. // that header, and the content provider must never be asked for an offset
  7128. // outside the representation.
  7129. auto check = [&](int status, const char *range) {
  7130. auto path =
  7131. std::string("/streamed-with-range?status=") + std::to_string(status);
  7132. auto ctx = path + " Range: " + range;
  7133. auto res = cli_.Get(path, Headers{{"Range", range}});
  7134. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7135. EXPECT_EQ(status, res->status) << ctx;
  7136. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7137. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7138. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7139. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7140. };
  7141. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7142. check(403, "bytes=3-5");
  7143. // The offset is far past the representation.
  7144. check(403, "bytes=100000-100200");
  7145. // `first_pos` is still -1 here, and the bounds asserts in
  7146. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7147. check(403, "bytes=-3");
  7148. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7149. // multipart branch would have written one that is empty.
  7150. check(403, "bytes=1-2, 4-5");
  7151. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7152. // covers the whole representation.
  7153. check(200, "bytes=3-5");
  7154. check(200, "bytes=1-2, 4-5");
  7155. }
  7156. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7157. auto res =
  7158. cli_.Get("/streamed-with-range",
  7159. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7160. "92233720368547758079223372036854775807"}});
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7163. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7164. EXPECT_EQ(false, res->has_header("Content-Range"));
  7165. EXPECT_EQ(0U, res->body.size());
  7166. }
  7167. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7168. auto res = cli_.Get(
  7169. "/with-range",
  7170. Headers{{"Range",
  7171. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7172. {"Accept-Encoding", ""}});
  7173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7175. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7176. EXPECT_EQ(true, res->has_header("Content-Range"));
  7177. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7178. EXPECT_EQ(std::string("abcdefg"), res->body);
  7179. }
  7180. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7181. auto res = cli_.Get("/with-range", Headers{
  7182. {"Range", "bytes=0-"},
  7183. {"Accept-Encoding", ""},
  7184. });
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(true, res->has_header("Content-Range"));
  7189. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7190. EXPECT_EQ(std::string("abcdefg"), res->body);
  7191. }
  7192. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7193. auto res = cli_.Get("/streamed-with-range",
  7194. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7197. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7198. EXPECT_EQ(false, res->has_header("Content-Range"));
  7199. EXPECT_EQ(267U, res->body.size());
  7200. // Check that both range contents are present
  7201. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7202. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7203. // Check that Content-Range headers are present for both ranges
  7204. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7205. std::string::npos);
  7206. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7207. std::string::npos);
  7208. }
  7209. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7210. Ranges ranges;
  7211. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7212. ranges.emplace_back(0, -1);
  7213. }
  7214. auto res = cli_.Get("/streamed-with-range?error",
  7215. Headers{{make_range_header(ranges)}});
  7216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7217. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7218. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7219. EXPECT_EQ(false, res->has_header("Content-Range"));
  7220. EXPECT_EQ(0U, res->body.size());
  7221. }
  7222. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7223. auto res = cli_.Get("/streamed-with-range",
  7224. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7227. EXPECT_EQ(5U, res->body.size());
  7228. // Check that overlapping ranges are coalesced into a single range
  7229. EXPECT_EQ("bcdef", res->body);
  7230. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7231. // Should be single range, not multipart
  7232. EXPECT_TRUE(res->has_header("Content-Range"));
  7233. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7234. }
  7235. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7236. auto res = cli_.Get("/streamed-with-range",
  7237. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7239. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7240. EXPECT_EQ(268U, res->body.size());
  7241. // Check that both range contents are present
  7242. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7243. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7244. // Check that Content-Range headers are present for both ranges
  7245. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7246. std::string::npos);
  7247. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7248. std::string::npos);
  7249. }
  7250. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7251. auto res = cli_.Get("/streamed-with-range",
  7252. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7255. EXPECT_EQ(269U, res->body.size());
  7256. // Check that both duplicate range contents are present
  7257. size_t first_abc = res->body.find("abc\r\n");
  7258. EXPECT_TRUE(first_abc != std::string::npos);
  7259. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7260. EXPECT_TRUE(second_abc != std::string::npos);
  7261. // Check that Content-Range headers are present for both ranges
  7262. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7263. EXPECT_TRUE(first_range != std::string::npos);
  7264. size_t second_range =
  7265. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7266. EXPECT_TRUE(second_range != std::string::npos);
  7267. }
  7268. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7269. auto res =
  7270. cli_.Get("/streamed-with-range?error",
  7271. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7273. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7274. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7275. EXPECT_EQ(false, res->has_header("Content-Range"));
  7276. EXPECT_EQ(0U, res->body.size());
  7277. }
  7278. TEST_F(ServerTest, GetStreamedEndless) {
  7279. uint64_t offset = 0;
  7280. auto res = cli_.Get("/streamed-cancel",
  7281. [&](const char * /*data*/, uint64_t data_length) {
  7282. if (offset < 100) {
  7283. offset += data_length;
  7284. return true;
  7285. }
  7286. return false;
  7287. });
  7288. ASSERT_TRUE(!res);
  7289. EXPECT_EQ(Error::Canceled, res.error());
  7290. }
  7291. TEST_F(ServerTest, ClientStop) {
  7292. std::atomic_size_t count{4};
  7293. std::vector<std::thread> threads;
  7294. for (auto i = count.load(); i != 0; --i) {
  7295. threads.emplace_back([&]() {
  7296. auto res = cli_.Get("/streamed-cancel",
  7297. [&](const char *, uint64_t) { return true; });
  7298. --count;
  7299. ASSERT_TRUE(!res);
  7300. EXPECT_TRUE(res.error() == Error::Canceled ||
  7301. res.error() == Error::Read || res.error() == Error::Write);
  7302. });
  7303. }
  7304. std::this_thread::sleep_for(std::chrono::seconds(2));
  7305. while (count != 0) {
  7306. cli_.stop();
  7307. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7308. }
  7309. for (auto &t : threads) {
  7310. t.join();
  7311. }
  7312. }
  7313. TEST_F(ServerTest, GetWithRange1) {
  7314. auto res = cli_.Get("/with-range", Headers{
  7315. make_range_header({{3, 5}}),
  7316. {"Accept-Encoding", ""},
  7317. });
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7320. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7321. EXPECT_EQ(true, res->has_header("Content-Range"));
  7322. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7323. EXPECT_EQ(std::string("def"), res->body);
  7324. }
  7325. TEST_F(ServerTest, GetWithRange2) {
  7326. auto res = cli_.Get("/with-range", Headers{
  7327. make_range_header({{1, -1}}),
  7328. {"Accept-Encoding", ""},
  7329. });
  7330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7331. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7332. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7333. EXPECT_EQ(true, res->has_header("Content-Range"));
  7334. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7335. EXPECT_EQ(std::string("bcdefg"), res->body);
  7336. }
  7337. TEST_F(ServerTest, GetWithRange3) {
  7338. auto res = cli_.Get("/with-range", Headers{
  7339. make_range_header({{0, 0}}),
  7340. {"Accept-Encoding", ""},
  7341. });
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7344. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7345. EXPECT_EQ(true, res->has_header("Content-Range"));
  7346. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7347. EXPECT_EQ(std::string("a"), res->body);
  7348. }
  7349. TEST_F(ServerTest, GetWithRange4) {
  7350. auto res = cli_.Get("/with-range", Headers{
  7351. make_range_header({{-1, 2}}),
  7352. {"Accept-Encoding", ""},
  7353. });
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7356. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7357. EXPECT_EQ(true, res->has_header("Content-Range"));
  7358. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7359. EXPECT_EQ(std::string("fg"), res->body);
  7360. }
  7361. TEST_F(ServerTest, GetWithRange5) {
  7362. auto res = cli_.Get("/with-range", Headers{
  7363. make_range_header({{0, 5}}),
  7364. {"Accept-Encoding", ""},
  7365. });
  7366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7367. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7368. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7369. EXPECT_EQ(true, res->has_header("Content-Range"));
  7370. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7371. EXPECT_EQ(std::string("abcdef"), res->body);
  7372. }
  7373. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7374. auto res =
  7375. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7377. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7378. }
  7379. TEST_F(ServerTest, GetWithRangeMultipart) {
  7380. auto res =
  7381. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7383. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7384. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7385. EXPECT_EQ(false, res->has_header("Content-Range"));
  7386. EXPECT_EQ(267U, res->body.size());
  7387. }
  7388. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7389. auto res = cli_.Get("/with-range",
  7390. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7392. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7393. }
  7394. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7395. auto res = cli_.Get("/with-range-customized-response",
  7396. Headers{{make_range_header({{1, 2}})}});
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7399. EXPECT_EQ(true, res->has_header("Content-Length"));
  7400. EXPECT_EQ(false, res->has_header("Content-Range"));
  7401. EXPECT_EQ(JSON_DATA, res->body);
  7402. }
  7403. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7404. auto res = cli_.Get("/with-range-customized-response",
  7405. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7407. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7408. EXPECT_EQ(true, res->has_header("Content-Length"));
  7409. EXPECT_EQ(false, res->has_header("Content-Range"));
  7410. EXPECT_EQ(JSON_DATA, res->body);
  7411. }
  7412. TEST_F(ServerTest, Issue1772) {
  7413. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7415. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7416. }
  7417. TEST_F(ServerTest, Issue609) {
  7418. auto res = cli_.Delete("/issue609");
  7419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7420. EXPECT_EQ(StatusCode::OK_200, res->status);
  7421. EXPECT_EQ(std::string("ok"), res->body);
  7422. }
  7423. TEST_F(ServerTest, GetStreamedChunked) {
  7424. auto res = cli_.Get("/streamed-chunked");
  7425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7426. EXPECT_EQ(StatusCode::OK_200, res->status);
  7427. EXPECT_EQ(std::string("123456789"), res->body);
  7428. }
  7429. TEST_F(ServerTest, GetStreamedChunked2) {
  7430. auto res = cli_.Get("/streamed-chunked2");
  7431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7432. EXPECT_EQ(StatusCode::OK_200, res->status);
  7433. EXPECT_EQ(std::string("123456789"), res->body);
  7434. }
  7435. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7436. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. EXPECT_EQ(std::string("123456789"), res->body);
  7440. EXPECT_TRUE(res->has_header("Trailer"));
  7441. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7442. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7443. // Trailers are now stored separately from headers (security fix)
  7444. EXPECT_EQ(2U, res->trailers.size());
  7445. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7446. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7447. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7448. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7449. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7450. // Verify trailers are NOT in headers (security verification)
  7451. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7452. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7453. }
  7454. TEST_F(ServerTest, LargeChunkedPost) {
  7455. Request req;
  7456. req.method = "POST";
  7457. req.path = "/large-chunked";
  7458. std::string host_and_port;
  7459. host_and_port += HOST;
  7460. host_and_port += ":";
  7461. host_and_port += std::to_string(PORT);
  7462. req.headers.emplace("Host", host_and_port.c_str());
  7463. req.headers.emplace("Accept", "*/*");
  7464. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7465. req.headers.emplace("Content-Type", "text/plain");
  7466. req.headers.emplace("Content-Length", "0");
  7467. req.headers.emplace("Transfer-Encoding", "chunked");
  7468. std::string long_string(30 * 1024u, 'a');
  7469. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7470. // Attempt to make a large enough post to exceed OS buffers, to test that
  7471. // the server handles short reads if the full chunk data isn't available.
  7472. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7473. auto res = std::make_shared<Response>();
  7474. auto error = Error::Success;
  7475. auto ret = cli_.send(req, *res, error);
  7476. ASSERT_TRUE(ret);
  7477. EXPECT_EQ(StatusCode::OK_200, res->status);
  7478. }
  7479. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7480. auto res = cli_.Get("/remote_addr");
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7484. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7485. }
  7486. TEST_F(ServerTest, GetMethodLocalAddr) {
  7487. auto res = cli_.Get("/local_addr");
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. EXPECT_EQ(StatusCode::OK_200, res->status);
  7490. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7491. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7492. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7493. }
  7494. TEST_F(ServerTest, HTTPResponseSplitting) {
  7495. auto res = cli_.Get("/http_response_splitting");
  7496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7497. EXPECT_EQ(StatusCode::OK_200, res->status);
  7498. }
  7499. TEST_F(ServerTest, SlowRequest) {
  7500. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7501. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7502. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7503. }
  7504. #if 0
  7505. TEST_F(ServerTest, SlowPost) {
  7506. char buffer[64 * 1024];
  7507. memset(buffer, 0x42, sizeof(buffer));
  7508. auto res = cli_.Post(
  7509. "/slowpost", 64 * 1024 * 1024,
  7510. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7511. auto ret = sink.write(buffer, sizeof(buffer));
  7512. EXPECT_TRUE(ret);
  7513. return true;
  7514. },
  7515. "text/plain");
  7516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7517. EXPECT_EQ(StatusCode::OK_200, res->status);
  7518. }
  7519. TEST_F(ServerTest, SlowPostFail) {
  7520. char buffer[64 * 1024];
  7521. memset(buffer, 0x42, sizeof(buffer));
  7522. cli_.set_write_timeout(std::chrono::seconds(0));
  7523. auto res = cli_.Post(
  7524. "/slowpost", 64 * 1024 * 1024,
  7525. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7526. sink.write(buffer, sizeof(buffer));
  7527. return true;
  7528. },
  7529. "text/plain");
  7530. ASSERT_TRUE(!res);
  7531. EXPECT_EQ(Error::Write, res.error());
  7532. }
  7533. #endif
  7534. TEST_F(ServerTest, Put) {
  7535. auto res = cli_.Put("/put", "PUT", "text/plain");
  7536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7537. EXPECT_EQ(StatusCode::OK_200, res->status);
  7538. EXPECT_EQ("PUT", res->body);
  7539. }
  7540. TEST_F(ServerTest, PutWithContentProvider) {
  7541. auto res = cli_.Put(
  7542. "/put", 3,
  7543. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7544. sink.os << "PUT";
  7545. return true;
  7546. },
  7547. "text/plain");
  7548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7549. EXPECT_EQ(StatusCode::OK_200, res->status);
  7550. EXPECT_EQ("PUT", res->body);
  7551. }
  7552. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7553. auto res = cli_.Post(
  7554. "/post", 42,
  7555. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7556. return false;
  7557. },
  7558. "text/plain");
  7559. ASSERT_TRUE(!res);
  7560. EXPECT_EQ(Error::Canceled, res.error());
  7561. }
  7562. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7563. auto res = cli_.Put(
  7564. "/put",
  7565. [](size_t /*offset*/, DataSink &sink) {
  7566. sink.os << "PUT";
  7567. sink.done();
  7568. return true;
  7569. },
  7570. "text/plain");
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ("PUT", res->body);
  7574. }
  7575. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7576. auto res = cli_.Post(
  7577. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7578. "text/plain");
  7579. ASSERT_TRUE(!res);
  7580. EXPECT_EQ(Error::Canceled, res.error());
  7581. }
  7582. TEST_F(ServerTest, PostLoopBack) {
  7583. std::string body;
  7584. auto res = cli_.Post(
  7585. "/post-loopback", 9,
  7586. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7587. EXPECT_EQ(9u, length);
  7588. sink.write("123", 3);
  7589. sink.write("456", 3);
  7590. sink.write("789", 3);
  7591. return true;
  7592. },
  7593. "text/plain",
  7594. [&body](const char *data, size_t data_length) {
  7595. body.append(data, data_length);
  7596. return true;
  7597. });
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ(StatusCode::OK_200, res->status);
  7600. EXPECT_EQ("123456789", body);
  7601. }
  7602. TEST_F(ServerTest, PutLoopBack) {
  7603. std::string body;
  7604. auto res = cli_.Put(
  7605. "/put-loopback", 9,
  7606. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7607. EXPECT_EQ(9u, length);
  7608. sink.write("123", 3);
  7609. sink.write("456", 3);
  7610. sink.write("789", 3);
  7611. return true;
  7612. },
  7613. "text/plain",
  7614. [&body](const char *data, size_t data_length) {
  7615. body.append(data, data_length);
  7616. return true;
  7617. });
  7618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7619. EXPECT_EQ(StatusCode::OK_200, res->status);
  7620. EXPECT_EQ("123456789", body);
  7621. }
  7622. TEST_F(ServerTest, PatchLoopBack) {
  7623. std::string body;
  7624. auto res = cli_.Patch(
  7625. "/patch-loopback", 9,
  7626. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7627. EXPECT_EQ(9u, length);
  7628. sink.write("123", 3);
  7629. sink.write("456", 3);
  7630. sink.write("789", 3);
  7631. return true;
  7632. },
  7633. "text/plain",
  7634. [&body](const char *data, size_t data_length) {
  7635. body.append(data, data_length);
  7636. return true;
  7637. });
  7638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7639. EXPECT_EQ(StatusCode::OK_200, res->status);
  7640. EXPECT_EQ("123456789", body);
  7641. }
  7642. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7643. std::string body;
  7644. auto res = cli_.Post(
  7645. "/post-loopback",
  7646. [](size_t /*offset*/, DataSink &sink) {
  7647. sink.write("123", 3);
  7648. sink.write("456", 3);
  7649. sink.write("789", 3);
  7650. sink.done();
  7651. return true;
  7652. },
  7653. "text/plain",
  7654. [&body](const char *data, size_t data_length) {
  7655. body.append(data, data_length);
  7656. return true;
  7657. });
  7658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7659. EXPECT_EQ(StatusCode::OK_200, res->status);
  7660. EXPECT_EQ("123456789", body);
  7661. }
  7662. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7663. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7664. cli_.set_compress(true);
  7665. auto res = cli_.Put(
  7666. "/put", 3,
  7667. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7668. sink.os << "PUT";
  7669. return true;
  7670. },
  7671. "text/plain");
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::OK_200, res->status);
  7674. EXPECT_EQ("PUT", res->body);
  7675. }
  7676. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7677. cli_.set_compress(true);
  7678. auto res = cli_.Post(
  7679. "/post", 42,
  7680. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7681. return false;
  7682. },
  7683. "text/plain");
  7684. ASSERT_TRUE(!res);
  7685. EXPECT_EQ(Error::Canceled, res.error());
  7686. }
  7687. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7688. cli_.set_compress(true);
  7689. auto res = cli_.Put(
  7690. "/put",
  7691. [](size_t /*offset*/, DataSink &sink) {
  7692. sink.os << "PUT";
  7693. sink.done();
  7694. return true;
  7695. },
  7696. "text/plain");
  7697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7698. EXPECT_EQ(StatusCode::OK_200, res->status);
  7699. EXPECT_EQ("PUT", res->body);
  7700. }
  7701. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7702. cli_.set_compress(true);
  7703. auto res = cli_.Post(
  7704. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7705. "text/plain");
  7706. ASSERT_TRUE(!res);
  7707. EXPECT_EQ(Error::Canceled, res.error());
  7708. }
  7709. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7710. cli_.set_compress(true);
  7711. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ(LARGE_DATA, res->body);
  7715. }
  7716. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7717. #ifdef CPPHTTPLIB_SSL_ENABLED
  7718. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7719. Client cli(s.c_str());
  7720. cli.enable_server_certificate_verification(false);
  7721. #else
  7722. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7723. Client cli(s.c_str());
  7724. #endif
  7725. cli.set_compress(true);
  7726. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7728. EXPECT_EQ(StatusCode::OK_200, res->status);
  7729. EXPECT_EQ(LARGE_DATA, res->body);
  7730. // The compressed size should be less than a 10th of the original. May vary
  7731. // depending on the zlib library.
  7732. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7733. static_cast<uint64_t>(10 * 1024 * 1024));
  7734. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7735. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7736. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7737. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7738. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7739. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7740. #endif
  7741. }
  7742. TEST_F(ServerTest, PutContentWithDeflate) {
  7743. cli_.set_compress(false);
  7744. Headers headers;
  7745. headers.emplace("Content-Encoding", "deflate");
  7746. // PUT in deflate format:
  7747. auto res = cli_.Put("/put", headers,
  7748. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(StatusCode::OK_200, res->status);
  7751. EXPECT_EQ("PUT", res->body);
  7752. }
  7753. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7754. Headers headers;
  7755. headers.emplace("Accept-Encoding", "gzip, deflate");
  7756. auto res = cli_.Get("/streamed-chunked", headers);
  7757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7758. EXPECT_EQ(StatusCode::OK_200, res->status);
  7759. EXPECT_EQ(std::string("123456789"), res->body);
  7760. }
  7761. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7762. Headers headers;
  7763. headers.emplace("Accept-Encoding", "gzip, deflate");
  7764. auto res = cli_.Get("/streamed-chunked2", headers);
  7765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7766. EXPECT_EQ(StatusCode::OK_200, res->status);
  7767. EXPECT_EQ(std::string("123456789"), res->body);
  7768. }
  7769. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7770. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. }
  7774. TEST(GzipDecompressor, ChunkedDecompression) {
  7775. std::string data;
  7776. for (size_t i = 0; i < 32 * 1024; ++i) {
  7777. data.push_back(static_cast<char>('a' + i % 26));
  7778. }
  7779. std::string compressed_data;
  7780. {
  7781. httplib::detail::gzip_compressor compressor;
  7782. bool result = compressor.compress(
  7783. data.data(), data.size(),
  7784. /*last=*/true,
  7785. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7786. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7787. compressed_data_size);
  7788. return true;
  7789. });
  7790. ASSERT_TRUE(result);
  7791. }
  7792. std::string decompressed_data;
  7793. {
  7794. httplib::detail::gzip_decompressor decompressor;
  7795. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7796. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7797. size_t chunk_size = 130;
  7798. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7799. chunk_begin += chunk_size) {
  7800. size_t current_chunk_size =
  7801. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7802. bool result = decompressor.decompress(
  7803. compressed_data.data() + chunk_begin, current_chunk_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. }
  7814. ASSERT_EQ(data, decompressed_data);
  7815. }
  7816. TEST(GzipDecompressor, DeflateDecompression) {
  7817. std::string original_text = "Raw deflate without gzip";
  7818. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7819. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7820. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7821. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  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. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7840. std::string original_text = "Raw deflate without gzip";
  7841. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7842. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7843. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7844. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7845. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7846. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7847. std::string decompressed_data;
  7848. {
  7849. httplib::detail::gzip_decompressor decompressor;
  7850. bool result = decompressor.decompress(
  7851. compressed_data.data(), compressed_data.size(),
  7852. [&](const char *decompressed_data_chunk,
  7853. size_t decompressed_data_chunk_size) {
  7854. decompressed_data.insert(decompressed_data.size(),
  7855. decompressed_data_chunk,
  7856. decompressed_data_chunk_size);
  7857. return true;
  7858. });
  7859. ASSERT_TRUE(result);
  7860. }
  7861. ASSERT_EQ(original_text, decompressed_data);
  7862. }
  7863. #endif
  7864. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7865. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7866. Headers headers;
  7867. headers.emplace("Accept-Encoding", "br");
  7868. auto res = cli_.Get("/streamed-chunked", headers);
  7869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7870. EXPECT_EQ(StatusCode::OK_200, res->status);
  7871. EXPECT_EQ(std::string("123456789"), res->body);
  7872. }
  7873. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7874. Headers headers;
  7875. headers.emplace("Accept-Encoding", "br");
  7876. auto res = cli_.Get("/streamed-chunked2", headers);
  7877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7878. EXPECT_EQ(StatusCode::OK_200, res->status);
  7879. EXPECT_EQ(std::string("123456789"), res->body);
  7880. }
  7881. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7882. cli_.set_compress(true);
  7883. auto res = cli_.Put(
  7884. "/put", 3,
  7885. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7886. sink.os << "PUT";
  7887. return true;
  7888. },
  7889. "text/plain");
  7890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7891. EXPECT_EQ(StatusCode::OK_200, res->status);
  7892. EXPECT_EQ("PUT", res->body);
  7893. }
  7894. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7895. cli_.set_compress(true);
  7896. auto res = cli_.Put(
  7897. "/put",
  7898. [](size_t /*offset*/, DataSink &sink) {
  7899. sink.os << "PUT";
  7900. sink.done();
  7901. return true;
  7902. },
  7903. "text/plain");
  7904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7905. EXPECT_EQ(StatusCode::OK_200, res->status);
  7906. EXPECT_EQ("PUT", res->body);
  7907. }
  7908. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7909. cli_.set_compress(true);
  7910. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7912. EXPECT_EQ(StatusCode::OK_200, res->status);
  7913. EXPECT_EQ(LARGE_DATA, res->body);
  7914. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7915. }
  7916. #endif
  7917. TEST_F(ServerTest, Patch) {
  7918. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_EQ(StatusCode::OK_200, res->status);
  7921. EXPECT_EQ("PATCH", res->body);
  7922. }
  7923. TEST_F(ServerTest, Delete) {
  7924. auto res = cli_.Delete("/delete");
  7925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7926. EXPECT_EQ(StatusCode::OK_200, res->status);
  7927. EXPECT_EQ("DELETE", res->body);
  7928. }
  7929. TEST_F(ServerTest, DeleteContentReceiver) {
  7930. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7932. EXPECT_EQ(StatusCode::OK_200, res->status);
  7933. EXPECT_EQ("content", res->body);
  7934. }
  7935. TEST_F(ServerTest, Options) {
  7936. auto res = cli_.Options("*");
  7937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7938. EXPECT_EQ(StatusCode::OK_200, res->status);
  7939. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7940. EXPECT_TRUE(res->body.empty());
  7941. }
  7942. TEST_F(ServerTest, URL) {
  7943. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7945. EXPECT_EQ(StatusCode::OK_200, res->status);
  7946. }
  7947. TEST_F(ServerTest, ArrayParam) {
  7948. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7950. EXPECT_EQ(StatusCode::OK_200, res->status);
  7951. }
  7952. TEST_F(ServerTest, ArrayParamValues) {
  7953. auto res =
  7954. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7956. EXPECT_EQ(StatusCode::OK_200, res->status);
  7957. }
  7958. TEST_F(ServerTest, NoMultipleHeaders) {
  7959. Headers headers = {{"Content-Length", "5"}};
  7960. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7961. "text/plain");
  7962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7963. EXPECT_EQ(StatusCode::OK_200, res->status);
  7964. }
  7965. TEST_F(ServerTest, PostContentReceiver) {
  7966. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7968. ASSERT_EQ(StatusCode::OK_200, res->status);
  7969. ASSERT_EQ("content", res->body);
  7970. }
  7971. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7972. UploadFormDataItems items = {
  7973. {"text1", "text default", "", ""},
  7974. {"text2", "aωb", "", ""},
  7975. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7976. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7977. {"file3", "", "", "application/octet-stream"},
  7978. };
  7979. auto res = cli_.Post("/content_receiver", items);
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::OK_200, res->status);
  7982. }
  7983. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7984. UploadFormDataItems items = {
  7985. {"text1", "text default", "", ""},
  7986. {"text2", "aωb", "", ""},
  7987. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7988. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7989. {"file3", "", "", "application/octet-stream"},
  7990. };
  7991. auto boundary = std::string("+++++");
  7992. std::string body;
  7993. for (const auto &item : items) {
  7994. body += "--" + boundary + "\r\n";
  7995. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7996. if (!item.filename.empty()) {
  7997. body += "; filename=\"" + item.filename + "\"";
  7998. }
  7999. body += "\r\n";
  8000. if (!item.content_type.empty()) {
  8001. body += "Content-Type: " + item.content_type + "\r\n";
  8002. }
  8003. body += "\r\n";
  8004. body += item.content + "\r\n";
  8005. }
  8006. body += "--" + boundary + "--\r\n";
  8007. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8008. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8010. EXPECT_EQ(StatusCode::OK_200, res->status);
  8011. }
  8012. TEST(MultipartFormDataTest, FieldEscaping) {
  8013. Server svr;
  8014. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8015. const ContentReader &content_reader) {
  8016. ASSERT_TRUE(req.is_multipart_form_data());
  8017. std::vector<FormData> received;
  8018. content_reader(
  8019. [&](const FormData &file) {
  8020. received.push_back(file);
  8021. return true;
  8022. },
  8023. [&](const char *data, size_t data_length) {
  8024. received.back().content.append(data, data_length);
  8025. return true;
  8026. });
  8027. // '"', CR and LF in names and filenames are escaped following the
  8028. // WHATWG HTML standard, so each part still parses as a single part
  8029. // with no injected headers. Content types get CR/LF escaped too,
  8030. // while '"' (legal there, e.g. quoted charset) is preserved.
  8031. ASSERT_EQ(4U, received.size());
  8032. EXPECT_EQ("na%22me", received[0].name);
  8033. EXPECT_EQ("quoted name", received[0].content);
  8034. EXPECT_EQ("file", received[1].name);
  8035. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8036. received[1].filename);
  8037. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8038. EXPECT_EQ("injected", received[1].content);
  8039. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8040. EXPECT_EQ("my%22file.txt", received[2].filename);
  8041. EXPECT_EQ("cr lf name", received[2].content);
  8042. EXPECT_EQ("typed", received[3].name);
  8043. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8044. received[3].content_type);
  8045. EXPECT_EQ("typed content", received[3].content);
  8046. });
  8047. auto port = svr.bind_to_any_port("localhost");
  8048. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8049. auto se = detail::scope_exit([&] {
  8050. svr.stop();
  8051. t.join();
  8052. ASSERT_FALSE(svr.is_running());
  8053. });
  8054. svr.wait_until_ready();
  8055. Client cli("localhost", port);
  8056. UploadFormDataItems items = {
  8057. {"na\"me", "quoted name", "", ""},
  8058. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8059. "application/octet-stream"},
  8060. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8061. {"typed", "typed content", "",
  8062. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8063. };
  8064. auto res = cli.Post("/post", items);
  8065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8066. EXPECT_EQ(StatusCode::OK_200, res->status);
  8067. }
  8068. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8069. const UploadFormDataItems items = {
  8070. {"name1", "Content 1", "", ""},
  8071. {"name2", "Content 2", "file2.txt", "text/plain"},
  8072. };
  8073. Server svr;
  8074. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8075. const ContentReader &content_reader) {
  8076. ASSERT_TRUE(req.is_multipart_form_data());
  8077. std::vector<FormData> received;
  8078. content_reader(
  8079. [&](const FormData &file) {
  8080. received.push_back(file);
  8081. return true;
  8082. },
  8083. [&](const char *data, size_t data_length) {
  8084. received.back().content.append(data, data_length);
  8085. return true;
  8086. });
  8087. ASSERT_EQ(2U, received.size());
  8088. EXPECT_EQ("name1", received[0].name);
  8089. EXPECT_EQ("Content 1", received[0].content);
  8090. EXPECT_EQ("name2", received[1].name);
  8091. EXPECT_EQ("Content 2", received[1].content);
  8092. EXPECT_EQ("file2.txt", received[1].filename);
  8093. EXPECT_EQ("text/plain", received[1].content_type);
  8094. });
  8095. auto port = svr.bind_to_any_port("localhost");
  8096. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8097. auto se = detail::scope_exit([&] {
  8098. svr.stop();
  8099. t.join();
  8100. ASSERT_FALSE(svr.is_running());
  8101. });
  8102. svr.wait_until_ready();
  8103. Client cli("localhost", port);
  8104. // Whole-body serialization with a generated boundary
  8105. {
  8106. MultipartFormDataWriter writer;
  8107. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8108. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8109. writer.content_type());
  8110. auto body = writer.serialize(items);
  8111. EXPECT_EQ(body.size(), writer.content_length(items));
  8112. auto res = cli.Post("/post", body, writer.content_type());
  8113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. }
  8116. // Per-part framing with a custom boundary via a content provider
  8117. {
  8118. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8119. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8120. MultipartFormDataWriter writer("custom-boundary_123");
  8121. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8122. std::string body;
  8123. for (const auto &item : items) {
  8124. body += writer.item_begin(item);
  8125. body += item.content;
  8126. body += MultipartFormDataWriter::item_end();
  8127. }
  8128. body += writer.finish();
  8129. EXPECT_EQ(body.size(), writer.content_length(items));
  8130. auto res = cli.Post(
  8131. "/post", body.size(),
  8132. [&](size_t offset, size_t length, DataSink &sink) {
  8133. sink.write(body.data() + offset, length);
  8134. return true;
  8135. },
  8136. writer.content_type());
  8137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8138. EXPECT_EQ(StatusCode::OK_200, res->status);
  8139. }
  8140. }
  8141. TEST_F(ServerTest, PostContentReceiverGzip) {
  8142. cli_.set_compress(true);
  8143. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8145. ASSERT_EQ(StatusCode::OK_200, res->status);
  8146. ASSERT_EQ("content", res->body);
  8147. }
  8148. TEST_F(ServerTest, PutContentReceiver) {
  8149. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. ASSERT_EQ(StatusCode::OK_200, res->status);
  8152. ASSERT_EQ("content", res->body);
  8153. }
  8154. TEST_F(ServerTest, PatchContentReceiver) {
  8155. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8157. ASSERT_EQ(StatusCode::OK_200, res->status);
  8158. ASSERT_EQ("content", res->body);
  8159. }
  8160. template <typename ClientType>
  8161. void TestWithHeadersAndContentReceiver(
  8162. ClientType &cli,
  8163. std::function<Result(ClientType &, const std::string &, const Headers &,
  8164. const std::string &, const std::string &,
  8165. ContentReceiver, DownloadProgress)>
  8166. request_func) {
  8167. Headers headers;
  8168. headers.emplace("X-Custom-Header", "test-value");
  8169. std::string received_body;
  8170. auto res = request_func(
  8171. cli, "/content_receiver", headers, "content", "application/json",
  8172. [&](const char *data, size_t data_length) {
  8173. received_body.append(data, data_length);
  8174. return true;
  8175. },
  8176. nullptr);
  8177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. EXPECT_EQ("content", received_body);
  8180. }
  8181. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8182. #ifdef CPPHTTPLIB_SSL_ENABLED
  8183. using ClientT = SSLClient;
  8184. #else
  8185. using ClientT = Client;
  8186. #endif
  8187. TestWithHeadersAndContentReceiver<ClientT>(
  8188. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8189. const std::string &body, const std::string &content_type,
  8190. ContentReceiver receiver, DownloadProgress progress) {
  8191. return cli.Post(path, headers, body, content_type, receiver, progress);
  8192. });
  8193. }
  8194. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8195. #ifdef CPPHTTPLIB_SSL_ENABLED
  8196. using ClientT = SSLClient;
  8197. #else
  8198. using ClientT = Client;
  8199. #endif
  8200. TestWithHeadersAndContentReceiver<ClientT>(
  8201. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8202. const std::string &body, const std::string &content_type,
  8203. ContentReceiver receiver, DownloadProgress progress) {
  8204. return cli.Put(path, headers, body, content_type, receiver, progress);
  8205. });
  8206. }
  8207. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8208. #ifdef CPPHTTPLIB_SSL_ENABLED
  8209. using ClientT = SSLClient;
  8210. #else
  8211. using ClientT = Client;
  8212. #endif
  8213. TestWithHeadersAndContentReceiver<ClientT>(
  8214. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8215. const std::string &body, const std::string &content_type,
  8216. ContentReceiver receiver, DownloadProgress progress) {
  8217. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8218. });
  8219. }
  8220. template <typename ClientType>
  8221. void TestWithHeadersAndContentReceiverWithProgress(
  8222. ClientType &cli,
  8223. std::function<Result(ClientType &, const std::string &, const Headers &,
  8224. const std::string &, const std::string &,
  8225. ContentReceiver, DownloadProgress)>
  8226. request_func) {
  8227. Headers headers;
  8228. headers.emplace("X-Test-Header", "progress-test");
  8229. std::string received_body;
  8230. auto progress_called = false;
  8231. auto res = request_func(
  8232. cli, "/content_receiver", headers, "content", "text/plain",
  8233. [&](const char *data, size_t data_length) {
  8234. received_body.append(data, data_length);
  8235. return true;
  8236. },
  8237. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8238. progress_called = true;
  8239. return true;
  8240. });
  8241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8242. EXPECT_EQ(StatusCode::OK_200, res->status);
  8243. EXPECT_EQ("content", received_body);
  8244. EXPECT_TRUE(progress_called);
  8245. }
  8246. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8247. #ifdef CPPHTTPLIB_SSL_ENABLED
  8248. using ClientT = SSLClient;
  8249. #else
  8250. using ClientT = Client;
  8251. #endif
  8252. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8253. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8254. const std::string &body, const std::string &content_type,
  8255. ContentReceiver receiver, DownloadProgress progress) {
  8256. return cli.Post(path, headers, body, content_type, receiver, progress);
  8257. });
  8258. }
  8259. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8260. #ifdef CPPHTTPLIB_SSL_ENABLED
  8261. using ClientT = SSLClient;
  8262. #else
  8263. using ClientT = Client;
  8264. #endif
  8265. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8266. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8267. const std::string &body, const std::string &content_type,
  8268. ContentReceiver receiver, DownloadProgress progress) {
  8269. return cli.Put(path, headers, body, content_type, receiver, progress);
  8270. });
  8271. }
  8272. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8273. #ifdef CPPHTTPLIB_SSL_ENABLED
  8274. using ClientT = SSLClient;
  8275. #else
  8276. using ClientT = Client;
  8277. #endif
  8278. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8279. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8280. const std::string &body, const std::string &content_type,
  8281. ContentReceiver receiver, DownloadProgress progress) {
  8282. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8283. });
  8284. }
  8285. template <typename ClientType>
  8286. void TestWithHeadersAndContentReceiverError(
  8287. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8288. const Headers &, const std::string &,
  8289. const std::string &, ContentReceiver)>
  8290. request_func) {
  8291. Headers headers;
  8292. headers.emplace("X-Error-Test", "true");
  8293. std::string received_body;
  8294. auto receiver_failed = false;
  8295. auto res =
  8296. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8297. [&](const char *data, size_t data_length) {
  8298. received_body.append(data, data_length);
  8299. receiver_failed = true;
  8300. return false;
  8301. });
  8302. ASSERT_FALSE(res);
  8303. EXPECT_TRUE(receiver_failed);
  8304. }
  8305. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8306. #ifdef CPPHTTPLIB_SSL_ENABLED
  8307. using ClientT = SSLClient;
  8308. #else
  8309. using ClientT = Client;
  8310. #endif
  8311. TestWithHeadersAndContentReceiverError<ClientT>(
  8312. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8313. const std::string &body, const std::string &content_type,
  8314. ContentReceiver receiver) {
  8315. return cli.Post(path, headers, body, content_type, receiver);
  8316. });
  8317. }
  8318. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8319. #ifdef CPPHTTPLIB_SSL_ENABLED
  8320. using ClientT = SSLClient;
  8321. #else
  8322. using ClientT = Client;
  8323. #endif
  8324. TestWithHeadersAndContentReceiverError<ClientT>(
  8325. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8326. const std::string &body, const std::string &content_type,
  8327. ContentReceiver receiver) {
  8328. return cli.Put(path, headers, body, content_type, receiver);
  8329. });
  8330. }
  8331. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8332. #ifdef CPPHTTPLIB_SSL_ENABLED
  8333. using ClientT = SSLClient;
  8334. #else
  8335. using ClientT = Client;
  8336. #endif
  8337. TestWithHeadersAndContentReceiverError<ClientT>(
  8338. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8339. const std::string &body, const std::string &content_type,
  8340. ContentReceiver receiver) {
  8341. return cli.Patch(path, headers, body, content_type, receiver);
  8342. });
  8343. }
  8344. TEST_F(ServerTest, PostQueryStringAndBody) {
  8345. auto res =
  8346. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. ASSERT_EQ(StatusCode::OK_200, res->status);
  8349. }
  8350. TEST_F(ServerTest, HTTP2Magic) {
  8351. Request req;
  8352. req.method = "PRI";
  8353. req.path = "*";
  8354. req.body = "SM";
  8355. auto res = std::make_shared<Response>();
  8356. auto error = Error::Success;
  8357. auto ret = cli_.send(req, *res, error);
  8358. ASSERT_TRUE(ret);
  8359. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8360. }
  8361. TEST_F(ServerTest, KeepAlive) {
  8362. auto res = cli_.Get("/hi");
  8363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8364. EXPECT_EQ(StatusCode::OK_200, res->status);
  8365. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8366. EXPECT_EQ("Hello World!", res->body);
  8367. res = cli_.Get("/hi");
  8368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8369. EXPECT_EQ(StatusCode::OK_200, res->status);
  8370. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8371. EXPECT_EQ("Hello World!", res->body);
  8372. res = cli_.Get("/hi");
  8373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8374. EXPECT_EQ(StatusCode::OK_200, res->status);
  8375. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8376. EXPECT_EQ("Hello World!", res->body);
  8377. res = cli_.Get("/not-exist");
  8378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8379. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8380. res = cli_.Post("/empty", "", "text/plain");
  8381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8382. EXPECT_EQ(StatusCode::OK_200, res->status);
  8383. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8384. EXPECT_EQ("empty", res->body);
  8385. EXPECT_EQ("close", res->get_header_value("Connection"));
  8386. res = cli_.Post(
  8387. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8388. "text/plain");
  8389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8392. EXPECT_EQ("empty", res->body);
  8393. cli_.set_keep_alive(false);
  8394. res = cli_.Get("/last-request");
  8395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8396. EXPECT_EQ(StatusCode::OK_200, res->status);
  8397. EXPECT_EQ("close", res->get_header_value("Connection"));
  8398. }
  8399. TEST_F(ServerTest, TooManyRedirect) {
  8400. cli_.set_follow_location(true);
  8401. auto res = cli_.Get("/redirect/0");
  8402. ASSERT_TRUE(!res);
  8403. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8404. }
  8405. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8406. Request req;
  8407. req.method = "FOOBAR";
  8408. req.path = "/hi";
  8409. cli_.set_keep_alive(true);
  8410. auto res = cli_.send(req);
  8411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8412. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8413. EXPECT_EQ("close", res->get_header_value("Connection"));
  8414. EXPECT_FALSE(cli_.is_socket_open());
  8415. }
  8416. TEST_F(ServerTest, CustomRouteReadsBody) {
  8417. const std::string xml =
  8418. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8419. Request req;
  8420. req.method = "PROPFIND";
  8421. req.path = "/dav/dir";
  8422. req.set_header("Depth", "1");
  8423. req.body = xml;
  8424. auto res = cli_.send(req);
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8427. EXPECT_EQ(xml, res->body);
  8428. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8429. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8430. }
  8431. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8432. Request req;
  8433. req.method = "PROPFIND";
  8434. req.path = "/dav/42";
  8435. auto res = cli_.send(req);
  8436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8437. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8438. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8439. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8440. }
  8441. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8442. Request req;
  8443. req.method = "PROPFIND";
  8444. req.path = "/dav-re/123";
  8445. auto res = cli_.send(req);
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8448. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8449. }
  8450. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8451. Request req;
  8452. req.method = "MKCOL";
  8453. req.path = "/dav-mkcol";
  8454. auto res = cli_.send(req);
  8455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8456. EXPECT_EQ(StatusCode::Created_201, res->status);
  8457. }
  8458. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8459. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8460. Request req;
  8461. req.method = "REPORT";
  8462. req.path = "/dav-report";
  8463. req.body = xml;
  8464. auto res = cli_.send(req);
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8467. EXPECT_EQ(xml, res->body);
  8468. }
  8469. // A content reader route must fire even when the request carries no body,
  8470. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8471. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8472. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8473. Request req;
  8474. req.method = "REPORT";
  8475. req.path = "/dav-report";
  8476. auto res = cli_.send(req);
  8477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8478. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8479. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8480. }
  8481. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8482. Request req;
  8483. req.method = "PROPFIND";
  8484. req.path = "/not-dav";
  8485. auto res = cli_.send(req);
  8486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8487. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8488. }
  8489. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8490. Request req;
  8491. req.method = "UNLOCK";
  8492. req.path = "/dav/dir";
  8493. cli_.set_keep_alive(true);
  8494. auto res = cli_.send(req);
  8495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8496. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8497. EXPECT_EQ("close", res->get_header_value("Connection"));
  8498. EXPECT_FALSE(cli_.is_socket_open());
  8499. }
  8500. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8501. // The mount point serves this path, but only for GET and HEAD.
  8502. auto get_res = cli_.Get("/dir/index.html");
  8503. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8504. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8505. Request req;
  8506. req.method = "PROPFIND";
  8507. req.path = "/dir/index.html";
  8508. auto res = cli_.send(req);
  8509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8511. }
  8512. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8513. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8514. cli_.set_keep_alive(true);
  8515. for (auto i = 0; i < 2; i++) {
  8516. Request req;
  8517. req.method = "PROPFIND";
  8518. req.path = "/dav/dir";
  8519. req.body = xml;
  8520. auto res = cli_.send(req);
  8521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8522. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8523. EXPECT_EQ(xml, res->body);
  8524. EXPECT_TRUE(cli_.is_socket_open());
  8525. }
  8526. // A built-in method must still be served on the same connection.
  8527. cli_.set_keep_alive(false);
  8528. auto res = cli_.Get("/hi");
  8529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8530. EXPECT_EQ(StatusCode::OK_200, res->status);
  8531. EXPECT_EQ("close", res->get_header_value("Connection"));
  8532. }
  8533. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8534. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8535. Request req;
  8536. req.method = "PROPFIND";
  8537. req.path = "/dav/dir";
  8538. req.set_header("Expect", "100-continue");
  8539. req.body = xml;
  8540. auto res = cli_.send(req);
  8541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8542. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8543. EXPECT_EQ(xml, res->body);
  8544. }
  8545. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8546. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8547. TEST_F(ServerTest, Gzip) {
  8548. Headers headers;
  8549. headers.emplace("Accept-Encoding", "gzip, deflate");
  8550. auto res = cli_.Get("/compress", headers);
  8551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8552. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8554. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8555. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8556. "7890123456789012345678901234567890",
  8557. res->body);
  8558. EXPECT_EQ(StatusCode::OK_200, res->status);
  8559. }
  8560. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8561. Headers headers;
  8562. headers.emplace("Accept-Encoding", "gzip, deflate");
  8563. auto res = cli_.Get("/compress-with-charset", headers);
  8564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8565. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8566. EXPECT_EQ("application/json; charset=utf-8",
  8567. res->get_header_value("Content-Type"));
  8568. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8569. "7890123456789012345678901234567890",
  8570. res->body);
  8571. EXPECT_EQ(StatusCode::OK_200, res->status);
  8572. }
  8573. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8574. Headers headers;
  8575. headers.emplace("Accept-Encoding", "");
  8576. auto res = cli_.Get("/compress", headers);
  8577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8578. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8579. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8580. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8581. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8582. "7890123456789012345678901234567890",
  8583. res->body);
  8584. EXPECT_EQ(StatusCode::OK_200, res->status);
  8585. }
  8586. TEST_F(ServerTest, GzipWithContentReceiver) {
  8587. Headers headers;
  8588. headers.emplace("Accept-Encoding", "gzip, deflate");
  8589. std::string body;
  8590. auto res =
  8591. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8592. EXPECT_EQ(100U, data_length);
  8593. body.append(data, data_length);
  8594. return true;
  8595. });
  8596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8597. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8598. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8599. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8600. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8601. "7890123456789012345678901234567890",
  8602. body);
  8603. EXPECT_EQ(StatusCode::OK_200, res->status);
  8604. }
  8605. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8606. Headers headers;
  8607. headers.emplace("Accept-Encoding", "gzip, deflate");
  8608. cli_.set_decompress(false);
  8609. auto res = cli_.Get("/compress", headers);
  8610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8611. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8612. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8613. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8614. EXPECT_EQ(33U, res->body.size());
  8615. EXPECT_EQ(StatusCode::OK_200, res->status);
  8616. }
  8617. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8618. Headers headers;
  8619. headers.emplace("Accept-Encoding", "");
  8620. std::string body;
  8621. auto res =
  8622. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8623. EXPECT_EQ(100U, data_length);
  8624. body.append(data, data_length);
  8625. return true;
  8626. });
  8627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8628. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8630. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8631. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8632. "7890123456789012345678901234567890",
  8633. body);
  8634. EXPECT_EQ(StatusCode::OK_200, res->status);
  8635. }
  8636. TEST_F(ServerTest, NoGzip) {
  8637. Headers headers;
  8638. headers.emplace("Accept-Encoding", "gzip, deflate");
  8639. auto res = cli_.Get("/nocompress", headers);
  8640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8641. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8642. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8643. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8644. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8645. "7890123456789012345678901234567890",
  8646. res->body);
  8647. EXPECT_EQ(StatusCode::OK_200, res->status);
  8648. }
  8649. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8650. Headers headers;
  8651. headers.emplace("Accept-Encoding", "gzip, deflate");
  8652. std::string body;
  8653. auto res = cli_.Get("/nocompress", headers,
  8654. [&](const char *data, size_t data_length) {
  8655. EXPECT_EQ(100U, data_length);
  8656. body.append(data, data_length);
  8657. return true;
  8658. });
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8661. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8662. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8663. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8664. "7890123456789012345678901234567890",
  8665. body);
  8666. EXPECT_EQ(StatusCode::OK_200, res->status);
  8667. }
  8668. TEST_F(ServerTest, MultipartFormDataGzip) {
  8669. UploadFormDataItems items = {
  8670. {"key1", "test", "", ""},
  8671. {"key2", "--abcdefg123", "", ""},
  8672. };
  8673. cli_.set_compress(true);
  8674. auto res = cli_.Post("/compress-multipart", items);
  8675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8676. EXPECT_EQ(StatusCode::OK_200, res->status);
  8677. }
  8678. #endif
  8679. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8680. // Static file compression is opt-in, so these run their own server rather than
  8681. // flipping it on for the shared ServerTest fixture, which would silently
  8682. // rewrite what every other static file test is asserting.
  8683. class StaticFileCompressionTest : public ::testing::Test {
  8684. protected:
  8685. void TearDown() override {
  8686. if (t_.joinable()) {
  8687. svr_.stop();
  8688. t_.join();
  8689. }
  8690. }
  8691. int start(const std::function<void(Server &)> &configure = nullptr) {
  8692. // Serves the same tree as a directory of build-time compressed assets
  8693. // would be served: the mount point names the coding the files are already
  8694. // stored in. Registered before "/" so it is the one that matches.
  8695. svr_.set_mount_point("/pre-encoded", "./www",
  8696. {{"Content-Encoding", "gzip"}});
  8697. svr_.set_mount_point("/", "./www");
  8698. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8699. res.set_file_content("./www/dir/index.html", "text/html");
  8700. });
  8701. svr_.Get("/pre-encoded-file-content",
  8702. [](const Request & /*req*/, Response &res) {
  8703. res.set_header("Content-Encoding", "gzip");
  8704. res.set_file_content("./www/dir/index.html", "text/html");
  8705. });
  8706. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8707. res.set_content_provider(
  8708. 6, "text/plain",
  8709. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8710. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8711. return true;
  8712. });
  8713. });
  8714. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8715. res.set_content_provider(
  8716. 1000, "text/plain",
  8717. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8718. if (offset < 100) {
  8719. std::string data(100, 'A');
  8720. sink.write(data.data(), data.size());
  8721. return true;
  8722. }
  8723. std::this_thread::sleep_for(std::chrono::seconds(2));
  8724. std::string data(900, 'B');
  8725. sink.write(data.data(), data.size());
  8726. return true;
  8727. });
  8728. });
  8729. if (configure) { configure(svr_); }
  8730. auto port = svr_.bind_to_any_port(HOST);
  8731. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8732. svr_.wait_until_ready();
  8733. return port;
  8734. }
  8735. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8736. // Every file under ./www except 1MB.txt is smaller than the default
  8737. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8738. // it out of the way.
  8739. static void enable_without_floor(Server &svr) {
  8740. svr.set_static_file_compression(true);
  8741. svr.set_static_file_compression_min_length(0);
  8742. }
  8743. Server svr_;
  8744. std::thread t_;
  8745. };
  8746. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8747. auto port = start();
  8748. Client cli(HOST, port);
  8749. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8751. EXPECT_EQ(StatusCode::OK_200, res->status);
  8752. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8753. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8754. EXPECT_EQ(1048576U, res->body.size());
  8755. }
  8756. TEST_F(StaticFileCompressionTest, MountPoint) {
  8757. auto port = start(enable);
  8758. Client cli(HOST, port);
  8759. cli.set_decompress(false);
  8760. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8762. EXPECT_EQ(StatusCode::OK_200, res->status);
  8763. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8764. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8765. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8766. // The response stays self-delimiting: a length, not a chunked body.
  8767. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8768. EXPECT_EQ(std::to_string(res->body.size()),
  8769. res->get_header_value("Content-Length"));
  8770. EXPECT_LT(res->body.size(), 1048576U);
  8771. EXPECT_FALSE(res->body.empty());
  8772. }
  8773. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8774. auto port = start(enable);
  8775. Client cli(HOST, port);
  8776. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8778. EXPECT_EQ(StatusCode::OK_200, res->status);
  8779. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8780. EXPECT_EQ(1048576U, res->body.size());
  8781. }
  8782. TEST_F(StaticFileCompressionTest, FileContent) {
  8783. auto port = start(enable_without_floor);
  8784. Client cli(HOST, port);
  8785. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8787. EXPECT_EQ(StatusCode::OK_200, res->status);
  8788. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8789. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8790. EXPECT_EQ(104U, res->body.size());
  8791. }
  8792. // A handler that serves an already-encoded file names the coding itself. The
  8793. // file-backed path decided its coding from Accept-Encoding and the content
  8794. // type alone, so it compressed the stored bytes a second time and appended a
  8795. // second Content-Encoding field line.
  8796. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8797. auto port = start(enable_without_floor);
  8798. Client cli(HOST, port);
  8799. cli.set_decompress(false);
  8800. auto res = cli.Get("/pre-encoded-file-content",
  8801. Headers{{"Accept-Encoding", "gzip"}});
  8802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8803. EXPECT_EQ(StatusCode::OK_200, res->status);
  8804. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8805. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8806. // Vary belongs to a coding the server chose, and it chose none here.
  8807. EXPECT_FALSE(res->has_header("Vary"));
  8808. // The file travels exactly as it is stored on disk.
  8809. EXPECT_EQ(104U, res->body.size());
  8810. }
  8811. // The 1MB file clears the default floor, so this one runs the configuration a
  8812. // deployment would actually have.
  8813. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8814. auto port = start(enable);
  8815. Client cli(HOST, port);
  8816. cli.set_decompress(false);
  8817. auto res =
  8818. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8820. EXPECT_EQ(StatusCode::OK_200, res->status);
  8821. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8822. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8823. EXPECT_FALSE(res->has_header("Vary"));
  8824. EXPECT_EQ(1048576U, res->body.size());
  8825. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8826. }
  8827. TEST_F(StaticFileCompressionTest, Head) {
  8828. auto port = start(enable);
  8829. Client cli(HOST, port);
  8830. cli.set_decompress(false);
  8831. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8832. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8833. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8835. EXPECT_EQ(StatusCode::OK_200, res->status);
  8836. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8837. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8838. // HEAD still reports the size a GET would return.
  8839. EXPECT_EQ(get->get_header_value("Content-Length"),
  8840. res->get_header_value("Content-Length"));
  8841. EXPECT_TRUE(res->body.empty());
  8842. }
  8843. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8844. auto port = start(enable);
  8845. Client cli(HOST, port);
  8846. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8847. {"Accept-Encoding", "gzip"}});
  8848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8849. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8850. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8851. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8852. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8853. EXPECT_EQ("cd", res->body);
  8854. }
  8855. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8856. auto port = start(enable);
  8857. Client cli(HOST, port);
  8858. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8860. EXPECT_EQ(StatusCode::OK_200, res->status);
  8861. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8862. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8863. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8864. }
  8865. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8866. auto port = start(enable);
  8867. Client cli(HOST, port);
  8868. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8870. EXPECT_EQ(StatusCode::OK_200, res->status);
  8871. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8872. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8873. EXPECT_TRUE(res->body.empty());
  8874. }
  8875. TEST_F(StaticFileCompressionTest, MinLength) {
  8876. auto port = start(enable);
  8877. Client cli(HOST, port);
  8878. // 104 bytes, well under the default floor. Compressing it would add the
  8879. // gzip header and trailer to a body that already fits in one packet.
  8880. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8882. EXPECT_EQ(StatusCode::OK_200, res->status);
  8883. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8884. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8885. }
  8886. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8887. auto port = start([](Server &svr) {
  8888. svr.set_static_file_compression(true);
  8889. svr.set_static_file_compression_min_length(1);
  8890. });
  8891. Client cli(HOST, port);
  8892. cli.set_decompress(false);
  8893. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8895. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8896. // A 9-byte file comes back larger than it went in, because gzip's header and
  8897. // trailer outweigh anything deflate can save. That is the end of the range
  8898. // the floor exists to keep out.
  8899. EXPECT_GT(res->body.size(), 9U);
  8900. }
  8901. TEST_F(StaticFileCompressionTest, MaxLength) {
  8902. auto port = start([](Server &svr) {
  8903. svr.set_static_file_compression(true);
  8904. svr.set_static_file_compression_min_length(0);
  8905. svr.set_static_file_compression_max_length(1024);
  8906. });
  8907. Client cli(HOST, port);
  8908. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8909. // defines `small` as a macro on Windows.
  8910. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8911. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8912. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8913. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8914. // Under it: compressed.
  8915. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8916. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8917. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8918. }
  8919. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8920. auto port = start(enable_without_floor);
  8921. Client cli(HOST, port);
  8922. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8923. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8924. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8925. auto identity_etag = identity->get_header_value("ETag");
  8926. ASSERT_FALSE(identity_etag.empty());
  8927. auto gzipped =
  8928. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8929. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8930. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8931. auto gzip_etag = gzipped->get_header_value("ETag");
  8932. ASSERT_FALSE(gzip_etag.empty());
  8933. // Two representations, two validators.
  8934. EXPECT_NE(identity_etag, gzip_etag);
  8935. // Each one revalidates against the request that would produce it...
  8936. auto fresh =
  8937. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8938. {"If-None-Match", gzip_etag}});
  8939. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8940. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8941. auto fresh_identity =
  8942. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8943. {"If-None-Match", identity_etag}});
  8944. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8945. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8946. // ...and not against the other representation.
  8947. auto crossed =
  8948. cli.Get("/dir/index.html",
  8949. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8950. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8951. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8952. }
  8953. // The opt-in covers responses the server reads off disk itself. A caller's own
  8954. // known-length provider keeps its Content-Length and, more importantly, keeps
  8955. // delivering incrementally: routing it through a compressor would hold every
  8956. // write back until zlib's window filled.
  8957. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8958. auto port = start(enable);
  8959. Client cli(HOST, port);
  8960. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8962. EXPECT_EQ(StatusCode::OK_200, res->status);
  8963. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8964. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8965. EXPECT_EQ("aaabbb", res->body);
  8966. }
  8967. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8968. auto port = start(enable);
  8969. Client cli(HOST, port);
  8970. cli.set_read_timeout(1, 0);
  8971. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8972. Headers{{"Accept-Encoding", "gzip"}});
  8973. ASSERT_TRUE(handle.is_valid());
  8974. // The provider writes 100 bytes and then stalls for longer than the read
  8975. // timeout. Those first bytes have to arrive anyway: run the response through
  8976. // a compressor and zlib holds them until its window fills, so the read would
  8977. // come back empty instead.
  8978. char buf[256];
  8979. auto n = handle.read(buf, sizeof(buf));
  8980. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8981. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8982. }
  8983. #endif
  8984. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8985. TEST_F(ServerTest, Brotli) {
  8986. Headers headers;
  8987. headers.emplace("Accept-Encoding", "br");
  8988. auto res = cli_.Get("/compress", headers);
  8989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8990. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8992. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8993. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8994. "7890123456789012345678901234567890",
  8995. res->body);
  8996. EXPECT_EQ(StatusCode::OK_200, res->status);
  8997. }
  8998. #endif
  8999. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9000. TEST_F(ServerTest, Zstd) {
  9001. Headers headers;
  9002. headers.emplace("Accept-Encoding", "zstd");
  9003. auto res = cli_.Get("/compress", headers);
  9004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9005. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9006. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9007. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9008. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9009. "7890123456789012345678901234567890",
  9010. res->body);
  9011. EXPECT_EQ(StatusCode::OK_200, res->status);
  9012. }
  9013. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9014. Headers headers;
  9015. headers.emplace("Accept-Encoding", "");
  9016. auto res = cli_.Get("/compress", headers);
  9017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9018. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9019. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9020. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9021. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9022. "7890123456789012345678901234567890",
  9023. res->body);
  9024. EXPECT_EQ(StatusCode::OK_200, res->status);
  9025. }
  9026. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9027. Headers headers;
  9028. headers.emplace("Accept-Encoding", "zstd");
  9029. std::string body;
  9030. auto res =
  9031. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9032. EXPECT_EQ(100U, data_length);
  9033. body.append(data, data_length);
  9034. return true;
  9035. });
  9036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9037. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9038. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9039. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9040. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9041. "7890123456789012345678901234567890",
  9042. body);
  9043. EXPECT_EQ(StatusCode::OK_200, res->status);
  9044. }
  9045. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9046. Headers headers;
  9047. headers.emplace("Accept-Encoding", "zstd");
  9048. cli_.set_decompress(false);
  9049. auto res = cli_.Get("/compress", headers);
  9050. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9051. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9052. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9053. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9055. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9056. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9057. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9058. EXPECT_EQ(StatusCode::OK_200, res->status);
  9059. ASSERT_EQ(26U, res->body.size());
  9060. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9061. 0);
  9062. }
  9063. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9064. Headers headers;
  9065. headers.emplace("Accept-Encoding", "");
  9066. std::string body;
  9067. auto res =
  9068. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9069. EXPECT_EQ(100U, data_length);
  9070. body.append(data, data_length);
  9071. return true;
  9072. });
  9073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9074. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9075. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9076. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9077. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9078. "7890123456789012345678901234567890",
  9079. body);
  9080. EXPECT_EQ(StatusCode::OK_200, res->status);
  9081. }
  9082. TEST_F(ServerTest, NoZstd) {
  9083. Headers headers;
  9084. headers.emplace("Accept-Encoding", "zstd");
  9085. auto res = cli_.Get("/nocompress", headers);
  9086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9087. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9088. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9089. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9090. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9091. "7890123456789012345678901234567890",
  9092. res->body);
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. }
  9095. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9096. Headers headers;
  9097. headers.emplace("Accept-Encoding", "zstd");
  9098. std::string body;
  9099. auto res = cli_.Get("/nocompress", headers,
  9100. [&](const char *data, size_t data_length) {
  9101. EXPECT_EQ(100U, data_length);
  9102. body.append(data, data_length);
  9103. return true;
  9104. });
  9105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9106. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9107. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9108. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9109. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9110. "7890123456789012345678901234567890",
  9111. body);
  9112. EXPECT_EQ(StatusCode::OK_200, res->status);
  9113. }
  9114. // TODO: How to enable zstd ??
  9115. TEST_F(ServerTest, MultipartFormDataZstd) {
  9116. UploadFormDataItems items = {
  9117. {"key1", "test", "", ""},
  9118. {"key2", "--abcdefg123", "", ""},
  9119. };
  9120. Headers headers;
  9121. headers.emplace("Accept-Encoding", "zstd");
  9122. cli_.set_compress(true);
  9123. auto res = cli_.Post("/compress-multipart", headers, items);
  9124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9125. EXPECT_EQ(StatusCode::OK_200, res->status);
  9126. }
  9127. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9128. Headers headers;
  9129. headers.emplace("Accept-Encoding", "zstd");
  9130. cli_.set_compress(true);
  9131. auto res = cli_.Put(
  9132. "/put", headers, 3,
  9133. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9134. sink.os << "PUT";
  9135. return true;
  9136. },
  9137. "text/plain");
  9138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9139. EXPECT_EQ(StatusCode::OK_200, res->status);
  9140. EXPECT_EQ("PUT", res->body);
  9141. }
  9142. // Pre-compression logging tests
  9143. TEST_F(ServerTest, PreCompressionLogging) {
  9144. // Test data for compression (matches the actual /compress endpoint content)
  9145. const std::string test_content =
  9146. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9147. "3456789012345678901234567890";
  9148. // Variables to capture logging data
  9149. std::string pre_compression_body;
  9150. std::string pre_compression_content_type;
  9151. std::string pre_compression_content_encoding;
  9152. std::string post_compression_body;
  9153. std::string post_compression_content_type;
  9154. std::string post_compression_content_encoding;
  9155. // Set up pre-compression logger
  9156. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9157. const Response &res) {
  9158. pre_compression_body = res.body;
  9159. pre_compression_content_type = res.get_header_value("Content-Type");
  9160. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9161. });
  9162. // Set up post-compression logger
  9163. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9164. post_compression_body = res.body;
  9165. post_compression_content_type = res.get_header_value("Content-Type");
  9166. post_compression_content_encoding =
  9167. res.get_header_value("Content-Encoding");
  9168. });
  9169. // Test with gzip compression
  9170. Headers headers;
  9171. headers.emplace("Accept-Encoding", "gzip");
  9172. auto res = cli_.Get("/compress", headers);
  9173. // Verify response was compressed
  9174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9175. EXPECT_EQ(StatusCode::OK_200, res->status);
  9176. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9177. // Verify pre-compression logger captured uncompressed content
  9178. EXPECT_EQ(test_content, pre_compression_body);
  9179. EXPECT_EQ("text/plain", pre_compression_content_type);
  9180. EXPECT_TRUE(pre_compression_content_encoding
  9181. .empty()); // No encoding header before compression
  9182. // Verify post-compression logger captured compressed content
  9183. EXPECT_NE(test_content,
  9184. post_compression_body); // Should be different after compression
  9185. EXPECT_EQ("text/plain", post_compression_content_type);
  9186. EXPECT_EQ("gzip", post_compression_content_encoding);
  9187. // Verify compressed content is smaller
  9188. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9189. }
  9190. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9191. const std::string test_content =
  9192. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9193. "3456789012345678901234567890";
  9194. std::string pre_compression_body;
  9195. std::string post_compression_body;
  9196. svr_.set_pre_compression_logger(
  9197. [&](const Request & /*req*/, const Response &res) {
  9198. pre_compression_body = res.body;
  9199. });
  9200. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9201. post_compression_body = res.body;
  9202. });
  9203. Headers headers;
  9204. headers.emplace("Accept-Encoding", "br");
  9205. auto res = cli_.Get("/compress", headers);
  9206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9207. EXPECT_EQ(StatusCode::OK_200, res->status);
  9208. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9209. // Verify pre-compression content is uncompressed
  9210. EXPECT_EQ(test_content, pre_compression_body);
  9211. // Verify post-compression content is compressed
  9212. EXPECT_NE(test_content, post_compression_body);
  9213. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9214. }
  9215. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9216. const std::string test_content =
  9217. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9218. "3456789012345678901234567890";
  9219. std::string pre_compression_body;
  9220. std::string post_compression_body;
  9221. svr_.set_pre_compression_logger(
  9222. [&](const Request & /*req*/, const Response &res) {
  9223. pre_compression_body = res.body;
  9224. });
  9225. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9226. post_compression_body = res.body;
  9227. });
  9228. // Request without compression (use /nocompress endpoint)
  9229. Headers headers;
  9230. auto res = cli_.Get("/nocompress", headers);
  9231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9232. EXPECT_EQ(StatusCode::OK_200, res->status);
  9233. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9234. // Pre-compression logger should not be called when no compression is applied
  9235. EXPECT_TRUE(
  9236. pre_compression_body.empty()); // Pre-compression logger not called
  9237. EXPECT_EQ(
  9238. test_content,
  9239. post_compression_body); // Post-compression logger captures final content
  9240. }
  9241. TEST_F(ServerTest, LoggerSeesContentLength) {
  9242. size_t logged_content_length = 0;
  9243. std::string logged_content_length_header;
  9244. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9245. logged_content_length = res.content_length_;
  9246. logged_content_length_header = res.get_header_value("Content-Length");
  9247. });
  9248. auto res = cli_.Get("/nocompress");
  9249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9250. EXPECT_EQ(StatusCode::OK_200, res->status);
  9251. EXPECT_EQ(res->body.size(), logged_content_length);
  9252. EXPECT_EQ(std::to_string(logged_content_length),
  9253. logged_content_length_header);
  9254. }
  9255. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9256. const std::string test_content =
  9257. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9258. "3456789012345678901234567890";
  9259. std::string pre_compression_body;
  9260. bool pre_logger_called = false;
  9261. // Set only pre-compression logger
  9262. svr_.set_pre_compression_logger(
  9263. [&](const Request & /*req*/, const Response &res) {
  9264. pre_compression_body = res.body;
  9265. pre_logger_called = true;
  9266. });
  9267. Headers headers;
  9268. headers.emplace("Accept-Encoding", "gzip");
  9269. auto res = cli_.Get("/compress", headers);
  9270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9271. EXPECT_EQ(StatusCode::OK_200, res->status);
  9272. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9273. // Verify pre-compression logger was called
  9274. EXPECT_TRUE(pre_logger_called);
  9275. EXPECT_EQ(test_content, pre_compression_body);
  9276. }
  9277. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9278. {
  9279. // Test with Expect: 100-continue header - success case
  9280. // Server returns 100 Continue, client sends body, server returns 200 OK
  9281. Request req;
  9282. req.method = "POST";
  9283. req.path = "/post-large";
  9284. req.set_header("Expect", "100-continue");
  9285. req.body = LARGE_DATA;
  9286. Response res;
  9287. auto error = Error::Success;
  9288. cli_.set_keep_alive(true);
  9289. auto ret = cli_.send(req, res, error);
  9290. EXPECT_TRUE(ret);
  9291. EXPECT_EQ(StatusCode::OK_200, res.status);
  9292. EXPECT_EQ(LARGE_DATA, res.body);
  9293. }
  9294. {
  9295. // Test with Expect: 100-continue header - error case
  9296. // Client should not send the body when server returns an error
  9297. Request req;
  9298. req.method = "POST";
  9299. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9300. req.set_header("Expect", "100-continue");
  9301. req.body = LARGE_DATA;
  9302. Response res;
  9303. auto error = Error::Success;
  9304. auto start = std::chrono::high_resolution_clock::now();
  9305. cli_.set_keep_alive(true);
  9306. auto ret = cli_.send(req, res, error);
  9307. auto end = std::chrono::high_resolution_clock::now();
  9308. auto elapsed =
  9309. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9310. .count();
  9311. // With Expect: 100-continue, request completes successfully but with error
  9312. EXPECT_TRUE(ret);
  9313. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9314. EXPECT_EQ("close", res.get_header_value("Connection"));
  9315. EXPECT_FALSE(cli_.is_socket_open());
  9316. EXPECT_LE(elapsed, 2000);
  9317. }
  9318. {
  9319. // Send an extra GET request to ensure error recovery without hanging
  9320. Request req;
  9321. req.method = "GET";
  9322. req.path = "/hi";
  9323. auto start = std::chrono::high_resolution_clock::now();
  9324. auto res = cli_.send(req);
  9325. auto end = std::chrono::high_resolution_clock::now();
  9326. auto elapsed =
  9327. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9328. .count();
  9329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9330. EXPECT_EQ(StatusCode::OK_200, res->status);
  9331. EXPECT_EQ("Hello World!", res->body);
  9332. EXPECT_LE(elapsed, 500);
  9333. }
  9334. }
  9335. TEST(ZstdDecompressor, ChunkedDecompression) {
  9336. std::string data;
  9337. for (size_t i = 0; i < 32 * 1024; ++i) {
  9338. data.push_back(static_cast<char>('a' + i % 26));
  9339. }
  9340. std::string compressed_data;
  9341. {
  9342. httplib::detail::zstd_compressor compressor;
  9343. bool result = compressor.compress(
  9344. data.data(), data.size(),
  9345. /*last=*/true,
  9346. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9347. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9348. compressed_data_size);
  9349. return true;
  9350. });
  9351. ASSERT_TRUE(result);
  9352. }
  9353. std::string decompressed_data;
  9354. {
  9355. httplib::detail::zstd_decompressor decompressor;
  9356. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9357. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9358. size_t chunk_size = 130;
  9359. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9360. chunk_begin += chunk_size) {
  9361. size_t current_chunk_size =
  9362. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9363. bool result = decompressor.decompress(
  9364. compressed_data.data() + chunk_begin, current_chunk_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. }
  9375. ASSERT_EQ(data, decompressed_data);
  9376. }
  9377. TEST(ZstdDecompressor, Decompress) {
  9378. std::string original_text = "Compressed with ZSTD";
  9379. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9380. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9381. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9382. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9383. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9384. std::string decompressed_data;
  9385. {
  9386. httplib::detail::zstd_decompressor decompressor;
  9387. bool result = decompressor.decompress(
  9388. compressed_data.data(), compressed_data.size(),
  9389. [&](const char *decompressed_data_chunk,
  9390. size_t decompressed_data_chunk_size) {
  9391. decompressed_data.insert(decompressed_data.size(),
  9392. decompressed_data_chunk,
  9393. decompressed_data_chunk_size);
  9394. return true;
  9395. });
  9396. ASSERT_TRUE(result);
  9397. }
  9398. ASSERT_EQ(original_text, decompressed_data);
  9399. }
  9400. #endif
  9401. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9402. // separate chunks so that the server sees each part in its own read(). Used to
  9403. // place a read boundary at a specific offset of a request body.
  9404. static bool send_request_in_parts(time_t read_timeout_sec,
  9405. const std::vector<std::string> &parts,
  9406. std::string *resp = nullptr,
  9407. int port = PORT) {
  9408. auto error = Error::Success;
  9409. auto client_sock = detail::create_client_socket(
  9410. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9411. /*connection_timeout_sec=*/5, 0,
  9412. /*read_timeout_sec=*/5, 0,
  9413. /*write_timeout_sec=*/5, 0, std::string(), error);
  9414. if (client_sock == INVALID_SOCKET) { return false; }
  9415. auto ret = detail::process_client_socket(
  9416. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9417. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9418. for (size_t i = 0; i < parts.size(); i++) {
  9419. const auto &part = parts[i];
  9420. if (part.size() !=
  9421. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9422. return false;
  9423. }
  9424. if (i + 1 < parts.size()) {
  9425. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9426. }
  9427. }
  9428. char buf[512];
  9429. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9430. while (line_reader.getline()) {
  9431. if (resp) { *resp += line_reader.ptr(); }
  9432. }
  9433. return true;
  9434. });
  9435. detail::close_socket(client_sock);
  9436. return ret;
  9437. }
  9438. // Sends a raw request to a server listening at HOST:PORT.
  9439. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9440. std::string *resp = nullptr, int port = PORT) {
  9441. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9442. }
  9443. #ifdef CPPHTTPLIB_SSL_ENABLED
  9444. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9445. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9446. ASSERT_TRUE(svr.is_valid());
  9447. svr.set_read_timeout(1, 0);
  9448. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9449. auto se = detail::scope_exit([&] {
  9450. svr.stop();
  9451. t.join();
  9452. ASSERT_FALSE(svr.is_running());
  9453. });
  9454. svr.wait_until_ready();
  9455. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9456. // keeps each wait well within the read timeout. The server gives up a
  9457. // second in, so the bytes sent after that fail.
  9458. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9459. parts.resize(26, std::string(1, '\0'));
  9460. EXPECT_FALSE(send_request_in_parts(5, parts));
  9461. }
  9462. #endif
  9463. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9464. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9465. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9466. const std::vector<std::string> &parts,
  9467. std::string *resp = nullptr,
  9468. int port = PORT) {
  9469. auto error = Error::Success;
  9470. auto sock = detail::create_client_socket(
  9471. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9472. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9473. /*write_timeout_sec=*/5, 0, std::string(), error);
  9474. if (sock == INVALID_SOCKET) { return false; }
  9475. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9476. auto ctx = SSL_CTX_new(TLS_client_method());
  9477. auto ssl = SSL_new(ctx);
  9478. auto ssl_se = detail::scope_exit([&] {
  9479. SSL_free(ssl);
  9480. SSL_CTX_free(ctx);
  9481. });
  9482. SSL_set_fd(ssl, static_cast<int>(sock));
  9483. if (SSL_connect(ssl) != 1) { return false; }
  9484. for (size_t i = 0; i < parts.size(); i++) {
  9485. const auto &part = parts[i];
  9486. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9487. static_cast<int>(part.size())) {
  9488. return false;
  9489. }
  9490. if (i + 1 < parts.size()) {
  9491. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9492. }
  9493. }
  9494. char buf[512];
  9495. int n;
  9496. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9497. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9498. }
  9499. return true;
  9500. }
  9501. #endif
  9502. // The request line, then a header value a byte at a time.
  9503. static std::vector<std::string> slow_request_head_parts() {
  9504. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9505. parts.resize(26, "a");
  9506. parts.emplace_back("\r\n\r\n");
  9507. return parts;
  9508. }
  9509. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9510. // within the one-second read timeout. The server gives up a second in, before
  9511. // the head is complete.
  9512. static void
  9513. expect_slow_request_head_dropped(Server &svr,
  9514. const std::function<std::string()> &send) {
  9515. std::atomic<bool> handled(false);
  9516. svr.Get("/", [&](const Request &, Response &res) {
  9517. handled = true;
  9518. res.set_content("ok", "text/plain");
  9519. });
  9520. svr.set_read_timeout(1, 0);
  9521. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9522. auto se = detail::scope_exit([&] {
  9523. svr.stop();
  9524. t.join();
  9525. ASSERT_FALSE(svr.is_running());
  9526. });
  9527. svr.wait_until_ready();
  9528. auto resp = send();
  9529. EXPECT_FALSE(handled);
  9530. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9531. }
  9532. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9533. Server svr;
  9534. expect_slow_request_head_dropped(svr, [] {
  9535. std::string resp;
  9536. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9537. return resp;
  9538. });
  9539. }
  9540. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9541. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9543. ASSERT_TRUE(svr.is_valid());
  9544. expect_slow_request_head_dropped(svr, [] {
  9545. std::string resp;
  9546. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9547. return resp;
  9548. });
  9549. }
  9550. #endif
  9551. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9552. Server svr;
  9553. std::string header_value;
  9554. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9555. header_value = req.get_header_value("foo");
  9556. res.set_content("ok", "text/plain");
  9557. });
  9558. thread t = thread([&] { svr.listen(HOST, PORT); });
  9559. auto se = detail::scope_exit([&] {
  9560. svr.stop();
  9561. t.join();
  9562. ASSERT_FALSE(svr.is_running());
  9563. });
  9564. svr.wait_until_ready();
  9565. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9566. // like characters are not treated the same - use vertical tab and escape.
  9567. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9568. "foo: \t \v bar \x1B\t \r\n"
  9569. "Connection: close\r\n"
  9570. "\r\n";
  9571. std::string res;
  9572. ASSERT_TRUE(send_request(5, req, &res));
  9573. EXPECT_EQ(header_value, "");
  9574. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9575. }
  9576. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9577. Server svr;
  9578. std::string received;
  9579. svr.Get("/order", [&](const Request &req, Response &res) {
  9580. received = entries_to_string(req.headers);
  9581. res.set_content("ok", "text/plain");
  9582. });
  9583. auto port = svr.bind_to_any_port(HOST);
  9584. thread t = thread([&] { svr.listen_after_bind(); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. t.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.wait_until_ready();
  9591. const std::string req = "GET /order HTTP/1.1\r\n"
  9592. "Host: localhost\r\n"
  9593. "X-First: 1\r\n"
  9594. "X-Dup: a\r\n"
  9595. "X-Second: 2\r\n"
  9596. "X-Dup: b\r\n"
  9597. "Connection: close\r\n"
  9598. "\r\n";
  9599. std::string res;
  9600. ASSERT_TRUE(send_request(5, req, &res, port));
  9601. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9602. EXPECT_EQ(
  9603. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9604. received);
  9605. }
  9606. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9607. Server svr;
  9608. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9609. res.set_header("Set-Cookie", "first=1");
  9610. res.set_header("X-Between", "y");
  9611. res.set_header("Set-Cookie", "second=2");
  9612. res.set_content("ok", "text/plain");
  9613. });
  9614. auto port = svr.bind_to_any_port(HOST);
  9615. thread t = thread([&] { svr.listen_after_bind(); });
  9616. auto se = detail::scope_exit([&] {
  9617. svr.stop();
  9618. t.join();
  9619. ASSERT_FALSE(svr.is_running());
  9620. });
  9621. svr.wait_until_ready();
  9622. Client cli(HOST, port);
  9623. auto res = cli.Get("/cookies");
  9624. ASSERT_TRUE(res);
  9625. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9626. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9627. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9628. }
  9629. // A stream may send a byte at a time with a small extension on each chunk,
  9630. // however long it runs
  9631. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9632. Server svr;
  9633. svr.Post("/count", [](const Request &req, Response &res) {
  9634. res.set_content(std::to_string(req.body.size()), "text/plain");
  9635. });
  9636. auto port = svr.bind_to_any_port(HOST);
  9637. ASSERT_LT(0, port);
  9638. thread t = thread([&] { svr.listen_after_bind(); });
  9639. auto se = detail::scope_exit([&] {
  9640. svr.stop();
  9641. t.join();
  9642. ASSERT_FALSE(svr.is_running());
  9643. });
  9644. svr.wait_until_ready();
  9645. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9646. "\r\nTransfer-Encoding: chunked\r\n"
  9647. "Connection: close\r\n\r\n";
  9648. for (auto i = 0; i < 4096; i++) {
  9649. req += "1;a=b\r\nx\r\n";
  9650. }
  9651. req += "0\r\n\r\n";
  9652. std::string res;
  9653. ASSERT_TRUE(send_request(5, req, &res, port));
  9654. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9655. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9656. }
  9657. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9658. Server svr;
  9659. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9660. auto i = new int(0);
  9661. res.set_header("Trailer", "X-Safe, X-Reflected");
  9662. res.set_chunked_content_provider(
  9663. "text/plain",
  9664. [i](size_t /*offset*/, DataSink &sink) {
  9665. if (*i == 0) {
  9666. sink.os << "body";
  9667. } else {
  9668. Headers trailer;
  9669. // A valid trailer that must survive.
  9670. trailer.emplace("X-Safe", "safe");
  9671. // Attacker-controlled value carrying CR/LF (response splitting).
  9672. trailer.emplace("X-Reflected",
  9673. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9674. // Attacker-controlled name carrying CR/LF.
  9675. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9676. sink.done_with_trailer(trailer);
  9677. }
  9678. (*i)++;
  9679. return true;
  9680. },
  9681. [i](bool /*success*/) { delete i; });
  9682. });
  9683. thread t = thread([&] { svr.listen(HOST, PORT); });
  9684. auto se = detail::scope_exit([&] {
  9685. svr.stop();
  9686. t.join();
  9687. ASSERT_FALSE(svr.is_running());
  9688. });
  9689. svr.wait_until_ready();
  9690. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9691. "Host: " + HOST +
  9692. "\r\n"
  9693. "Connection: close\r\n"
  9694. "\r\n";
  9695. std::string res;
  9696. ASSERT_TRUE(send_request(5, req, &res));
  9697. // The injected fields must not appear anywhere in the raw response.
  9698. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9699. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9700. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9701. // Invalid trailers are dropped entirely, matching set_header().
  9702. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9703. // The valid trailer still passes through.
  9704. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9705. }
  9706. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9707. // A custom header writer gets only the fields the default one writes
  9708. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9709. std::string s;
  9710. for (const auto &h : hdrs) {
  9711. s += h.first + ": " + h.second + "\r\n";
  9712. }
  9713. s += "\r\n";
  9714. return strm.write(s.data(), s.size());
  9715. };
  9716. for (auto custom_writer : {false, true}) {
  9717. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9718. Server svr;
  9719. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9720. svr.set_post_routing_handler([](const Request &, Response &res) {
  9721. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9722. });
  9723. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9724. // res.headers is a public field an application can populate directly,
  9725. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9726. // A valid header that must survive.
  9727. res.headers.emplace("X-Safe", "safe");
  9728. // Attacker-controlled value carrying CR/LF (response splitting).
  9729. res.headers.emplace("X-Reflected",
  9730. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9731. // Attacker-controlled name carrying CR/LF.
  9732. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9733. res.set_content("body", "text/plain");
  9734. });
  9735. thread t = thread([&] { svr.listen(HOST, PORT); });
  9736. auto se = detail::scope_exit([&] {
  9737. svr.stop();
  9738. t.join();
  9739. ASSERT_FALSE(svr.is_running());
  9740. });
  9741. svr.wait_until_ready();
  9742. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9743. "Host: " + HOST +
  9744. "\r\n"
  9745. "Connection: close\r\n"
  9746. "\r\n";
  9747. std::string res;
  9748. ASSERT_TRUE(send_request(5, req, &res));
  9749. // The injected fields must not appear anywhere in the raw response.
  9750. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9751. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9752. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9753. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9754. // Invalid headers are dropped entirely, matching set_header().
  9755. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9756. // The valid header still passes through.
  9757. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9758. }
  9759. }
  9760. // Forward declaration: in split builds split.py strips `inline` and moves the
  9761. // definition into httplib.cc, so detail::write_request_line is not visible from
  9762. // the public httplib.h. Re-declaring it here lets the tests link against the
  9763. // symbol in both header-only and split builds.
  9764. namespace httplib {
  9765. namespace detail {
  9766. ssize_t write_request_line(Stream &strm, const std::string &method,
  9767. const std::string &path);
  9768. } // namespace detail
  9769. } // namespace httplib
  9770. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9771. // A well-formed target is written verbatim.
  9772. {
  9773. detail::BufferStream strm;
  9774. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9775. EXPECT_GT(n, 0);
  9776. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9777. }
  9778. // A target carrying CR/LF, SP or other control octets must be rejected
  9779. // before anything reaches the wire, otherwise it splits the request line and
  9780. // injects a header or a whole request.
  9781. const std::string evil_targets[] = {
  9782. "/a\r\nInjected: pwned",
  9783. "/a\rInjected",
  9784. "/a\nInjected",
  9785. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9786. "/a b",
  9787. "/a\tb",
  9788. "/a\x7f",
  9789. };
  9790. for (const auto &evil : evil_targets) {
  9791. detail::BufferStream strm;
  9792. auto n = detail::write_request_line(strm, "GET", evil);
  9793. EXPECT_LT(n, 0);
  9794. EXPECT_TRUE(strm.get_buffer().empty());
  9795. }
  9796. }
  9797. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9798. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9799. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9800. // target reaches write_request. The client must fail cleanly with
  9801. // Error::Write instead of putting a request-line-less, header-injecting
  9802. // request on the wire.
  9803. Server svr;
  9804. svr.Get("/a", [](const Request &, Response &res) {
  9805. res.set_content("ok", "text/plain");
  9806. });
  9807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9808. auto se = detail::scope_exit([&] {
  9809. svr.stop();
  9810. thread.join();
  9811. ASSERT_FALSE(svr.is_running());
  9812. });
  9813. svr.wait_until_ready();
  9814. {
  9815. Client cli(HOST, PORT);
  9816. cli.set_path_encode(false);
  9817. // The request is rejected before anything is written, so the connection
  9818. // stays silent and the subsequent response read would otherwise block for
  9819. // the full default read timeout. Shorten it -- the assertion is on the
  9820. // error, not the timeout.
  9821. cli.set_read_timeout(1, 0);
  9822. auto res = cli.Get("/a\r\nInjected: pwned");
  9823. EXPECT_FALSE(res);
  9824. EXPECT_EQ(Error::Write, res.error());
  9825. }
  9826. }
  9827. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9828. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9829. // including extension methods.
  9830. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9831. for (const auto &method : good_methods) {
  9832. detail::BufferStream strm;
  9833. auto n = detail::write_request_line(strm, method, "/");
  9834. EXPECT_GT(n, 0);
  9835. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9836. }
  9837. // A method carrying CR/LF would split the request line and smuggle a whole
  9838. // request ahead of the real one. A space or an empty method corrupts the
  9839. // request line. All must be rejected before anything reaches the wire.
  9840. const std::string evil_methods[] = {
  9841. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9842. "GET\r\nInjected: pwned",
  9843. "GET\r",
  9844. "GET\n",
  9845. "GE T",
  9846. "",
  9847. };
  9848. for (const auto &evil : evil_methods) {
  9849. detail::BufferStream strm;
  9850. auto n = detail::write_request_line(strm, evil, "/");
  9851. EXPECT_LT(n, 0);
  9852. EXPECT_TRUE(strm.get_buffer().empty());
  9853. }
  9854. }
  9855. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9856. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9857. // through Client::send must fail with Error::Write and no request, neither
  9858. // the smuggled one nor the real one, may reach the server.
  9859. Server svr;
  9860. std::atomic<int> request_count(0);
  9861. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9862. request_count++;
  9863. res.status = StatusCode::OK_200;
  9864. return Server::HandlerResponse::Handled;
  9865. });
  9866. auto port = svr.bind_to_any_port(HOST);
  9867. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9868. auto se = detail::scope_exit([&] {
  9869. svr.stop();
  9870. thread.join();
  9871. ASSERT_FALSE(svr.is_running());
  9872. });
  9873. svr.wait_until_ready();
  9874. {
  9875. Client cli(HOST, port);
  9876. const std::string evil_methods[] = {
  9877. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9878. "GE T",
  9879. "",
  9880. };
  9881. for (const auto &evil : evil_methods) {
  9882. Request req;
  9883. req.method = evil;
  9884. req.path = "/";
  9885. auto res = cli.send(req);
  9886. EXPECT_FALSE(res);
  9887. EXPECT_EQ(Error::Write, res.error());
  9888. }
  9889. auto handle =
  9890. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9891. EXPECT_FALSE(handle.is_valid());
  9892. EXPECT_EQ(Error::Write, handle.error);
  9893. // A valid request on the same client still goes through.
  9894. auto res = cli.Get("/");
  9895. ASSERT_TRUE(res);
  9896. EXPECT_EQ(StatusCode::OK_200, res->status);
  9897. }
  9898. EXPECT_EQ(1, request_count.load());
  9899. }
  9900. // Sends a raw request and verifies that there isn't a crash or exception.
  9901. static void test_raw_request(const std::string &req,
  9902. std::string *out = nullptr) {
  9903. Server svr;
  9904. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9905. res.set_content("ok", "text/plain");
  9906. });
  9907. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9908. res.set_content("ok", "text/plain");
  9909. });
  9910. svr.Get("/header_field_value_check",
  9911. [&](const Request & /*req*/, Response &res) {
  9912. res.set_content("ok", "text/plain");
  9913. });
  9914. svr.CustomRoute("PROPFIND", "/dav",
  9915. [&](const Request & /*req*/, Response &res) {
  9916. res.status = StatusCode::MultiStatus_207;
  9917. });
  9918. // Server read timeout must be longer than the client read timeout for the
  9919. // bug to reproduce, probably to force the server to process a request
  9920. // without a trailing blank line.
  9921. const time_t client_read_timeout_sec = 1;
  9922. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9923. bool listen_thread_ok = false;
  9924. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9925. auto se = detail::scope_exit([&] {
  9926. svr.stop();
  9927. t.join();
  9928. ASSERT_FALSE(svr.is_running());
  9929. EXPECT_TRUE(listen_thread_ok);
  9930. });
  9931. svr.wait_until_ready();
  9932. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9933. }
  9934. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9935. // A certain header line causes an exception if the header property is parsed
  9936. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9937. test_raw_request(
  9938. "GET /hi HTTP/1.1\r\n"
  9939. " : "
  9940. " "
  9941. " ");
  9942. }
  9943. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9944. // A certain header line causes an exception if the header property *name* is
  9945. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9946. // greedy matcher and requires backtracking when there are a lot of ":"
  9947. // characters.
  9948. // This occurs with libc++ but not libstdc++.
  9949. test_raw_request(
  9950. "GET /hi HTTP/1.1\r\n"
  9951. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9952. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9953. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9954. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9955. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9956. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9957. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9958. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9959. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9960. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9961. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9962. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9963. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9964. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9965. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9966. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9967. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9968. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9969. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9970. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9971. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9972. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9973. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9974. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9975. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9976. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9977. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9978. "&&&%%%");
  9979. }
  9980. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9981. // Make sure this doesn't crash the server.
  9982. // In a previous version of the header line regex, the "\r" rendered the line
  9983. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9984. // a new position where the leading white space ended and the field value
  9985. // began.
  9986. // The crash occurs with libc++ but not libstdc++.
  9987. test_raw_request("GET /hi HTTP/1.1\r\n"
  9988. "a:" +
  9989. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9990. "\r\n"
  9991. "\r\n");
  9992. }
  9993. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9994. const char *rejected[] = {
  9995. // RFC 9112 §3: one SP between the parts, and nothing else
  9996. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9997. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9998. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9999. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10000. // A request-target has no fragment
  10001. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10002. // An HTTP/1.1 request needs a Host
  10003. "GET /hi HTTP/1.1\r\n\r\n",
  10004. };
  10005. for (auto request : rejected) {
  10006. std::string out;
  10007. test_raw_request(request, &out);
  10008. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10009. }
  10010. std::string out;
  10011. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10012. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10013. }
  10014. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10015. // RFC 9112 §6.1
  10016. const char *requests[] = {
  10017. "PUT /put_hi HTTP/1.1\r\n"
  10018. "Host: localhost\r\n"
  10019. "Content-Length: 0\r\n"
  10020. "Transfer-Encoding: chunked\r\n"
  10021. "\r\n"
  10022. "0\r\n\r\n",
  10023. "PUT /put_hi HTTP/1.0\r\n"
  10024. "Connection: keep-alive\r\n"
  10025. "Transfer-Encoding: chunked\r\n"
  10026. "\r\n"
  10027. "0\r\n\r\n",
  10028. };
  10029. for (auto request : requests) {
  10030. std::string out;
  10031. test_raw_request(request, &out);
  10032. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10033. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10034. }
  10035. }
  10036. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10037. std::string out;
  10038. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10039. "Content-Type: text/plain\r\n"
  10040. "Transfer-Encoding: chunked\r\n"
  10041. "\r\n"
  10042. "nothex\r\n",
  10043. &out);
  10044. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10045. }
  10046. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10047. std::string out;
  10048. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10049. "Content-Type: text/plain\r\n"
  10050. "Transfer-Encoding: chunked\r\n"
  10051. "\r\n"
  10052. "3\r\n"
  10053. "xyz\r\n"
  10054. "NaN\r\n",
  10055. &out);
  10056. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10057. }
  10058. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10059. std::string out;
  10060. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10061. "Content-Type: text/plain\r\n"
  10062. "Transfer-Encoding: chunked\r\n"
  10063. "\r\n"
  10064. // Length is too large for 64 bits.
  10065. "1ffffffffffffffff\r\n"
  10066. "xyz\r\n",
  10067. &out);
  10068. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10069. }
  10070. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10071. test_raw_request("GET /hi HTTP/1.1\r\n"
  10072. "Content-Type: text/plain\r\n\r");
  10073. }
  10074. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10075. std::string out;
  10076. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10077. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10078. }
  10079. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10080. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10081. std::string out;
  10082. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10083. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10084. }
  10085. }
  10086. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10087. std::string out;
  10088. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10089. "Host: localhost\r\n"
  10090. "Connection: close\r\n\r\n",
  10091. &out);
  10092. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10093. }
  10094. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10095. Server svr;
  10096. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10097. EXPECT_TRUE(!req.remote_addr.empty());
  10098. });
  10099. thread t = thread([&] { svr.listen(HOST, PORT); });
  10100. auto se = detail::scope_exit([&] {
  10101. svr.stop();
  10102. t.join();
  10103. ASSERT_FALSE(svr.is_running());
  10104. });
  10105. svr.wait_until_ready();
  10106. // Send an invalid request line to trigger Bad Request
  10107. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10108. std::string out;
  10109. ASSERT_TRUE(send_request(5, bad_req, &out));
  10110. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10111. }
  10112. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10113. // answered right away rather than blocking on a read that waits for EOF.
  10114. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10115. std::string out;
  10116. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10117. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10118. }
  10119. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10120. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10121. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10122. for (const auto *method : methods) {
  10123. Server svr;
  10124. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10125. EXPECT_FALSE(svr.is_valid()) << method;
  10126. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10127. }
  10128. }
  10129. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10130. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10131. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10132. for (const auto *method : methods) {
  10133. Server svr;
  10134. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10135. EXPECT_FALSE(svr.is_valid()) << method;
  10136. }
  10137. }
  10138. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10139. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10140. "COPY", "MOVE", "LOCK",
  10141. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10142. Server svr;
  10143. for (const auto *method : methods) {
  10144. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10145. }
  10146. EXPECT_TRUE(svr.is_valid());
  10147. }
  10148. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10149. Server svr;
  10150. svr.CustomRoute("POST", "/x",
  10151. [](const Request &, Response &, const ContentReader &) {});
  10152. EXPECT_FALSE(svr.is_valid());
  10153. }
  10154. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10155. Server svr;
  10156. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10157. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10158. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10159. EXPECT_FALSE(svr.is_valid());
  10160. }
  10161. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10162. Server svr;
  10163. auto captured = Error::Success;
  10164. svr.set_error_logger(
  10165. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10166. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10167. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10168. }
  10169. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10170. std::string out;
  10171. std::string request(
  10172. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10173. test_raw_request(request, &out);
  10174. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10175. }
  10176. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10177. std::string out;
  10178. std::string request(
  10179. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10180. test_raw_request(request, &out);
  10181. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10182. }
  10183. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10184. std::string out;
  10185. std::string request(
  10186. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10187. test_raw_request(request, &out);
  10188. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10189. }
  10190. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10191. std::string out;
  10192. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10193. "Host: localhost\r\n"
  10194. "Test: \r\n\r\n",
  10195. &out);
  10196. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10197. }
  10198. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10199. Server svr;
  10200. std::string x_custom;
  10201. std::string cookie;
  10202. std::string xff;
  10203. std::string x_unicode;
  10204. std::string x_iis;
  10205. svr.Get("/check", [&](const Request &req, Response &res) {
  10206. x_custom = req.get_header_value("X-Custom");
  10207. cookie = req.get_header_value("Cookie");
  10208. xff = req.get_header_value("X-Forwarded-For");
  10209. x_unicode = req.get_header_value("X-Unicode");
  10210. x_iis = req.get_header_value("X-IIS");
  10211. res.set_content("ok", "text/plain");
  10212. });
  10213. thread t = thread([&] { svr.listen(HOST, PORT); });
  10214. auto se = detail::scope_exit([&] {
  10215. svr.stop();
  10216. t.join();
  10217. ASSERT_FALSE(svr.is_running());
  10218. });
  10219. svr.wait_until_ready();
  10220. const std::string req = "GET /check HTTP/1.1\r\n"
  10221. "Host: localhost\r\n"
  10222. "X-Custom: a%0D%0AInjected: b\r\n"
  10223. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10224. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10225. "X-Unicode: %E3%81%82\r\n"
  10226. "X-IIS: %u00E9\r\n"
  10227. "Connection: close\r\n"
  10228. "\r\n";
  10229. std::string res;
  10230. ASSERT_TRUE(send_request(5, req, &res));
  10231. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10232. // Every value must be returned verbatim (wire form), with no decoding.
  10233. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10234. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10235. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10236. EXPECT_EQ("%E3%81%82", x_unicode);
  10237. EXPECT_EQ("%u00E9", x_iis);
  10238. }
  10239. // Applications that previously relied on automatic percent-decoding can
  10240. // reproduce the old behavior by explicitly calling decode_path_component()
  10241. // or, for RFC 3986 conformance, decode_uri_component().
  10242. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10243. Server svr;
  10244. std::string decoded;
  10245. svr.Get("/check", [&](const Request &req, Response &res) {
  10246. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10247. res.set_content("ok", "text/plain");
  10248. });
  10249. thread t = thread([&] { svr.listen(HOST, PORT); });
  10250. auto se = detail::scope_exit([&] {
  10251. svr.stop();
  10252. t.join();
  10253. ASSERT_FALSE(svr.is_running());
  10254. });
  10255. svr.wait_until_ready();
  10256. const std::string req = "GET /check HTTP/1.1\r\n"
  10257. "Host: localhost\r\n"
  10258. "X-Custom: hello%20world\r\n"
  10259. "Connection: close\r\n"
  10260. "\r\n";
  10261. std::string res;
  10262. ASSERT_TRUE(send_request(5, req, &res));
  10263. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10264. EXPECT_EQ("hello world", decoded);
  10265. }
  10266. // Regression test for #2033. Browsers send Referer values that include
  10267. // percent-encoded characters such as %0A inside the URL. Decoding the
  10268. // header value would either trip the post-decode CR/LF/NUL guard (the
  10269. // original bug, returning 400) or, after that guard was relaxed, silently
  10270. // store a literal LF — both unacceptable. The wire form must round-trip.
  10271. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10272. Server svr;
  10273. std::string referer;
  10274. svr.Get("/check", [&](const Request &req, Response &res) {
  10275. referer = req.get_header_value("Referer");
  10276. res.set_content("ok", "text/plain");
  10277. });
  10278. thread t = thread([&] { svr.listen(HOST, PORT); });
  10279. auto se = detail::scope_exit([&] {
  10280. svr.stop();
  10281. t.join();
  10282. ASSERT_FALSE(svr.is_running());
  10283. });
  10284. svr.wait_until_ready();
  10285. const std::string req = "GET /check HTTP/1.1\r\n"
  10286. "Host: localhost\r\n"
  10287. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10288. "Connection: close\r\n"
  10289. "\r\n";
  10290. std::string res;
  10291. ASSERT_TRUE(send_request(5, req, &res));
  10292. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10293. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10294. }
  10295. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10296. Server svr;
  10297. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10298. res.set_header("Cache-Control", "no-cache");
  10299. res.set_chunked_content_provider(
  10300. "text/event-stream", [](size_t offset, DataSink &sink) {
  10301. std::string s = "data:";
  10302. s += std::to_string(offset);
  10303. s += "\n\n";
  10304. auto ret = sink.write(s.data(), s.size());
  10305. EXPECT_TRUE(ret);
  10306. std::this_thread::sleep_for(std::chrono::seconds(1));
  10307. return true;
  10308. });
  10309. });
  10310. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10311. svr.wait_until_ready();
  10312. Client client(HOST, PORT);
  10313. const Headers headers = {{"Accept", "text/event-stream"}};
  10314. auto get_thread = std::thread([&client, &headers]() {
  10315. auto res = client.Get(
  10316. "/events", headers,
  10317. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10318. });
  10319. auto se = detail::scope_exit([&] {
  10320. svr.stop();
  10321. get_thread.join();
  10322. listen_thread.join();
  10323. ASSERT_FALSE(svr.is_running());
  10324. });
  10325. // Give GET time to get a few messages.
  10326. std::this_thread::sleep_for(std::chrono::seconds(2));
  10327. }
  10328. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10329. httplib::Server svr;
  10330. svr.Post("/hi",
  10331. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10332. res.status = StatusCode::OK_200;
  10333. });
  10334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10335. svr.wait_until_ready();
  10336. Client cli(HOST, PORT);
  10337. auto res = cli.Post("/hi", "data", "text/plain");
  10338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10339. EXPECT_EQ(StatusCode::OK_200, res->status);
  10340. svr.stop();
  10341. thread.join();
  10342. ASSERT_FALSE(svr.is_running());
  10343. res = cli.Post("/hi", "data", "text/plain");
  10344. ASSERT_FALSE(res);
  10345. }
  10346. TEST(ServerStopTest, ListenFailure) {
  10347. Server svr;
  10348. auto t = thread([&]() {
  10349. auto ret = svr.listen("????", PORT);
  10350. EXPECT_FALSE(ret);
  10351. });
  10352. svr.wait_until_ready();
  10353. svr.stop();
  10354. t.join();
  10355. }
  10356. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10357. TEST(ServerStopTest, Decommision) {
  10358. Server svr;
  10359. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10360. for (int i = 0; i < 4; i++) {
  10361. auto is_even = !(i % 2);
  10362. std::thread t{[&] {
  10363. try {
  10364. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10365. if (is_even) {
  10366. throw std::runtime_error("Some thing that happens to go wrong.");
  10367. }
  10368. svr.listen(HOST, PORT);
  10369. } catch (...) { svr.decommission(); }
  10370. }};
  10371. svr.wait_until_ready();
  10372. // Server is up
  10373. {
  10374. Client cli(HOST, PORT);
  10375. auto res = cli.Get("/hi");
  10376. if (is_even) {
  10377. EXPECT_FALSE(res);
  10378. } else {
  10379. EXPECT_TRUE(res);
  10380. EXPECT_EQ("hi...", res->body);
  10381. }
  10382. }
  10383. svr.stop();
  10384. t.join();
  10385. // Server is down...
  10386. {
  10387. Client cli(HOST, PORT);
  10388. auto res = cli.Get("/hi");
  10389. EXPECT_FALSE(res);
  10390. }
  10391. }
  10392. }
  10393. #endif
  10394. // Helper function for string body upload progress tests
  10395. template <typename SetupHandler, typename ClientCall>
  10396. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10397. ClientCall &&client_call,
  10398. const string &body) {
  10399. Server svr;
  10400. setup_handler(svr);
  10401. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10402. auto se = detail::scope_exit([&] {
  10403. svr.stop();
  10404. t.join();
  10405. });
  10406. svr.wait_until_ready();
  10407. Client cli(HOST, PORT);
  10408. vector<uint64_t> progress_values;
  10409. bool progress_called = false;
  10410. auto res =
  10411. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10412. progress_values.push_back(current);
  10413. progress_called = true;
  10414. return true;
  10415. });
  10416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10417. EXPECT_EQ(200, res->status);
  10418. EXPECT_TRUE(progress_called);
  10419. }
  10420. TEST(UploadProgressTest, PostStringBodyBasic) {
  10421. TestStringBodyUploadProgress(
  10422. [](Server &svr) {
  10423. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10424. res.set_content("received", "text/plain");
  10425. });
  10426. },
  10427. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10428. return cli.Post("/test", body, "text/plain", progress_callback);
  10429. },
  10430. "test data for upload progress");
  10431. }
  10432. TEST(UploadProgressTest, PutStringBodyBasic) {
  10433. TestStringBodyUploadProgress(
  10434. [](Server &svr) {
  10435. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10436. res.set_content("put received", "text/plain");
  10437. });
  10438. },
  10439. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10440. return cli.Put("/test", body, "text/plain", progress_callback);
  10441. },
  10442. "put test data for upload progress");
  10443. }
  10444. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10445. TestStringBodyUploadProgress(
  10446. [](Server &svr) {
  10447. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10448. res.set_content("patch received", "text/plain");
  10449. });
  10450. },
  10451. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10452. return cli.Patch("/test", body, "text/plain", progress_callback);
  10453. },
  10454. "patch test data for upload progress");
  10455. }
  10456. // Helper function for content provider upload progress tests
  10457. template <typename SetupHandler, typename ClientCall>
  10458. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10459. ClientCall &&client_call) {
  10460. Server svr;
  10461. setup_handler(svr);
  10462. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10463. auto se = detail::scope_exit([&] {
  10464. svr.stop();
  10465. t.join();
  10466. });
  10467. svr.wait_until_ready();
  10468. Client cli(HOST, PORT);
  10469. vector<uint64_t> progress_values;
  10470. auto res =
  10471. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10472. progress_values.push_back(current);
  10473. return true;
  10474. });
  10475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10476. EXPECT_EQ(200, res->status);
  10477. EXPECT_FALSE(progress_values.empty());
  10478. }
  10479. TEST(UploadProgressTest, PostContentProviderProgress) {
  10480. TestContentProviderUploadProgress(
  10481. [](Server &svr) {
  10482. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10483. res.set_content("provider received", "text/plain");
  10484. });
  10485. },
  10486. [](Client &cli, UploadProgress progress_callback) {
  10487. return cli.Post(
  10488. "/test", 9,
  10489. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10490. sink.os << "test data";
  10491. return true;
  10492. },
  10493. "text/plain", progress_callback);
  10494. });
  10495. }
  10496. // Helper function for multipart upload progress tests
  10497. template <typename SetupHandler, typename ClientCall>
  10498. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10499. ClientCall &&client_call,
  10500. const string &endpoint) {
  10501. Server svr;
  10502. setup_handler(svr);
  10503. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10504. auto se = detail::scope_exit([&] {
  10505. svr.stop();
  10506. t.join();
  10507. });
  10508. svr.wait_until_ready();
  10509. Client cli(HOST, PORT);
  10510. vector<uint64_t> progress_values;
  10511. UploadFormDataItems items = {
  10512. {"field1", "value1", "", ""},
  10513. {"field2", "longer value for progress tracking test", "", ""},
  10514. {"file1", "file content data for upload progress", "test.txt",
  10515. "text/plain"}};
  10516. auto res = client_call(cli, endpoint, items,
  10517. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10518. progress_values.push_back(current);
  10519. return true;
  10520. });
  10521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10522. EXPECT_EQ(200, res->status);
  10523. EXPECT_FALSE(progress_values.empty());
  10524. }
  10525. TEST(UploadProgressTest, PostMultipartProgress) {
  10526. TestMultipartUploadProgress(
  10527. [](Server &svr) {
  10528. svr.Post("/multipart", [](const Request &req, Response &res) {
  10529. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10530. res.set_content("multipart received", "text/plain");
  10531. });
  10532. },
  10533. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10534. UploadProgress progress_callback) {
  10535. return cli.Post(endpoint, items, progress_callback);
  10536. },
  10537. "/multipart");
  10538. }
  10539. // Helper function for basic download progress tests
  10540. template <typename SetupHandler, typename ClientCall>
  10541. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10542. ClientCall &&client_call, const string &endpoint,
  10543. size_t expected_content_size) {
  10544. Server svr;
  10545. setup_handler(svr);
  10546. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10547. auto se = detail::scope_exit([&] {
  10548. svr.stop();
  10549. t.join();
  10550. });
  10551. svr.wait_until_ready();
  10552. Client cli(HOST, PORT);
  10553. vector<uint64_t> progress_values;
  10554. auto res = client_call(cli, endpoint,
  10555. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10556. progress_values.push_back(current);
  10557. return true;
  10558. });
  10559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10560. EXPECT_EQ(200, res->status);
  10561. EXPECT_FALSE(progress_values.empty());
  10562. EXPECT_EQ(expected_content_size, res->body.size());
  10563. }
  10564. TEST(DownloadProgressTest, GetBasic) {
  10565. TestBasicDownloadProgress(
  10566. [](Server &svr) {
  10567. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10568. string content(1000, 'D');
  10569. res.set_content(content, "text/plain");
  10570. });
  10571. },
  10572. [](Client &cli, const string &endpoint,
  10573. DownloadProgress progress_callback) {
  10574. return cli.Get(endpoint, progress_callback);
  10575. },
  10576. "/download", 1000u);
  10577. }
  10578. // Helper function for content receiver download progress tests
  10579. template <typename SetupHandler, typename ClientCall>
  10580. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10581. ClientCall &&client_call,
  10582. const string &endpoint,
  10583. size_t expected_content_size) {
  10584. Server svr;
  10585. setup_handler(svr);
  10586. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10587. auto se = detail::scope_exit([&] {
  10588. svr.stop();
  10589. t.join();
  10590. });
  10591. svr.wait_until_ready();
  10592. Client cli(HOST, PORT);
  10593. vector<uint64_t> progress_values;
  10594. string received_body;
  10595. auto res = client_call(
  10596. cli, endpoint,
  10597. [&](const char *data, size_t data_length) -> bool {
  10598. received_body.append(data, data_length);
  10599. return true;
  10600. },
  10601. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10602. progress_values.push_back(current);
  10603. return true;
  10604. });
  10605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10606. EXPECT_EQ(200, res->status);
  10607. EXPECT_FALSE(progress_values.empty());
  10608. EXPECT_EQ(expected_content_size, received_body.size());
  10609. EXPECT_TRUE(res->body.empty());
  10610. }
  10611. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10612. TestContentReceiverDownloadProgress(
  10613. [](Server &svr) {
  10614. svr.Get("/download-receiver",
  10615. [](const Request & /*req*/, Response &res) {
  10616. string content(2000, 'R');
  10617. res.set_content(content, "text/plain");
  10618. });
  10619. },
  10620. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10621. DownloadProgress progress_callback) {
  10622. return cli.Get(endpoint, content_receiver, progress_callback);
  10623. },
  10624. "/download-receiver", 2000u);
  10625. }
  10626. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10627. // A provider reaching a pass with nothing to hand over - an empty buffer
  10628. // popped off a queue, say - must not be taken to mean the body is finished.
  10629. // It used to end the loop with the terminating chunk unwritten while the
  10630. // server still considered the response complete, so the peer waited for an
  10631. // end that never arrived.
  10632. Server svr;
  10633. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10634. auto step = std::make_shared<int>(0);
  10635. res.set_chunked_content_provider("text/plain",
  10636. [step](size_t /*offset*/, DataSink &sink) {
  10637. switch ((*step)++) {
  10638. case 0: sink.write("", 0); break;
  10639. case 1: sink.write("hello", 5); break;
  10640. default: sink.done(); break;
  10641. }
  10642. return true;
  10643. });
  10644. });
  10645. auto port = svr.bind_to_any_port(HOST);
  10646. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10647. auto listen_se = detail::scope_exit([&] {
  10648. svr.stop();
  10649. listen_thread.join();
  10650. ASSERT_FALSE(svr.is_running());
  10651. });
  10652. svr.wait_until_ready();
  10653. Client cli(HOST, port);
  10654. // Without the fix the body is never terminated, so bound the wait rather
  10655. // than letting the test hang on the default read timeout.
  10656. cli.set_read_timeout(5, 0);
  10657. auto res = cli.Get("/stream");
  10658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10659. EXPECT_EQ(StatusCode::OK_200, res->status);
  10660. EXPECT_EQ("hello", res->body);
  10661. }
  10662. TEST(StreamingTest, NoContentLengthStreaming) {
  10663. Server svr;
  10664. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10665. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10666. if (offset < 6) {
  10667. sink.os << (offset < 3 ? "a" : "b");
  10668. } else {
  10669. sink.done();
  10670. }
  10671. return true;
  10672. });
  10673. });
  10674. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10675. auto listen_se = detail::scope_exit([&] {
  10676. svr.stop();
  10677. listen_thread.join();
  10678. ASSERT_FALSE(svr.is_running());
  10679. });
  10680. svr.wait_until_ready();
  10681. Client client(HOST, PORT);
  10682. auto get_thread = std::thread([&client]() {
  10683. std::string s;
  10684. auto res =
  10685. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10686. s += std::string(data, len);
  10687. return true;
  10688. });
  10689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10690. EXPECT_EQ(StatusCode::OK_200, res->status);
  10691. EXPECT_EQ("aaabbb", s);
  10692. });
  10693. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10694. // Give GET time to get a few messages.
  10695. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10696. }
  10697. TEST(MountTest, Unmount) {
  10698. Server svr;
  10699. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10700. auto se = detail::scope_exit([&] {
  10701. svr.stop();
  10702. listen_thread.join();
  10703. ASSERT_FALSE(svr.is_running());
  10704. });
  10705. svr.wait_until_ready();
  10706. Client cli("localhost", PORT);
  10707. svr.set_mount_point("/mount2", "./www2");
  10708. auto res = cli.Get("/");
  10709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10710. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10711. res = cli.Get("/mount2/dir/test.html");
  10712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10713. EXPECT_EQ(StatusCode::OK_200, res->status);
  10714. svr.set_mount_point("/", "./www");
  10715. res = cli.Get("/dir/");
  10716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10717. EXPECT_EQ(StatusCode::OK_200, res->status);
  10718. svr.remove_mount_point("/");
  10719. res = cli.Get("/dir/");
  10720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10721. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10722. svr.remove_mount_point("/mount2");
  10723. res = cli.Get("/mount2/dir/test.html");
  10724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10725. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10726. }
  10727. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10728. Server svr;
  10729. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10730. svr.Get("/api/hello", [](const Request &, Response &res) {
  10731. res.set_content("api", "text/plain");
  10732. });
  10733. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10734. auto se = detail::scope_exit([&] {
  10735. svr.stop();
  10736. listen_thread.join();
  10737. ASSERT_FALSE(svr.is_running());
  10738. });
  10739. svr.wait_until_ready();
  10740. Client cli(HOST, PORT);
  10741. auto res = cli.Get("/dir/test.html");
  10742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10743. EXPECT_EQ(StatusCode::OK_200, res->status);
  10744. res = cli.Get("/api/hello");
  10745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10746. EXPECT_EQ(StatusCode::OK_200, res->status);
  10747. EXPECT_EQ("api", res->body);
  10748. }
  10749. TEST(MountTest, PathSegmentBoundary) {
  10750. Server svr;
  10751. svr.set_mount_point("/mount2", "./www2");
  10752. svr.set_mount_point("/", "./www");
  10753. auto port = svr.bind_to_any_port(HOST);
  10754. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10755. auto se = detail::scope_exit([&] {
  10756. svr.stop();
  10757. listen_thread.join();
  10758. ASSERT_FALSE(svr.is_running());
  10759. });
  10760. svr.wait_until_ready();
  10761. Client cli(HOST, port);
  10762. auto res = cli.Get("/mount2/dir/test.html");
  10763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10764. EXPECT_EQ(StatusCode::OK_200, res->status);
  10765. // "/mount2" must not match part-way through a path segment.
  10766. res = cli.Get("/mount2dir/test.html");
  10767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10768. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10769. // A mount point ending in '/' keeps matching every path below it.
  10770. res = cli.Get("/dir/test.html");
  10771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10772. EXPECT_EQ(StatusCode::OK_200, res->status);
  10773. }
  10774. TEST(MountTest, Redicect) {
  10775. Server svr;
  10776. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10777. auto se = detail::scope_exit([&] {
  10778. svr.stop();
  10779. listen_thread.join();
  10780. ASSERT_FALSE(svr.is_running());
  10781. });
  10782. svr.set_mount_point("/", "./www");
  10783. svr.wait_until_ready();
  10784. Client cli("localhost", PORT);
  10785. auto res = cli.Get("/dir/");
  10786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10787. EXPECT_EQ(StatusCode::OK_200, res->status);
  10788. res = cli.Get("/dir");
  10789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10790. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10791. res = cli.Get("/file");
  10792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10793. EXPECT_EQ(StatusCode::OK_200, res->status);
  10794. res = cli.Get("/file/");
  10795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10796. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10797. cli.set_follow_location(true);
  10798. res = cli.Get("/dir");
  10799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10800. EXPECT_EQ(StatusCode::OK_200, res->status);
  10801. }
  10802. TEST(MountTest, MultibytesPathName) {
  10803. Server svr;
  10804. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10805. auto se = detail::scope_exit([&] {
  10806. svr.stop();
  10807. listen_thread.join();
  10808. ASSERT_FALSE(svr.is_running());
  10809. });
  10810. svr.set_mount_point("/", "./www");
  10811. svr.wait_until_ready();
  10812. Client cli("localhost", PORT);
  10813. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10815. EXPECT_EQ(StatusCode::OK_200, res->status);
  10816. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10817. }
  10818. // A mount point serves no path with an empty segment or one ending in '.' or
  10819. // a space, so a guard in the pre-routing handler sees the path of every file
  10820. // that is served
  10821. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10822. Server svr;
  10823. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10824. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10825. if (req.path == "/dir/test.html") {
  10826. res.status = StatusCode::Unauthorized_401;
  10827. return Server::HandlerResponse::Handled;
  10828. }
  10829. return Server::HandlerResponse::Unhandled;
  10830. });
  10831. auto port = svr.bind_to_any_port(HOST);
  10832. ASSERT_LT(0, port);
  10833. thread t = thread([&] { svr.listen_after_bind(); });
  10834. auto se = detail::scope_exit([&] {
  10835. svr.stop();
  10836. t.join();
  10837. ASSERT_FALSE(svr.is_running());
  10838. });
  10839. svr.wait_until_ready();
  10840. Client cli(HOST, port);
  10841. for (auto path :
  10842. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10843. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10844. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  10845. "/dir/test.html%3A%3A$DATA"}) {
  10846. SCOPED_TRACE(path);
  10847. auto res = cli.Get(path);
  10848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10850. }
  10851. }
  10852. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10853. Server svr;
  10854. svr.set_mount_point("/", "./www");
  10855. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10856. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10857. auto port = svr.bind_to_any_port(HOST);
  10858. ASSERT_GT(port, 0);
  10859. thread t = thread([&] { svr.listen_after_bind(); });
  10860. auto se = detail::scope_exit([&] {
  10861. svr.stop();
  10862. t.join();
  10863. ASSERT_FALSE(svr.is_running());
  10864. });
  10865. svr.wait_until_ready();
  10866. Client cli(HOST, port);
  10867. auto res = cli.Get("/dir/test.abcde");
  10868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10869. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10870. res = cli.Get("/dir/test.html");
  10871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10872. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10873. }
  10874. #ifdef _WIN32
  10875. // Issue #2435: mmap::open() must succeed even when another handle holds
  10876. // the file open for writing (e.g. an active log file).
  10877. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10878. const char *path = "mmap_concurrent_writer_test.txt";
  10879. const char *content = "hello";
  10880. {
  10881. std::ofstream f(path, std::ios::binary);
  10882. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10883. }
  10884. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10885. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10886. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10887. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10888. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10889. detail::mmap m(path);
  10890. ASSERT_TRUE(m.is_open());
  10891. EXPECT_EQ(strlen(content), m.size());
  10892. char buf[8];
  10893. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10894. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10895. }
  10896. #endif
  10897. #ifndef _WIN32
  10898. // A directory or a device has no size to serve.
  10899. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10900. const char *path = "./mmap_not_regular_test_dir";
  10901. ASSERT_EQ(0, ::mkdir(path, 0755));
  10902. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10903. for (auto p : {path, "/dev/null"}) {
  10904. detail::mmap m(p);
  10905. EXPECT_FALSE(m.is_open()) << p;
  10906. EXPECT_EQ(0U, m.size()) << p;
  10907. }
  10908. Server svr;
  10909. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10910. res.set_file_content("/dev/null");
  10911. });
  10912. auto port = svr.bind_to_any_port(HOST);
  10913. thread t = thread([&] { svr.listen_after_bind(); });
  10914. auto se = detail::scope_exit([&] {
  10915. svr.stop();
  10916. t.join();
  10917. });
  10918. svr.wait_until_ready();
  10919. auto res = Client(HOST, port).Get("/null");
  10920. ASSERT_TRUE(res);
  10921. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10922. }
  10923. #endif
  10924. #ifdef __linux__
  10925. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10926. TEST(MmapTest, FileIsNotMapped) {
  10927. const char *path = "mmap_not_mapped_test.txt";
  10928. {
  10929. std::ofstream f(path, std::ios::binary);
  10930. f << "hello";
  10931. }
  10932. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10933. detail::mmap m(path);
  10934. ASSERT_TRUE(m.is_open());
  10935. std::ifstream maps("/proc/self/maps");
  10936. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10937. std::istreambuf_iterator<char>());
  10938. EXPECT_EQ(std::string::npos, mappings.find(path));
  10939. }
  10940. #endif
  10941. TEST(KeepAliveTest, ReadTimeout) {
  10942. Server svr;
  10943. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10944. std::this_thread::sleep_for(std::chrono::seconds(2));
  10945. res.set_content("a", "text/plain");
  10946. });
  10947. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10948. res.set_content("b", "text/plain");
  10949. });
  10950. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", 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("localhost", PORT);
  10958. cli.set_keep_alive(true);
  10959. cli.set_read_timeout(std::chrono::seconds(1));
  10960. auto resa = cli.Get("/a");
  10961. ASSERT_FALSE(resa);
  10962. EXPECT_EQ(Error::Read, resa.error());
  10963. auto resb = cli.Get("/b");
  10964. ASSERT_TRUE(resb);
  10965. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10966. EXPECT_EQ("b", resb->body);
  10967. }
  10968. TEST(KeepAliveTest, MaxCount) {
  10969. size_t keep_alive_max_count = 3;
  10970. Server svr;
  10971. svr.set_keep_alive_max_count(keep_alive_max_count);
  10972. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10973. res.set_content("Hello World!", "text/plain");
  10974. });
  10975. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10976. auto se = detail::scope_exit([&] {
  10977. svr.stop();
  10978. listen_thread.join();
  10979. ASSERT_FALSE(svr.is_running());
  10980. });
  10981. svr.wait_until_ready();
  10982. Client cli(HOST, PORT);
  10983. cli.set_keep_alive(true);
  10984. for (size_t i = 0; i < 5; i++) {
  10985. auto result = cli.Get("/hi");
  10986. ASSERT_TRUE(result);
  10987. EXPECT_EQ(StatusCode::OK_200, result->status);
  10988. if (i == keep_alive_max_count - 1) {
  10989. EXPECT_EQ("close", result->get_header_value("Connection"));
  10990. } else {
  10991. EXPECT_FALSE(result->has_header("Connection"));
  10992. }
  10993. }
  10994. }
  10995. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10996. // can pull the next one into the server's buffer. The server must serve it
  10997. // without waiting for the socket to become readable again. The keep-alive
  10998. // timeout outlasts the client's read timeout, so a request left waiting for it
  10999. // shows up as a missing response.
  11000. static void serve_pipelining_routes(Server &svr,
  11001. const std::function<void(int)> &client) {
  11002. svr.set_keep_alive_timeout(5);
  11003. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11004. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11005. });
  11006. svr.Post("/echo", [](const Request &req, Response &res) {
  11007. res.set_content("echo " + req.body, "text/plain");
  11008. });
  11009. auto port = svr.bind_to_any_port(HOST);
  11010. thread t = thread([&] { svr.listen_after_bind(); });
  11011. auto se = detail::scope_exit([&] {
  11012. svr.stop();
  11013. t.join();
  11014. });
  11015. svr.wait_until_ready();
  11016. client(port);
  11017. }
  11018. static std::string
  11019. send_pipelined_requests(const std::vector<std::string> &parts) {
  11020. Server svr;
  11021. std::string res;
  11022. serve_pipelining_routes(svr, [&](int port) {
  11023. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11024. });
  11025. return res;
  11026. }
  11027. static void expect_in_order(const std::string &res,
  11028. const std::vector<std::string> &bodies) {
  11029. size_t pos = 0;
  11030. for (const auto &body : bodies) {
  11031. pos = res.find(body, pos);
  11032. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11033. pos += body.size();
  11034. }
  11035. }
  11036. TEST(KeepAliveTest, PipelinedRequests) {
  11037. auto res = send_pipelined_requests(
  11038. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11039. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11040. "Content-Length: 4\r\n\r\nbody"
  11041. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11042. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11043. }
  11044. // The second request starts in the server's buffer and ends on the socket.
  11045. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11046. auto res =
  11047. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11048. "GET /hi/2 HTTP/1.1\r\nHo",
  11049. "st: localhost\r\nConnection: close\r\n\r\n"});
  11050. expect_in_order(res, {"hi 1", "hi 2"});
  11051. }
  11052. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11053. // CRLF after a body does not turn into a 400 for the next request.
  11054. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11055. auto res = send_pipelined_requests(
  11056. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11057. "Content-Length: 4\r\n\r\nbody\r\n"
  11058. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11059. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11060. expect_in_order(res, {"echo body", "hi 2"});
  11061. }
  11062. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11063. // must not be served as the next request.
  11064. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11065. auto res = send_pipelined_requests(
  11066. {"INVALID REQUEST LINE\r\n\r\n"
  11067. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11068. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11069. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11070. }
  11071. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11072. // Over TLS, the next request is held by the TLS library as already decrypted
  11073. // data rather than on the socket.
  11074. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11076. std::string res;
  11077. serve_pipelining_routes(svr, [&](int port) {
  11078. // One part, so all three requests arrive in one TLS record
  11079. EXPECT_TRUE(send_ssl_request_in_parts(
  11080. 2,
  11081. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11082. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11083. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11084. &res, port));
  11085. });
  11086. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11087. }
  11088. #endif
  11089. TEST(KeepAliveTest, Issue1041) {
  11090. Server svr;
  11091. svr.set_keep_alive_timeout(3);
  11092. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11093. res.set_content("Hello World!", "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. auto result = cli.Get("/hi");
  11105. ASSERT_TRUE(result);
  11106. EXPECT_EQ(StatusCode::OK_200, result->status);
  11107. std::this_thread::sleep_for(std::chrono::seconds(5));
  11108. result = cli.Get("/hi");
  11109. ASSERT_TRUE(result);
  11110. EXPECT_EQ(StatusCode::OK_200, result->status);
  11111. }
  11112. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11113. Server svr;
  11114. svr.set_keep_alive_max_count(0);
  11115. std::set<int> remote_ports;
  11116. svr.Get("/hi", [&](const Request &req, Response &res) {
  11117. remote_ports.insert(req.remote_port);
  11118. res.set_content("hi", "text/plain");
  11119. });
  11120. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11121. auto se = detail::scope_exit([&] {
  11122. svr.stop();
  11123. listen_thread.join();
  11124. ASSERT_FALSE(svr.is_running());
  11125. });
  11126. svr.wait_until_ready();
  11127. Client cli(HOST, PORT);
  11128. cli.set_keep_alive(true);
  11129. for (int i = 0; i < 3; i++) {
  11130. auto res = cli.Get("/hi");
  11131. ASSERT_TRUE(res);
  11132. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11133. }
  11134. // All three over one connection
  11135. EXPECT_EQ(1u, remote_ports.size());
  11136. }
  11137. TEST(KeepAliveTest, Issue1959) {
  11138. Server svr;
  11139. svr.set_keep_alive_timeout(5);
  11140. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11141. res.set_content("a", "text/plain");
  11142. });
  11143. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11144. auto se = detail::scope_exit([&] {
  11145. if (!svr.is_running()) return;
  11146. svr.stop();
  11147. listen_thread.join();
  11148. ASSERT_FALSE(svr.is_running());
  11149. });
  11150. svr.wait_until_ready();
  11151. Client cli("localhost", PORT);
  11152. cli.set_keep_alive(true);
  11153. using namespace std::chrono;
  11154. auto start = steady_clock::now();
  11155. cli.Get("/a");
  11156. svr.stop();
  11157. listen_thread.join();
  11158. auto end = steady_clock::now();
  11159. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11160. EXPECT_LT(elapsed, 5000);
  11161. }
  11162. #ifdef CPPHTTPLIB_SSL_ENABLED
  11163. TEST(KeepAliveTest, SSLClientReconnection) {
  11164. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11165. ASSERT_TRUE(svr.is_valid());
  11166. svr.set_keep_alive_timeout(1);
  11167. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11168. res.set_content("Hello World!", "text/plain");
  11169. });
  11170. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11171. auto se = detail::scope_exit([&] {
  11172. svr.stop();
  11173. listen_thread.join();
  11174. ASSERT_FALSE(svr.is_running());
  11175. });
  11176. svr.wait_until_ready();
  11177. SSLClient cli(HOST, PORT);
  11178. cli.enable_server_certificate_verification(false);
  11179. cli.set_keep_alive(true);
  11180. auto result = cli.Get("/hi");
  11181. ASSERT_TRUE(result);
  11182. EXPECT_EQ(StatusCode::OK_200, result->status);
  11183. result = cli.Get("/hi");
  11184. ASSERT_TRUE(result);
  11185. EXPECT_EQ(StatusCode::OK_200, result->status);
  11186. std::this_thread::sleep_for(std::chrono::seconds(2));
  11187. // Recoonect
  11188. result = cli.Get("/hi");
  11189. ASSERT_TRUE(result);
  11190. EXPECT_EQ(StatusCode::OK_200, result->status);
  11191. result = cli.Get("/hi");
  11192. ASSERT_TRUE(result);
  11193. EXPECT_EQ(StatusCode::OK_200, result->status);
  11194. }
  11195. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11197. ASSERT_TRUE(svr.is_valid());
  11198. svr.set_keep_alive_timeout(1);
  11199. std::string content = "reconnect";
  11200. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11201. res.set_content("Hello World!", "text/plain");
  11202. });
  11203. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11204. auto se = detail::scope_exit([&] {
  11205. svr.stop();
  11206. listen_thread.join();
  11207. ASSERT_FALSE(svr.is_running());
  11208. });
  11209. svr.wait_until_ready();
  11210. SSLClient cli(HOST, PORT);
  11211. cli.enable_server_certificate_verification(false);
  11212. cli.set_keep_alive(true);
  11213. auto result = cli.Post(
  11214. "/hi", content.size(),
  11215. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11216. sink.write(content.c_str(), content.size());
  11217. return true;
  11218. },
  11219. "text/plain");
  11220. ASSERT_TRUE(result);
  11221. EXPECT_EQ(200, result->status);
  11222. std::this_thread::sleep_for(std::chrono::seconds(2));
  11223. // Recoonect
  11224. result = cli.Post(
  11225. "/hi", content.size(),
  11226. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11227. sink.write(content.c_str(), content.size());
  11228. return true;
  11229. },
  11230. "text/plain");
  11231. ASSERT_TRUE(result);
  11232. EXPECT_EQ(200, result->status);
  11233. result = cli.Post(
  11234. "/hi", content.size(),
  11235. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11236. sink.write(content.c_str(), content.size());
  11237. return true;
  11238. },
  11239. "text/plain");
  11240. ASSERT_TRUE(result);
  11241. EXPECT_EQ(200, result->status);
  11242. }
  11243. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11244. using namespace httplib::tls;
  11245. {
  11246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11247. ASSERT_TRUE(svr.is_valid());
  11248. svr.Get("/sni", [&](const Request &req, Response &res) {
  11249. std::string expected = req.sni();
  11250. EXPECT_EQ(expected, req.get_param_value("expected"));
  11251. res.set_content("ok", "text/plain");
  11252. });
  11253. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11254. auto se = detail::scope_exit([&] {
  11255. svr.stop();
  11256. listen_thread.join();
  11257. ASSERT_FALSE(svr.is_running());
  11258. });
  11259. svr.wait_until_ready();
  11260. {
  11261. SSLClient cli("localhost", PORT);
  11262. cli.enable_server_certificate_verification(false);
  11263. auto res = cli.Get("/sni?expected=localhost");
  11264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11265. }
  11266. {
  11267. SSLClient cli("::1", PORT);
  11268. cli.enable_server_certificate_verification(false);
  11269. auto res = cli.Get("/sni?expected=");
  11270. // NOTE: This may fail if the server is listening on IPv4 only
  11271. // (e.g., when localhost resolves to 127.0.0.1 only)
  11272. if (res) {
  11273. EXPECT_EQ(StatusCode::OK_200, res->status);
  11274. } else {
  11275. EXPECT_EQ(Error::Connection, res.error());
  11276. }
  11277. }
  11278. }
  11279. }
  11280. // The SNI of a failed handshake does not reach the next connection that the
  11281. // same worker thread serves
  11282. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11284. ASSERT_TRUE(svr.is_valid());
  11285. svr.new_task_queue = [] { return new ThreadPool(1); };
  11286. svr.Get("/sni", [](const Request &req, Response &res) {
  11287. res.set_content(req.sni(), "text/plain");
  11288. });
  11289. auto port = svr.bind_to_any_port("127.0.0.1");
  11290. ASSERT_LT(0, port);
  11291. thread t = thread([&] { svr.listen_after_bind(); });
  11292. auto se = detail::scope_exit([&] {
  11293. svr.stop();
  11294. t.join();
  11295. ASSERT_FALSE(svr.is_running());
  11296. });
  11297. svr.wait_until_ready();
  11298. {
  11299. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11300. SSLClient cli("localhost", port);
  11301. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11302. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11303. auto res = cli.Get("/sni");
  11304. ASSERT_FALSE(res);
  11305. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11306. }
  11307. // An IP host sends no SNI (RFC 6066)
  11308. SSLClient cli("127.0.0.1", port);
  11309. cli.enable_server_certificate_verification(false);
  11310. auto res = cli.Get("/sni");
  11311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11312. EXPECT_EQ("", res->body);
  11313. }
  11314. #endif
  11315. TEST(ClientProblemDetectionTest, ContentProvider) {
  11316. Server svr;
  11317. size_t content_length = 1024 * 1024;
  11318. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11319. res.set_content_provider(
  11320. content_length, "text/plain",
  11321. [&](size_t offset, size_t length, DataSink &sink) {
  11322. auto out_len = std::min(length, static_cast<size_t>(1024));
  11323. std::string out(out_len, '@');
  11324. sink.write(out.data(), out_len);
  11325. return offset < 4096;
  11326. },
  11327. [](bool success) { ASSERT_FALSE(success); });
  11328. });
  11329. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11330. res.set_content_provider(
  11331. 0, "text/plain",
  11332. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11333. EXPECT_TRUE(false);
  11334. return true;
  11335. },
  11336. [](bool success) { ASSERT_FALSE(success); });
  11337. });
  11338. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11339. auto se = detail::scope_exit([&] {
  11340. svr.stop();
  11341. listen_thread.join();
  11342. ASSERT_FALSE(svr.is_running());
  11343. });
  11344. svr.wait_until_ready();
  11345. Client cli("localhost", PORT);
  11346. {
  11347. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11348. size_t /*data_length*/) { return false; });
  11349. ASSERT_FALSE(res);
  11350. }
  11351. {
  11352. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11353. size_t /*data_length*/) { return false; });
  11354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11355. }
  11356. }
  11357. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11358. // A provider that reports success without writing anything and without
  11359. // calling done() used to be handed the same offset and length again on every
  11360. // pass, so it spun for as long as the peer stayed connected.
  11361. Server svr;
  11362. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11363. res.set_content("ok", "text/plain");
  11364. });
  11365. auto port = svr.bind_to_any_port(HOST);
  11366. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11367. auto se = detail::scope_exit([&] {
  11368. svr.stop();
  11369. listen_thread.join();
  11370. ASSERT_FALSE(svr.is_running());
  11371. });
  11372. svr.wait_until_ready();
  11373. std::atomic<int> call_count{0};
  11374. Client cli(HOST, port);
  11375. auto res = cli.Post(
  11376. "/", 1024,
  11377. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11378. // Give up after enough passes to show the spin, so that losing the
  11379. // check below fails this test instead of hanging it.
  11380. return ++call_count < 100;
  11381. },
  11382. "text/plain");
  11383. ASSERT_FALSE(res);
  11384. EXPECT_EQ(Error::Write, res.error());
  11385. EXPECT_EQ(1, call_count.load());
  11386. }
  11387. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11388. // A writer only has to assign `write`. The other three used to be left as
  11389. // empty std::functions, so a provider calling one threw
  11390. // std::bad_function_call out of the thread running it and took the whole
  11391. // process down.
  11392. DataSink sink;
  11393. std::string written;
  11394. sink.write = [&](const char *data, size_t data_len) {
  11395. written.append(data, data_len);
  11396. return true;
  11397. };
  11398. EXPECT_TRUE(sink.is_writable());
  11399. sink.done();
  11400. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11401. EXPECT_TRUE(written.empty());
  11402. }
  11403. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11404. // A sink that cannot carry trailers still has to finish.
  11405. DataSink sink;
  11406. auto done_count = 0;
  11407. sink.done = [&]() { done_count++; };
  11408. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11409. EXPECT_EQ(1, done_count);
  11410. }
  11411. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11412. Server svr;
  11413. const std::string body(4096, 'x');
  11414. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11415. res.set_content_provider(body.size(), "text/plain",
  11416. [&](size_t offset, size_t length, DataSink &sink) {
  11417. sink.write(body.data() + offset, length);
  11418. sink.done();
  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. auto res = cli.Get("/");
  11432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11433. EXPECT_EQ(StatusCode::OK_200, res->status);
  11434. EXPECT_EQ(body, res->body);
  11435. }
  11436. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11437. Server svr;
  11438. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11439. res.set_content_provider(
  11440. 1024, "text/plain",
  11441. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11442. sink.write("hello", 5);
  11443. sink.done(); // short of the 1024 bytes the response promised
  11444. return true;
  11445. });
  11446. });
  11447. auto port = svr.bind_to_any_port(HOST);
  11448. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11449. auto se = detail::scope_exit([&] {
  11450. svr.stop();
  11451. listen_thread.join();
  11452. ASSERT_FALSE(svr.is_running());
  11453. });
  11454. svr.wait_until_ready();
  11455. Client cli(HOST, port);
  11456. cli.set_read_timeout(5, 0);
  11457. // The response is short of its Content-Length, so the client cannot read a
  11458. // complete body. What matters is that this returns at all: a no-op done()
  11459. // would leave the writer looping over a provider that never makes progress.
  11460. auto res = cli.Get("/");
  11461. EXPECT_FALSE(res);
  11462. }
  11463. // Read as the next response by a peer that sees it after a framed body.
  11464. static const std::string smuggled_response =
  11465. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11466. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11467. Server svr;
  11468. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11469. res.set_content_provider(
  11470. 5, "text/plain",
  11471. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11472. auto data = "AAAAA" + smuggled_response;
  11473. sink.write(data.data(), data.size());
  11474. return true;
  11475. });
  11476. });
  11477. thread t = thread([&] { svr.listen(HOST, PORT); });
  11478. auto se = detail::scope_exit([&] {
  11479. svr.stop();
  11480. t.join();
  11481. ASSERT_FALSE(svr.is_running());
  11482. });
  11483. svr.wait_until_ready();
  11484. std::string resp;
  11485. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11486. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11487. resp.clear();
  11488. ASSERT_TRUE(send_request(
  11489. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11490. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11491. }
  11492. TEST(NoContentTest, BodyIsNotSent) {
  11493. Server svr;
  11494. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11495. res.status = StatusCode::NoContent_204;
  11496. res.set_content(smuggled_response, "text/plain");
  11497. });
  11498. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11499. res.status = StatusCode::NotModified_304;
  11500. res.set_chunked_content_provider(
  11501. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11502. sink.write(smuggled_response.data(), smuggled_response.size());
  11503. sink.done();
  11504. return true;
  11505. });
  11506. });
  11507. thread t = thread([&] { svr.listen(HOST, PORT); });
  11508. auto se = detail::scope_exit([&] {
  11509. svr.stop();
  11510. t.join();
  11511. ASSERT_FALSE(svr.is_running());
  11512. });
  11513. svr.wait_until_ready();
  11514. for (auto path : {"/204", "/304"}) {
  11515. std::string resp;
  11516. ASSERT_TRUE(send_request(
  11517. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11518. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11519. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11520. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11521. }
  11522. }
  11523. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11524. Server svr;
  11525. std::atomic<bool> smuggled(false);
  11526. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11527. res.set_content("ok", "text/plain");
  11528. });
  11529. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11530. smuggled = true;
  11531. });
  11532. auto port = svr.bind_to_any_port(HOST);
  11533. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11534. auto se = detail::scope_exit([&] {
  11535. svr.stop();
  11536. listen_thread.join();
  11537. ASSERT_FALSE(svr.is_running());
  11538. });
  11539. svr.wait_until_ready();
  11540. // What follows the body would be read as the next request.
  11541. Client cli(HOST, port);
  11542. auto res = cli.Post(
  11543. "/", 5,
  11544. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11545. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11546. sink.write(data.data(), data.size());
  11547. return true;
  11548. },
  11549. "text/plain");
  11550. ASSERT_FALSE(res);
  11551. EXPECT_EQ(Error::Write, res.error());
  11552. EXPECT_FALSE(smuggled);
  11553. }
  11554. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11555. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11556. // The compressed path builds the whole body before connecting, so this
  11557. // fails client-side and never reaches a server.
  11558. Client cli(HOST, PORT);
  11559. cli.set_compress(true);
  11560. auto res = cli.Post(
  11561. "/", 1024,
  11562. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11563. sink.write("hello", 5);
  11564. sink.done(); // short of the 1024 bytes the request announced
  11565. return true;
  11566. },
  11567. "text/plain");
  11568. ASSERT_FALSE(res);
  11569. EXPECT_EQ(Error::Write, res.error());
  11570. }
  11571. #endif
  11572. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11573. Server svr;
  11574. svr.set_error_handler([](Request const &, Response &res) -> void {
  11575. res.set_chunked_content_provider(
  11576. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11577. sink.os << "hello";
  11578. sink.os << "world";
  11579. sink.done();
  11580. return true;
  11581. });
  11582. });
  11583. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11584. auto se = detail::scope_exit([&] {
  11585. svr.stop();
  11586. listen_thread.join();
  11587. ASSERT_FALSE(svr.is_running());
  11588. });
  11589. svr.wait_until_ready();
  11590. Client cli("localhost", PORT);
  11591. auto res = cli.Get("/");
  11592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11594. EXPECT_EQ("helloworld", res->body);
  11595. }
  11596. // A body set after a content provider must replace it, not be sent through it.
  11597. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11598. Server svr;
  11599. svr.set_mount_point("/", "./www");
  11600. svr.set_file_request_handler([](const Request &req, Response &res) {
  11601. if (req.path == "/dir/test.html") {
  11602. res.status = StatusCode::Forbidden_403;
  11603. res.set_content(std::string(5000, 'D'), "text/plain");
  11604. } else if (req.path == "/file") {
  11605. res.status = StatusCode::Forbidden_403;
  11606. res.body = "Denied";
  11607. }
  11608. });
  11609. auto port = svr.bind_to_any_port(HOST);
  11610. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11611. auto se = detail::scope_exit([&] {
  11612. svr.stop();
  11613. t.join();
  11614. ASSERT_FALSE(svr.is_running());
  11615. });
  11616. svr.wait_until_ready();
  11617. Client cli(HOST, port);
  11618. {
  11619. auto res = cli.Get("/dir/test.html");
  11620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11621. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11622. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11623. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11624. }
  11625. {
  11626. auto res = cli.Get("/file");
  11627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11628. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11629. EXPECT_EQ("Denied", res->body);
  11630. }
  11631. {
  11632. auto res = cli.Get("/dir/index.html");
  11633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11634. EXPECT_EQ(StatusCode::OK_200, res->status);
  11635. EXPECT_EQ(0U, res->body.find("<html>"));
  11636. }
  11637. }
  11638. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11639. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11640. Server svr;
  11641. std::vector<bool> released;
  11642. std::mutex released_mutex;
  11643. auto releaser = [&](bool success) {
  11644. std::lock_guard<std::mutex> guard(released_mutex);
  11645. released.push_back(success);
  11646. };
  11647. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11648. return sink.write(&"hello"[offset], length);
  11649. };
  11650. svr.Get("/sized", [&](const Request &, Response &res) {
  11651. res.status = StatusCode::NotFound_404;
  11652. res.set_content_provider(5, "text/plain", provider, releaser);
  11653. });
  11654. svr.Get("/chunked", [&](const Request &, Response &res) {
  11655. res.status = StatusCode::ServiceUnavailable_503;
  11656. res.set_chunked_content_provider(
  11657. "text/plain",
  11658. [](size_t, DataSink &sink) {
  11659. sink.os << "chunk";
  11660. sink.done();
  11661. return true;
  11662. },
  11663. releaser);
  11664. });
  11665. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11666. res.set_content_provider(5, "text/plain", provider, releaser);
  11667. throw std::runtime_error("after the provider");
  11668. });
  11669. svr.set_error_handler([](const Request &req, Response &res) {
  11670. // Leave the exception handler's content to it.
  11671. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11672. res.set_content(std::string(1000, 'E'), "text/html");
  11673. return Server::HandlerResponse::Handled;
  11674. });
  11675. svr.set_exception_handler(
  11676. [](const Request &, Response &res, std::exception_ptr) {
  11677. res.status = StatusCode::InternalServerError_500;
  11678. res.set_content(std::string(1000, 'X'), "text/html");
  11679. });
  11680. auto port = svr.bind_to_any_port(HOST);
  11681. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11682. auto se = detail::scope_exit([&] {
  11683. svr.stop();
  11684. t.join();
  11685. ASSERT_FALSE(svr.is_running());
  11686. });
  11687. svr.wait_until_ready();
  11688. Client cli(HOST, port);
  11689. {
  11690. auto res = cli.Get("/sized");
  11691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11692. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11693. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11694. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11695. }
  11696. {
  11697. auto res = cli.Get("/chunked");
  11698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11699. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11700. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11701. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11702. }
  11703. {
  11704. auto res = cli.Get("/throw");
  11705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11706. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11707. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11708. }
  11709. std::lock_guard<std::mutex> guard(released_mutex);
  11710. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11711. }
  11712. #endif
  11713. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11714. Server svr;
  11715. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11716. return sink.write(&"abc"[offset], length);
  11717. };
  11718. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11719. res.set_file_content("./www/dir/test.html");
  11720. res.set_content("body", "text/plain");
  11721. });
  11722. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11723. res.set_content(std::string(100, 'B'), "text/plain");
  11724. res.set_file_content("./www/dir/test.html");
  11725. });
  11726. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11727. res.set_content(std::string(100, 'B'), "text/plain");
  11728. res.set_content_provider(3, "text/x-provider", abc);
  11729. });
  11730. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11731. res.set_content_provider(3, "text/x-provider", abc);
  11732. res.set_content(std::string(100, 'B'), "text/plain");
  11733. });
  11734. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11735. res.set_content_provider(3, "text/x-provider", abc);
  11736. res.set_file_content("./www/dir/test.html", "text/x-file");
  11737. });
  11738. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11739. res.set_file_content("./www/dir/test.html");
  11740. res.set_header("Content-Type", "text/x-handler");
  11741. });
  11742. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11743. res.set_content_provider(3, "text/plain", abc);
  11744. res.body = "direct";
  11745. });
  11746. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11747. res.set_file_content("./www/dir/test.html");
  11748. res.body = "direct";
  11749. });
  11750. auto port = svr.bind_to_any_port(HOST);
  11751. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11752. auto se = detail::scope_exit([&] {
  11753. svr.stop();
  11754. t.join();
  11755. ASSERT_FALSE(svr.is_running());
  11756. });
  11757. svr.wait_until_ready();
  11758. Client cli(HOST, port);
  11759. auto expect_body = [&](const char *path, const std::string &body,
  11760. const std::string &type) {
  11761. // Uncompressed, so Content-Length can be compared with the body.
  11762. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11763. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11764. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11765. EXPECT_EQ(body, res->body) << path;
  11766. EXPECT_EQ(std::to_string(body.size()),
  11767. res->get_header_value("Content-Length"))
  11768. << path;
  11769. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11770. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11771. };
  11772. expect_body("/file-then-body", "body", "text/plain");
  11773. expect_body("/body-then-file", "test.html", "text/html");
  11774. expect_body("/body-then-provider", "abc", "text/x-provider");
  11775. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11776. expect_body("/provider-then-file", "test.html", "text/x-file");
  11777. expect_body("/file-then-header", "test.html", "text/x-handler");
  11778. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11779. expect_body("/file-then-direct-body", "direct", "text/plain");
  11780. // Ranges are checked against the body, not the dropped provider.
  11781. {
  11782. auto res = cli.Get("/provider-then-direct-body",
  11783. Headers{{make_range_header({{1, 2}})}});
  11784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11785. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11786. EXPECT_EQ("ir", res->body);
  11787. }
  11788. {
  11789. auto res = cli.Get("/file-then-direct-body",
  11790. Headers{{make_range_header({{7, 8}})}});
  11791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11792. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11793. }
  11794. }
  11795. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11796. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11797. const char *path = "./truncated_while_served.txt";
  11798. const size_t size = 32 * 1024 * 1024;
  11799. {
  11800. std::ofstream f(path, std::ios::binary);
  11801. f << std::string(size, 'x');
  11802. }
  11803. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11804. // Over TLS, where the bytes are encrypted in this process rather than
  11805. // copied by send().
  11806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11807. svr.Get("/file", [&](const Request &, Response &res) {
  11808. res.set_file_content(path, "text/plain");
  11809. });
  11810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11811. auto se = detail::scope_exit([&] {
  11812. svr.stop();
  11813. thread.join();
  11814. ASSERT_FALSE(svr.is_running());
  11815. });
  11816. svr.wait_until_ready();
  11817. // The file shrinks once the first bytes are in, as a rewrite in place
  11818. // would, and reading the mapping past its new end used to raise SIGBUS.
  11819. SSLClient cli(HOST, PORT);
  11820. cli.enable_server_certificate_verification(false);
  11821. size_t received = 0;
  11822. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11823. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11824. received += len;
  11825. return true;
  11826. });
  11827. EXPECT_FALSE(res);
  11828. EXPECT_LT(received, size);
  11829. }
  11830. #endif
  11831. // Forward declaration (see the base64_encode note).
  11832. namespace httplib {
  11833. namespace detail {
  11834. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11835. const std::string &content_type,
  11836. EncodingType encoding);
  11837. } // namespace detail
  11838. } // namespace httplib
  11839. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11840. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11841. ASSERT_TRUE(mm->is_open());
  11842. Response res;
  11843. detail::set_file_content_provider(res, mm, "text/html",
  11844. detail::EncodingType::None);
  11845. std::string out;
  11846. DataSink sink;
  11847. sink.write = [&](const char *d, size_t l) {
  11848. out.append(d, l);
  11849. return true;
  11850. };
  11851. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11852. EXPECT_EQ("test.html", out);
  11853. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11854. EXPECT_EQ("test.html", out);
  11855. }
  11856. TEST(LongPollingTest, ClientCloseDetection) {
  11857. Server svr;
  11858. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11859. res.set_chunked_content_provider(
  11860. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11861. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11862. sink.os << "hello";
  11863. auto count = 10;
  11864. while (count > 0 && sink.is_writable()) {
  11865. this_thread::sleep_for(chrono::milliseconds(10));
  11866. count--;
  11867. }
  11868. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11869. return true;
  11870. });
  11871. });
  11872. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11873. auto se = detail::scope_exit([&] {
  11874. svr.stop();
  11875. listen_thread.join();
  11876. ASSERT_FALSE(svr.is_running());
  11877. });
  11878. svr.wait_until_ready();
  11879. Client cli("localhost", PORT);
  11880. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11881. EXPECT_EQ("hello", string(data, data_length));
  11882. return false; // close the socket immediately.
  11883. });
  11884. ASSERT_FALSE(res);
  11885. }
  11886. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11887. Server svr;
  11888. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11889. res.set_chunked_content_provider(
  11890. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11891. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11892. sink.os << "hello";
  11893. EXPECT_TRUE(sink.os.good());
  11894. // Wait for the client to close the connection
  11895. auto count = 10;
  11896. while (count > 0 && sink.is_writable()) {
  11897. this_thread::sleep_for(chrono::milliseconds(10));
  11898. count--;
  11899. }
  11900. // After client disconnect, write repeatedly until the socket
  11901. // write actually fails (small writes may be absorbed by the
  11902. // kernel buffer)
  11903. std::string chunk(1024, 'x');
  11904. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11905. sink.os << chunk;
  11906. }
  11907. EXPECT_TRUE(sink.os.fail());
  11908. return true;
  11909. });
  11910. });
  11911. auto port = svr.bind_to_any_port("localhost");
  11912. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11913. auto se = detail::scope_exit([&] {
  11914. svr.stop();
  11915. listen_thread.join();
  11916. ASSERT_FALSE(svr.is_running());
  11917. });
  11918. svr.wait_until_ready();
  11919. Client cli("localhost", port);
  11920. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11921. EXPECT_EQ("hello", string(data, data_length));
  11922. return false; // close the socket immediately.
  11923. });
  11924. ASSERT_FALSE(res);
  11925. }
  11926. TEST(GetWithParametersTest, GetWithParameters) {
  11927. Server svr;
  11928. svr.Get("/", [&](const Request &req, Response &) {
  11929. EXPECT_EQ("world", req.get_param_value("hello"));
  11930. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11931. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11932. });
  11933. svr.Get("/params", [&](const Request &req, Response &) {
  11934. EXPECT_EQ("world", req.get_param_value("hello"));
  11935. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11936. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11937. });
  11938. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11939. EXPECT_EQ("resource-id", req.matches[1]);
  11940. EXPECT_EQ("foo", req.get_param_value("param1"));
  11941. EXPECT_EQ("bar", req.get_param_value("param2"));
  11942. });
  11943. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11944. EXPECT_EQ("user-id", req.path_params.at("id"));
  11945. EXPECT_EQ("foo", req.get_param_value("param1"));
  11946. EXPECT_EQ("bar", req.get_param_value("param2"));
  11947. });
  11948. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11949. auto se = detail::scope_exit([&] {
  11950. svr.stop();
  11951. listen_thread.join();
  11952. ASSERT_FALSE(svr.is_running());
  11953. });
  11954. svr.wait_until_ready();
  11955. {
  11956. Client cli(HOST, PORT);
  11957. Params params;
  11958. params.emplace("hello", "world");
  11959. params.emplace("hello2", "world2");
  11960. params.emplace("hello3", "world3");
  11961. auto res = cli.Get("/", params, Headers{});
  11962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11963. EXPECT_EQ(StatusCode::OK_200, res->status);
  11964. }
  11965. {
  11966. Client cli(HOST, PORT);
  11967. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11969. EXPECT_EQ(StatusCode::OK_200, res->status);
  11970. }
  11971. {
  11972. Client cli(HOST, PORT);
  11973. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11975. EXPECT_EQ(StatusCode::OK_200, res->status);
  11976. }
  11977. {
  11978. Client cli(HOST, PORT);
  11979. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11981. EXPECT_EQ(StatusCode::OK_200, res->status);
  11982. }
  11983. }
  11984. TEST(GetWithParametersTest, GetWithParameters2) {
  11985. Server svr;
  11986. svr.Get("/", [&](const Request &req, Response &res) {
  11987. auto text = req.get_param_value("hello");
  11988. res.set_content(text, "text/plain");
  11989. });
  11990. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11991. auto se = detail::scope_exit([&] {
  11992. svr.stop();
  11993. listen_thread.join();
  11994. ASSERT_FALSE(svr.is_running());
  11995. });
  11996. svr.wait_until_ready();
  11997. Client cli("localhost", PORT);
  11998. Params params;
  11999. params.emplace("hello", "world");
  12000. std::string body;
  12001. auto res = cli.Get("/", params, Headers{},
  12002. [&](const char *data, size_t data_length) {
  12003. body.append(data, data_length);
  12004. return true;
  12005. });
  12006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12007. EXPECT_EQ(StatusCode::OK_200, res->status);
  12008. EXPECT_EQ("world", body);
  12009. }
  12010. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12011. Server svr;
  12012. svr.Get("/search", [&](const Request &req, Response &res) {
  12013. auto q = req.get_param_value("q");
  12014. res.set_content(q, "text/plain");
  12015. });
  12016. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12017. auto se = detail::scope_exit([&] {
  12018. svr.stop();
  12019. listen_thread.join();
  12020. ASSERT_FALSE(svr.is_running());
  12021. });
  12022. svr.wait_until_ready();
  12023. Client cli("localhost", PORT);
  12024. // Verify that Get(path, params) works without requiring Headers argument
  12025. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12027. EXPECT_EQ(StatusCode::OK_200, res->status);
  12028. EXPECT_EQ("cpp-httplib", res->body);
  12029. }
  12030. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12031. auto host = "httpbingo.org";
  12032. auto path = std::string{"/range/32"};
  12033. #ifdef CPPHTTPLIB_SSL_ENABLED
  12034. SSLClient cli(host);
  12035. #else
  12036. Client cli(host);
  12037. #endif
  12038. cli.set_default_headers({make_range_header({{1, 10}})});
  12039. cli.set_connection_timeout(5);
  12040. {
  12041. auto res = cli.Get(path);
  12042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12043. EXPECT_EQ("bcdefghijk", res->body);
  12044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12045. }
  12046. {
  12047. auto res = cli.Get(path);
  12048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12049. EXPECT_EQ("bcdefghijk", res->body);
  12050. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12051. }
  12052. }
  12053. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12054. Server svr;
  12055. svr.set_default_headers({{"Hello", "World"}});
  12056. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12057. res.set_content("ok", "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. Client cli("localhost", PORT);
  12067. auto res = cli.Get("/");
  12068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12069. EXPECT_EQ(StatusCode::OK_200, res->status);
  12070. EXPECT_EQ("ok", res->body);
  12071. EXPECT_EQ("World", res->get_header_value("Hello"));
  12072. }
  12073. #ifdef CPPHTTPLIB_SSL_ENABLED
  12074. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12076. ASSERT_TRUE(svr.is_valid());
  12077. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12078. std::this_thread::sleep_for(std::chrono::seconds(2));
  12079. res.set_content("a", "text/plain");
  12080. });
  12081. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12082. res.set_content("b", "text/plain");
  12083. });
  12084. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12085. auto se = detail::scope_exit([&] {
  12086. svr.stop();
  12087. listen_thread.join();
  12088. ASSERT_FALSE(svr.is_running());
  12089. });
  12090. svr.wait_until_ready();
  12091. SSLClient cli("localhost", PORT);
  12092. cli.enable_server_certificate_verification(false);
  12093. cli.set_keep_alive(true);
  12094. cli.set_read_timeout(std::chrono::seconds(1));
  12095. auto resa = cli.Get("/a");
  12096. ASSERT_TRUE(!resa);
  12097. EXPECT_EQ(Error::Read, resa.error());
  12098. auto resb = cli.Get("/b");
  12099. ASSERT_TRUE(resb);
  12100. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12101. EXPECT_EQ("b", resb->body);
  12102. }
  12103. // Closing an idle keep-alive connection sends close_notify and returns. The
  12104. // server must not wait for the client's close_notify: an idle client never
  12105. // sends one, so the worker would be held until the read timeout expires, and
  12106. // stop() would wait for it.
  12107. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12108. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12109. ASSERT_TRUE(svr.is_valid());
  12110. svr.set_keep_alive_timeout(1);
  12111. svr.set_read_timeout(10, 0);
  12112. svr.Get("/", [](const Request &, Response &res) {
  12113. res.set_content("ok", "text/plain");
  12114. });
  12115. auto port = svr.bind_to_any_port(HOST);
  12116. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12117. auto se = detail::scope_exit([&] {
  12118. if (listen_thread.joinable()) {
  12119. svr.stop();
  12120. listen_thread.join();
  12121. }
  12122. });
  12123. svr.wait_until_ready();
  12124. SSLClient cli(HOST, port);
  12125. cli.enable_server_certificate_verification(false);
  12126. cli.set_keep_alive(true);
  12127. auto res = cli.Get("/");
  12128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12129. EXPECT_EQ(StatusCode::OK_200, res->status);
  12130. // Stay idle past the keep-alive timeout so the server closes the connection.
  12131. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12132. auto start = std::chrono::steady_clock::now();
  12133. svr.stop();
  12134. listen_thread.join();
  12135. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12136. std::chrono::steady_clock::now() - start)
  12137. .count();
  12138. EXPECT_LT(elapsed, 3000);
  12139. }
  12140. #endif
  12141. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12142. protected:
  12143. ServerTestWithAI_PASSIVE()
  12144. : cli_(HOST, PORT)
  12145. #ifdef CPPHTTPLIB_SSL_ENABLED
  12146. ,
  12147. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12148. #endif
  12149. {
  12150. #ifdef CPPHTTPLIB_SSL_ENABLED
  12151. cli_.enable_server_certificate_verification(false);
  12152. #endif
  12153. }
  12154. virtual void SetUp() {
  12155. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12156. res.set_content("Hello World!", "text/plain");
  12157. });
  12158. t_ = thread(
  12159. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12160. svr_.wait_until_ready();
  12161. }
  12162. virtual void TearDown() {
  12163. svr_.stop();
  12164. t_.join();
  12165. }
  12166. #ifdef CPPHTTPLIB_SSL_ENABLED
  12167. SSLClient cli_;
  12168. SSLServer svr_;
  12169. #else
  12170. Client cli_;
  12171. Server svr_;
  12172. #endif
  12173. thread t_;
  12174. };
  12175. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12176. auto res = cli_.Get("/hi");
  12177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12178. EXPECT_EQ(StatusCode::OK_200, res->status);
  12179. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12180. EXPECT_EQ("Hello World!", res->body);
  12181. }
  12182. class ServerUpDownTest : public ::testing::Test {
  12183. protected:
  12184. ServerUpDownTest() : cli_(HOST, PORT) {}
  12185. virtual void SetUp() {
  12186. t_ = thread([&]() {
  12187. svr_.bind_to_any_port(HOST);
  12188. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12189. ASSERT_TRUE(svr_.listen_after_bind());
  12190. });
  12191. svr_.wait_until_ready();
  12192. }
  12193. virtual void TearDown() {
  12194. svr_.stop();
  12195. t_.join();
  12196. }
  12197. Client cli_;
  12198. Server svr_;
  12199. thread t_;
  12200. };
  12201. TEST_F(ServerUpDownTest, QuickStartStop) {
  12202. // Should not crash, especially when run with
  12203. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12204. }
  12205. class PayloadMaxLengthTest : public ::testing::Test {
  12206. protected:
  12207. PayloadMaxLengthTest()
  12208. : cli_(HOST, PORT)
  12209. #ifdef CPPHTTPLIB_SSL_ENABLED
  12210. ,
  12211. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12212. #endif
  12213. {
  12214. #ifdef CPPHTTPLIB_SSL_ENABLED
  12215. cli_.enable_server_certificate_verification(false);
  12216. #endif
  12217. }
  12218. virtual void SetUp() {
  12219. svr_.set_payload_max_length(8);
  12220. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12221. res.set_content("test", "text/plain");
  12222. });
  12223. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12224. svr_.wait_until_ready();
  12225. }
  12226. virtual void TearDown() {
  12227. svr_.stop();
  12228. t_.join();
  12229. }
  12230. #ifdef CPPHTTPLIB_SSL_ENABLED
  12231. SSLClient cli_;
  12232. SSLServer svr_;
  12233. #else
  12234. Client cli_;
  12235. Server svr_;
  12236. #endif
  12237. thread t_;
  12238. };
  12239. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12240. auto res = cli_.Post("/test", "123456789", "text/plain");
  12241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12242. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12243. res = cli_.Post("/test", "12345678", "text/plain");
  12244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12245. EXPECT_EQ(StatusCode::OK_200, res->status);
  12246. }
  12247. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12248. // Test chunked encoding with payload exceeding the 8-byte limit
  12249. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12250. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12252. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12253. }
  12254. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12255. // Test chunked encoding with payload within the 8-byte limit
  12256. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12257. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12259. EXPECT_EQ(StatusCode::OK_200, res->status);
  12260. }
  12261. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12262. // Test using send_request to send chunked data exceeding payload limit
  12263. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12264. "Host: " +
  12265. std::string(HOST) + ":" + std::to_string(PORT) +
  12266. "\r\n"
  12267. "Transfer-Encoding: chunked\r\n"
  12268. "Connection: close\r\n"
  12269. "\r\n"
  12270. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12271. "0123456789\r\n"
  12272. "0\r\n" // End chunk
  12273. "\r\n";
  12274. std::string response;
  12275. bool result = send_request(1, chunked_request, &response);
  12276. if (!result) {
  12277. // If send_request fails, it might be because the server closed the
  12278. // connection due to payload limit enforcement, which is acceptable
  12279. SUCCEED()
  12280. << "Server rejected oversized chunked request (connection closed)";
  12281. } else {
  12282. // If we got a response, check if it's an error response or connection was
  12283. // closed early Short response length indicates connection was closed due to
  12284. // payload limit
  12285. if (response.length() <= 10) {
  12286. SUCCEED() << "Server closed connection for oversized chunked request";
  12287. } else {
  12288. // Check for error status codes
  12289. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12290. response.find("Payload Too Large") != std::string::npos ||
  12291. response.find("400") != std::string::npos);
  12292. }
  12293. }
  12294. }
  12295. class LargePayloadMaxLengthTest : public ::testing::Test {
  12296. protected:
  12297. LargePayloadMaxLengthTest()
  12298. : cli_(HOST, PORT)
  12299. #ifdef CPPHTTPLIB_SSL_ENABLED
  12300. ,
  12301. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12302. #endif
  12303. {
  12304. #ifdef CPPHTTPLIB_SSL_ENABLED
  12305. cli_.enable_server_certificate_verification(false);
  12306. #endif
  12307. }
  12308. virtual void SetUp() {
  12309. // Set 10MB payload limit
  12310. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12311. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12312. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12313. res.set_content("Large payload test", "text/plain");
  12314. });
  12315. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12316. svr_.wait_until_ready();
  12317. }
  12318. virtual void TearDown() {
  12319. svr_.stop();
  12320. t_.join();
  12321. }
  12322. #ifdef CPPHTTPLIB_SSL_ENABLED
  12323. SSLClient cli_;
  12324. SSLServer svr_;
  12325. #else
  12326. Client cli_;
  12327. Server svr_;
  12328. #endif
  12329. thread t_;
  12330. };
  12331. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12332. // Test chunked encoding with payload within 10MB limit
  12333. std::string medium_payload(5 * 1024 * 1024,
  12334. 'A'); // 5MB payload, within 10MB limit
  12335. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12337. EXPECT_EQ(StatusCode::OK_200, res->status);
  12338. }
  12339. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12340. // Test chunked encoding with payload exceeding 10MB limit
  12341. std::string large_payload(12 * 1024 * 1024,
  12342. 'B'); // 12MB payload, exceeds 10MB limit
  12343. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12344. // Server may either return 413 or close the connection
  12345. if (res) {
  12346. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12347. } else {
  12348. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12349. }
  12350. }
  12351. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12352. Server svr;
  12353. svr.Get("/", [](const Request &, Response &res) {
  12354. // Claims the most the client accepts, far more than it sends, then drops
  12355. // the connection.
  12356. res.set_content_provider(std::string().max_size(), "text/plain",
  12357. [](size_t, size_t, DataSink &sink) {
  12358. sink.write("abc", 3);
  12359. return false;
  12360. });
  12361. });
  12362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12363. auto se = detail::scope_exit([&] {
  12364. svr.stop();
  12365. thread.join();
  12366. ASSERT_FALSE(svr.is_running());
  12367. });
  12368. svr.wait_until_ready();
  12369. Client cli(HOST, PORT);
  12370. cli.set_payload_max_length(0);
  12371. EXPECT_FALSE(cli.Get("/"));
  12372. }
  12373. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12374. // Stream API does, not as a plain read failure
  12375. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12376. Server svr;
  12377. svr.Get("/big", [](const Request &, Response &res) {
  12378. res.set_content(std::string(100000, 'b'), "text/plain");
  12379. });
  12380. auto port = svr.bind_to_any_port(HOST);
  12381. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12382. auto se = detail::scope_exit([&] {
  12383. svr.stop();
  12384. thread.join();
  12385. });
  12386. svr.wait_until_ready();
  12387. Client cli(HOST, port);
  12388. cli.set_payload_max_length(1000);
  12389. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12390. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12391. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12392. [](const char *, size_t) { return true; });
  12393. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12394. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12395. // Small on the wire, over the limit once decompressed
  12396. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12397. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12398. #endif
  12399. }
  12400. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12401. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12402. // path.
  12403. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12404. Server svr;
  12405. const size_t LIMIT = 64 * 1024; // 64KB
  12406. svr.set_payload_max_length(LIMIT);
  12407. size_t total = 0;
  12408. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12409. const ContentReader &content_reader) {
  12410. content_reader([&](const char * /*data*/, size_t len) {
  12411. total += len;
  12412. return true;
  12413. });
  12414. res.status = 200;
  12415. res.set_content("stream_ok", "text/plain");
  12416. });
  12417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12418. auto se = detail::scope_exit([&] {
  12419. svr.stop();
  12420. thread.join();
  12421. ASSERT_FALSE(svr.is_running());
  12422. });
  12423. svr.wait_until_ready();
  12424. // Prepare 256KB raw data and gzip-compress it
  12425. std::string raw(256 * 1024, 'A');
  12426. std::string gz;
  12427. {
  12428. z_stream zs{};
  12429. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12430. Z_DEFAULT_STRATEGY);
  12431. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12432. zs.avail_in = static_cast<uInt>(raw.size());
  12433. char outbuf[4096];
  12434. int ret;
  12435. do {
  12436. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12437. zs.avail_out = sizeof(outbuf);
  12438. ret = deflate(&zs, Z_FINISH);
  12439. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12440. } while (ret != Z_STREAM_END);
  12441. deflateEnd(&zs);
  12442. }
  12443. Client cli(HOST, PORT);
  12444. cli.set_connection_timeout(std::chrono::seconds(5));
  12445. Headers headers = {{"Content-Encoding", "gzip"}};
  12446. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12447. "application/octet-stream");
  12448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12449. // Server must reject oversized decompressed payloads with 413.
  12450. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12451. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12452. EXPECT_LE(total, LIMIT);
  12453. }
  12454. #endif
  12455. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12456. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12457. // the payload must be passed through untouched instead of being rejected.
  12458. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12459. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12460. Server svr;
  12461. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12462. res.set_content(body, "image/jpeg");
  12463. res.set_header("Content-Encoding", "UTF-8");
  12464. });
  12465. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12466. res.set_content(body, "image/jpeg");
  12467. res.set_header("Content-Encoding", "identity");
  12468. });
  12469. svr.Post("/echo", [](const Request &req, Response &res) {
  12470. res.set_content(req.body, "image/jpeg");
  12471. });
  12472. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12473. auto se = detail::scope_exit([&] {
  12474. svr.stop();
  12475. t.join();
  12476. ASSERT_FALSE(svr.is_running());
  12477. });
  12478. svr.wait_until_ready();
  12479. Client cli(HOST, PORT);
  12480. {
  12481. auto res = cli.Get("/image");
  12482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12483. EXPECT_EQ(StatusCode::OK_200, res->status);
  12484. EXPECT_EQ(body, res->body);
  12485. }
  12486. {
  12487. auto res = cli.Get("/identity");
  12488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12489. EXPECT_EQ(StatusCode::OK_200, res->status);
  12490. EXPECT_EQ(body, res->body);
  12491. }
  12492. {
  12493. // The same applies to a request body reaching the server.
  12494. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12495. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12497. EXPECT_EQ(StatusCode::OK_200, res->status);
  12498. EXPECT_EQ(body, res->body);
  12499. }
  12500. }
  12501. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12502. // gzip-encoded response even when the build has no zlib support.
  12503. static const char GZIPPED_HELLO_WORLD[] = {
  12504. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12505. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12506. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12507. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12508. // A content coding is a whole token, not something the field value merely
  12509. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12510. // as "fibre" look like Brotli, and turned a multi-coding value like
  12511. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12512. // it was never meant to see.
  12513. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12514. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12515. Server svr;
  12516. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12517. res.set_content(body, "image/jpeg");
  12518. res.set_header("Content-Encoding", "fibre");
  12519. });
  12520. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12521. res.set_content(body, "image/jpeg");
  12522. res.set_header("Content-Encoding", "gzip, br");
  12523. });
  12524. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12525. res.set_content(body, "image/jpeg");
  12526. res.set_header("Content-Encoding", "x-zstd-ish");
  12527. });
  12528. auto port = svr.bind_to_any_port(HOST);
  12529. thread t = thread([&]() { svr.listen_after_bind(); });
  12530. auto se = detail::scope_exit([&] {
  12531. svr.stop();
  12532. t.join();
  12533. ASSERT_FALSE(svr.is_running());
  12534. });
  12535. svr.wait_until_ready();
  12536. Client cli(HOST, port);
  12537. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12538. auto res = cli.Get(path);
  12539. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12540. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12541. // Not a coding we recognize, so the payload comes back untouched
  12542. EXPECT_EQ(body, res->body) << path;
  12543. }
  12544. }
  12545. // A content coding cpp-httplib recognizes but was not built with must be
  12546. // reported as such. Handing the still-compressed payload back to the caller
  12547. // would silently corrupt it.
  12548. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12549. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12550. Server svr;
  12551. // "image/jpeg" keeps the server from applying a content coding of its own,
  12552. // so the hand-crafted Content-Encoding below survives.
  12553. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12554. res.set_content(gzipped, "image/jpeg");
  12555. res.set_header("Content-Encoding", "gzip");
  12556. });
  12557. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12558. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12559. res.set_content(gzipped, "image/jpeg");
  12560. res.set_header("Content-Encoding", "GZIP");
  12561. });
  12562. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12563. auto se = detail::scope_exit([&] {
  12564. svr.stop();
  12565. t.join();
  12566. ASSERT_FALSE(svr.is_running());
  12567. });
  12568. svr.wait_until_ready();
  12569. Client cli(HOST, PORT);
  12570. {
  12571. auto res = cli.Get("/gzipped");
  12572. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12574. EXPECT_EQ("Hello World!", res->body);
  12575. #else
  12576. ASSERT_FALSE(res);
  12577. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12578. #endif
  12579. }
  12580. {
  12581. // open_stream() must behave the same way.
  12582. auto handle = cli.open_stream("GET", "/gzipped");
  12583. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12584. ASSERT_TRUE(handle.is_valid());
  12585. std::string received;
  12586. char buf[256];
  12587. ssize_t n;
  12588. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12589. received.append(buf, static_cast<size_t>(n));
  12590. }
  12591. EXPECT_EQ("Hello World!", received);
  12592. #else
  12593. EXPECT_FALSE(handle.is_valid());
  12594. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12595. #endif
  12596. }
  12597. {
  12598. // A differently-cased coding must not be mistaken for an unknown one, or
  12599. // the body would be handed back still compressed.
  12600. auto res = cli.Get("/gzipped-uppercase");
  12601. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12603. EXPECT_EQ("Hello World!", res->body);
  12604. #else
  12605. ASSERT_FALSE(res);
  12606. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12607. #endif
  12608. }
  12609. }
  12610. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12611. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12612. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12613. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12614. // body a second time and appending a second Content-Encoding field line, so
  12615. // clients that decode one coding per listed value handed back raw gzip bytes.
  12616. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12617. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12618. Server svr;
  12619. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12620. // keeps the server from applying a coding of its own.
  12621. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12622. res.set_content(gzipped, "text/plain");
  12623. res.set_header("Content-Encoding", "gzip");
  12624. });
  12625. auto port = svr.bind_to_any_port(HOST);
  12626. thread t = thread([&]() { svr.listen_after_bind(); });
  12627. auto se = detail::scope_exit([&] {
  12628. svr.stop();
  12629. t.join();
  12630. ASSERT_FALSE(svr.is_running());
  12631. });
  12632. svr.wait_until_ready();
  12633. Client cli(HOST, port);
  12634. Headers headers = {{"Accept-Encoding", "gzip"}};
  12635. auto res = cli.Get("/pre-gzipped", headers);
  12636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12637. EXPECT_EQ(StatusCode::OK_200, res->status);
  12638. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12639. EXPECT_EQ("Hello World!", res->body);
  12640. }
  12641. // set_compress(false) sends every handler response as it is, buffered or
  12642. // streamed
  12643. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12644. const std::string text(1000, 'a');
  12645. Server svr;
  12646. svr.set_compress(false);
  12647. svr.Get("/buffered", [&](const Request &, Response &res) {
  12648. res.set_content(text, "text/plain");
  12649. });
  12650. svr.Get("/streamed", [&](const Request &, Response &res) {
  12651. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12652. sink.write(text.data(), text.size());
  12653. sink.done();
  12654. return true;
  12655. });
  12656. });
  12657. auto port = svr.bind_to_any_port(HOST);
  12658. ASSERT_LT(0, port);
  12659. thread t = thread([&] { svr.listen_after_bind(); });
  12660. auto se = detail::scope_exit([&] {
  12661. svr.stop();
  12662. t.join();
  12663. ASSERT_FALSE(svr.is_running());
  12664. });
  12665. svr.wait_until_ready();
  12666. Client cli(HOST, port);
  12667. cli.set_decompress(false);
  12668. for (auto path : {"/buffered", "/streamed"}) {
  12669. SCOPED_TRACE(path);
  12670. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12672. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12673. EXPECT_EQ(text, res->body);
  12674. }
  12675. }
  12676. // A chunked provider settles its coding where the headers are written and
  12677. // reuses it at write time. Both ends of that have to hold: a handler's own
  12678. // Content-Encoding suppresses the coding, and a response without one is still
  12679. // compressed as it always was.
  12680. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12681. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12682. const std::string plain = "Hello World! Hello World! Hello World!";
  12683. Server svr;
  12684. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12685. res.set_header("Content-Encoding", "gzip");
  12686. res.set_chunked_content_provider(
  12687. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12688. sink.write(gzipped.data(), gzipped.size());
  12689. sink.done();
  12690. return true;
  12691. });
  12692. });
  12693. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12694. res.set_chunked_content_provider(
  12695. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12696. sink.write(plain.data(), plain.size());
  12697. sink.done();
  12698. return true;
  12699. });
  12700. });
  12701. auto port = svr.bind_to_any_port(HOST);
  12702. thread t = thread([&]() { svr.listen_after_bind(); });
  12703. auto se = detail::scope_exit([&] {
  12704. svr.stop();
  12705. t.join();
  12706. ASSERT_FALSE(svr.is_running());
  12707. });
  12708. svr.wait_until_ready();
  12709. Client cli(HOST, port);
  12710. Headers headers = {{"Accept-Encoding", "gzip"}};
  12711. {
  12712. auto res = cli.Get("/pre-gzipped", headers);
  12713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12714. EXPECT_EQ(StatusCode::OK_200, res->status);
  12715. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12716. EXPECT_EQ("Hello World!", res->body);
  12717. }
  12718. {
  12719. auto res = cli.Get("/negotiated", headers);
  12720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12721. EXPECT_EQ(StatusCode::OK_200, res->status);
  12722. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12723. EXPECT_EQ(plain, res->body);
  12724. }
  12725. }
  12726. #endif
  12727. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12728. // the same message as the comma-joined one, so both have to be read the same
  12729. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12730. // single gzip coding, and a body the sender says was encoded twice was handed
  12731. // back after one pass, still compressed but presented as decoded.
  12732. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12733. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12734. Server svr;
  12735. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12736. res.set_content(body, "image/jpeg");
  12737. res.headers.emplace("Content-Encoding", "gzip");
  12738. res.headers.emplace("Content-Encoding", "gzip");
  12739. });
  12740. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12741. res.set_content(body, "image/jpeg");
  12742. res.set_header("Content-Encoding", "gzip, gzip");
  12743. });
  12744. auto port = svr.bind_to_any_port(HOST);
  12745. thread t = thread([&]() { svr.listen_after_bind(); });
  12746. auto se = detail::scope_exit([&] {
  12747. svr.stop();
  12748. t.join();
  12749. ASSERT_FALSE(svr.is_running());
  12750. });
  12751. svr.wait_until_ready();
  12752. Client cli(HOST, port);
  12753. // Two codings is not something cpp-httplib decodes, so both representations
  12754. // take the pass-through path rather than one of them being gunzipped once.
  12755. for (const char *path : {"/split", "/joined"}) {
  12756. auto res = cli.Get(path);
  12757. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12758. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12759. EXPECT_EQ(body, res->body) << path;
  12760. }
  12761. }
  12762. // Regression test for DoS vulnerability: a malicious server sending a response
  12763. // without Content-Length header must not cause unbounded memory consumption on
  12764. // the client side. The client should stop reading after a reasonable limit,
  12765. // similar to the server-side set_payload_max_length protection.
  12766. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12767. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12768. #ifndef _WIN32
  12769. signal(SIGPIPE, SIG_IGN);
  12770. #endif
  12771. auto server_thread = std::thread([] {
  12772. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12773. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12774. default_socket_options(srv);
  12775. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12776. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12777. sockaddr_in addr{};
  12778. addr.sin_family = AF_INET;
  12779. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12780. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12781. int opt = 1;
  12782. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12783. #ifdef _WIN32
  12784. reinterpret_cast<const char *>(&opt),
  12785. #else
  12786. &opt,
  12787. #endif
  12788. sizeof(opt));
  12789. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12790. ::listen(srv, 1);
  12791. sockaddr_in cli_addr{};
  12792. socklen_t cli_len = sizeof(cli_addr);
  12793. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12794. if (cli != INVALID_SOCKET) {
  12795. char buf[4096];
  12796. ::recv(cli, buf, sizeof(buf), 0);
  12797. // Malicious response: no Content-Length, no chunked encoding
  12798. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12799. "Connection: close\r\n"
  12800. "\r\n";
  12801. ::send(cli,
  12802. #ifdef _WIN32
  12803. static_cast<const char *>(response_header.c_str()),
  12804. static_cast<int>(response_header.size()),
  12805. #else
  12806. response_header.c_str(), response_header.size(),
  12807. #endif
  12808. 0);
  12809. // Send 10MB of data
  12810. std::string chunk(64 * 1024, 'A');
  12811. size_t total_sent = 0;
  12812. while (total_sent < MALICIOUS_DATA_SIZE) {
  12813. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12814. auto sent = ::send(cli,
  12815. #ifdef _WIN32
  12816. static_cast<const char *>(chunk.c_str()),
  12817. static_cast<int>(to_send),
  12818. #else
  12819. chunk.c_str(), to_send,
  12820. #endif
  12821. 0);
  12822. if (sent <= 0) break;
  12823. total_sent += static_cast<size_t>(sent);
  12824. }
  12825. detail::close_socket(cli);
  12826. }
  12827. detail::close_socket(srv);
  12828. });
  12829. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12830. size_t total_read = 0;
  12831. {
  12832. Client cli("127.0.0.1", PORT + 2);
  12833. cli.set_read_timeout(5, 0);
  12834. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12835. auto stream = cli.open_stream("GET", "/malicious");
  12836. ASSERT_TRUE(stream.is_valid());
  12837. char buffer[64 * 1024];
  12838. ssize_t n;
  12839. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12840. total_read += static_cast<size_t>(n);
  12841. }
  12842. } // StreamHandle and Client destroyed here, closing the socket
  12843. server_thread.join();
  12844. // With set_payload_max_length, the client must stop reading before consuming
  12845. // all 10MB. The read loop should be cut off at or near the configured limit.
  12846. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12847. << "Client read " << total_read << " bytes, exceeding the configured "
  12848. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12849. }
  12850. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12851. // the entire response body without truncation.
  12852. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12853. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12854. #ifndef _WIN32
  12855. signal(SIGPIPE, SIG_IGN);
  12856. #endif
  12857. auto server_thread = std::thread([] {
  12858. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12859. default_socket_options(srv);
  12860. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12861. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12862. sockaddr_in addr{};
  12863. addr.sin_family = AF_INET;
  12864. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12865. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12866. int opt = 1;
  12867. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12868. #ifdef _WIN32
  12869. reinterpret_cast<const char *>(&opt),
  12870. #else
  12871. &opt,
  12872. #endif
  12873. sizeof(opt));
  12874. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12875. ::listen(srv, 1);
  12876. sockaddr_in cli_addr{};
  12877. socklen_t cli_len = sizeof(cli_addr);
  12878. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12879. if (cli != INVALID_SOCKET) {
  12880. char buf[4096];
  12881. ::recv(cli, buf, sizeof(buf), 0);
  12882. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12883. "Connection: close\r\n"
  12884. "\r\n";
  12885. ::send(cli,
  12886. #ifdef _WIN32
  12887. static_cast<const char *>(response_header.c_str()),
  12888. static_cast<int>(response_header.size()),
  12889. #else
  12890. response_header.c_str(), response_header.size(),
  12891. #endif
  12892. 0);
  12893. std::string chunk(64 * 1024, 'A');
  12894. size_t total_sent = 0;
  12895. while (total_sent < DATA_SIZE) {
  12896. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12897. auto sent = ::send(cli,
  12898. #ifdef _WIN32
  12899. static_cast<const char *>(chunk.c_str()),
  12900. static_cast<int>(to_send),
  12901. #else
  12902. chunk.c_str(), to_send,
  12903. #endif
  12904. 0);
  12905. if (sent <= 0) break;
  12906. total_sent += static_cast<size_t>(sent);
  12907. }
  12908. #ifdef _WIN32
  12909. ::shutdown(cli, SD_SEND);
  12910. #else
  12911. ::shutdown(cli, SHUT_WR);
  12912. #endif
  12913. // Drain until the client closes its end, ensuring all data is delivered
  12914. char drain[1024];
  12915. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12916. detail::close_socket(cli);
  12917. }
  12918. detail::close_socket(srv);
  12919. });
  12920. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12921. size_t total_read = 0;
  12922. {
  12923. Client cli("127.0.0.1", PORT + 2);
  12924. cli.set_read_timeout(5, 0);
  12925. cli.set_payload_max_length(0); // 0 means no limit
  12926. auto stream = cli.open_stream("GET", "/data");
  12927. ASSERT_TRUE(stream.is_valid());
  12928. char buffer[64 * 1024];
  12929. ssize_t n;
  12930. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12931. total_read += static_cast<size_t>(n);
  12932. }
  12933. }
  12934. server_thread.join();
  12935. EXPECT_EQ(total_read, DATA_SIZE)
  12936. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12937. << " bytes without truncation, but only read " << total_read << " bytes.";
  12938. }
  12939. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12940. // enormous Content-Length must not cause the client to pre-allocate a huge
  12941. // response body buffer. The reservation is capped at payload_max_length_, and
  12942. // the read itself fails when the body exceeds the limit.
  12943. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12944. #ifndef _WIN32
  12945. signal(SIGPIPE, SIG_IGN);
  12946. #endif
  12947. auto server_thread = std::thread([] {
  12948. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12949. default_socket_options(srv);
  12950. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12951. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12952. sockaddr_in addr{};
  12953. addr.sin_family = AF_INET;
  12954. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12955. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12956. int opt = 1;
  12957. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12958. #ifdef _WIN32
  12959. reinterpret_cast<const char *>(&opt),
  12960. #else
  12961. &opt,
  12962. #endif
  12963. sizeof(opt));
  12964. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12965. ::listen(srv, 1);
  12966. sockaddr_in cli_addr{};
  12967. socklen_t cli_len = sizeof(cli_addr);
  12968. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12969. if (cli != INVALID_SOCKET) {
  12970. char buf[4096];
  12971. ::recv(cli, buf, sizeof(buf), 0);
  12972. // Malicious response: claim a 20GB body but send only a tiny payload.
  12973. std::string response = "HTTP/1.1 200 OK\r\n"
  12974. "Content-Length: 20000000000\r\n"
  12975. "\r\n"
  12976. "abc";
  12977. ::send(cli,
  12978. #ifdef _WIN32
  12979. static_cast<const char *>(response.c_str()),
  12980. static_cast<int>(response.size()),
  12981. #else
  12982. response.c_str(), response.size(),
  12983. #endif
  12984. 0);
  12985. detail::close_socket(cli);
  12986. }
  12987. detail::close_socket(srv);
  12988. });
  12989. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12990. {
  12991. Client cli("127.0.0.1", PORT + 2);
  12992. cli.set_read_timeout(5, 0);
  12993. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12994. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12995. // (server claims more bytes than payload_max_length permits), but it must
  12996. // not exhaust memory before getting there.
  12997. auto res = cli.Get("/malicious");
  12998. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12999. }
  13000. server_thread.join();
  13001. }
  13002. // Verify that content_receiver bypasses the default payload_max_length,
  13003. // allowing streaming downloads larger than 100MB without requiring an explicit
  13004. // set_payload_max_length call.
  13005. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13006. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13007. #ifndef _WIN32
  13008. signal(SIGPIPE, SIG_IGN);
  13009. #endif
  13010. auto server_thread = std::thread([] {
  13011. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13012. default_socket_options(srv);
  13013. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13014. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13015. sockaddr_in addr{};
  13016. addr.sin_family = AF_INET;
  13017. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13018. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13019. int opt = 1;
  13020. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13021. #ifdef _WIN32
  13022. reinterpret_cast<const char *>(&opt),
  13023. #else
  13024. &opt,
  13025. #endif
  13026. sizeof(opt));
  13027. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13028. ::listen(srv, 1);
  13029. sockaddr_in cli_addr{};
  13030. socklen_t cli_len = sizeof(cli_addr);
  13031. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13032. if (cli != INVALID_SOCKET) {
  13033. char buf[4096];
  13034. ::recv(cli, buf, sizeof(buf), 0);
  13035. // Response with Content-Length larger than default 100MB limit
  13036. auto content_length = std::to_string(DATA_SIZE);
  13037. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13038. "Content-Length: " +
  13039. content_length +
  13040. "\r\n"
  13041. "Connection: close\r\n"
  13042. "\r\n";
  13043. ::send(cli,
  13044. #ifdef _WIN32
  13045. static_cast<const char *>(response_header.c_str()),
  13046. static_cast<int>(response_header.size()),
  13047. #else
  13048. response_header.c_str(), response_header.size(),
  13049. #endif
  13050. 0);
  13051. std::string chunk(64 * 1024, 'A');
  13052. size_t total_sent = 0;
  13053. while (total_sent < DATA_SIZE) {
  13054. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13055. auto sent = ::send(cli,
  13056. #ifdef _WIN32
  13057. static_cast<const char *>(chunk.c_str()),
  13058. static_cast<int>(to_send),
  13059. #else
  13060. chunk.c_str(), to_send,
  13061. #endif
  13062. 0);
  13063. if (sent <= 0) break;
  13064. total_sent += static_cast<size_t>(sent);
  13065. }
  13066. detail::close_socket(cli);
  13067. }
  13068. detail::close_socket(srv);
  13069. });
  13070. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13071. size_t total_received = 0;
  13072. {
  13073. Client cli("127.0.0.1", PORT + 2);
  13074. cli.set_read_timeout(10, 0);
  13075. // Do NOT call set_payload_max_length — use the default 100MB limit
  13076. auto res =
  13077. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13078. total_received += data_length;
  13079. return true;
  13080. });
  13081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13082. EXPECT_EQ(StatusCode::OK_200, res->status);
  13083. }
  13084. server_thread.join();
  13085. EXPECT_EQ(total_received, DATA_SIZE)
  13086. << "With content_receiver, the client should read all " << DATA_SIZE
  13087. << " bytes despite the default 100MB payload_max_length, but only read "
  13088. << total_received << " bytes.";
  13089. }
  13090. // Verify that an explicit set_payload_max_length smaller than the response is
  13091. // enforced even when a content_receiver is used.
  13092. TEST(ClientVulnerabilityTest,
  13093. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13094. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13095. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13096. #ifndef _WIN32
  13097. signal(SIGPIPE, SIG_IGN);
  13098. #endif
  13099. auto server_thread = std::thread([] {
  13100. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13101. default_socket_options(srv);
  13102. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13103. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13104. sockaddr_in addr{};
  13105. addr.sin_family = AF_INET;
  13106. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13107. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13108. int opt = 1;
  13109. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13110. #ifdef _WIN32
  13111. reinterpret_cast<const char *>(&opt),
  13112. #else
  13113. &opt,
  13114. #endif
  13115. sizeof(opt));
  13116. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13117. ::listen(srv, 1);
  13118. sockaddr_in cli_addr{};
  13119. socklen_t cli_len = sizeof(cli_addr);
  13120. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13121. if (cli != INVALID_SOCKET) {
  13122. char buf[4096];
  13123. ::recv(cli, buf, sizeof(buf), 0);
  13124. auto content_length = std::to_string(DATA_SIZE);
  13125. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13126. "Content-Length: " +
  13127. content_length +
  13128. "\r\n"
  13129. "Connection: close\r\n"
  13130. "\r\n";
  13131. ::send(cli,
  13132. #ifdef _WIN32
  13133. static_cast<const char *>(response_header.c_str()),
  13134. static_cast<int>(response_header.size()),
  13135. #else
  13136. response_header.c_str(), response_header.size(),
  13137. #endif
  13138. 0);
  13139. std::string chunk(64 * 1024, 'A');
  13140. size_t total_sent = 0;
  13141. while (total_sent < DATA_SIZE) {
  13142. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13143. auto sent = ::send(cli,
  13144. #ifdef _WIN32
  13145. static_cast<const char *>(chunk.c_str()),
  13146. static_cast<int>(to_send),
  13147. #else
  13148. chunk.c_str(), to_send,
  13149. #endif
  13150. 0);
  13151. if (sent <= 0) break;
  13152. total_sent += static_cast<size_t>(sent);
  13153. }
  13154. detail::close_socket(cli);
  13155. }
  13156. detail::close_socket(srv);
  13157. });
  13158. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13159. size_t total_received = 0;
  13160. {
  13161. Client cli("127.0.0.1", PORT + 2);
  13162. cli.set_read_timeout(10, 0);
  13163. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13164. auto res =
  13165. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13166. total_received += data_length;
  13167. return true;
  13168. });
  13169. // Should fail because 200MB exceeds the explicit 150MB limit
  13170. EXPECT_FALSE(res);
  13171. }
  13172. server_thread.join();
  13173. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13174. << "Client with content_receiver should respect the explicit "
  13175. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13176. << total_received << " bytes.";
  13177. }
  13178. // Verify that an explicit set_payload_max_length larger than the response
  13179. // allows the content_receiver to read all data successfully.
  13180. TEST(ClientVulnerabilityTest,
  13181. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13182. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13183. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13184. #ifndef _WIN32
  13185. signal(SIGPIPE, SIG_IGN);
  13186. #endif
  13187. auto server_thread = std::thread([] {
  13188. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13189. default_socket_options(srv);
  13190. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13191. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13192. sockaddr_in addr{};
  13193. addr.sin_family = AF_INET;
  13194. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13195. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13196. int opt = 1;
  13197. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13198. #ifdef _WIN32
  13199. reinterpret_cast<const char *>(&opt),
  13200. #else
  13201. &opt,
  13202. #endif
  13203. sizeof(opt));
  13204. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13205. ::listen(srv, 1);
  13206. sockaddr_in cli_addr{};
  13207. socklen_t cli_len = sizeof(cli_addr);
  13208. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13209. if (cli != INVALID_SOCKET) {
  13210. char buf[4096];
  13211. ::recv(cli, buf, sizeof(buf), 0);
  13212. auto content_length = std::to_string(DATA_SIZE);
  13213. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13214. "Content-Length: " +
  13215. content_length +
  13216. "\r\n"
  13217. "Connection: close\r\n"
  13218. "\r\n";
  13219. ::send(cli,
  13220. #ifdef _WIN32
  13221. static_cast<const char *>(response_header.c_str()),
  13222. static_cast<int>(response_header.size()),
  13223. #else
  13224. response_header.c_str(), response_header.size(),
  13225. #endif
  13226. 0);
  13227. std::string chunk(64 * 1024, 'A');
  13228. size_t total_sent = 0;
  13229. while (total_sent < DATA_SIZE) {
  13230. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13231. auto sent = ::send(cli,
  13232. #ifdef _WIN32
  13233. static_cast<const char *>(chunk.c_str()),
  13234. static_cast<int>(to_send),
  13235. #else
  13236. chunk.c_str(), to_send,
  13237. #endif
  13238. 0);
  13239. if (sent <= 0) break;
  13240. total_sent += static_cast<size_t>(sent);
  13241. }
  13242. #ifdef _WIN32
  13243. ::shutdown(cli, SD_SEND);
  13244. #else
  13245. ::shutdown(cli, SHUT_WR);
  13246. #endif
  13247. char drain[1024];
  13248. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13249. detail::close_socket(cli);
  13250. }
  13251. detail::close_socket(srv);
  13252. });
  13253. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13254. size_t total_received = 0;
  13255. {
  13256. Client cli("127.0.0.1", PORT + 2);
  13257. cli.set_read_timeout(10, 0);
  13258. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13259. auto res =
  13260. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13261. total_received += data_length;
  13262. return true;
  13263. });
  13264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13265. EXPECT_EQ(StatusCode::OK_200, res->status);
  13266. }
  13267. server_thread.join();
  13268. EXPECT_EQ(total_received, DATA_SIZE)
  13269. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13270. << " bytes (larger than " << DATA_SIZE
  13271. << " bytes response), content_receiver should read all data, but only "
  13272. "read "
  13273. << total_received << " bytes.";
  13274. }
  13275. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13276. // Regression test for "zip bomb" attack on the client side: a malicious server
  13277. // sends a small gzip-compressed response that decompresses to a huge payload.
  13278. // The client must enforce payload_max_length on the decompressed size.
  13279. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13280. constexpr size_t DECOMPRESSED_SIZE =
  13281. 10 * 1024 * 1024; // 10MB after decompression
  13282. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13283. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13284. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13285. std::string compressed;
  13286. {
  13287. httplib::detail::gzip_compressor compressor;
  13288. bool ok =
  13289. compressor.compress(uncompressed.data(), uncompressed.size(),
  13290. /*last=*/true, [&](const char *buf, size_t len) {
  13291. compressed.append(buf, len);
  13292. return true;
  13293. });
  13294. ASSERT_TRUE(ok);
  13295. }
  13296. // Sanity: compressed data should be much smaller than the decompressed size
  13297. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13298. #ifndef _WIN32
  13299. signal(SIGPIPE, SIG_IGN);
  13300. #endif
  13301. // Set up the listening socket in the main thread so the server is guaranteed
  13302. // to be ready before the client connects (eliminates race condition).
  13303. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13304. default_socket_options(srv);
  13305. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13306. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13307. sockaddr_in addr{};
  13308. addr.sin_family = AF_INET;
  13309. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13310. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13311. int opt = 1;
  13312. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13313. #ifdef _WIN32
  13314. reinterpret_cast<const char *>(&opt),
  13315. #else
  13316. &opt,
  13317. #endif
  13318. sizeof(opt));
  13319. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13320. ASSERT_EQ(0, ::listen(srv, 1));
  13321. auto server_thread = std::thread([&compressed, srv] {
  13322. sockaddr_in cli_addr{};
  13323. socklen_t cli_len = sizeof(cli_addr);
  13324. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13325. if (cli != INVALID_SOCKET) {
  13326. // Read the full HTTP request (until \r\n\r\n)
  13327. char buf[4096];
  13328. size_t total = 0;
  13329. while (total < sizeof(buf)) {
  13330. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13331. if (n <= 0) break;
  13332. total += static_cast<size_t>(n);
  13333. // Check for end of headers
  13334. if (total >= 4) {
  13335. std::string req(buf, total);
  13336. if (req.find("\r\n\r\n") != std::string::npos) break;
  13337. }
  13338. }
  13339. // Malicious response: gzip-compressed body, no Content-Length
  13340. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13341. "Content-Encoding: gzip\r\n"
  13342. "Connection: close\r\n"
  13343. "\r\n";
  13344. ::send(cli,
  13345. #ifdef _WIN32
  13346. static_cast<const char *>(response_header.c_str()),
  13347. static_cast<int>(response_header.size()),
  13348. #else
  13349. response_header.c_str(), response_header.size(),
  13350. #endif
  13351. 0);
  13352. // Send the compressed payload (small on the wire, huge when decompressed)
  13353. size_t total_sent = 0;
  13354. while (total_sent < compressed.size()) {
  13355. auto to_send = std::min(compressed.size() - total_sent,
  13356. static_cast<size_t>(64 * 1024));
  13357. auto sent =
  13358. ::send(cli,
  13359. #ifdef _WIN32
  13360. static_cast<const char *>(compressed.c_str() + total_sent),
  13361. static_cast<int>(to_send),
  13362. #else
  13363. compressed.c_str() + total_sent, to_send,
  13364. #endif
  13365. 0);
  13366. if (sent <= 0) break;
  13367. total_sent += static_cast<size_t>(sent);
  13368. }
  13369. detail::close_socket(cli);
  13370. }
  13371. });
  13372. auto se = detail::scope_exit([&] {
  13373. detail::close_socket(srv);
  13374. server_thread.join();
  13375. });
  13376. size_t total_decompressed = 0;
  13377. {
  13378. Client cli("127.0.0.1", PORT + 3);
  13379. cli.set_read_timeout(5, 0);
  13380. cli.set_decompress(true);
  13381. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13382. auto stream = cli.open_stream("GET", "/zipbomb");
  13383. ASSERT_TRUE(stream.is_valid());
  13384. char buffer[64 * 1024];
  13385. ssize_t n;
  13386. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13387. total_decompressed += static_cast<size_t>(n);
  13388. }
  13389. }
  13390. // The decompressed size must be capped by payload_max_length. Without
  13391. // protection, the client would decompress the full 10MB from a tiny
  13392. // compressed payload, enabling a zip bomb DoS attack.
  13393. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13394. << "Client decompressed " << total_decompressed
  13395. << " bytes from a gzip response. The decompressed size should be "
  13396. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13397. }
  13398. #endif
  13399. TEST(HostAndPortPropertiesTest, NoSSL) {
  13400. httplib::Client cli("www.google.com", 1234);
  13401. ASSERT_EQ("www.google.com", cli.host());
  13402. ASSERT_EQ(1234, cli.port());
  13403. }
  13404. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13405. httplib::Client cli("www.google.com:1234");
  13406. ASSERT_EQ("www.google.com", cli.host());
  13407. ASSERT_EQ(1234, cli.port());
  13408. }
  13409. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13410. // Port number that overflows int — should not crash, client becomes invalid
  13411. httplib::Client cli("http://www.google.com:99999999999999999999");
  13412. ASSERT_FALSE(cli.is_valid());
  13413. }
  13414. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13415. // Port 99999 exceeds valid range (1-65535) — should not crash
  13416. httplib::Client cli("http://www.google.com:99999");
  13417. ASSERT_FALSE(cli.is_valid());
  13418. auto res = cli.Get("/");
  13419. EXPECT_FALSE(res);
  13420. EXPECT_EQ(Error::Connection, res.error());
  13421. }
  13422. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13423. httplib::Client cli("http://user:pass@localhost:1234");
  13424. ASSERT_FALSE(cli.is_valid());
  13425. EXPECT_FALSE(cli.Get("/"));
  13426. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13427. }
  13428. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13429. httplib::Client cli("http://www.google.com:80abc");
  13430. ASSERT_FALSE(cli.is_valid());
  13431. }
  13432. #ifdef CPPHTTPLIB_SSL_ENABLED
  13433. TEST(HostAndPortPropertiesTest, SSL) {
  13434. httplib::SSLClient cli("www.google.com");
  13435. ASSERT_EQ("www.google.com", cli.host());
  13436. ASSERT_EQ(443, cli.port());
  13437. }
  13438. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13439. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13440. std::string cert;
  13441. read_file(CA_CERT_FILE, cert);
  13442. httplib::SSLClient httplib_client("www.google.com");
  13443. // Load CA store first time
  13444. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13445. // Load CA store second time (update)
  13446. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13447. // Verify client is still valid and can make connections
  13448. httplib_client.enable_server_certificate_verification(true);
  13449. auto res = httplib_client.Get("/");
  13450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13451. // Google may return 200 or 301 depending on various factors
  13452. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13453. res->status == StatusCode::MovedPermanently_301);
  13454. }
  13455. TEST(SSLClientTest, ServerNameIndication_Online) {
  13456. auto host = "httpbingo.org";
  13457. auto path = std::string{"/get"};
  13458. SSLClient cli(host, 443);
  13459. auto res = cli.Get(path);
  13460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13461. ASSERT_EQ(StatusCode::OK_200, res->status);
  13462. }
  13463. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13464. // Use a site that will cause SSL verification failure due to self-signed cert
  13465. SSLClient cli("self-signed.badssl.com", 443);
  13466. cli.enable_server_certificate_verification(true);
  13467. auto res = cli.Get("/");
  13468. ASSERT_TRUE(!res);
  13469. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13470. // Verify backend error is captured for SSLServerVerification
  13471. // This occurs when certificate verification fails
  13472. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13473. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13474. EXPECT_NE(0UL, res.ssl_backend_error());
  13475. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13476. res.ssl_error());
  13477. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13478. #if !defined(_WIN32) || \
  13479. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13480. // On non-Windows or when Windows Schannel is disabled, the error comes
  13481. // from OpenSSL's verification
  13482. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13483. res.ssl_backend_error());
  13484. #endif
  13485. #endif
  13486. }
  13487. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13488. // Use a site where hostname doesn't match the certificate
  13489. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13490. SSLClient cli("wrong.host.badssl.com", 443);
  13491. cli.enable_server_certificate_verification(true);
  13492. cli.enable_server_hostname_verification(true);
  13493. auto res = cli.Get("/");
  13494. ASSERT_TRUE(!res);
  13495. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13496. // Verify backend error is captured for hostname verification failure
  13497. EXPECT_NE(0UL, res.ssl_backend_error());
  13498. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13499. res.ssl_error());
  13500. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13501. #if !defined(_WIN32) || \
  13502. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13503. // On non-Windows or when Windows Schannel is disabled, the error comes
  13504. // from OpenSSL's hostname verification
  13505. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13506. res.ssl_backend_error());
  13507. #endif
  13508. #endif
  13509. }
  13510. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13511. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13512. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13513. SSLClient cli("www.google.com", 443);
  13514. cli.enable_server_certificate_verification(true);
  13515. auto res = cli.Get("/");
  13516. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13517. }
  13518. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13519. SSLClient cli("www.google.com", 443);
  13520. cli.enable_server_certificate_verification(true);
  13521. cli.enable_windows_certificate_verification(false);
  13522. auto res = cli.Get("/");
  13523. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13524. }
  13525. // The server sends an intermediate cross-signed by a root Windows trusts,
  13526. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13527. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13528. SSLClient cli("accounts.spotify.com", 443);
  13529. auto res = cli.Get("/");
  13530. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13531. << " ssl_backend_error=" << res.ssl_backend_error();
  13532. }
  13533. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13534. // policy status, which no backend reports for a self-signed certificate.
  13535. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13536. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13537. ASSERT_TRUE(svr.is_valid());
  13538. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13539. auto se = detail::scope_exit([&] {
  13540. svr.stop();
  13541. t.join();
  13542. ASSERT_FALSE(svr.is_running());
  13543. });
  13544. svr.wait_until_ready();
  13545. SSLClient cli("127.0.0.1", PORT);
  13546. cli.set_connection_timeout(30);
  13547. auto res = cli.Get("/");
  13548. ASSERT_FALSE(res);
  13549. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13550. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13551. }
  13552. #endif
  13553. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13554. Client cli("https://google.com");
  13555. auto res = cli.Get("/");
  13556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13557. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13558. }
  13559. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13560. SSLClient cli("google.com");
  13561. cli.set_ca_cert_path(CA_CERT_FILE);
  13562. auto res = cli.Get("/");
  13563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13564. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13565. }
  13566. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13567. SSLClient cli("google.com");
  13568. cli.enable_server_certificate_verification(true);
  13569. cli.set_ca_cert_path("hello");
  13570. auto res = cli.Get("/");
  13571. ASSERT_TRUE(!res);
  13572. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13573. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13574. // should be set
  13575. EXPECT_EQ(0, res.ssl_error());
  13576. // Verify backend error is captured for SSLLoadingCerts
  13577. // This error occurs when loading CA certificates fails
  13578. EXPECT_NE(0UL, res.ssl_backend_error());
  13579. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13580. // OpenSSL specific error codes:
  13581. // > openssl errstr 0x80000002
  13582. // error:80000002:system library::No such file or directory
  13583. // > openssl errstr 0xA000126
  13584. // error:0A000126:SSL routines::unexpected eof while reading
  13585. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13586. res.ssl_backend_error() == 0xA000126);
  13587. #endif
  13588. }
  13589. TEST(SSLClientTest, ServerCertificateVerification4) {
  13590. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13591. ASSERT_TRUE(svr.is_valid());
  13592. svr.Get("/test", [&](const Request &, Response &res) {
  13593. res.set_content("test", "text/plain");
  13594. svr.stop();
  13595. ASSERT_TRUE(true);
  13596. });
  13597. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13598. auto se = detail::scope_exit([&] {
  13599. t.join();
  13600. ASSERT_FALSE(svr.is_running());
  13601. });
  13602. svr.wait_until_ready();
  13603. SSLClient cli("127.0.0.1", PORT);
  13604. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13605. cli.enable_server_certificate_verification(true);
  13606. cli.set_connection_timeout(30);
  13607. auto res = cli.Get("/test");
  13608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13609. ASSERT_EQ(StatusCode::OK_200, res->status);
  13610. }
  13611. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13612. std::string cert;
  13613. read_file(CA_CERT_FILE, cert);
  13614. SSLClient cli("google.com");
  13615. cli.load_ca_cert_store(cert.data(), cert.size());
  13616. const auto res = cli.Get("/");
  13617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13618. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13619. }
  13620. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13621. // clang-format off
  13622. static constexpr char cert[] =
  13623. "GlobalSign Root CA\n"
  13624. "==================\n"
  13625. "-----BEGIN CERTIFICATE-----\n"
  13626. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13627. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13628. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13629. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13630. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13631. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13632. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13633. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13634. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13635. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13636. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13637. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13638. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13639. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13640. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13641. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13642. "-----END CERTIFICATE-----\n";
  13643. // clang-format on
  13644. SSLClient cli("google.com");
  13645. cli.load_ca_cert_store(cert, sizeof(cert));
  13646. const auto res = cli.Get("/");
  13647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13648. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13649. }
  13650. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13651. SSLClient cli("www.youtube.com");
  13652. cli.set_ca_cert_path(CA_CERT_FILE);
  13653. cli.enable_server_certificate_verification(true);
  13654. cli.set_follow_location(true);
  13655. auto res = cli.Get("/");
  13656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13657. ASSERT_EQ(StatusCode::OK_200, res->status);
  13658. }
  13659. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13660. SSLClient cli("wWw.YouTube.Com");
  13661. cli.set_ca_cert_path(CA_CERT_FILE);
  13662. cli.enable_server_certificate_verification(true);
  13663. cli.enable_server_hostname_verification(true);
  13664. cli.set_follow_location(true);
  13665. auto res = cli.Get("/");
  13666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13667. ASSERT_EQ(StatusCode::OK_200, res->status);
  13668. }
  13669. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13670. SSLClient cli("gOoGlE.COm");
  13671. cli.enable_server_certificate_verification(true);
  13672. cli.enable_server_hostname_verification(true);
  13673. cli.set_follow_location(true);
  13674. auto res = cli.Get("/");
  13675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13676. ASSERT_EQ(StatusCode::OK_200, res->status);
  13677. }
  13678. TEST(SSLClientTest, Issue2004_Online) {
  13679. Client client("https://google.com");
  13680. client.set_follow_location(true);
  13681. auto res = client.Get("/");
  13682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13683. ASSERT_EQ(StatusCode::OK_200, res->status);
  13684. auto body = res->body;
  13685. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13686. }
  13687. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13688. // Create SSLClient with invalid cert/key to make is_valid() return false
  13689. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13690. "nonexistent_key.pem");
  13691. // is_valid() should be false due to cert loading failure
  13692. ASSERT_FALSE(cli.is_valid());
  13693. auto res = cli.Get("/");
  13694. ASSERT_FALSE(res);
  13695. EXPECT_EQ(Error::SSLConnection, res.error());
  13696. }
  13697. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13698. // Test for Issue #2251: SSL error not properly reported when client cert
  13699. // and key paths are swapped or mismatched
  13700. // This simulates the scenario where user accidentally swaps the cert and key
  13701. // files
  13702. // Using client cert file as private key and vice versa (completely wrong)
  13703. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13704. // Should fail validation due to cert/key mismatch
  13705. ASSERT_FALSE(cli.is_valid());
  13706. // Attempt to make a request should fail with proper error
  13707. auto res = cli.Get("/");
  13708. ASSERT_FALSE(res);
  13709. EXPECT_EQ(Error::SSLConnection, res.error());
  13710. // SSL error should be recorded in the Result object (this is the key fix for
  13711. // Issue #2251)
  13712. auto backend_error = res.ssl_backend_error();
  13713. EXPECT_NE(0u, backend_error);
  13714. }
  13715. // Tests cert/key mismatch detection at the TLS context level
  13716. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13717. // Test that using mismatched cert/key causes connection failure.
  13718. // We verify this at the SSLClient level rather than through internal
  13719. // TLS API functions.
  13720. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13721. cli.enable_server_certificate_verification(false);
  13722. cli.set_connection_timeout(2);
  13723. // The mismatch should cause a connection or handshake error
  13724. auto res = cli.Get("/test");
  13725. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13726. // Either way, the request should fail
  13727. EXPECT_FALSE(res);
  13728. }
  13729. #endif
  13730. #if 0
  13731. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13732. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13733. ASSERT_TRUE(cli != nullptr);
  13734. cli->set_address_family(AF_INET6);
  13735. cli->set_interface("en0");
  13736. auto res = cli->Get("/get");
  13737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13738. ASSERT_EQ(StatusCode::OK_200, res->status);
  13739. }
  13740. #endif
  13741. // Client certificate tests - work with all TLS backends
  13742. #ifdef CPPHTTPLIB_SSL_ENABLED
  13743. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13744. void ClientCertPresent(
  13745. const std::string &client_cert_file,
  13746. const std::string &client_private_key_file,
  13747. const std::string &client_encrypted_private_key_pass = std::string(),
  13748. const ClientCertServerSetup &setup = nullptr) {
  13749. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13750. ASSERT_TRUE(svr.is_valid());
  13751. if (setup) { setup(svr); }
  13752. svr.Get("/test", [&](const Request &req, Response &res) {
  13753. res.set_content("test", "text/plain");
  13754. auto cert = req.peer_cert();
  13755. ASSERT_TRUE(static_cast<bool>(cert));
  13756. std::string common_name = cert.subject_cn();
  13757. EXPECT_EQ("Common Name", common_name);
  13758. });
  13759. auto port = svr.bind_to_any_port(HOST);
  13760. ASSERT_LT(0, port);
  13761. thread t = thread([&]() { svr.listen_after_bind(); });
  13762. auto se = detail::scope_exit([&] {
  13763. svr.stop();
  13764. t.join();
  13765. ASSERT_FALSE(svr.is_running());
  13766. });
  13767. svr.wait_until_ready();
  13768. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13769. client_encrypted_private_key_pass);
  13770. cli.enable_server_certificate_verification(false);
  13771. cli.set_connection_timeout(30);
  13772. auto res = cli.Get("/test");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. ASSERT_EQ(StatusCode::OK_200, res->status);
  13775. }
  13776. TEST(SSLClientServerTest, ClientCertPresent) {
  13777. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13778. }
  13779. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13780. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13781. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13782. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13783. }
  13784. // Expects svr, which must require client certificates, to reject a client
  13785. // that has none
  13786. void RejectsClientWithoutCert(SSLServer &svr) {
  13787. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13788. auto port = svr.bind_to_any_port(HOST);
  13789. ASSERT_LT(0, port);
  13790. thread t = thread([&]() { svr.listen_after_bind(); });
  13791. auto se = detail::scope_exit([&] {
  13792. svr.stop();
  13793. t.join();
  13794. ASSERT_FALSE(svr.is_running());
  13795. });
  13796. svr.wait_until_ready();
  13797. SSLClient cli(HOST, port);
  13798. cli.set_connection_timeout(30);
  13799. // Skip the server certificate check, so that the request fails because the
  13800. // client certificate is missing rather than because cert.pem is not trusted
  13801. cli.enable_server_certificate_verification(false);
  13802. auto res = cli.Get("/test");
  13803. ASSERT_FALSE(res);
  13804. // The server rejects the client during the handshake, or on TLS 1.3 right
  13805. // after it, which the client notices on its first write or read
  13806. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13807. res.error() == Error::Write || res.error() == Error::Read)
  13808. << to_string(res.error());
  13809. if (res.error() == Error::SSLConnection) {
  13810. EXPECT_NE(0UL, res.ssl_backend_error());
  13811. }
  13812. // A rejection noticed on the write keeps the TLS error the write hit
  13813. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13814. }
  13815. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13817. ASSERT_TRUE(svr.is_valid());
  13818. if (setup) { setup(svr); }
  13819. RejectsClientWithoutCert(svr);
  13820. }
  13821. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13822. // A server that requires client certificates must keep requiring them after
  13823. // setup changes it, and keep accepting a client that has one
  13824. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13825. ClientCertMissing(setup);
  13826. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13827. setup);
  13828. }
  13829. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13830. ClientCertStillRequired([](SSLServer &svr) {
  13831. ASSERT_TRUE(tls::set_verify_callback(
  13832. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13833. });
  13834. }
  13835. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13836. ClientCertStillRequired([](SSLServer &svr) {
  13837. ASSERT_TRUE(tls::set_verify_callback(
  13838. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13839. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13840. });
  13841. }
  13842. // The client verifies the server certificate during the handshake, so a
  13843. // server that fails the check never gets the client certificate, even when a
  13844. // verifier of the client's own accepts it
  13845. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13846. struct Case {
  13847. const char *trusted_ca;
  13848. const char *host;
  13849. Error error;
  13850. };
  13851. // cert2.pem names localhost: the first client does not trust it, and the
  13852. // second trusts it but asks for another name
  13853. for (const auto &c :
  13854. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13855. Case{SERVER_CERT2_FILE, "example.com",
  13856. Error::SSLServerHostnameVerification}}) {
  13857. for (auto with_verifier : {false, true}) {
  13858. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13859. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13860. CLIENT_CA_CERT_FILE);
  13861. ASSERT_TRUE(svr.is_valid());
  13862. std::atomic<bool> got_client_cert{false};
  13863. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13864. [&](const tls::VerifyContext &) {
  13865. got_client_cert = true;
  13866. return true;
  13867. }));
  13868. auto port = svr.bind_to_any_port("127.0.0.1");
  13869. ASSERT_LT(0, port);
  13870. thread t = thread([&] { svr.listen_after_bind(); });
  13871. svr.wait_until_ready();
  13872. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13873. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13874. cli.set_ca_cert_path(c.trusted_ca);
  13875. if (with_verifier) {
  13876. cli.set_server_certificate_verifier(
  13877. [](const tls::VerifyContext &) { return true; });
  13878. }
  13879. auto res = cli.Get("/");
  13880. EXPECT_FALSE(res);
  13881. EXPECT_EQ(c.error, res.error());
  13882. svr.stop();
  13883. t.join();
  13884. EXPECT_FALSE(got_client_cert);
  13885. }
  13886. }
  13887. }
  13888. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13889. std::string cert_pem, key_pem, ca_pem;
  13890. read_file(SERVER_CERT_FILE, cert_pem);
  13891. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13892. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13893. ASSERT_TRUE(
  13894. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13895. }
  13896. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13898. ASSERT_TRUE(svr.is_valid());
  13899. UpdateCertsPemWithClientCA(svr);
  13900. RejectsClientWithoutCert(svr);
  13901. }
  13902. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13903. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13904. }
  13905. // A TLS error from one request must not show up in a later request's Result
  13906. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13908. ASSERT_TRUE(svr.is_valid());
  13909. svr.Get("/test", [](const Request &, Response &res) {
  13910. res.set_content("test", "text/plain");
  13911. });
  13912. auto port = svr.bind_to_any_port(HOST);
  13913. ASSERT_LT(0, port);
  13914. thread t = thread([&]() { svr.listen_after_bind(); });
  13915. auto se = detail::scope_exit([&] {
  13916. svr.stop();
  13917. t.join();
  13918. ASSERT_FALSE(svr.is_running());
  13919. });
  13920. svr.wait_until_ready();
  13921. SSLClient cli(HOST, port);
  13922. cli.set_connection_timeout(30);
  13923. cli.enable_server_hostname_verification(false);
  13924. // cert.pem is not trusted, so the handshake fails
  13925. ASSERT_FALSE(cli.Get("/test"));
  13926. cli.enable_server_certificate_verification(false);
  13927. auto res = cli.Get("/test");
  13928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13929. EXPECT_EQ(0, res.ssl_error());
  13930. EXPECT_EQ(0UL, res.ssl_backend_error());
  13931. }
  13932. // PEM memory-based constructor tests (works with all TLS backends).
  13933. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13934. // terminator after it.
  13935. void PemMemoryClientCertPresent(
  13936. const std::string &client_cert_file,
  13937. const std::string &client_private_key_file,
  13938. const std::string &client_encrypted_private_key_pass = std::string(),
  13939. bool exact_size = false) {
  13940. // Read PEM files into memory
  13941. std::string server_cert_pem, server_key_pem;
  13942. std::string client_ca_pem;
  13943. std::string client_cert_pem, client_key_pem;
  13944. read_file(SERVER_CERT_FILE, server_cert_pem);
  13945. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13946. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13947. read_file(client_cert_file, client_cert_pem);
  13948. read_file(client_private_key_file, client_key_pem);
  13949. std::list<std::vector<char>> exact_copies;
  13950. auto data = [&](const std::string &pem) -> const char * {
  13951. if (!exact_size) { return pem.c_str(); }
  13952. exact_copies.emplace_back(pem.begin(), pem.end());
  13953. return exact_copies.back().data();
  13954. };
  13955. // Create server with PEM memory
  13956. SSLServer::PemMemory server_pem = {
  13957. data(server_cert_pem),
  13958. server_cert_pem.size(),
  13959. data(server_key_pem),
  13960. server_key_pem.size(),
  13961. data(client_ca_pem),
  13962. client_ca_pem.size(),
  13963. nullptr // no password for server key
  13964. };
  13965. SSLServer svr(server_pem);
  13966. ASSERT_TRUE(svr.is_valid());
  13967. svr.Get("/test", [&](const Request &req, Response &res) {
  13968. res.set_content("test", "text/plain");
  13969. auto cert = req.peer_cert();
  13970. ASSERT_TRUE(static_cast<bool>(cert));
  13971. EXPECT_EQ("Common Name", cert.subject_cn());
  13972. });
  13973. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13974. auto se = detail::scope_exit([&] {
  13975. svr.stop();
  13976. t.join();
  13977. ASSERT_FALSE(svr.is_running());
  13978. });
  13979. svr.wait_until_ready();
  13980. // Create client with PEM memory
  13981. const char *password = client_encrypted_private_key_pass.empty()
  13982. ? nullptr
  13983. : client_encrypted_private_key_pass.c_str();
  13984. SSLClient::PemMemory client_pem = {
  13985. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13986. client_key_pem.size(), password};
  13987. SSLClient cli(HOST, PORT, client_pem);
  13988. cli.enable_server_certificate_verification(false);
  13989. cli.set_connection_timeout(30);
  13990. auto res = cli.Get("/test");
  13991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13992. ASSERT_EQ(StatusCode::OK_200, res->status);
  13993. }
  13994. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13995. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13996. }
  13997. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13998. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13999. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14000. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14001. }
  14002. // A server built from PEM memory with a client CA requires client certificates,
  14003. // also when the CA is a NUL-terminated string passed with a length of 0
  14004. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14005. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14006. read_file(SERVER_CERT_FILE, server_cert_pem);
  14007. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14008. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14009. SSLServer::PemMemory server_pem = {
  14010. server_cert_pem.c_str(),
  14011. server_cert_pem.size(),
  14012. server_key_pem.c_str(),
  14013. server_key_pem.size(),
  14014. client_ca_pem.c_str(),
  14015. client_ca_pem.size(),
  14016. nullptr // no password for server key
  14017. };
  14018. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14019. SCOPED_TRACE(client_ca_pem_len);
  14020. server_pem.client_ca_pem_len = client_ca_pem_len;
  14021. SSLServer svr(server_pem);
  14022. ASSERT_TRUE(svr.is_valid());
  14023. RejectsClientWithoutCert(svr);
  14024. }
  14025. // An empty CA fails to load instead of turning the check off
  14026. server_pem.client_ca_pem = "";
  14027. server_pem.client_ca_pem_len = 0;
  14028. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14029. }
  14030. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14031. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14032. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14033. true);
  14034. }
  14035. // A length shorter than the PEM cuts it short, so it no longer loads
  14036. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14037. std::string cert, key;
  14038. read_file(SERVER_CERT_FILE, cert);
  14039. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14040. for (auto cut_cert : {true, false}) {
  14041. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14042. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14043. SSLServer::PemMemory server_pem = {
  14044. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14045. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14046. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14047. key_len, nullptr};
  14048. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14049. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14050. key.c_str(), key_len, nullptr};
  14051. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14052. }
  14053. }
  14054. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14055. class NoListenSSLServer : public SSLServer {
  14056. public:
  14057. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14058. const char *client_ca_cert_file_path,
  14059. const char *client_ca_cert_dir_path = nullptr)
  14060. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14061. client_ca_cert_dir_path),
  14062. stop_(false) {}
  14063. std::atomic_bool stop_;
  14064. private:
  14065. bool process_and_close_socket(socket_t /*sock*/) override {
  14066. // Don't create SSL context
  14067. while (!stop_.load()) {
  14068. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14069. }
  14070. return true;
  14071. }
  14072. };
  14073. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14074. CLIENT_CA_CERT_FILE);
  14075. ASSERT_TRUE(svr.is_valid());
  14076. svr.Get("/test", [&](const Request &, Response &res) {
  14077. res.set_content("test", "text/plain");
  14078. });
  14079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14080. auto se = detail::scope_exit([&] {
  14081. svr.stop_ = true;
  14082. svr.stop();
  14083. t.join();
  14084. ASSERT_FALSE(svr.is_running());
  14085. });
  14086. svr.wait_until_ready();
  14087. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14088. cli.enable_server_certificate_verification(false);
  14089. cli.set_connection_timeout(1);
  14090. auto res = cli.Get("/test");
  14091. ASSERT_TRUE(!res);
  14092. EXPECT_EQ(Error::SSLConnection, res.error());
  14093. // Timeout results in WantRead error code (maps to backend-specific value)
  14094. EXPECT_NE(0, res.ssl_error());
  14095. }
  14096. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14097. // Test SSLServer with client certificate verification using the standard
  14098. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14099. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14100. CLIENT_CA_CERT_DIR);
  14101. ASSERT_TRUE(svr.is_valid());
  14102. svr.Get("/test", [&](const Request &req, Response &res) {
  14103. res.set_content("test", "text/plain");
  14104. auto cert = req.peer_cert();
  14105. ASSERT_TRUE(static_cast<bool>(cert));
  14106. auto common_name = cert.subject_cn();
  14107. EXPECT_EQ("Common Name", common_name);
  14108. });
  14109. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14110. auto se = detail::scope_exit([&] {
  14111. svr.stop();
  14112. t.join();
  14113. ASSERT_FALSE(svr.is_running());
  14114. });
  14115. svr.wait_until_ready();
  14116. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14117. cli.enable_server_certificate_verification(false);
  14118. cli.set_connection_timeout(30);
  14119. auto res = cli.Get("/test");
  14120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14121. ASSERT_EQ(StatusCode::OK_200, res->status);
  14122. }
  14123. // Test verify_hostname on every backend: a host is named by a SAN only
  14124. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14125. using namespace httplib::tls;
  14126. // We need a running server to test against
  14127. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14128. ASSERT_TRUE(svr.is_valid());
  14129. svr.Get("/test", [](const Request &, Response &res) {
  14130. res.set_content("ok", "text/plain");
  14131. });
  14132. thread t([&]() { svr.listen(HOST, PORT); });
  14133. auto se = detail::scope_exit([&] {
  14134. svr.stop();
  14135. t.join();
  14136. });
  14137. svr.wait_until_ready();
  14138. bool verify_callback_called = false;
  14139. bool verify_result_wrong = false;
  14140. SSLClient cli(HOST, PORT);
  14141. cli.enable_server_certificate_verification(true);
  14142. cli.set_ca_cert_path(CA_CERT_FILE);
  14143. cli.set_connection_timeout(5);
  14144. // Note: Test certificate has CN="Common Name", not "localhost"
  14145. bool verify_result_cn = false;
  14146. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14147. verify_callback_called = true;
  14148. if (!ctx.cert) return false;
  14149. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14150. verify_result_cn = ctx.check_hostname("Common Name");
  14151. // Test 2: wrong hostname should not match
  14152. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14153. return true; // Accept for the purpose of this test
  14154. });
  14155. auto res = cli.Get("/test");
  14156. // The request may succeed or fail depending on cert configuration
  14157. // but the callback should have been called
  14158. ASSERT_TRUE(verify_callback_called)
  14159. << "Verify callback should have been called";
  14160. EXPECT_FALSE(verify_result_cn)
  14161. << "verify_hostname must not match the certificate CN (no SAN)";
  14162. // Wrong hostname should not match
  14163. EXPECT_FALSE(verify_result_wrong)
  14164. << "verify_hostname should not match 'wronghost.example.com'";
  14165. }
  14166. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14167. // backend verifies it.
  14168. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14169. // Certificate CN is "localhost" and it carries no SAN.
  14170. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14171. ASSERT_TRUE(svr.is_valid());
  14172. svr.Get("/test", [](const Request &, Response &res) {
  14173. res.set_content("ok", "text/plain");
  14174. });
  14175. auto port = svr.bind_to_any_port(HOST);
  14176. thread t([&]() { svr.listen_after_bind(); });
  14177. auto se = detail::scope_exit([&] {
  14178. svr.stop();
  14179. t.join();
  14180. });
  14181. svr.wait_until_ready();
  14182. SSLClient cli("localhost", port);
  14183. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14184. cli.enable_server_certificate_verification(true);
  14185. cli.set_connection_timeout(5);
  14186. auto res = cli.Get("/test");
  14187. ASSERT_FALSE(res);
  14188. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14189. // The same certificate is accepted once host name verification is off, so the
  14190. // failure above is the host name and not the chain.
  14191. cli.enable_server_hostname_verification(false);
  14192. res = cli.Get("/test");
  14193. ASSERT_TRUE(res) << to_string(res.error());
  14194. EXPECT_EQ(StatusCode::OK_200, res->status);
  14195. }
  14196. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14197. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14198. // X509_check_ip behavior and must hold for every backend.
  14199. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14200. using namespace httplib::tls;
  14201. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14202. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14203. ASSERT_TRUE(svr.is_valid());
  14204. svr.Get("/test", [](const Request &, Response &res) {
  14205. res.set_content("ok", "text/plain");
  14206. });
  14207. thread t([&]() { svr.listen(HOST, PORT); });
  14208. auto se = detail::scope_exit([&] {
  14209. svr.stop();
  14210. t.join();
  14211. });
  14212. svr.wait_until_ready();
  14213. bool verify_callback_called = false;
  14214. bool ip_matched_via_cn = true;
  14215. SSLClient cli(HOST, PORT);
  14216. cli.enable_server_certificate_verification(true);
  14217. cli.set_ca_cert_path(CA_CERT_FILE);
  14218. cli.set_connection_timeout(5);
  14219. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14220. verify_callback_called = true;
  14221. if (!ctx.cert) return false;
  14222. // The IP appears only in the CN, so it must NOT be accepted.
  14223. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14224. return true; // Accept for the purpose of this test
  14225. });
  14226. cli.Get("/test");
  14227. ASSERT_TRUE(verify_callback_called)
  14228. << "Verify callback should have been called";
  14229. EXPECT_FALSE(ip_matched_via_cn)
  14230. << "An IP host must not be authenticated via the certificate CN";
  14231. }
  14232. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14233. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14234. using namespace httplib::tls;
  14235. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14236. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14237. ASSERT_TRUE(svr.is_valid());
  14238. svr.Get("/test", [](const Request &, Response &res) {
  14239. res.set_content("ok", "text/plain");
  14240. });
  14241. thread t([&]() { svr.listen(HOST, PORT); });
  14242. auto se = detail::scope_exit([&] {
  14243. svr.stop();
  14244. t.join();
  14245. });
  14246. svr.wait_until_ready();
  14247. bool verify_callback_called = false;
  14248. bool san_matched = false;
  14249. bool wrong_ipv6_matched = true;
  14250. bool cn_ipv6_matched = true;
  14251. SSLClient cli(HOST, PORT);
  14252. cli.enable_server_certificate_verification(true);
  14253. cli.set_ca_cert_path(CA_CERT_FILE);
  14254. cli.set_connection_timeout(5);
  14255. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14256. verify_callback_called = true;
  14257. if (!ctx.cert) return false;
  14258. // Matches the IPv6 iPAddress SAN.
  14259. san_matched = ctx.check_hostname("2001:db8::1");
  14260. // A different IPv6 address must not match.
  14261. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14262. // "::1" lives only in the CN, so it must not be accepted.
  14263. cn_ipv6_matched = ctx.check_hostname("::1");
  14264. return true; // Accept for the purpose of this test
  14265. });
  14266. cli.Get("/test");
  14267. ASSERT_TRUE(verify_callback_called)
  14268. << "Verify callback should have been called";
  14269. EXPECT_TRUE(san_matched)
  14270. << "verify_hostname should match an IPv6 iPAddress SAN";
  14271. EXPECT_FALSE(wrong_ipv6_matched)
  14272. << "verify_hostname should not match a non-matching IPv6 address";
  14273. EXPECT_FALSE(cn_ipv6_matched)
  14274. << "An IPv6 host must not be authenticated via the certificate CN";
  14275. }
  14276. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14277. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14278. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14279. using namespace httplib::tls;
  14280. // SANs: DNS:a.zz, IP:42.46.122.122
  14281. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14282. ASSERT_TRUE(svr.is_valid());
  14283. svr.Get("/test", [](const Request &, Response &res) {
  14284. res.set_content("ok", "text/plain");
  14285. });
  14286. auto port = svr.bind_to_any_port(HOST);
  14287. thread t([&]() { svr.listen_after_bind(); });
  14288. auto se = detail::scope_exit([&] {
  14289. svr.stop();
  14290. t.join();
  14291. });
  14292. svr.wait_until_ready();
  14293. bool verify_callback_called = false;
  14294. bool dns_san_matched = false;
  14295. bool ip_san_matched = false;
  14296. bool ip_matched_via_dns_san = true;
  14297. bool dns_matched_via_ip_san = true;
  14298. bool cn_matched_next_to_dns_san = true;
  14299. SSLClient cli(HOST, port);
  14300. cli.enable_server_certificate_verification(true);
  14301. cli.set_ca_cert_path(CA_CERT_FILE);
  14302. cli.set_connection_timeout(5);
  14303. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14304. verify_callback_called = true;
  14305. if (!ctx.cert) return false;
  14306. dns_san_matched = ctx.check_hostname("a.zz");
  14307. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14308. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14309. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14310. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14311. return true; // Accept for the purpose of this test
  14312. });
  14313. cli.Get("/test");
  14314. ASSERT_TRUE(verify_callback_called)
  14315. << "Verify callback should have been called";
  14316. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14317. EXPECT_TRUE(ip_san_matched)
  14318. << "verify_hostname should match an iPAddress SAN";
  14319. EXPECT_FALSE(ip_matched_via_dns_san)
  14320. << "An IP host must not be authenticated via a dNSName SAN";
  14321. EXPECT_FALSE(dns_matched_via_ip_san)
  14322. << "A DNS host must not be authenticated via an iPAddress SAN";
  14323. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14324. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14325. }
  14326. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14327. // "www.*.example.test" names one host and not every host under example.test.
  14328. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14329. using namespace httplib::tls;
  14330. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14331. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14332. ASSERT_TRUE(svr.is_valid());
  14333. svr.Get("/test", [](const Request &, Response &res) {
  14334. res.set_content("ok", "text/plain");
  14335. });
  14336. auto port = svr.bind_to_any_port(HOST);
  14337. thread t([&]() { svr.listen_after_bind(); });
  14338. auto se = detail::scope_exit([&] {
  14339. svr.stop();
  14340. t.join();
  14341. });
  14342. svr.wait_until_ready();
  14343. bool verify_callback_called = false;
  14344. bool leftmost_wildcard_matched = false;
  14345. bool wildcard_spanned_labels = true;
  14346. bool inner_wildcard_matched = true;
  14347. SSLClient cli(HOST, port);
  14348. cli.enable_server_certificate_verification(true);
  14349. cli.set_ca_cert_path(CA_CERT_FILE);
  14350. cli.set_connection_timeout(5);
  14351. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14352. verify_callback_called = true;
  14353. if (!ctx.cert) return false;
  14354. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14355. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14356. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14357. return true; // Accept for the purpose of this test
  14358. });
  14359. cli.Get("/test");
  14360. ASSERT_TRUE(verify_callback_called)
  14361. << "Verify callback should have been called";
  14362. EXPECT_TRUE(leftmost_wildcard_matched)
  14363. << "A leftmost wildcard should match a single label";
  14364. EXPECT_FALSE(wildcard_spanned_labels)
  14365. << "A wildcard label must not match more than one label";
  14366. EXPECT_FALSE(inner_wildcard_matched)
  14367. << "A wildcard outside the leftmost label must not be honoured";
  14368. }
  14369. // sans() must report each SAN entry under its own type.
  14370. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14371. using namespace httplib::tls;
  14372. // SANs: DNS:a.zz, IP:42.46.122.122
  14373. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14374. ASSERT_TRUE(svr.is_valid());
  14375. svr.Get("/test", [](const Request &, Response &res) {
  14376. res.set_content("ok", "text/plain");
  14377. });
  14378. auto port = svr.bind_to_any_port(HOST);
  14379. thread t([&]() { svr.listen_after_bind(); });
  14380. auto se = detail::scope_exit([&] {
  14381. svr.stop();
  14382. t.join();
  14383. });
  14384. svr.wait_until_ready();
  14385. bool verify_callback_called = false;
  14386. std::vector<SanEntry> sans;
  14387. SSLClient cli(HOST, port);
  14388. cli.enable_server_certificate_verification(true);
  14389. cli.set_ca_cert_path(CA_CERT_FILE);
  14390. cli.set_connection_timeout(5);
  14391. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14392. verify_callback_called = true;
  14393. if (!ctx.cert) return false;
  14394. sans = ctx.sans();
  14395. return true; // Accept for the purpose of this test
  14396. });
  14397. cli.Get("/test");
  14398. ASSERT_TRUE(verify_callback_called)
  14399. << "Verify callback should have been called";
  14400. auto has_san = [&](SanType type, const std::string &value) {
  14401. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14402. return san.type == type && san.value == value;
  14403. });
  14404. };
  14405. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14406. << "sans() should report the dNSName SAN";
  14407. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14408. << "sans() should report the iPAddress SAN";
  14409. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14410. << "sans() must not report the dNSName SAN as an address";
  14411. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14412. << "sans() must not report the iPAddress SAN as a DNS name";
  14413. }
  14414. #endif
  14415. // mbedTLS-specific callback constructor test
  14416. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14417. #ifdef CPPHTTPLIB_SSL_ENABLED
  14418. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14419. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14420. ASSERT_TRUE(svr.is_valid());
  14421. // Set up a handler to verify client certificate is present
  14422. bool client_cert_verified = false;
  14423. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14424. // Verify that client certificate was provided
  14425. client_cert_verified = true;
  14426. res.set_content("success", "text/plain");
  14427. });
  14428. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14429. auto se = detail::scope_exit([&] {
  14430. svr.stop();
  14431. t.join();
  14432. ASSERT_FALSE(svr.is_running());
  14433. });
  14434. svr.wait_until_ready();
  14435. // Client with certificate
  14436. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14437. cli.enable_server_certificate_verification(false);
  14438. cli.set_connection_timeout(30);
  14439. auto res = cli.Get("/test");
  14440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14441. ASSERT_EQ(StatusCode::OK_200, res->status);
  14442. ASSERT_TRUE(client_cert_verified);
  14443. EXPECT_EQ("success", res->body);
  14444. }
  14445. #endif
  14446. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14447. // backends
  14448. #ifdef CPPHTTPLIB_SSL_ENABLED
  14449. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14450. using namespace httplib::tls;
  14451. // Test that when client CA cert file is provided,
  14452. // the server properly requests and validates client certificates
  14453. // Create a server with client authentication
  14454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14455. ASSERT_TRUE(svr.is_valid());
  14456. bool handler_called = false;
  14457. svr.Get("/test", [&](const Request &req, Response &res) {
  14458. handler_called = true;
  14459. // Verify that a client certificate was provided
  14460. auto cert = req.peer_cert();
  14461. ASSERT_TRUE(static_cast<bool>(cert));
  14462. // Get the issuer name
  14463. std::string issuer_str = cert.issuer_name();
  14464. ASSERT_FALSE(issuer_str.empty());
  14465. // The client certificate should be issued by our test CA
  14466. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14467. res.set_content("authenticated", "text/plain");
  14468. });
  14469. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14470. auto se = detail::scope_exit([&] {
  14471. svr.stop();
  14472. t.join();
  14473. ASSERT_FALSE(svr.is_running());
  14474. });
  14475. svr.wait_until_ready();
  14476. // Connect with a client certificate issued by the CA
  14477. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14478. cli.enable_server_certificate_verification(false);
  14479. cli.set_connection_timeout(30);
  14480. auto res = cli.Get("/test");
  14481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14482. ASSERT_EQ(StatusCode::OK_200, res->status);
  14483. ASSERT_TRUE(handler_called);
  14484. EXPECT_EQ("authenticated", res->body);
  14485. }
  14486. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14487. using namespace httplib::tls;
  14488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14489. ASSERT_TRUE(svr.is_valid());
  14490. svr.Get("/test", [](const Request &, Response &res) {
  14491. res.set_content("ok", "text/plain");
  14492. });
  14493. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14494. auto se = detail::scope_exit([&] {
  14495. svr.stop();
  14496. t.join();
  14497. });
  14498. svr.wait_until_ready();
  14499. SSLClient cli(HOST, PORT);
  14500. cli.enable_server_certificate_verification(false);
  14501. cli.set_connection_timeout(30);
  14502. bool cert_checked = false;
  14503. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14504. if (ctx.cert) {
  14505. auto sans = ctx.sans();
  14506. // Test certificate may or may not have SANs - just verify the API
  14507. // works If SANs exist, verify the types are valid
  14508. for (const auto &san : sans) {
  14509. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14510. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14511. san.type == SanType::OTHER);
  14512. EXPECT_FALSE(san.value.empty());
  14513. }
  14514. cert_checked = true;
  14515. }
  14516. return true;
  14517. });
  14518. auto res = cli.Get("/test");
  14519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14520. EXPECT_TRUE(cert_checked);
  14521. }
  14522. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14523. using namespace httplib::tls;
  14524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14525. ASSERT_TRUE(svr.is_valid());
  14526. svr.Get("/test", [](const Request &, Response &res) {
  14527. res.set_content("ok", "text/plain");
  14528. });
  14529. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14530. auto se = detail::scope_exit([&] {
  14531. svr.stop();
  14532. t.join();
  14533. });
  14534. svr.wait_until_ready();
  14535. SSLClient cli(HOST, PORT);
  14536. cli.enable_server_certificate_verification(false);
  14537. cli.set_connection_timeout(30);
  14538. bool validity_checked = false;
  14539. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14540. if (ctx.cert) {
  14541. time_t not_before = 0, not_after = 0;
  14542. bool result = ctx.validity(not_before, not_after);
  14543. EXPECT_TRUE(result);
  14544. // Verify that not_before < now < not_after for a valid cert
  14545. time_t now = time(nullptr);
  14546. EXPECT_LT(not_before, now);
  14547. EXPECT_GT(not_after, now);
  14548. validity_checked = true;
  14549. }
  14550. return true;
  14551. });
  14552. auto res = cli.Get("/test");
  14553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14554. EXPECT_TRUE(validity_checked);
  14555. }
  14556. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14557. using namespace httplib::tls;
  14558. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14559. ASSERT_TRUE(svr.is_valid());
  14560. svr.Get("/test", [](const Request &, Response &res) {
  14561. res.set_content("ok", "text/plain");
  14562. });
  14563. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14564. auto se = detail::scope_exit([&] {
  14565. svr.stop();
  14566. t.join();
  14567. });
  14568. svr.wait_until_ready();
  14569. SSLClient cli(HOST, PORT);
  14570. cli.enable_server_certificate_verification(false);
  14571. cli.set_connection_timeout(30);
  14572. bool serial_checked = false;
  14573. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14574. if (ctx.cert) {
  14575. std::string serial = ctx.serial();
  14576. EXPECT_FALSE(serial.empty());
  14577. // Serial should be a hex string
  14578. for (char c : serial) {
  14579. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14580. (c >= 'a' && c <= 'f'));
  14581. }
  14582. serial_checked = true;
  14583. }
  14584. return true;
  14585. });
  14586. auto res = cli.Get("/test");
  14587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14588. EXPECT_TRUE(serial_checked);
  14589. }
  14590. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14591. // Test 1: Valid CA file - no error should be recorded
  14592. {
  14593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14594. CLIENT_CA_CERT_FILE);
  14595. ASSERT_TRUE(svr.is_valid());
  14596. // With valid setup, last_ssl_error should be 0
  14597. EXPECT_EQ(0, svr.ssl_last_error());
  14598. }
  14599. // Test 2: Invalid CA file content
  14600. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14601. {
  14602. // Create a temporary file with completely invalid content
  14603. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14604. {
  14605. std::ofstream ofs(temp_invalid_ca);
  14606. ofs << "This is not a certificate file at all\n";
  14607. ofs << "Just plain text content\n";
  14608. }
  14609. // Create server with invalid CA file
  14610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14611. // Clean up temporary file
  14612. std::remove(temp_invalid_ca);
  14613. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14614. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14615. // Note: SSL_CTX_load_verify_locations typically fails first,
  14616. // but our error handling code path is still exercised
  14617. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14618. }
  14619. }
  14620. TEST(VerifyCallbackTest, VerifyContextFields) {
  14621. using namespace httplib::tls;
  14622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14623. ASSERT_TRUE(svr.is_valid());
  14624. svr.Get("/test", [](const Request &, Response &res) {
  14625. res.set_content("ok", "text/plain");
  14626. });
  14627. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14628. auto se = detail::scope_exit([&] {
  14629. svr.stop();
  14630. t.join();
  14631. });
  14632. svr.wait_until_ready();
  14633. SSLClient cli(HOST, PORT);
  14634. cli.enable_server_certificate_verification(false);
  14635. cli.set_connection_timeout(30);
  14636. int callback_count = 0;
  14637. bool saw_leaf_cert = false;
  14638. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14639. if (ctx.cert) {
  14640. callback_count++;
  14641. // We should see at least one certificate (the leaf)
  14642. std::string cn = ctx.subject_cn();
  14643. if (!cn.empty()) { saw_leaf_cert = true; }
  14644. // Verify context fields are populated
  14645. EXPECT_NE(ctx.session, nullptr);
  14646. EXPECT_GE(ctx.depth, 0);
  14647. }
  14648. return true;
  14649. });
  14650. auto res = cli.Get("/test");
  14651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14652. EXPECT_GT(callback_count, 0);
  14653. EXPECT_TRUE(saw_leaf_cert);
  14654. }
  14655. // A verifier that accepts runs alongside the built-in verification, and is the
  14656. // only check once that is turned off.
  14657. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14658. using namespace httplib::tls;
  14659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14660. ASSERT_TRUE(svr.is_valid());
  14661. svr.Get("/test", [](const Request &, Response &res) {
  14662. res.set_content("ok", "text/plain");
  14663. });
  14664. auto port = svr.bind_to_any_port(HOST);
  14665. thread t([&]() { svr.listen_after_bind(); });
  14666. auto se = detail::scope_exit([&] {
  14667. svr.stop();
  14668. t.join();
  14669. });
  14670. svr.wait_until_ready();
  14671. SSLClient cli(HOST, port);
  14672. cli.enable_server_hostname_verification(false);
  14673. auto calls = 0;
  14674. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14675. calls++;
  14676. return true;
  14677. });
  14678. // cert.pem is not trusted
  14679. auto res = cli.Get("/test");
  14680. ASSERT_FALSE(res);
  14681. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14682. EXPECT_GT(calls, 0);
  14683. cli.enable_server_certificate_verification(false);
  14684. res = cli.Get("/test");
  14685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14686. EXPECT_EQ("ok", res->body);
  14687. }
  14688. // A verifier belongs to the client that set it, not to the thread that set it.
  14689. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14690. using namespace httplib::tls;
  14691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14692. ASSERT_TRUE(svr.is_valid());
  14693. svr.Get("/test", [](const Request &, Response &res) {
  14694. res.set_content("ok", "text/plain");
  14695. });
  14696. auto port = svr.bind_to_any_port(HOST);
  14697. thread t([&]() { svr.listen_after_bind(); });
  14698. auto se = detail::scope_exit([&] {
  14699. svr.stop();
  14700. t.join();
  14701. });
  14702. svr.wait_until_ready();
  14703. auto rejecting_calls = 0;
  14704. SSLClient rejecting(HOST, port);
  14705. rejecting.enable_server_certificate_verification(false);
  14706. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14707. rejecting_calls++;
  14708. return false;
  14709. });
  14710. auto accepting_calls = 0;
  14711. SSLClient accepting(HOST, port);
  14712. accepting.enable_server_certificate_verification(false);
  14713. // Set on another thread than the requests below.
  14714. thread([&]() {
  14715. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14716. accepting_calls++;
  14717. return true;
  14718. });
  14719. }).join();
  14720. // Requested on another thread than the verifier was set on.
  14721. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14722. EXPECT_GT(rejecting_calls, 0);
  14723. auto res = accepting.Get("/test");
  14724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14725. EXPECT_GT(accepting_calls, 0);
  14726. }
  14727. // A verifier replaced while a handshake runs it lives until it returns.
  14728. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14729. using namespace httplib::tls;
  14730. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14731. ASSERT_TRUE(svr.is_valid());
  14732. svr.Get("/test", [](const Request &, Response &res) {
  14733. res.set_content("ok", "text/plain");
  14734. });
  14735. auto port = svr.bind_to_any_port(HOST);
  14736. thread t([&]() { svr.listen_after_bind(); });
  14737. auto se = detail::scope_exit([&] {
  14738. svr.stop();
  14739. t.join();
  14740. });
  14741. svr.wait_until_ready();
  14742. SSLClient cli(HOST, port);
  14743. cli.enable_server_certificate_verification(false);
  14744. std::promise<void> entered;
  14745. std::promise<void> replaced;
  14746. auto replaced_future = replaced.get_future();
  14747. auto first_call = true;
  14748. // Long enough to live on the heap
  14749. std::string expected(64, 'v');
  14750. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14751. if (first_call) {
  14752. first_call = false;
  14753. entered.set_value();
  14754. replaced_future.wait();
  14755. }
  14756. return expected == std::string(64, 'v');
  14757. });
  14758. thread request([&]() {
  14759. auto res = cli.Get("/test");
  14760. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14761. });
  14762. entered.get_future().wait();
  14763. cli.set_server_certificate_verifier(
  14764. [](const VerifyContext &) { return true; });
  14765. replaced.set_value();
  14766. request.join();
  14767. }
  14768. // VerifyContext::session is the same handle the other tls:: functions take.
  14769. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14770. using namespace httplib::tls;
  14771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14772. ASSERT_TRUE(svr.is_valid());
  14773. svr.Get("/test", [](const Request &, Response &res) {
  14774. res.set_content("ok", "text/plain");
  14775. });
  14776. auto port = svr.bind_to_any_port(HOST);
  14777. thread t([&]() { svr.listen_after_bind(); });
  14778. auto se = detail::scope_exit([&] {
  14779. svr.stop();
  14780. t.join();
  14781. });
  14782. svr.wait_until_ready();
  14783. SSLClient cli(HOST, port);
  14784. cli.enable_server_certificate_verification(false);
  14785. session_t verifier_session = nullptr;
  14786. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14787. verifier_session = ctx.session;
  14788. return true;
  14789. });
  14790. session_t session_verifier_session = nullptr;
  14791. cli.set_session_verifier([&](session_t session) {
  14792. session_verifier_session = session;
  14793. return SSLVerifierResponse::NoDecisionMade;
  14794. });
  14795. auto res = cli.Get("/test");
  14796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14797. EXPECT_NE(nullptr, verifier_session);
  14798. EXPECT_EQ(session_verifier_session, verifier_session);
  14799. }
  14800. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14801. using httplib::tls::TlsError;
  14802. // Test that verify_error_to_string returns empty for success
  14803. std::string success_str = TlsError::verify_error_to_string(0);
  14804. EXPECT_TRUE(success_str.empty());
  14805. // Test that verify_error_to_string returns non-empty for error codes
  14806. // Using a common error code (certificate expired)
  14807. std::string error_str =
  14808. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14809. EXPECT_FALSE(error_str.empty());
  14810. }
  14811. TEST(SessionVerifierTest, CertificateAccepted) {
  14812. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14813. ASSERT_TRUE(svr.is_valid());
  14814. svr.Get("/test", [](const Request &, Response &res) {
  14815. res.set_content("ok", "text/plain");
  14816. });
  14817. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14818. auto se = detail::scope_exit([&] {
  14819. svr.stop();
  14820. t.join();
  14821. });
  14822. svr.wait_until_ready();
  14823. SSLClient cli(HOST, PORT);
  14824. cli.enable_server_certificate_verification(false);
  14825. cli.set_connection_timeout(30);
  14826. bool callback_called = false;
  14827. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14828. EXPECT_NE(session, nullptr);
  14829. callback_called = true;
  14830. return SSLVerifierResponse::CertificateAccepted;
  14831. });
  14832. auto res = cli.Get("/test");
  14833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14834. EXPECT_EQ(200, res->status);
  14835. EXPECT_TRUE(callback_called);
  14836. }
  14837. TEST(SessionVerifierTest, CertificateRejected) {
  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. SSLClient cli(HOST, PORT);
  14850. cli.enable_server_certificate_verification(false);
  14851. cli.set_connection_timeout(30);
  14852. bool callback_called = false;
  14853. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14854. EXPECT_NE(session, nullptr);
  14855. callback_called = true;
  14856. return SSLVerifierResponse::CertificateRejected;
  14857. });
  14858. auto res = cli.Get("/test");
  14859. EXPECT_FALSE(res);
  14860. EXPECT_TRUE(callback_called);
  14861. }
  14862. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14863. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14864. ASSERT_TRUE(svr.is_valid());
  14865. svr.Get("/test", [](const Request &, Response &res) {
  14866. res.set_content("ok", "text/plain");
  14867. });
  14868. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14869. auto se = detail::scope_exit([&] {
  14870. svr.stop();
  14871. t.join();
  14872. });
  14873. svr.wait_until_ready();
  14874. // NoDecisionMade with verification disabled should succeed (no default check)
  14875. SSLClient cli(HOST, PORT);
  14876. cli.enable_server_certificate_verification(false);
  14877. cli.set_connection_timeout(30);
  14878. bool callback_called = false;
  14879. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14880. EXPECT_NE(session, nullptr);
  14881. callback_called = true;
  14882. return SSLVerifierResponse::NoDecisionMade;
  14883. });
  14884. auto res = cli.Get("/test");
  14885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14886. EXPECT_EQ(200, res->status);
  14887. EXPECT_TRUE(callback_called);
  14888. }
  14889. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14891. ASSERT_TRUE(svr.is_valid());
  14892. svr.Get("/test", [](const Request &, Response &res) {
  14893. res.set_content("ok", "text/plain");
  14894. });
  14895. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14896. auto se = detail::scope_exit([&] {
  14897. svr.stop();
  14898. t.join();
  14899. });
  14900. svr.wait_until_ready();
  14901. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14902. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14903. // so we only check that the request fails, not whether the callback was
  14904. // called.
  14905. SSLClient cli(HOST, PORT);
  14906. cli.enable_server_certificate_verification(true);
  14907. cli.set_connection_timeout(30);
  14908. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14909. EXPECT_NE(session, nullptr);
  14910. return SSLVerifierResponse::NoDecisionMade;
  14911. });
  14912. auto res = cli.Get("/test");
  14913. EXPECT_FALSE(res);
  14914. }
  14915. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14916. // Test SSL server using PemMemory constructor with client CA certificates
  14917. // Read PEM files
  14918. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14919. read_file(SERVER_CERT_FILE, server_cert_pem);
  14920. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14921. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14922. // Create SSLServer with PemMemory constructor including client CA
  14923. SSLServer::PemMemory server_pem = {
  14924. server_cert_pem.c_str(),
  14925. server_cert_pem.size(),
  14926. server_key_pem.c_str(),
  14927. server_key_pem.size(),
  14928. client_ca_pem.c_str(),
  14929. client_ca_pem.size(),
  14930. nullptr // no password for server key
  14931. };
  14932. SSLServer svr(server_pem);
  14933. ASSERT_TRUE(svr.is_valid());
  14934. // No SSL error should be recorded for valid setup
  14935. EXPECT_EQ(0, svr.ssl_last_error());
  14936. // Set up server endpoints
  14937. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14938. res.set_content("ok", "text/plain");
  14939. });
  14940. // Start server in a thread
  14941. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14942. svr.wait_until_ready();
  14943. // Connect with client certificate (using constructor with paths)
  14944. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14945. cli.enable_server_certificate_verification(false);
  14946. auto res = cli.Get("/test-pem-ca");
  14947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14948. EXPECT_EQ(200, res->status);
  14949. EXPECT_EQ("ok", res->body);
  14950. svr.stop();
  14951. server_thread.join();
  14952. }
  14953. #endif
  14954. #ifdef _WIN32
  14955. TEST(CleanupTest, WSACleanup) {
  14956. int ret = WSACleanup();
  14957. ASSERT_EQ(0, ret);
  14958. }
  14959. #endif
  14960. #ifndef CPPHTTPLIB_SSL_ENABLED
  14961. TEST(NoSSLSupport, SimpleInterface) {
  14962. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14963. }
  14964. #endif
  14965. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14966. TEST(InvalidScheme, SimpleInterface) {
  14967. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14968. }
  14969. #endif
  14970. TEST(NoScheme, SimpleInterface) {
  14971. Client cli("yahoo.com:80");
  14972. ASSERT_TRUE(cli.is_valid());
  14973. }
  14974. TEST(SendAPI, SimpleInterface_Online) {
  14975. Client cli("http://yahoo.com");
  14976. Request req;
  14977. req.method = "GET";
  14978. req.path = "/";
  14979. auto res = cli.send(req);
  14980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14981. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14982. }
  14983. TEST(SendAPI, WithParamsInRequest) {
  14984. Server svr;
  14985. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14986. EXPECT_TRUE(req.has_param("test"));
  14987. EXPECT_EQ("test_value", req.get_param_value("test"));
  14988. });
  14989. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14990. auto se = detail::scope_exit([&] {
  14991. svr.stop();
  14992. t.join();
  14993. ASSERT_FALSE(svr.is_running());
  14994. });
  14995. svr.wait_until_ready();
  14996. Client cli(HOST, PORT);
  14997. {
  14998. Request req;
  14999. req.method = "GET";
  15000. req.path = "/";
  15001. req.params.emplace("test", "test_value");
  15002. auto res = cli.send(req);
  15003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15004. }
  15005. {
  15006. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15008. }
  15009. }
  15010. TEST(ClientImplMethods, GetSocketTest) {
  15011. httplib::Server svr;
  15012. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15013. res.status = StatusCode::OK_200;
  15014. });
  15015. auto port = svr.bind_to_any_port("127.0.0.1");
  15016. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15017. auto se = detail::scope_exit([&] {
  15018. svr.stop();
  15019. thread.join();
  15020. ASSERT_FALSE(svr.is_running());
  15021. });
  15022. svr.wait_until_ready();
  15023. {
  15024. httplib::Client cli("127.0.0.1", port);
  15025. cli.set_keep_alive(true);
  15026. // Use the behavior of cpp-httplib of opening the connection
  15027. // only when the first request happens. If that changes,
  15028. // this test would be obsolete.
  15029. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15030. // This also implicitly tests the server. But other tests would fail much
  15031. // earlier than this one to be considered.
  15032. auto res = cli.Get("/");
  15033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15034. EXPECT_EQ(StatusCode::OK_200, res->status);
  15035. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15036. }
  15037. }
  15038. #ifdef CPPHTTPLIB_SSL_ENABLED
  15039. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15040. Client cli("http://yahoo.com");
  15041. auto res = cli.Get("/");
  15042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15043. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15044. cli.set_follow_location(true);
  15045. res = cli.Get("/");
  15046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15047. EXPECT_EQ(StatusCode::OK_200, res->status);
  15048. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15049. }
  15050. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15051. Client cli("https://yahoo.com");
  15052. auto res = cli.Get("/");
  15053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15054. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15055. cli.set_follow_location(true);
  15056. res = cli.Get("/");
  15057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15058. EXPECT_EQ(StatusCode::OK_200, res->status);
  15059. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15060. }
  15061. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15062. Client cli("https://yahoo.com");
  15063. auto res = cli.Get("/");
  15064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15065. ASSERT_FALSE(!res);
  15066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15067. ASSERT_FALSE(res == nullptr);
  15068. ASSERT_TRUE(res != nullptr);
  15069. EXPECT_EQ(Error::Success, res.error());
  15070. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15071. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15072. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15073. cli.set_follow_location(true);
  15074. res = cli.Get("/");
  15075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15076. EXPECT_EQ(Error::Success, res.error());
  15077. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15078. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15079. EXPECT_EQ(StatusCode::OK_200, res->status);
  15080. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15081. }
  15082. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15083. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15084. Client cli("https://cdnjs.cloudflare.com");
  15085. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15086. Headers{{"Accept-Encoding", "br"}});
  15087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15088. EXPECT_EQ(StatusCode::OK_200, res->status);
  15089. EXPECT_EQ(287630U, res->body.size());
  15090. EXPECT_EQ("application/javascript; charset=utf-8",
  15091. res->get_header_value("Content-Type"));
  15092. }
  15093. #endif
  15094. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15095. #undef REDIR_HOST // Silence compiler warning
  15096. #define REDIR_HOST "https://httpbingo.org"
  15097. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15098. Client cli(REDIR_HOST);
  15099. cli.set_follow_location(true);
  15100. auto res =
  15101. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15103. EXPECT_EQ(StatusCode::OK_200, res->status);
  15104. }
  15105. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15106. Client cli(REDIR_HOST);
  15107. cli.set_follow_location(true);
  15108. Params params;
  15109. params.emplace("url", "http://example.com");
  15110. params.emplace("status_code", "302");
  15111. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15113. EXPECT_EQ(StatusCode::OK_200, res->status);
  15114. }
  15115. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15116. Client cli(REDIR_HOST);
  15117. cli.set_follow_location(true);
  15118. Params params;
  15119. params.emplace("url", "http://example.com");
  15120. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15122. EXPECT_EQ(StatusCode::OK_200, res->status);
  15123. }
  15124. TEST(HttpToHttpsRedirectTest, CertFile) {
  15125. auto ssl_port = PORT + 1;
  15126. Server svr;
  15127. ASSERT_TRUE(svr.is_valid());
  15128. svr.Get("/index", [&](const Request &, Response &res) {
  15129. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15130. "/index");
  15131. svr.stop();
  15132. });
  15133. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15134. ASSERT_TRUE(ssl_svr.is_valid());
  15135. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15136. res.set_content("test", "text/plain");
  15137. ssl_svr.stop();
  15138. });
  15139. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15140. thread t2 =
  15141. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15142. auto se = detail::scope_exit([&] {
  15143. t2.join();
  15144. t.join();
  15145. ASSERT_FALSE(svr.is_running());
  15146. });
  15147. svr.wait_until_ready();
  15148. ssl_svr.wait_until_ready();
  15149. Client cli("127.0.0.1", PORT);
  15150. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15151. cli.enable_server_certificate_verification(true);
  15152. cli.set_follow_location(true);
  15153. cli.set_connection_timeout(30);
  15154. auto res = cli.Get("/index");
  15155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15156. ASSERT_EQ(StatusCode::OK_200, res->status);
  15157. }
  15158. TEST(SSLClientRedirectTest, CertFile) {
  15159. auto ssl_port = PORT + 1;
  15160. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15161. ASSERT_TRUE(ssl_svr1.is_valid());
  15162. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15163. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15164. "/index");
  15165. ssl_svr1.stop();
  15166. });
  15167. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15168. ASSERT_TRUE(ssl_svr2.is_valid());
  15169. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15170. res.set_content("test", "text/plain");
  15171. ssl_svr2.stop();
  15172. });
  15173. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15174. thread t2 =
  15175. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15176. auto se = detail::scope_exit([&] {
  15177. t2.join();
  15178. t.join();
  15179. ASSERT_FALSE(ssl_svr1.is_running());
  15180. });
  15181. ssl_svr1.wait_until_ready();
  15182. ssl_svr2.wait_until_ready();
  15183. SSLClient cli("127.0.0.1", PORT);
  15184. std::string cert;
  15185. read_file(SERVER_CERT2_FILE, cert);
  15186. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15187. cli.enable_server_certificate_verification(true);
  15188. cli.set_follow_location(true);
  15189. cli.set_connection_timeout(30);
  15190. auto res = cli.Get("/index");
  15191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15192. ASSERT_EQ(StatusCode::OK_200, res->status);
  15193. }
  15194. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15195. // another port, so the client follows it with a new client.
  15196. static Result GetThroughTlsRedirectToDifferentPort(
  15197. const std::function<void(SSLClient &)> &setup,
  15198. const char *target_cert = SERVER_CERT2_FILE,
  15199. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15200. auto ssl_port = PORT + 1;
  15201. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15202. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15203. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15204. "/index");
  15205. });
  15206. SSLServer ssl_svr2(target_cert, target_key);
  15207. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15208. res.set_content("test", "text/plain");
  15209. });
  15210. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15211. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15212. auto se = detail::scope_exit([&] {
  15213. ssl_svr2.stop();
  15214. ssl_svr1.stop();
  15215. t2.join();
  15216. t.join();
  15217. });
  15218. ssl_svr1.wait_until_ready();
  15219. ssl_svr2.wait_until_ready();
  15220. SSLClient cli("127.0.0.1", PORT);
  15221. cli.set_follow_location(true);
  15222. cli.set_connection_timeout(30);
  15223. setup(cli);
  15224. return cli.Get("/index");
  15225. }
  15226. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15227. auto calls = 0;
  15228. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15229. cli.enable_server_certificate_verification(false);
  15230. // Accept the first server only.
  15231. cli.set_session_verifier([&](tls::session_t) {
  15232. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15233. : SSLVerifierResponse::CertificateRejected;
  15234. });
  15235. });
  15236. ASSERT_FALSE(res);
  15237. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15238. EXPECT_EQ(2, calls);
  15239. }
  15240. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15241. std::string pinned;
  15242. auto res = GetThroughTlsRedirectToDifferentPort(
  15243. [&](SSLClient &cli) {
  15244. cli.enable_server_certificate_verification(false);
  15245. // Pin the first certificate seen.
  15246. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15247. if (pinned.empty()) { pinned = ctx.serial(); }
  15248. return ctx.serial() == pinned;
  15249. });
  15250. },
  15251. // A certificate other than the first server's.
  15252. SERVER_CERT_FILE);
  15253. EXPECT_FALSE(res);
  15254. EXPECT_FALSE(pinned.empty());
  15255. }
  15256. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15257. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15258. std::string cert;
  15259. read_file(SERVER_CERT2_FILE, cert);
  15260. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15261. });
  15262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15263. EXPECT_EQ(StatusCode::OK_200, res->status);
  15264. }
  15265. // The target's certificate is signed by the root CA, which the first server's
  15266. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15267. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15268. auto res = GetThroughTlsRedirectToDifferentPort(
  15269. [](SSLClient &cli) {
  15270. std::string root_ca, cert;
  15271. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15272. read_file(SERVER_CERT2_FILE, cert);
  15273. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15274. cli.load_ca_cert_store(cert.data(), cert.size());
  15275. cli.enable_server_hostname_verification(false);
  15276. },
  15277. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15279. EXPECT_EQ(StatusCode::OK_200, res->status);
  15280. }
  15281. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15282. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15283. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15284. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15285. auto res = GetThroughTlsRedirectToDifferentPort(
  15286. [](SSLClient &cli) {
  15287. std::string root_ca, cert;
  15288. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15289. read_file(SERVER_CERT2_FILE, cert);
  15290. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15291. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15292. cli.enable_server_hostname_verification(false);
  15293. },
  15294. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15295. ASSERT_FALSE(res);
  15296. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15297. }
  15298. #endif
  15299. #endif
  15300. #ifdef CPPHTTPLIB_SSL_ENABLED
  15301. // Test that set_ca_cert_store() skips system certs (consistent with
  15302. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15303. // should be trusted - system certs should NOT be loaded.
  15304. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15305. // Load a specific cert that is NOT a system CA cert
  15306. std::string cert;
  15307. read_file(SERVER_CERT2_FILE, cert);
  15308. SSLClient cli("google.com");
  15309. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15310. cli.enable_server_certificate_verification(true);
  15311. // This should FAIL because:
  15312. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15313. // 2. System certs should NOT be loaded when custom store is set
  15314. // If system certs WERE loaded, this would succeed
  15315. auto res = cli.Get("/");
  15316. ASSERT_FALSE(res);
  15317. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15318. }
  15319. // Same as above, but through the native store handle path. Regression test:
  15320. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15321. // merged system certs into the user-provided store.
  15322. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15323. std::string cert;
  15324. read_file(SERVER_CERT2_FILE, cert);
  15325. SSLClient cli("google.com");
  15326. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15327. cli.enable_server_certificate_verification(true);
  15328. auto res = cli.Get("/");
  15329. ASSERT_FALSE(res);
  15330. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15331. }
  15332. // A custom store set via the native handle must still verify a server whose
  15333. // cert it does contain.
  15334. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15335. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15336. ASSERT_TRUE(svr.is_valid());
  15337. svr.Get("/test", [&](const Request &, Response &res) {
  15338. res.set_content("test", "text/plain");
  15339. });
  15340. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15341. auto se = detail::scope_exit([&] {
  15342. svr.stop();
  15343. t.join();
  15344. ASSERT_FALSE(svr.is_running());
  15345. });
  15346. svr.wait_until_ready();
  15347. SSLClient cli("127.0.0.1", PORT);
  15348. std::string cert;
  15349. read_file(SERVER_CERT2_FILE, cert);
  15350. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15351. cli.enable_server_certificate_verification(true);
  15352. cli.set_connection_timeout(30);
  15353. auto res = cli.Get("/test");
  15354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15355. ASSERT_EQ(StatusCode::OK_200, res->status);
  15356. }
  15357. // CA certs loaded through the universal Client must be transferred to the
  15358. // client created internally for following an HTTPS redirect. Regression test:
  15359. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15360. // the CA data for redirect transfer.
  15361. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15362. auto ssl_port = PORT + 1;
  15363. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15364. ASSERT_TRUE(ssl_svr1.is_valid());
  15365. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15366. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15367. "/index");
  15368. });
  15369. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15370. ASSERT_TRUE(ssl_svr2.is_valid());
  15371. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15372. res.set_content("test", "text/plain");
  15373. });
  15374. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15375. thread t2 =
  15376. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15377. auto se = detail::scope_exit([&] {
  15378. ssl_svr2.stop();
  15379. ssl_svr1.stop();
  15380. t2.join();
  15381. t.join();
  15382. ASSERT_FALSE(ssl_svr1.is_running());
  15383. });
  15384. ssl_svr1.wait_until_ready();
  15385. ssl_svr2.wait_until_ready();
  15386. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15387. std::string cert;
  15388. read_file(SERVER_CERT2_FILE, cert);
  15389. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15390. cli.enable_server_certificate_verification(true);
  15391. cli.set_follow_location(true);
  15392. cli.set_connection_timeout(30);
  15393. auto res = cli.Get("/index");
  15394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15395. ASSERT_EQ(StatusCode::OK_200, res->status);
  15396. }
  15397. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15398. // so a host signed by a system CA verifies even though a custom CA is set
  15399. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15400. std::string cert;
  15401. read_file(SERVER_CERT2_FILE, cert);
  15402. SSLClient cli("google.com");
  15403. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15404. cli.enable_system_ca(true);
  15405. cli.enable_server_certificate_verification(true);
  15406. auto res = cli.Get("/");
  15407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15408. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15409. }
  15410. // The custom CA remains effective when combined with the system CA
  15411. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15412. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15413. ASSERT_TRUE(svr.is_valid());
  15414. svr.Get("/test", [&](const Request &, Response &res) {
  15415. res.set_content("test", "text/plain");
  15416. });
  15417. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15418. auto se = detail::scope_exit([&] {
  15419. svr.stop();
  15420. t.join();
  15421. ASSERT_FALSE(svr.is_running());
  15422. });
  15423. svr.wait_until_ready();
  15424. SSLClient cli("127.0.0.1", PORT);
  15425. std::string cert;
  15426. read_file(SERVER_CERT2_FILE, cert);
  15427. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15428. cli.enable_system_ca(true);
  15429. cli.enable_server_certificate_verification(true);
  15430. cli.set_connection_timeout(30);
  15431. auto res = cli.Get("/test");
  15432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15433. ASSERT_EQ(StatusCode::OK_200, res->status);
  15434. }
  15435. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15436. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15437. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15438. static CFDictionaryRef
  15439. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15440. const SecTrustSettingsResult *result) {
  15441. auto constraint =
  15442. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15443. &kCFTypeDictionaryValueCallBacks);
  15444. if (policy) {
  15445. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15446. }
  15447. if (policy_string) {
  15448. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15449. kCFStringEncodingUTF8);
  15450. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15451. CFRelease(str);
  15452. }
  15453. if (result) {
  15454. auto number_value = static_cast<SInt32>(*result);
  15455. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15456. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15457. CFRelease(number);
  15458. }
  15459. return constraint;
  15460. }
  15461. static SecTrustSettingsResult
  15462. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15463. auto trust_settings =
  15464. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15465. for (auto constraint : constraints) {
  15466. CFArrayAppendValue(trust_settings, constraint);
  15467. CFRelease(constraint);
  15468. }
  15469. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15470. CFRelease(trust_settings);
  15471. return result;
  15472. }
  15473. // The system CA loader takes a Keychain certificate as a trusted root only
  15474. // when its Trust Settings say so for SSL, not merely because it has some.
  15475. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15476. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15477. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15478. const auto deny = kSecTrustSettingsResultDeny;
  15479. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15480. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15481. auto x509_policy = SecPolicyCreateBasicX509();
  15482. // "Always Trust", which stores no constraint at all
  15483. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15484. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15485. ssl_trust_settings_result(
  15486. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15487. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15488. ssl_trust_settings_result(
  15489. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15490. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15491. ssl_trust_settings_result(
  15492. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15493. // "Never Trust", for everything or for SSL
  15494. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15495. ssl_trust_settings_result(
  15496. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15497. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15498. ssl_trust_settings_result(
  15499. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15500. // Trusted for another policy, for one host, or not at all
  15501. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15502. ssl_trust_settings_result(
  15503. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15504. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15505. ssl_trust_settings_result({make_usage_constraint(
  15506. ssl_policy, "www.example.com", &trust_root)}));
  15507. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15508. ssl_trust_settings_result(
  15509. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15510. // The first constraint that applies to SSL decides
  15511. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15512. ssl_trust_settings_result(
  15513. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15514. make_usage_constraint(nullptr, nullptr, &deny)}));
  15515. CFRelease(x509_policy);
  15516. CFRelease(ssl_policy);
  15517. }
  15518. #endif
  15519. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15520. // skip chain verification entirely (only the certificate identity was
  15521. // checked), so a server presenting an untrusted certificate with a matching
  15522. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15523. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15524. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15525. ASSERT_TRUE(svr.is_valid());
  15526. svr.Get("/test", [&](const Request &, Response &res) {
  15527. res.set_content("test", "text/plain");
  15528. });
  15529. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15530. auto se = detail::scope_exit([&] {
  15531. svr.stop();
  15532. t.join();
  15533. ASSERT_FALSE(svr.is_running());
  15534. });
  15535. svr.wait_until_ready();
  15536. SSLClient cli("127.0.0.1", PORT);
  15537. std::string cert;
  15538. // A trusted CA that did not sign the server certificate. The server cert
  15539. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15540. // this connection.
  15541. read_file(CLIENT_CA_CERT_FILE, cert);
  15542. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15543. cli.enable_server_certificate_verification(true);
  15544. cli.set_connection_timeout(30);
  15545. auto res = cli.Get("/test");
  15546. ASSERT_FALSE(res);
  15547. }
  15548. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15549. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15550. // CA that failed to come through fails verification instead of trusting them.
  15551. // (wolfSSL does not list the system CAs it loaded.)
  15552. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15553. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15554. ASSERT_TRUE(svr.is_valid());
  15555. auto port = svr.bind_to_any_port("127.0.0.1");
  15556. ASSERT_LT(0, port);
  15557. thread t = thread([&] { svr.listen_after_bind(); });
  15558. auto se = detail::scope_exit([&] {
  15559. svr.stop();
  15560. t.join();
  15561. ASSERT_FALSE(svr.is_running());
  15562. });
  15563. svr.wait_until_ready();
  15564. // The CAs a client trusts once its first request has loaded them
  15565. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15566. Client cli("https://127.0.0.1:" + std::to_string(port));
  15567. setup(cli);
  15568. cli.Get("/");
  15569. return tls::get_ca_names(cli.tls_context()).size();
  15570. };
  15571. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15572. EXPECT_EQ(0u,
  15573. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15574. }
  15575. #endif
  15576. // A TLS setting changed between requests applies to the next one, not just to
  15577. // the next connection
  15578. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15579. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15580. ASSERT_TRUE(svr.is_valid());
  15581. svr.Get("/", [](const Request &req, Response &res) {
  15582. res.set_content(std::to_string(req.remote_port), "text/plain");
  15583. });
  15584. auto port = svr.bind_to_any_port("127.0.0.1");
  15585. ASSERT_LT(0, port);
  15586. thread t = thread([&] { svr.listen_after_bind(); });
  15587. auto se = detail::scope_exit([&] {
  15588. svr.stop();
  15589. t.join();
  15590. ASSERT_FALSE(svr.is_running());
  15591. });
  15592. svr.wait_until_ready();
  15593. SSLClient cli("127.0.0.1", port);
  15594. cli.set_keep_alive(true);
  15595. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15596. cli.enable_server_certificate_verification(false);
  15597. // The port the request went out from, so a new one means a new connection
  15598. auto client_port = [&] {
  15599. auto res = cli.Get("/");
  15600. return res ? res->body : std::string();
  15601. };
  15602. auto last = client_port();
  15603. ASSERT_FALSE(last.empty());
  15604. // Setting a value it already has keeps the connection
  15605. cli.enable_server_certificate_verification(false);
  15606. cli.enable_server_hostname_verification(true);
  15607. EXPECT_EQ(last, client_port());
  15608. cli.enable_server_certificate_verification(true);
  15609. auto res = cli.Get("/");
  15610. EXPECT_FALSE(res);
  15611. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15612. std::string ca;
  15613. read_file(SERVER_CERT2_FILE, ca);
  15614. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15615. last = client_port();
  15616. ASSERT_FALSE(last.empty());
  15617. std::vector<std::function<void()>> setters = {
  15618. [&] { cli.enable_server_hostname_verification(false); },
  15619. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15620. [&] {
  15621. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15622. },
  15623. [&] {
  15624. cli.set_server_certificate_verifier(
  15625. [](const tls::VerifyContext &) { return true; });
  15626. },
  15627. [&] {
  15628. cli.set_session_verifier(
  15629. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15630. },
  15631. };
  15632. for (const auto &setter : setters) {
  15633. setter();
  15634. auto next = client_port();
  15635. ASSERT_FALSE(next.empty());
  15636. EXPECT_NE(last, next);
  15637. last = next;
  15638. }
  15639. cli.set_session_verifier(
  15640. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15641. auto handle = cli.open_stream("GET", "/");
  15642. EXPECT_FALSE(handle.is_valid());
  15643. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15644. }
  15645. // A PEM given to create_ca_store() needs no NUL after it
  15646. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15647. std::string pem;
  15648. read_file(SERVER_CERT2_FILE, pem);
  15649. auto buf = pem + "X";
  15650. auto store = tls::create_ca_store(buf.data(), pem.size());
  15651. EXPECT_TRUE(store != nullptr);
  15652. SSLClient cli("localhost");
  15653. cli.set_ca_cert_store(store);
  15654. }
  15655. // enable_system_ca(false) prevents system CA loading entirely
  15656. TEST(SSLClientTest, DisableSystemCa_Online) {
  15657. SSLClient cli("google.com");
  15658. cli.enable_system_ca(false);
  15659. cli.enable_server_certificate_verification(true);
  15660. auto res = cli.Get("/");
  15661. ASSERT_FALSE(res);
  15662. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15663. // itself when the CA chain is empty
  15664. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15665. res.error() == Error::SSLConnection);
  15666. }
  15667. // The universal Client forwards enable_system_ca()
  15668. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15669. std::string cert;
  15670. read_file(SERVER_CERT2_FILE, cert);
  15671. Client cli("https://google.com");
  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. auto res = cli.Get("/");
  15676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15677. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15678. }
  15679. // The system CA policy must carry over to the client created internally for
  15680. // following a cross-host HTTPS redirect
  15681. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15682. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15683. ASSERT_TRUE(svr.is_valid());
  15684. svr.Get("/index", [&](const Request &, Response &res) {
  15685. res.set_redirect("https://www.google.com/");
  15686. });
  15687. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15688. auto se = detail::scope_exit([&] {
  15689. svr.stop();
  15690. t.join();
  15691. ASSERT_FALSE(svr.is_running());
  15692. });
  15693. svr.wait_until_ready();
  15694. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15695. std::string cert;
  15696. read_file(SERVER_CERT2_FILE, cert);
  15697. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15698. cli.enable_system_ca(true);
  15699. cli.enable_server_certificate_verification(true);
  15700. cli.set_follow_location(true);
  15701. cli.set_connection_timeout(30);
  15702. // Receiving any response proves the redirect client completed the TLS
  15703. // handshake with a system-CA-signed host
  15704. auto res = cli.Get("/index");
  15705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15706. }
  15707. TEST(MultipartFormDataTest, LargeData) {
  15708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15709. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15710. const ContentReader &content_reader) {
  15711. if (req.is_multipart_form_data()) {
  15712. std::vector<FormData> items;
  15713. content_reader(
  15714. [&](const FormData &file) {
  15715. items.push_back(file);
  15716. return true;
  15717. },
  15718. [&](const char *data, size_t data_length) {
  15719. items.back().content.append(data, data_length);
  15720. return true;
  15721. });
  15722. EXPECT_TRUE(std::string(items[0].name) == "document");
  15723. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15724. EXPECT_TRUE(items[0].filename == "2MB_data");
  15725. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15726. EXPECT_TRUE(items[1].name == "hello");
  15727. EXPECT_TRUE(items[1].content == "world");
  15728. EXPECT_TRUE(items[1].filename == "");
  15729. EXPECT_TRUE(items[1].content_type == "");
  15730. } else {
  15731. std::string body;
  15732. content_reader([&](const char *data, size_t data_length) {
  15733. body.append(data, data_length);
  15734. return true;
  15735. });
  15736. }
  15737. });
  15738. auto port = svr.bind_to_any_port(HOST);
  15739. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15740. auto se = detail::scope_exit([&] {
  15741. svr.stop();
  15742. t.join();
  15743. ASSERT_FALSE(svr.is_running());
  15744. });
  15745. svr.wait_until_ready();
  15746. {
  15747. std::string data(1024 * 1024 * 2, '.');
  15748. std::stringstream buffer;
  15749. buffer << data;
  15750. SSLClient cli(HOST, port);
  15751. cli.enable_server_certificate_verification(false);
  15752. UploadFormDataItems items{
  15753. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15754. {"hello", "world", "", ""},
  15755. };
  15756. auto res = cli.Post("/post", items);
  15757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15758. ASSERT_EQ(StatusCode::OK_200, res->status);
  15759. }
  15760. }
  15761. TEST(MultipartFormDataTest, DataProviderItems) {
  15762. std::random_device seed_gen;
  15763. std::mt19937 random(seed_gen());
  15764. std::string rand1;
  15765. rand1.resize(1000);
  15766. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15767. std::string rand2;
  15768. rand2.resize(3000);
  15769. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15770. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15771. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15772. const ContentReader &content_reader) {
  15773. ASSERT_FALSE(req.is_multipart_form_data());
  15774. std::string body;
  15775. content_reader([&](const char *data, size_t data_length) {
  15776. body.append(data, data_length);
  15777. return true;
  15778. });
  15779. EXPECT_EQ(body, "");
  15780. });
  15781. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15782. const ContentReader &content_reader) {
  15783. ASSERT_TRUE(req.is_multipart_form_data());
  15784. std::vector<FormData> items;
  15785. content_reader(
  15786. [&](const FormData &file) {
  15787. items.push_back(file);
  15788. return true;
  15789. },
  15790. [&](const char *data, size_t data_length) {
  15791. items.back().content.append(data, data_length);
  15792. return true;
  15793. });
  15794. ASSERT_TRUE(items.size() == 2);
  15795. EXPECT_EQ(std::string(items[0].name), "name1");
  15796. EXPECT_EQ(items[0].content, "Testing123");
  15797. EXPECT_EQ(items[0].filename, "filename1");
  15798. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15799. EXPECT_EQ(items[1].name, "name2");
  15800. EXPECT_EQ(items[1].content, "Testing456");
  15801. EXPECT_EQ(items[1].filename, "");
  15802. EXPECT_EQ(items[1].content_type, "");
  15803. });
  15804. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15805. const ContentReader &content_reader) {
  15806. ASSERT_TRUE(req.is_multipart_form_data());
  15807. std::vector<FormData> items;
  15808. content_reader(
  15809. [&](const FormData &file) {
  15810. items.push_back(file);
  15811. return true;
  15812. },
  15813. [&](const char *data, size_t data_length) {
  15814. items.back().content.append(data, data_length);
  15815. return true;
  15816. });
  15817. ASSERT_TRUE(items.size() == 2);
  15818. EXPECT_EQ(items[0].name, "name3");
  15819. EXPECT_EQ(items[0].content, rand1);
  15820. EXPECT_EQ(items[0].filename, "filename3");
  15821. EXPECT_EQ(items[0].content_type, "");
  15822. EXPECT_EQ(items[1].name, "name4");
  15823. EXPECT_EQ(items[1].content, rand2);
  15824. EXPECT_EQ(items[1].filename, "filename4");
  15825. EXPECT_EQ(items[1].content_type, "");
  15826. });
  15827. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15828. const ContentReader &content_reader) {
  15829. ASSERT_TRUE(req.is_multipart_form_data());
  15830. std::vector<FormData> items;
  15831. content_reader(
  15832. [&](const FormData &file) {
  15833. items.push_back(file);
  15834. return true;
  15835. },
  15836. [&](const char *data, size_t data_length) {
  15837. items.back().content.append(data, data_length);
  15838. return true;
  15839. });
  15840. ASSERT_TRUE(items.size() == 4);
  15841. EXPECT_EQ(std::string(items[0].name), "name1");
  15842. EXPECT_EQ(items[0].content, "Testing123");
  15843. EXPECT_EQ(items[0].filename, "filename1");
  15844. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15845. EXPECT_EQ(items[1].name, "name2");
  15846. EXPECT_EQ(items[1].content, "Testing456");
  15847. EXPECT_EQ(items[1].filename, "");
  15848. EXPECT_EQ(items[1].content_type, "");
  15849. EXPECT_EQ(items[2].name, "name3");
  15850. EXPECT_EQ(items[2].content, rand1);
  15851. EXPECT_EQ(items[2].filename, "filename3");
  15852. EXPECT_EQ(items[2].content_type, "");
  15853. EXPECT_EQ(items[3].name, "name4");
  15854. EXPECT_EQ(items[3].content, rand2);
  15855. EXPECT_EQ(items[3].filename, "filename4");
  15856. EXPECT_EQ(items[3].content_type, "");
  15857. });
  15858. auto port = svr.bind_to_any_port("localhost");
  15859. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15860. auto se = detail::scope_exit([&] {
  15861. svr.stop();
  15862. t.join();
  15863. ASSERT_FALSE(svr.is_running());
  15864. });
  15865. svr.wait_until_ready();
  15866. {
  15867. SSLClient cli("localhost", port);
  15868. cli.enable_server_certificate_verification(false);
  15869. UploadFormDataItems items{
  15870. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15871. {"name2", "Testing456", "", ""}, // not a file
  15872. };
  15873. {
  15874. auto res = cli.Post("/post-none", {}, {}, {});
  15875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15876. ASSERT_EQ(StatusCode::OK_200, res->status);
  15877. }
  15878. FormDataProviderItems providers;
  15879. {
  15880. auto res =
  15881. cli.Post("/post-items", {}, items, providers); // empty providers
  15882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15883. ASSERT_EQ(StatusCode::OK_200, res->status);
  15884. }
  15885. providers.push_back({"name3",
  15886. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15887. // test the offset is given correctly at each step
  15888. if (!offset)
  15889. sink.os.write(rand1.data(), 30);
  15890. else if (offset == 30)
  15891. sink.os.write(rand1.data() + 30, 300);
  15892. else if (offset == 330)
  15893. sink.os.write(rand1.data() + 330, 670);
  15894. else if (offset == rand1.size())
  15895. sink.done();
  15896. return true;
  15897. },
  15898. "filename3",
  15899. {}});
  15900. providers.push_back({"name4",
  15901. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15902. // test the offset is given correctly at each step
  15903. if (!offset)
  15904. sink.os.write(rand2.data(), 2000);
  15905. else if (offset == 2000)
  15906. sink.os.write(rand2.data() + 2000, 1);
  15907. else if (offset == 2001)
  15908. sink.os.write(rand2.data() + 2001, 999);
  15909. else if (offset == rand2.size())
  15910. sink.done();
  15911. return true;
  15912. },
  15913. "filename4",
  15914. {}});
  15915. {
  15916. auto res = cli.Post("/post-providers", {}, {}, providers);
  15917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15918. ASSERT_EQ(StatusCode::OK_200, res->status);
  15919. }
  15920. {
  15921. auto res = cli.Post("/post-both", {}, items, providers);
  15922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15923. ASSERT_EQ(StatusCode::OK_200, res->status);
  15924. }
  15925. }
  15926. }
  15927. TEST(MultipartFormDataTest, BadHeader) {
  15928. Server svr;
  15929. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15930. res.set_content("ok", "text/plain");
  15931. });
  15932. thread t = thread([&] { svr.listen(HOST, PORT); });
  15933. auto se = detail::scope_exit([&] {
  15934. svr.stop();
  15935. t.join();
  15936. ASSERT_FALSE(svr.is_running());
  15937. });
  15938. svr.wait_until_ready();
  15939. const std::string body =
  15940. "This is the preamble. It is to be ignored, though it\r\n"
  15941. "is a handy place for composition agents to include an\r\n"
  15942. "explanatory note to non-MIME conformant readers.\r\n"
  15943. "\r\n"
  15944. "\r\n"
  15945. "--simple boundary\r\n"
  15946. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15947. ": BAD...\r\n"
  15948. "\r\n"
  15949. "value1\r\n"
  15950. "--simple boundary\r\n"
  15951. "Content-Disposition: form-data; name=\"field2\"; "
  15952. "filename=\"example.txt\"\r\n"
  15953. "\r\n"
  15954. "value2\r\n"
  15955. "--simple boundary--\r\n"
  15956. "This is the epilogue. It is also to be ignored.\r\n";
  15957. std::string content_type =
  15958. R"(multipart/form-data; boundary="simple boundary")";
  15959. Client cli(HOST, PORT);
  15960. auto res = cli.Post("/post", body, content_type.c_str());
  15961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15962. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15963. }
  15964. TEST(MultipartFormDataTest, WithPreamble) {
  15965. Server svr;
  15966. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15967. res.set_content("ok", "text/plain");
  15968. });
  15969. thread t = thread([&] { svr.listen(HOST, PORT); });
  15970. auto se = detail::scope_exit([&] {
  15971. svr.stop();
  15972. t.join();
  15973. ASSERT_FALSE(svr.is_running());
  15974. });
  15975. svr.wait_until_ready();
  15976. const std::string body =
  15977. "This is the preamble. It is to be ignored, though it\r\n"
  15978. "is a handy place for composition agents to include an\r\n"
  15979. "explanatory note to non-MIME conformant readers.\r\n"
  15980. "\r\n"
  15981. "\r\n"
  15982. "--simple boundary\r\n"
  15983. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15984. "\r\n"
  15985. "value1\r\n"
  15986. "--simple boundary\r\n"
  15987. "Content-Disposition: form-data; name=\"field2\"; "
  15988. "filename=\"example.txt\"\r\n"
  15989. "\r\n"
  15990. "value2\r\n"
  15991. "--simple boundary--\r\n"
  15992. "This is the epilogue. It is also to be ignored.\r\n";
  15993. std::string content_type =
  15994. R"(multipart/form-data; boundary="simple boundary")";
  15995. Client cli(HOST, PORT);
  15996. auto res = cli.Post("/post", body, content_type.c_str());
  15997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15998. EXPECT_EQ(StatusCode::OK_200, res->status);
  15999. }
  16000. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16002. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16003. const ContentReader &content_reader) {
  16004. if (req.is_multipart_form_data()) {
  16005. std::vector<FormData> items;
  16006. content_reader(
  16007. [&](const FormData &file) {
  16008. items.push_back(file);
  16009. return true;
  16010. },
  16011. [&](const char *data, size_t data_length) {
  16012. items.back().content.append(data, data_length);
  16013. return true;
  16014. });
  16015. EXPECT_TRUE(std::string(items[0].name) == "document");
  16016. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16017. EXPECT_TRUE(items[0].filename == "2MB_data");
  16018. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16019. EXPECT_TRUE(items[1].name == "hello");
  16020. EXPECT_TRUE(items[1].content == "world");
  16021. EXPECT_TRUE(items[1].filename == "");
  16022. EXPECT_TRUE(items[1].content_type == "");
  16023. } else {
  16024. std::string body;
  16025. content_reader([&](const char *data, size_t data_length) {
  16026. body.append(data, data_length);
  16027. return true;
  16028. });
  16029. }
  16030. });
  16031. auto port = svr.bind_to_any_port("localhost");
  16032. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16033. auto se = detail::scope_exit([&] {
  16034. svr.stop();
  16035. t.join();
  16036. ASSERT_FALSE(svr.is_running());
  16037. });
  16038. svr.wait_until_ready();
  16039. {
  16040. std::string data(1024 * 1024 * 2, '.');
  16041. std::stringstream buffer;
  16042. buffer << data;
  16043. SSLClient cli("localhost", port);
  16044. cli.enable_server_certificate_verification(false);
  16045. UploadFormDataItems items{
  16046. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16047. {"hello", "world", "", ""},
  16048. };
  16049. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16051. ASSERT_EQ(StatusCode::OK_200, res->status);
  16052. }
  16053. }
  16054. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16055. std::string data(1024 * 1024 * 2, '&');
  16056. std::stringstream buffer;
  16057. buffer << data;
  16058. Client cli("https://localhost:8080");
  16059. UploadFormDataItems items{
  16060. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16061. {"hello", "world", "", ""},
  16062. };
  16063. for (const char &c : " \t\r\n") {
  16064. auto res =
  16065. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16066. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16067. ASSERT_FALSE(res);
  16068. }
  16069. }
  16070. TEST(MultipartFormDataTest, PutFormData) {
  16071. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16072. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16073. const ContentReader &content_reader) {
  16074. if (req.is_multipart_form_data()) {
  16075. std::vector<FormData> items;
  16076. content_reader(
  16077. [&](const FormData &file) {
  16078. items.push_back(file);
  16079. return true;
  16080. },
  16081. [&](const char *data, size_t data_length) {
  16082. items.back().content.append(data, data_length);
  16083. return true;
  16084. });
  16085. EXPECT_TRUE(std::string(items[0].name) == "document");
  16086. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16087. EXPECT_TRUE(items[0].filename == "2MB_data");
  16088. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16089. EXPECT_TRUE(items[1].name == "hello");
  16090. EXPECT_TRUE(items[1].content == "world");
  16091. EXPECT_TRUE(items[1].filename == "");
  16092. EXPECT_TRUE(items[1].content_type == "");
  16093. } else {
  16094. std::string body;
  16095. content_reader([&](const char *data, size_t data_length) {
  16096. body.append(data, data_length);
  16097. return true;
  16098. });
  16099. }
  16100. });
  16101. auto port = svr.bind_to_any_port("localhost");
  16102. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16103. auto se = detail::scope_exit([&] {
  16104. svr.stop();
  16105. t.join();
  16106. ASSERT_FALSE(svr.is_running());
  16107. });
  16108. svr.wait_until_ready();
  16109. {
  16110. std::string data(1024 * 1024 * 2, '&');
  16111. std::stringstream buffer;
  16112. buffer << data;
  16113. SSLClient cli("localhost", port);
  16114. cli.enable_server_certificate_verification(false);
  16115. UploadFormDataItems items{
  16116. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16117. {"hello", "world", "", ""},
  16118. };
  16119. auto res = cli.Put("/put", items);
  16120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16121. ASSERT_EQ(StatusCode::OK_200, res->status);
  16122. }
  16123. }
  16124. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16126. svr.Put("/put_customboundary",
  16127. [&](const Request &req, const Response & /*res*/,
  16128. const ContentReader &content_reader) {
  16129. if (req.is_multipart_form_data()) {
  16130. std::vector<FormData> items;
  16131. content_reader(
  16132. [&](const FormData &file) {
  16133. items.push_back(file);
  16134. return true;
  16135. },
  16136. [&](const char *data, size_t data_length) {
  16137. items.back().content.append(data, data_length);
  16138. return true;
  16139. });
  16140. EXPECT_TRUE(std::string(items[0].name) == "document");
  16141. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16142. EXPECT_TRUE(items[0].filename == "2MB_data");
  16143. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16144. EXPECT_TRUE(items[1].name == "hello");
  16145. EXPECT_TRUE(items[1].content == "world");
  16146. EXPECT_TRUE(items[1].filename == "");
  16147. EXPECT_TRUE(items[1].content_type == "");
  16148. } else {
  16149. std::string body;
  16150. content_reader([&](const char *data, size_t data_length) {
  16151. body.append(data, data_length);
  16152. return true;
  16153. });
  16154. }
  16155. });
  16156. auto port = svr.bind_to_any_port("localhost");
  16157. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16158. auto se = detail::scope_exit([&] {
  16159. svr.stop();
  16160. t.join();
  16161. ASSERT_FALSE(svr.is_running());
  16162. });
  16163. svr.wait_until_ready();
  16164. {
  16165. std::string data(1024 * 1024 * 2, '&');
  16166. std::stringstream buffer;
  16167. buffer << data;
  16168. SSLClient cli("localhost", port);
  16169. cli.enable_server_certificate_verification(false);
  16170. UploadFormDataItems items{
  16171. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16172. {"hello", "world", "", ""},
  16173. };
  16174. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16176. ASSERT_EQ(StatusCode::OK_200, res->status);
  16177. }
  16178. }
  16179. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16180. std::string data(1024 * 1024 * 2, '&');
  16181. std::stringstream buffer;
  16182. buffer << data;
  16183. Client cli("https://localhost:8080");
  16184. cli.enable_server_certificate_verification(false);
  16185. UploadFormDataItems items{
  16186. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16187. {"hello", "world", "", ""},
  16188. };
  16189. for (const char &c : " \t\r\n") {
  16190. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16191. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16192. ASSERT_FALSE(res);
  16193. }
  16194. }
  16195. TEST(MultipartFormDataTest, AlternateFilename) {
  16196. auto handled = false;
  16197. Server svr;
  16198. svr.Post("/test", [&](const Request &req, Response &res) {
  16199. ASSERT_EQ(2u, req.form.files.size());
  16200. ASSERT_EQ(1u, req.form.fields.size());
  16201. // Test files
  16202. const auto &file1 = req.form.get_file("file1");
  16203. ASSERT_EQ("file1", file1.name);
  16204. ASSERT_EQ("A.txt", file1.filename);
  16205. ASSERT_EQ("text/plain", file1.content_type);
  16206. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16207. const auto &file2 = req.form.get_file("file2");
  16208. ASSERT_EQ("file2", file2.name);
  16209. ASSERT_EQ("a.html", file2.filename);
  16210. ASSERT_EQ("text/html", file2.content_type);
  16211. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16212. file2.content);
  16213. // Test text field
  16214. const auto &text = req.form.get_field("text");
  16215. ASSERT_EQ("text default", text);
  16216. res.set_content("ok", "text/plain");
  16217. handled = true;
  16218. });
  16219. thread t = thread([&] { svr.listen(HOST, PORT); });
  16220. auto se = detail::scope_exit([&] {
  16221. svr.stop();
  16222. t.join();
  16223. ASSERT_FALSE(svr.is_running());
  16224. ASSERT_TRUE(handled);
  16225. });
  16226. svr.wait_until_ready();
  16227. auto req = "POST /test HTTP/1.1\r\n"
  16228. "Host: localhost\r\n"
  16229. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16230. "Content-Length: 399\r\n"
  16231. "\r\n"
  16232. "----------\r\n"
  16233. "Content-Disposition: form-data; name=\"text\"\r\n"
  16234. "\r\n"
  16235. "text default\r\n"
  16236. "----------\r\n"
  16237. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16238. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16239. "Content-Type: text/plain\r\n"
  16240. "\r\n"
  16241. "Content of a.txt.\r\n"
  16242. "\r\n"
  16243. "----------\r\n"
  16244. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16245. "\"a.html\"\r\n"
  16246. "Content-Type: text/html\r\n"
  16247. "\r\n"
  16248. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16249. "\r\n"
  16250. "------------\r\n";
  16251. ASSERT_TRUE(send_request(1, req));
  16252. }
  16253. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16254. auto handled = false;
  16255. Server svr;
  16256. svr.Post("/test", [&](const Request &req, Response &res) {
  16257. // Case-insensitive "utf-8''" prefix with a long value
  16258. const auto &file = req.form.get_file("file1");
  16259. ASSERT_EQ("file1", file.name);
  16260. // 8000 chars exercises both the Content-Disposition parser and the
  16261. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16262. // Prior to the fix, std::regex_match on this header would cause O(N)
  16263. // stack recursion in libstdc++, leading to SIGSEGV.
  16264. std::string expected_filename(8000, 'A');
  16265. ASSERT_EQ(expected_filename, file.filename);
  16266. res.set_content("ok", "text/plain");
  16267. handled = true;
  16268. });
  16269. thread t = thread([&] { svr.listen(HOST, PORT); });
  16270. auto se = detail::scope_exit([&] {
  16271. svr.stop();
  16272. t.join();
  16273. ASSERT_FALSE(svr.is_running());
  16274. ASSERT_TRUE(handled);
  16275. });
  16276. svr.wait_until_ready();
  16277. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16278. // Regression test for GHSA-qq6v-r583-3h69
  16279. std::string long_filename(8000, 'A');
  16280. std::string body = "----------\r\n"
  16281. "Content-Disposition: form-data; name=\"file1\"; "
  16282. "filename*=\"Utf-8''" +
  16283. long_filename +
  16284. "\"\r\n"
  16285. "\r\n"
  16286. "hello\r\n"
  16287. "------------\r\n";
  16288. auto req = "POST /test HTTP/1.1\r\n"
  16289. "Host: localhost\r\n"
  16290. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16291. "Content-Length: " +
  16292. std::to_string(body.size()) + "\r\n\r\n" + body;
  16293. ASSERT_TRUE(send_request(1, req));
  16294. }
  16295. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16296. auto handled = false;
  16297. Server svr;
  16298. svr.Post("/test", [&](const Request &req, Response &) {
  16299. ASSERT_EQ(2u, req.form.fields.size());
  16300. const auto &text1 = req.form.get_field("text1");
  16301. ASSERT_EQ("text1", text1);
  16302. const auto &text2 = req.form.get_field("text2");
  16303. ASSERT_EQ("text2", text2);
  16304. handled = true;
  16305. });
  16306. thread t = thread([&] { svr.listen(HOST, PORT); });
  16307. auto se = detail::scope_exit([&] {
  16308. svr.stop();
  16309. t.join();
  16310. ASSERT_FALSE(svr.is_running());
  16311. ASSERT_TRUE(handled);
  16312. });
  16313. svr.wait_until_ready();
  16314. auto req = "POST /test HTTP/1.1\r\n"
  16315. "Host: localhost\r\n"
  16316. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16317. "Content-Length: 146\r\n"
  16318. "\r\n----------\r\n"
  16319. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16320. "\r\n"
  16321. "text1"
  16322. "\r\n----------\r\n"
  16323. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16324. "\r\n"
  16325. "text2"
  16326. "\r\n------------";
  16327. std::string response;
  16328. ASSERT_TRUE(send_request(1, req, &response));
  16329. ASSERT_EQ("200", response.substr(9, 3));
  16330. }
  16331. TEST(MultipartFormDataTest, ContentLength) {
  16332. auto handled = false;
  16333. Server svr;
  16334. svr.Post("/test", [&](const Request &req, Response &) {
  16335. ASSERT_EQ(2u, req.form.fields.size());
  16336. const auto &text1 = req.form.get_field("text1");
  16337. ASSERT_EQ("text1", text1);
  16338. const auto &text2 = req.form.get_field("text2");
  16339. ASSERT_EQ("text2", text2);
  16340. handled = true;
  16341. });
  16342. thread t = thread([&] { svr.listen(HOST, PORT); });
  16343. auto se = detail::scope_exit([&] {
  16344. svr.stop();
  16345. t.join();
  16346. ASSERT_FALSE(svr.is_running());
  16347. ASSERT_TRUE(handled);
  16348. });
  16349. svr.wait_until_ready();
  16350. auto req = "POST /test HTTP/1.1\r\n"
  16351. "Host: localhost\r\n"
  16352. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16353. "Content-Length: 167\r\n"
  16354. "\r\n----------\r\n"
  16355. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16356. "Content-Length: 5\r\n"
  16357. "\r\n"
  16358. "text1"
  16359. "\r\n----------\r\n"
  16360. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16361. "\r\n"
  16362. "text2"
  16363. "\r\n------------\r\n";
  16364. std::string response;
  16365. ASSERT_TRUE(send_request(1, req, &response));
  16366. ASSERT_EQ("200", response.substr(9, 3));
  16367. }
  16368. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16369. auto handled = false;
  16370. Server svr;
  16371. svr.Post("/test", [&](const Request &req, Response &) {
  16372. ASSERT_EQ(2u, req.form.fields.size());
  16373. const auto &text1 = req.form.get_field("text1");
  16374. ASSERT_EQ("text1", text1);
  16375. // TODO: Add header access for text fields if needed
  16376. const auto &text2 = req.form.get_field("text2");
  16377. ASSERT_EQ("text2", text2);
  16378. // TODO: Header access for text fields needs to be implemented
  16379. // auto &headers = it->second.headers;
  16380. // ASSERT_EQ(3U, headers.size());
  16381. // auto custom_header = headers.find("x-whatever");
  16382. // ASSERT_TRUE(custom_header != headers.end());
  16383. // ASSERT_NE("customvalue", custom_header->second);
  16384. // ASSERT_EQ("CustomValue", custom_header->second);
  16385. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16386. handled = true;
  16387. });
  16388. thread t = thread([&] { svr.listen(HOST, PORT); });
  16389. auto se = detail::scope_exit([&] {
  16390. svr.stop();
  16391. t.join();
  16392. ASSERT_FALSE(svr.is_running());
  16393. ASSERT_TRUE(handled);
  16394. });
  16395. svr.wait_until_ready();
  16396. auto req = "POST /test HTTP/1.1\r\n"
  16397. "Host: localhost\r\n"
  16398. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16399. "Content-Length: 232\r\n"
  16400. "\r\n----------\r\n"
  16401. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16402. "Content-Length: 5\r\n"
  16403. "X-Test: 1\r\n"
  16404. "\r\n"
  16405. "text1"
  16406. "\r\n----------\r\n"
  16407. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16408. "Content-Type: text/plain\r\n"
  16409. "X-Whatever: CustomValue\r\n"
  16410. "\r\n"
  16411. "text2"
  16412. "\r\n------------\r\n"
  16413. "That should be disregarded. Not even read";
  16414. std::string response;
  16415. ASSERT_TRUE(send_request(1, req, &response));
  16416. ASSERT_EQ("200", response.substr(9, 3));
  16417. }
  16418. TEST(MultipartFormDataTest, LargeHeader) {
  16419. auto handled = false;
  16420. Server svr;
  16421. svr.Post("/test", [&](const Request &req, Response &) {
  16422. ASSERT_EQ(1u, req.form.fields.size());
  16423. const auto &text = req.form.get_field("name1");
  16424. ASSERT_EQ("text1", text);
  16425. handled = true;
  16426. });
  16427. thread t = thread([&] { svr.listen(HOST, PORT); });
  16428. auto se = detail::scope_exit([&] {
  16429. svr.stop();
  16430. t.join();
  16431. ASSERT_FALSE(svr.is_running());
  16432. ASSERT_TRUE(handled);
  16433. });
  16434. svr.wait_until_ready();
  16435. auto boundary = std::string("cpp-httplib-multipart-data");
  16436. std::string content = "--" + boundary +
  16437. "\r\n"
  16438. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16439. "\r\n"
  16440. "text1\r\n"
  16441. "--" +
  16442. boundary + "--\r\n";
  16443. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16444. "Host: localhost\r\n"
  16445. "Content-Type: multipart/form-data;boundary=" +
  16446. boundary +
  16447. "\r\n"
  16448. "Content-Length: " +
  16449. std::to_string(content.size()) +
  16450. "\r\n"
  16451. "Dummy-Header: ";
  16452. std::string header_suffix = "\r\n"
  16453. "\r\n";
  16454. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16455. size_t header_dummy_size =
  16456. read_buff_size -
  16457. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16458. auto header_dummy = std::string(header_dummy_size, '@');
  16459. auto req = header_prefix + header_dummy + header_suffix + content;
  16460. std::string response;
  16461. ASSERT_TRUE(send_request(1, req, &response));
  16462. ASSERT_EQ("200", response.substr(9, 3));
  16463. }
  16464. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16465. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16466. // (not chunked Transfer-Encoding) after the streaming refactor.
  16467. auto handled = false;
  16468. Server svr;
  16469. svr.Post("/upload", [&](const Request &req, Response &res) {
  16470. auto cl_it = req.headers.find("Content-Length");
  16471. EXPECT_TRUE(cl_it != req.headers.end());
  16472. auto te_it = req.headers.find("Transfer-Encoding");
  16473. EXPECT_TRUE(te_it == req.headers.end());
  16474. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16475. res.set_content("ok", "text/plain");
  16476. handled = true;
  16477. });
  16478. auto port = svr.bind_to_any_port(HOST);
  16479. auto t = thread([&] { svr.listen_after_bind(); });
  16480. auto se = detail::scope_exit([&] {
  16481. svr.stop();
  16482. t.join();
  16483. ASSERT_FALSE(svr.is_running());
  16484. ASSERT_TRUE(handled);
  16485. });
  16486. svr.wait_until_ready();
  16487. UploadFormDataItems items = {
  16488. {"field1", "hello", "", "text/plain"},
  16489. {"file1", "world", "test.txt", "application/octet-stream"},
  16490. };
  16491. Client cli(HOST, port);
  16492. auto res = cli.Post("/upload", {}, items);
  16493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16494. EXPECT_EQ(StatusCode::OK_200, res->status);
  16495. }
  16496. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16497. // Verify that make_multipart_content_provider coalesces many small segments
  16498. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16499. constexpr size_t kItemCount = 1000;
  16500. UploadFormDataItems items;
  16501. items.reserve(kItemCount);
  16502. for (size_t i = 0; i < kItemCount; i++) {
  16503. items.push_back(
  16504. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16505. }
  16506. const std::string boundary = "----test-boundary";
  16507. auto content_length = detail::get_multipart_content_length(items, boundary);
  16508. auto provider = detail::make_multipart_content_provider(items, boundary);
  16509. // Drive the provider the same way write_content_with_progress does
  16510. size_t write_count = 0;
  16511. size_t total_bytes = 0;
  16512. DataSink sink;
  16513. size_t offset = 0;
  16514. sink.write = [&](const char *d, size_t l) -> bool {
  16515. (void)d;
  16516. write_count++;
  16517. total_bytes += l;
  16518. offset += l;
  16519. return true;
  16520. };
  16521. sink.is_writable = []() -> bool { return true; };
  16522. while (offset < content_length) {
  16523. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16524. }
  16525. EXPECT_EQ(content_length, total_bytes);
  16526. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16527. // With buffering into 64KB blocks, write_count should be much smaller.
  16528. auto segment_count = 3 * kItemCount + 1;
  16529. EXPECT_LT(write_count, segment_count / 10);
  16530. }
  16531. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16532. // Integration test: send many UploadFormDataItems and verify the server
  16533. // receives all of them correctly (#2410).
  16534. constexpr size_t kItemCount = 500;
  16535. auto handled = false;
  16536. Server svr;
  16537. svr.Post("/upload", [&](const Request &req, Response &res) {
  16538. EXPECT_EQ(kItemCount, req.form.fields.size());
  16539. for (size_t i = 0; i < kItemCount; i++) {
  16540. auto key = "field" + std::to_string(i);
  16541. auto val = "value" + std::to_string(i);
  16542. auto it = req.form.fields.find(key);
  16543. if (it != req.form.fields.end()) {
  16544. EXPECT_EQ(val, it->second.content);
  16545. } else {
  16546. ADD_FAILURE() << "Missing field: " << key;
  16547. }
  16548. }
  16549. res.set_content("ok", "text/plain");
  16550. handled = true;
  16551. });
  16552. auto port = svr.bind_to_any_port(HOST);
  16553. auto t = thread([&] { svr.listen_after_bind(); });
  16554. auto se = detail::scope_exit([&] {
  16555. svr.stop();
  16556. t.join();
  16557. ASSERT_FALSE(svr.is_running());
  16558. ASSERT_TRUE(handled);
  16559. });
  16560. svr.wait_until_ready();
  16561. UploadFormDataItems items;
  16562. items.reserve(kItemCount);
  16563. for (size_t i = 0; i < kItemCount; i++) {
  16564. items.push_back(
  16565. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16566. }
  16567. Client cli(HOST, port);
  16568. auto res = cli.Post("/upload", items);
  16569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16570. EXPECT_EQ(StatusCode::OK_200, res->status);
  16571. }
  16572. TEST(MultipartFormDataTest, MakeFileProvider) {
  16573. // Verify make_file_provider sends a file's contents correctly.
  16574. const std::string file_content(4096, 'Z');
  16575. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16576. {
  16577. std::ofstream ofs(tmp_path, std::ios::binary);
  16578. ofs.write(file_content.data(),
  16579. static_cast<std::streamsize>(file_content.size()));
  16580. }
  16581. auto handled = false;
  16582. Server svr;
  16583. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16584. const ContentReader &content_reader) {
  16585. ASSERT_TRUE(req.is_multipart_form_data());
  16586. std::vector<FormData> items;
  16587. content_reader(
  16588. [&](const FormData &file) {
  16589. items.push_back(file);
  16590. return true;
  16591. },
  16592. [&](const char *data, size_t data_length) {
  16593. items.back().content.append(data, data_length);
  16594. return true;
  16595. });
  16596. ASSERT_EQ(1u, items.size());
  16597. EXPECT_EQ("myfile", items[0].name);
  16598. EXPECT_EQ("data.bin", items[0].filename);
  16599. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16600. EXPECT_EQ(file_content, items[0].content);
  16601. handled = true;
  16602. });
  16603. auto port = svr.bind_to_any_port(HOST);
  16604. auto t = thread([&] { svr.listen_after_bind(); });
  16605. auto se = detail::scope_exit([&] {
  16606. svr.stop();
  16607. t.join();
  16608. ASSERT_FALSE(svr.is_running());
  16609. ASSERT_TRUE(handled);
  16610. std::remove(tmp_path.c_str());
  16611. });
  16612. svr.wait_until_ready();
  16613. FormDataProviderItems providers;
  16614. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16615. "application/octet-stream"));
  16616. Client cli(HOST, port);
  16617. auto res = cli.Post("/upload", {}, {}, providers);
  16618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16619. EXPECT_EQ(StatusCode::OK_200, res->status);
  16620. }
  16621. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16622. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16623. // (100) headers is rejected with a 400 Bad Request response.
  16624. Server svr;
  16625. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16626. res.set_content("ok", "text/plain");
  16627. });
  16628. thread t = thread([&] { svr.listen(HOST, PORT); });
  16629. auto se = detail::scope_exit([&] {
  16630. svr.stop();
  16631. t.join();
  16632. ASSERT_FALSE(svr.is_running());
  16633. });
  16634. svr.wait_until_ready();
  16635. // Build a multipart part with 101 custom headers (exceeding
  16636. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16637. std::stringstream body;
  16638. body << "--simpleboundary\r\n"
  16639. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16640. for (int i = 0; i < 101; i++) {
  16641. body << "X-Custom-Header-" << i << ": value\r\n";
  16642. }
  16643. body << "\r\n"
  16644. << "value1\r\n"
  16645. << "--simpleboundary--\r\n";
  16646. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16647. Client cli(HOST, PORT);
  16648. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16650. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16651. }
  16652. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16653. // A body that never contains the declared boundary must not be accumulated
  16654. // while the parser waits for it. Buffering it would also make every read
  16655. // rescan everything seen so far, which is quadratic in the body size.
  16656. Server svr;
  16657. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16658. res.set_content("ok", "text/plain");
  16659. });
  16660. auto port = svr.bind_to_any_port(HOST);
  16661. thread t = thread([&] { svr.listen_after_bind(); });
  16662. auto se = detail::scope_exit([&] {
  16663. svr.stop();
  16664. t.join();
  16665. ASSERT_FALSE(svr.is_running());
  16666. });
  16667. svr.wait_until_ready();
  16668. Client cli(HOST, port);
  16669. cli.set_read_timeout(60, 0);
  16670. cli.set_write_timeout(60, 0);
  16671. // '-' is the worst case: it matches the first character of the boundary, so
  16672. // every position has to be checked against it.
  16673. auto post_dashes = [&](size_t size) {
  16674. const std::string body(size, '-');
  16675. auto start = std::chrono::steady_clock::now();
  16676. auto res =
  16677. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16678. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16679. std::chrono::steady_clock::now() - start)
  16680. .count();
  16681. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16682. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16683. return ms;
  16684. };
  16685. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16686. // Windows.
  16687. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16688. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16689. // Comparing the two sizes rather than checking an absolute duration keeps
  16690. // this meaningful across build types and CI load, both of which move the
  16691. // absolute numbers by more than an order of magnitude. Four times the bytes
  16692. // costs about four times the time when parsing is linear, and about sixteen
  16693. // times when the body is buffered and rescanned.
  16694. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16695. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16696. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16697. << "ms, which suggests the body is being buffered and rescanned";
  16698. }
  16699. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16700. // A boundary can only be followed by CRLF or by "--", so anything else is
  16701. // malformed no matter what comes next. The parser must say so right away
  16702. // instead of buffering the rest of the declared body.
  16703. Server svr;
  16704. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16705. res.set_content("ok", "text/plain");
  16706. });
  16707. auto port = svr.bind_to_any_port(HOST);
  16708. thread t = thread([&] { svr.listen_after_bind(); });
  16709. auto se = detail::scope_exit([&] {
  16710. svr.stop();
  16711. t.join();
  16712. ASSERT_FALSE(svr.is_running());
  16713. });
  16714. svr.wait_until_ready();
  16715. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16716. // buffers instead of failing would still be waiting for the remaining bytes.
  16717. const std::string body = "--zzzz\r\n"
  16718. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16719. "\r\n"
  16720. "text1"
  16721. "\r\n--zzzzXX";
  16722. const std::string req = "POST /post HTTP/1.1\r\n"
  16723. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16724. "Content-Length: 1048576\r\n"
  16725. "\r\n" +
  16726. body;
  16727. std::string response;
  16728. ASSERT_TRUE(send_request(3, req, &response, port));
  16729. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16730. EXPECT_EQ("400", response.substr(9, 3));
  16731. }
  16732. // Posts a multipart body split into two writes, so that the server sees the
  16733. // split at whatever offset the caller chose, and expects the single "text1"
  16734. // field to come through.
  16735. static void expect_split_multipart_ok(const std::string &body1,
  16736. const std::string &body2) {
  16737. auto handled = false;
  16738. Server svr;
  16739. svr.Post("/post", [&](const Request &req, Response &) {
  16740. EXPECT_EQ(1u, req.form.fields.size());
  16741. EXPECT_EQ("text1", req.form.get_field("text1"));
  16742. handled = true;
  16743. });
  16744. auto port = svr.bind_to_any_port(HOST);
  16745. thread t = thread([&] { svr.listen_after_bind(); });
  16746. auto se = detail::scope_exit([&] {
  16747. svr.stop();
  16748. t.join();
  16749. ASSERT_FALSE(svr.is_running());
  16750. ASSERT_TRUE(handled);
  16751. });
  16752. svr.wait_until_ready();
  16753. // "Connection: close" makes the server close once it has answered, so the
  16754. // response drain ends immediately instead of idling until the read timeout.
  16755. const std::string head =
  16756. "POST /post HTTP/1.1\r\n"
  16757. "Host: localhost\r\n"
  16758. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16759. "Connection: close\r\n"
  16760. "Content-Length: " +
  16761. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16762. std::string response;
  16763. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16764. ASSERT_GE(response.size(), 12u) << "no response";
  16765. EXPECT_EQ("200", response.substr(9, 3));
  16766. }
  16767. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16768. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16769. // ignored, including when it does not arrive in the same read as the
  16770. // close-delimiter itself.
  16771. expect_split_multipart_ok("--zzzz\r\n"
  16772. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16773. "\r\n"
  16774. "text1"
  16775. "\r\n--zzzz--",
  16776. "\r\nthis epilogue must be ignored\r\n");
  16777. }
  16778. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16779. // The initial boundary may be preceded by a preamble of any length and may
  16780. // straddle a read boundary. Discarding data while waiting for it must not
  16781. // throw away a partial boundary sitting at the end of the buffer.
  16782. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16783. "zz\r\n"
  16784. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16785. "\r\n"
  16786. "text1"
  16787. "\r\n--zzzz--\r\n");
  16788. }
  16789. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16790. // The received boundary was only checked for being non-empty, so it could be
  16791. // as long as a header is allowed to be. The parser scans the body for
  16792. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16793. // costs a nearly full comparison at nearly every position, making the
  16794. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16795. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16796. Server svr;
  16797. svr.Post("/post", [](const Request &req, Response &res) {
  16798. EXPECT_EQ(1u, req.form.fields.size());
  16799. EXPECT_EQ("text1", req.form.get_field("text1"));
  16800. res.set_content("ok", "text/plain");
  16801. });
  16802. auto port = svr.bind_to_any_port(HOST);
  16803. thread t = thread([&] { svr.listen_after_bind(); });
  16804. auto se = detail::scope_exit([&] {
  16805. svr.stop();
  16806. t.join();
  16807. ASSERT_FALSE(svr.is_running());
  16808. });
  16809. svr.wait_until_ready();
  16810. Client cli(HOST, port);
  16811. auto post_with_boundary_of_length = [&](size_t len) {
  16812. const std::string boundary(len, 'a');
  16813. const std::string body =
  16814. "--" + boundary +
  16815. "\r\n"
  16816. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16817. "\r\n"
  16818. "text1"
  16819. "\r\n--" +
  16820. boundary + "--\r\n";
  16821. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16822. };
  16823. auto res = post_with_boundary_of_length(70);
  16824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16825. EXPECT_EQ(StatusCode::OK_200, res->status);
  16826. res = post_with_boundary_of_length(71);
  16827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16828. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16829. }
  16830. TEST(MakeFileBodyTest, Basic) {
  16831. const std::string file_content(4096, 'Z');
  16832. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16833. {
  16834. std::ofstream ofs(tmp_path, std::ios::binary);
  16835. ofs.write(file_content.data(),
  16836. static_cast<std::streamsize>(file_content.size()));
  16837. }
  16838. auto handled = false;
  16839. Server svr;
  16840. svr.Post("/upload", [&](const Request &req, Response &res) {
  16841. EXPECT_EQ(file_content, req.body);
  16842. handled = true;
  16843. res.status = StatusCode::OK_200;
  16844. });
  16845. auto port = svr.bind_to_any_port(HOST);
  16846. auto t = thread([&] { svr.listen_after_bind(); });
  16847. auto se = detail::scope_exit([&] {
  16848. svr.stop();
  16849. t.join();
  16850. ASSERT_FALSE(svr.is_running());
  16851. ASSERT_TRUE(handled);
  16852. std::remove(tmp_path.c_str());
  16853. });
  16854. svr.wait_until_ready();
  16855. auto fb = make_file_body(tmp_path);
  16856. ASSERT_GT(fb.first, 0u);
  16857. Client cli(HOST, port);
  16858. auto res =
  16859. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16861. EXPECT_EQ(StatusCode::OK_200, res->status);
  16862. }
  16863. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16864. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16865. {
  16866. std::ofstream ofs(path, std::ios::binary);
  16867. const std::string content(100, 'A');
  16868. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16869. }
  16870. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16871. auto body = make_file_body(path);
  16872. ASSERT_EQ(100u, body.first);
  16873. ASSERT_TRUE(static_cast<bool>(body.second));
  16874. // Rewritten shorter after its length was measured - and, on a server, after
  16875. // that length has already gone out as Content-Length.
  16876. {
  16877. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16878. const std::string content(10, 'A');
  16879. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16880. }
  16881. std::string written;
  16882. DataSink sink;
  16883. sink.write = [&](const char *d, size_t l) {
  16884. written.append(d, l);
  16885. return true;
  16886. };
  16887. // The provider has to report failure. write_content_with_progress() advances
  16888. // its offset only by what was written, so a provider that returns true
  16889. // without completing the length it promised is called again straight away,
  16890. // and again.
  16891. EXPECT_FALSE(body.second(0, body.first, sink));
  16892. EXPECT_EQ(std::string(10, 'A'), written);
  16893. }
  16894. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16895. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16896. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16897. {
  16898. std::ofstream ofs(path, std::ios::binary);
  16899. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16900. }
  16901. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16902. auto body = make_file_body(path);
  16903. ASSERT_EQ(content.size(), body.first);
  16904. ASSERT_TRUE(static_cast<bool>(body.second));
  16905. std::string written;
  16906. DataSink sink;
  16907. sink.write = [&](const char *d, size_t l) {
  16908. written.append(d, l);
  16909. return true;
  16910. };
  16911. EXPECT_TRUE(body.second(0, body.first, sink));
  16912. EXPECT_EQ(content, written);
  16913. }
  16914. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16915. static constexpr unsigned int number_of_tasks{1000000};
  16916. std::atomic_uint count{0};
  16917. std::unique_ptr<TaskQueue> task_queue{
  16918. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16919. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16920. auto queued = task_queue->enqueue(
  16921. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16922. EXPECT_TRUE(queued);
  16923. }
  16924. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16925. task_queue->shutdown();
  16926. #else
  16927. EXPECT_NO_THROW(task_queue->shutdown());
  16928. #endif
  16929. EXPECT_EQ(number_of_tasks, count.load());
  16930. }
  16931. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16932. static constexpr unsigned int number_of_tasks{1000000};
  16933. static constexpr unsigned int qlimit{2};
  16934. unsigned int queued_count{0};
  16935. std::atomic_uint count{0};
  16936. std::unique_ptr<TaskQueue> task_queue{
  16937. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16938. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16939. if (task_queue->enqueue(
  16940. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16941. queued_count++;
  16942. }
  16943. }
  16944. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16945. task_queue->shutdown();
  16946. #else
  16947. EXPECT_NO_THROW(task_queue->shutdown());
  16948. #endif
  16949. EXPECT_EQ(queued_count, count.load());
  16950. EXPECT_TRUE(queued_count <= number_of_tasks);
  16951. EXPECT_TRUE(queued_count >= qlimit);
  16952. }
  16953. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16954. // Use a short idle timeout so a dynamic thread spawns, times out and
  16955. // exits during the test, and the pool keeps working afterwards.
  16956. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16957. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16958. /*idle_timeout_sec=*/1}};
  16959. std::atomic_uint count{0};
  16960. std::condition_variable cv;
  16961. std::mutex mtx;
  16962. bool release = false;
  16963. // Block the base thread so the second task spawns a dynamic thread.
  16964. EXPECT_TRUE(task_queue->enqueue([&] {
  16965. std::unique_lock<std::mutex> lock(mtx);
  16966. while (!release) {
  16967. cv.wait(lock);
  16968. }
  16969. count++;
  16970. }));
  16971. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16972. // Let the dynamic thread finish its task and exceed the idle timeout.
  16973. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16974. {
  16975. std::unique_lock<std::mutex> lock(mtx);
  16976. release = true;
  16977. }
  16978. cv.notify_all();
  16979. // The pool must still accept and run tasks after the dynamic thread exited.
  16980. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16981. task_queue->shutdown();
  16982. EXPECT_EQ(3u, count.load());
  16983. }
  16984. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16985. static constexpr size_t number_of_tasks{32};
  16986. std::unique_ptr<TaskQueue> task_queue{
  16987. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16988. // Let the base threads go idle so the burst below finds them waiting.
  16989. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16990. std::mutex mtx;
  16991. std::condition_variable cv;
  16992. size_t running = 0;
  16993. bool release = false;
  16994. for (size_t i = 0; i < number_of_tasks; i++) {
  16995. EXPECT_TRUE(task_queue->enqueue([&] {
  16996. std::unique_lock<std::mutex> lock(mtx);
  16997. running++;
  16998. cv.notify_all();
  16999. cv.wait(lock, [&] { return release; });
  17000. }));
  17001. }
  17002. {
  17003. std::unique_lock<std::mutex> lock(mtx);
  17004. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17005. [&] { return running == number_of_tasks; }));
  17006. release = true;
  17007. }
  17008. cv.notify_all();
  17009. task_queue->shutdown();
  17010. }
  17011. TEST(TaskQueueTest, MaxQueuedRequests) {
  17012. static constexpr unsigned int qlimit{3};
  17013. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17014. std::condition_variable sem_cv;
  17015. std::mutex sem_mtx;
  17016. int credits = 0;
  17017. bool queued;
  17018. /* Fill up the queue with tasks that will block until we give them credits to
  17019. * complete. */
  17020. for (unsigned int n = 0; n <= qlimit;) {
  17021. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17022. std::unique_lock<std::mutex> lock(sem_mtx);
  17023. while (credits <= 0) {
  17024. sem_cv.wait(lock);
  17025. }
  17026. /* Consume the credit and signal the test code if they are all gone. */
  17027. if (--credits == 0) { sem_cv.notify_one(); }
  17028. });
  17029. if (n < qlimit) {
  17030. /* The first qlimit enqueues must succeed. */
  17031. EXPECT_TRUE(queued);
  17032. } else {
  17033. /* The last one will succeed only when the worker thread
  17034. * starts and dequeues the first blocking task. Although
  17035. * not necessary for the correctness of this test, we sleep for
  17036. * a short while to avoid busy waiting. */
  17037. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17038. }
  17039. if (queued) { n++; }
  17040. }
  17041. /* Further enqueues must fail since the queue is full. */
  17042. for (auto i = 0; i < 4; i++) {
  17043. queued = task_queue->enqueue([] {});
  17044. EXPECT_FALSE(queued);
  17045. }
  17046. /* Give the credits to allow the previous tasks to complete. */
  17047. {
  17048. std::unique_lock<std::mutex> lock(sem_mtx);
  17049. credits += qlimit + 1;
  17050. }
  17051. sem_cv.notify_all();
  17052. /* Wait for all the credits to be consumed. */
  17053. {
  17054. std::unique_lock<std::mutex> lock(sem_mtx);
  17055. while (credits > 0) {
  17056. sem_cv.wait(lock);
  17057. }
  17058. }
  17059. /* Check that we are able again to enqueue at least qlimit tasks. */
  17060. for (unsigned int i = 0; i < qlimit; i++) {
  17061. queued = task_queue->enqueue([] {});
  17062. EXPECT_TRUE(queued);
  17063. }
  17064. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17065. task_queue->shutdown();
  17066. #else
  17067. EXPECT_NO_THROW(task_queue->shutdown());
  17068. #endif
  17069. }
  17070. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17071. Server svr;
  17072. std::string method;
  17073. std::string body;
  17074. auto has_content_length = false;
  17075. auto has_transfer_encoding = false;
  17076. std::atomic<int> bad_requests{0};
  17077. // Leftover body bytes get parsed as a malformed request and answered with
  17078. // 400
  17079. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17080. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17081. });
  17082. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17083. res.set_redirect("/down", StatusCode::SeeOther_303);
  17084. });
  17085. svr.Get("/down", [&](const Request &req, Response &res) {
  17086. method = req.method;
  17087. body = req.body;
  17088. has_content_length = req.has_header("Content-Length");
  17089. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17090. res.set_content("ok", "text/plain");
  17091. });
  17092. auto port = svr.bind_to_any_port(HOST);
  17093. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17094. auto se = detail::scope_exit([&] {
  17095. svr.stop();
  17096. thread.join();
  17097. ASSERT_FALSE(svr.is_running());
  17098. });
  17099. svr.wait_until_ready();
  17100. const std::string payload = "SECRET-BODY";
  17101. auto check = [&](Client &cli, const Result &res) {
  17102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17103. EXPECT_EQ(StatusCode::OK_200, res->status);
  17104. EXPECT_EQ("ok", res->body);
  17105. EXPECT_EQ("GET", method);
  17106. EXPECT_TRUE(body.empty());
  17107. EXPECT_FALSE(has_content_length);
  17108. EXPECT_FALSE(has_transfer_encoding);
  17109. // Nothing of the original body may be left on the connection
  17110. auto res2 = cli.Get("/down");
  17111. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17112. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17113. EXPECT_EQ("ok", res2->body);
  17114. EXPECT_EQ(0, bad_requests);
  17115. };
  17116. // With content length
  17117. {
  17118. Client cli(HOST, port);
  17119. cli.set_keep_alive(true);
  17120. cli.set_follow_location(true);
  17121. auto res = cli.Post(
  17122. "/up", payload.size(),
  17123. [&](size_t offset, size_t length, DataSink &sink) {
  17124. return sink.write(payload.data() + offset, length);
  17125. },
  17126. "text/plain");
  17127. check(cli, res);
  17128. }
  17129. // Without content length (chunked)
  17130. {
  17131. Client cli(HOST, port);
  17132. cli.set_keep_alive(true);
  17133. cli.set_follow_location(true);
  17134. auto res = cli.Post(
  17135. "/up",
  17136. [&](size_t /*offset*/, DataSink &sink) {
  17137. sink.write(payload.data(), payload.size());
  17138. sink.done();
  17139. return true;
  17140. },
  17141. "text/plain");
  17142. check(cli, res);
  17143. }
  17144. }
  17145. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17146. Server svr;
  17147. std::string target;
  17148. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17149. // Echo the still-encoded name back in the Location
  17150. const std::string prefix = "/start/";
  17151. res.status = StatusCode::Found_302;
  17152. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17153. });
  17154. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17155. target = req.target;
  17156. res.set_content("ok", "text/plain");
  17157. });
  17158. auto port = svr.bind_to_any_port(HOST);
  17159. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17160. auto se = detail::scope_exit([&] {
  17161. svr.stop();
  17162. thread.join();
  17163. ASSERT_FALSE(svr.is_running());
  17164. });
  17165. svr.wait_until_ready();
  17166. // Decoding the Location path would turn the first four into a path
  17167. // separator, a query delimiter, a fragment delimiter and a different
  17168. // percent-encoded octet. The rest must keep reaching the server as they are.
  17169. const std::vector<std::string> names = {
  17170. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17171. };
  17172. for (auto path_encode : {true, false}) {
  17173. Client cli(HOST, port);
  17174. cli.set_follow_location(true);
  17175. cli.set_path_encode(path_encode);
  17176. for (const auto &name : names) {
  17177. target.clear();
  17178. auto res = cli.Get("/start/" + name);
  17179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17180. EXPECT_EQ(StatusCode::OK_200, res->status);
  17181. EXPECT_EQ("/dest/" + name, target);
  17182. }
  17183. }
  17184. }
  17185. TEST(RedirectTest, NotModifiedIsReturned) {
  17186. Server svr;
  17187. svr.Get("/cached", [](const Request &, Response &res) {
  17188. res.status = StatusCode::NotModified_304;
  17189. });
  17190. auto port = svr.bind_to_any_port(HOST);
  17191. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17192. auto se = detail::scope_exit([&] {
  17193. svr.stop();
  17194. thread.join();
  17195. ASSERT_FALSE(svr.is_running());
  17196. });
  17197. svr.wait_until_ready();
  17198. Client cli(HOST, port);
  17199. cli.set_follow_location(true);
  17200. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17202. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17203. }
  17204. TEST(RedirectTest, NoLocationIsReturned) {
  17205. Server svr;
  17206. svr.Get("/no-location", [](const Request &, Response &res) {
  17207. res.status = StatusCode::Found_302;
  17208. res.set_content("no location", "text/plain");
  17209. });
  17210. auto port = svr.bind_to_any_port(HOST);
  17211. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17212. auto se = detail::scope_exit([&] {
  17213. svr.stop();
  17214. thread.join();
  17215. ASSERT_FALSE(svr.is_running());
  17216. });
  17217. svr.wait_until_ready();
  17218. Client cli(HOST, port);
  17219. cli.set_follow_location(true);
  17220. auto res = cli.Get("/no-location");
  17221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17222. EXPECT_EQ(StatusCode::Found_302, res->status);
  17223. EXPECT_EQ("no location", res->body);
  17224. // The callbacks see the body of the response that is returned
  17225. auto handler_called = false;
  17226. auto progress_called = false;
  17227. std::string body;
  17228. auto res2 = cli.Get(
  17229. "/no-location",
  17230. [&](const Response &) {
  17231. handler_called = true;
  17232. return true;
  17233. },
  17234. [&](const char *data, size_t data_length) {
  17235. body.append(data, data_length);
  17236. return true;
  17237. },
  17238. [&](size_t, size_t) {
  17239. progress_called = true;
  17240. return true;
  17241. });
  17242. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17243. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17244. EXPECT_TRUE(handler_called);
  17245. EXPECT_TRUE(progress_called);
  17246. EXPECT_EQ("no location", body);
  17247. }
  17248. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17249. Server svr;
  17250. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17251. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  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("val&key2=val2", res->body);
  17270. }
  17271. }
  17272. #endif
  17273. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17274. Server svr;
  17275. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17276. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17277. });
  17278. svr.Get("/hello", [](const Request &req, Response &res) {
  17279. res.set_content(req.get_param_value("key"), "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("AByz09 ~-._ &?ü+", res->body);
  17295. }
  17296. }
  17297. TEST(RedirectTest, RedirectWithPlusInPath) {
  17298. Server svr;
  17299. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17300. res.set_redirect("/a+b");
  17301. });
  17302. // Route pattern uses regex; escape + as \\+
  17303. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17304. res.set_content(req.path, "text/plain");
  17305. });
  17306. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17307. auto se = detail::scope_exit([&] {
  17308. svr.stop();
  17309. thread.join();
  17310. ASSERT_FALSE(svr.is_running());
  17311. });
  17312. svr.wait_until_ready();
  17313. {
  17314. Client cli(HOST, PORT);
  17315. cli.set_follow_location(true);
  17316. auto res = cli.Get("/");
  17317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17318. EXPECT_EQ(StatusCode::OK_200, res->status);
  17319. EXPECT_EQ("/a+b", res->body);
  17320. }
  17321. }
  17322. TEST(RedirectTest, ResolveRelativeLocation) {
  17323. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17324. const std::vector<std::pair<std::string, std::string>> cases = {
  17325. {"g", "/b/c/g"},
  17326. {"./g", "/b/c/g"},
  17327. {"g/", "/b/c/g/"},
  17328. {"?y", "/b/c/d;p?y"},
  17329. {"g?y", "/b/c/g?y"},
  17330. {"#s", "/b/c/d;p?q#s"},
  17331. {"g#s", "/b/c/g#s"},
  17332. {"g?y#s", "/b/c/g?y#s"},
  17333. {";x", "/b/c/;x"},
  17334. {"g;x", "/b/c/g;x"},
  17335. {".", "/b/c/"},
  17336. {"./", "/b/c/"},
  17337. {"..", "/b/"},
  17338. {"../", "/b/"},
  17339. {"../g", "/b/g"},
  17340. {"../..", "/"},
  17341. {"../../", "/"},
  17342. {"../../g", "/g"},
  17343. {"../../../g", "/g"},
  17344. {"g.", "/b/c/g."},
  17345. {".g", "/b/c/.g"},
  17346. {"g..", "/b/c/g.."},
  17347. {"..g", "/b/c/..g"},
  17348. {"./../g", "/b/g"},
  17349. {"./g/.", "/b/c/g/"},
  17350. {"g/./h", "/b/c/g/h"},
  17351. {"g/../h", "/b/c/h"},
  17352. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17353. {"g;x=1/../y", "/b/c/y"},
  17354. {"g?y/./x", "/b/c/g?y/./x"},
  17355. {"g#s/../x", "/b/c/g#s/../x"},
  17356. // Not relative-path references, so left for parse_url.
  17357. {"/g", "/g"},
  17358. {"//g", "//g"},
  17359. {"http://g/x", "http://g/x"},
  17360. {"g:h", "g:h"},
  17361. };
  17362. for (const auto &c : cases) {
  17363. EXPECT_EQ(c.second,
  17364. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17365. << c.first;
  17366. }
  17367. }
  17368. TEST(RedirectTest, RemoveDotSegments) {
  17369. // RFC 3986 section 5.2.4
  17370. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17371. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17372. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17373. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17374. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17375. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17376. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17377. }
  17378. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17379. Server svr;
  17380. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17381. res.set_redirect("/dir/../target?x=1");
  17382. });
  17383. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17384. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17385. "/dir/./../target");
  17386. });
  17387. svr.Get("/target", [](const Request &req, Response &res) {
  17388. res.set_content(req.path, "text/plain");
  17389. });
  17390. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17391. auto se = detail::scope_exit([&] {
  17392. svr.stop();
  17393. th.join();
  17394. ASSERT_FALSE(svr.is_running());
  17395. });
  17396. svr.wait_until_ready();
  17397. Client cli("localhost", PORT);
  17398. cli.set_follow_location(true);
  17399. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17400. auto res = cli.Get(path);
  17401. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17402. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17403. EXPECT_EQ("/target", res->body) << path;
  17404. }
  17405. }
  17406. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17407. Server svr;
  17408. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17409. res.set_redirect(req.get_param_value("to"));
  17410. });
  17411. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17412. res.set_content(req.target, "text/plain");
  17413. });
  17414. svr.Get("/other", [](const Request &req, Response &res) {
  17415. res.set_content(req.target, "text/plain");
  17416. });
  17417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17418. auto se = detail::scope_exit([&] {
  17419. svr.stop();
  17420. thread.join();
  17421. ASSERT_FALSE(svr.is_running());
  17422. });
  17423. svr.wait_until_ready();
  17424. const std::vector<std::pair<std::string, std::string>> cases = {
  17425. {"next", "/dir/next"},
  17426. {"./next?x=1", "/dir/next?x=1"},
  17427. {"../other", "/other"},
  17428. };
  17429. for (const auto &c : cases) {
  17430. Client cli(HOST, PORT);
  17431. cli.set_follow_location(true);
  17432. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17433. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17434. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17435. EXPECT_EQ(c.second, res->body) << c.first;
  17436. }
  17437. }
  17438. #ifdef CPPHTTPLIB_SSL_ENABLED
  17439. TEST(RedirectTest, Issue2185_Online) {
  17440. SSLClient client("github.com");
  17441. client.set_follow_location(true);
  17442. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17443. "Coollab-Windows.zip");
  17444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17445. EXPECT_EQ(StatusCode::OK_200, res->status);
  17446. EXPECT_EQ(9920427U, res->body.size());
  17447. }
  17448. #endif
  17449. TEST(VulnerabilityTest, CRLFInjection) {
  17450. Server svr;
  17451. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17452. res.set_content("Hello 1", "text/plain");
  17453. });
  17454. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17455. res.set_content("Hello 2", "text/plain");
  17456. });
  17457. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17458. res.set_content("Hello 3", "text/plain");
  17459. });
  17460. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17461. res.set_content("Hello 4", "text/plain");
  17462. });
  17463. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17464. for (const auto &x : req.headers) {
  17465. auto key = x.first;
  17466. EXPECT_STRNE("evil", key.c_str());
  17467. }
  17468. });
  17469. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17470. auto se = detail::scope_exit([&] {
  17471. svr.stop();
  17472. thread.join();
  17473. ASSERT_FALSE(svr.is_running());
  17474. });
  17475. svr.wait_until_ready();
  17476. {
  17477. Client cli(HOST, PORT);
  17478. cli.Post("/test1", "A=B",
  17479. "application/x-www-form-urlencoded\r\nevil: hello1");
  17480. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17481. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17482. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17483. }
  17484. }
  17485. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17486. auto server_thread = std::thread([] {
  17487. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17488. default_socket_options(srv);
  17489. sockaddr_in addr{};
  17490. addr.sin_family = AF_INET;
  17491. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17492. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17493. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17494. ::listen(srv, 1);
  17495. sockaddr_in cli_addr{};
  17496. socklen_t cli_len = sizeof(cli_addr);
  17497. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17498. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17499. std::string buf_all;
  17500. char buf[2048];
  17501. ssize_t n;
  17502. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17503. buf_all.append(buf, static_cast<size_t>(n));
  17504. size_t pos;
  17505. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17506. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17507. auto e = request_block.find("\r\n");
  17508. if (e != std::string::npos) {
  17509. auto request_line = request_block.substr(0, e);
  17510. std::string msg =
  17511. "CRLF injection detected in request line: '" + request_line + "'";
  17512. EXPECT_FALSE(true) << msg;
  17513. }
  17514. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17515. ::send(cli,
  17516. #ifdef _WIN32
  17517. static_cast<const char *>(resp.c_str()),
  17518. static_cast<int>(resp.size()),
  17519. #else
  17520. resp.c_str(), resp.size(),
  17521. #endif
  17522. 0);
  17523. buf_all.erase(0, pos + 4);
  17524. }
  17525. }
  17526. detail::close_socket(cli);
  17527. detail::close_socket(srv);
  17528. });
  17529. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17530. auto cli = Client("127.0.0.1", PORT + 1);
  17531. auto headers = Headers{
  17532. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17533. {"Connection", "keep-alive"}};
  17534. auto res = cli.Get("/hi", headers);
  17535. EXPECT_FALSE(res);
  17536. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17537. server_thread.join();
  17538. }
  17539. // A request rejected before any byte reaches the socket must fail right away
  17540. // instead of waiting for a response the server will never send.
  17541. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17542. // The kernel completes the TCP handshake from the listen backlog, so the
  17543. // client connects, but nothing ever reads, responds or closes.
  17544. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17545. default_socket_options(srv);
  17546. sockaddr_in addr{};
  17547. addr.sin_family = AF_INET;
  17548. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17549. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17550. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17551. ASSERT_EQ(0, ::listen(srv, 8));
  17552. auto cli = Client("127.0.0.1", PORT + 1);
  17553. cli.set_read_timeout(10, 0);
  17554. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17555. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17556. std::chrono::steady_clock::now() - start)
  17557. .count();
  17558. };
  17559. {
  17560. Request req;
  17561. req.method = "GE T";
  17562. req.path = "/";
  17563. auto start = std::chrono::steady_clock::now();
  17564. auto res = cli.send(req);
  17565. EXPECT_FALSE(res);
  17566. EXPECT_EQ(Error::Write, res.error());
  17567. EXPECT_LT(elapsed_ms(start), 1000);
  17568. }
  17569. {
  17570. auto start = std::chrono::steady_clock::now();
  17571. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17572. EXPECT_FALSE(res);
  17573. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17574. EXPECT_LT(elapsed_ms(start), 1000);
  17575. }
  17576. EXPECT_FALSE(cli.is_socket_open());
  17577. detail::close_socket(srv);
  17578. }
  17579. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17580. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17581. default_socket_options(srv);
  17582. sockaddr_in addr{};
  17583. addr.sin_family = AF_INET;
  17584. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17585. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17586. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17587. ASSERT_EQ(0, ::listen(srv, 1));
  17588. std::string received;
  17589. auto server_thread = std::thread([&] {
  17590. auto sock = ::accept(srv, nullptr, nullptr);
  17591. if (sock == INVALID_SOCKET) { return; }
  17592. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17593. char buf[2048];
  17594. ssize_t n;
  17595. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17596. received.append(buf, static_cast<size_t>(n));
  17597. }
  17598. detail::close_socket(sock);
  17599. });
  17600. {
  17601. auto cli = Client("127.0.0.1", PORT + 1);
  17602. // "Z" sorts after the default headers, so writing straight to the socket
  17603. // would have sent the request line and those headers before the rejection.
  17604. auto handle =
  17605. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17606. EXPECT_FALSE(handle.is_valid());
  17607. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17608. }
  17609. server_thread.join();
  17610. detail::close_socket(srv);
  17611. EXPECT_TRUE(received.empty()) << received;
  17612. }
  17613. TEST(PathParamsTest, StaticMatch) {
  17614. const auto pattern = "/users/all";
  17615. detail::PathParamsMatcher matcher(pattern);
  17616. Request request;
  17617. request.path = "/users/all";
  17618. ASSERT_TRUE(matcher.match(request));
  17619. std::unordered_map<std::string, std::string> expected_params = {};
  17620. EXPECT_EQ(request.path_params, expected_params);
  17621. }
  17622. TEST(PathParamsTest, StaticMismatch) {
  17623. const auto pattern = "/users/all";
  17624. detail::PathParamsMatcher matcher(pattern);
  17625. Request request;
  17626. request.path = "/users/1";
  17627. ASSERT_FALSE(matcher.match(request));
  17628. }
  17629. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17630. const auto pattern = "/users/:id/subscriptions";
  17631. detail::PathParamsMatcher matcher(pattern);
  17632. Request request;
  17633. request.path = "/users/42/subscriptions";
  17634. ASSERT_TRUE(matcher.match(request));
  17635. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17636. EXPECT_EQ(request.path_params, expected_params);
  17637. }
  17638. TEST(PathParamsTest, SingleParamInTheEnd) {
  17639. const auto pattern = "/users/:id";
  17640. detail::PathParamsMatcher matcher(pattern);
  17641. Request request;
  17642. request.path = "/users/24";
  17643. ASSERT_TRUE(matcher.match(request));
  17644. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17645. EXPECT_EQ(request.path_params, expected_params);
  17646. }
  17647. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17648. const auto pattern = "/users/:id/";
  17649. detail::PathParamsMatcher matcher(pattern);
  17650. Request request;
  17651. request.path = "/users/42/";
  17652. ASSERT_TRUE(matcher.match(request));
  17653. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17654. EXPECT_EQ(request.path_params, expected_params);
  17655. }
  17656. TEST(PathParamsTest, EmptyParam) {
  17657. const auto pattern = "/users/:id/";
  17658. detail::PathParamsMatcher matcher(pattern);
  17659. Request request;
  17660. request.path = "/users//";
  17661. ASSERT_TRUE(matcher.match(request));
  17662. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17663. EXPECT_EQ(request.path_params, expected_params);
  17664. }
  17665. TEST(PathParamsTest, FragmentMismatch) {
  17666. const auto pattern = "/users/:id/";
  17667. detail::PathParamsMatcher matcher(pattern);
  17668. Request request;
  17669. request.path = "/admins/24/";
  17670. ASSERT_FALSE(matcher.match(request));
  17671. }
  17672. TEST(PathParamsTest, ExtraFragments) {
  17673. const auto pattern = "/users/:id";
  17674. detail::PathParamsMatcher matcher(pattern);
  17675. Request request;
  17676. request.path = "/users/42/subscriptions";
  17677. ASSERT_FALSE(matcher.match(request));
  17678. }
  17679. TEST(PathParamsTest, MissingTrailingParam) {
  17680. const auto pattern = "/users/:id";
  17681. detail::PathParamsMatcher matcher(pattern);
  17682. Request request;
  17683. request.path = "/users";
  17684. ASSERT_FALSE(matcher.match(request));
  17685. }
  17686. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17687. const auto pattern = "/users/:id/subscriptions";
  17688. detail::PathParamsMatcher matcher(pattern);
  17689. Request request;
  17690. request.path = "/users/subscriptions";
  17691. ASSERT_FALSE(matcher.match(request));
  17692. }
  17693. TEST(PathParamsTest, MultipleParams) {
  17694. const auto pattern = "/users/:userid/subscriptions/:subid";
  17695. detail::PathParamsMatcher matcher(pattern);
  17696. Request request;
  17697. request.path = "/users/42/subscriptions/2";
  17698. ASSERT_TRUE(matcher.match(request));
  17699. std::unordered_map<std::string, std::string> expected_params = {
  17700. {"userid", "42"}, {"subid", "2"}};
  17701. EXPECT_EQ(request.path_params, expected_params);
  17702. }
  17703. TEST(PathParamsTest, SequenceOfParams) {
  17704. const auto pattern = "/values/:x/:y/:z";
  17705. detail::PathParamsMatcher matcher(pattern);
  17706. Request request;
  17707. request.path = "/values/1/2/3";
  17708. ASSERT_TRUE(matcher.match(request));
  17709. std::unordered_map<std::string, std::string> expected_params = {
  17710. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17711. EXPECT_EQ(request.path_params, expected_params);
  17712. }
  17713. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17714. const auto pattern = "/prefix:suffix";
  17715. detail::PathParamsMatcher matcher(pattern);
  17716. Request request;
  17717. request.path = "/prefix:suffix";
  17718. ASSERT_TRUE(matcher.match(request));
  17719. const std::unordered_map<std::string, std::string> expected_params = {};
  17720. EXPECT_EQ(request.path_params, expected_params);
  17721. }
  17722. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17723. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17724. // calling thread's stack on a long enough path for a quantified pattern;
  17725. // RegexMatcher must refuse to run regex matching on paths beyond
  17726. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17727. detail::RegexMatcher matcher("/files/(.*)");
  17728. Request within_limit;
  17729. within_limit.path = "/files/" + std::string(10, 'A');
  17730. EXPECT_TRUE(matcher.match(within_limit));
  17731. Request over_limit;
  17732. over_limit.path =
  17733. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17734. EXPECT_FALSE(matcher.match(over_limit));
  17735. }
  17736. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17737. Server svr;
  17738. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17739. res.set_content("ok", "text/plain");
  17740. });
  17741. auto port = svr.bind_to_any_port(HOST);
  17742. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17743. auto se = detail::scope_exit([&] {
  17744. svr.stop();
  17745. thread.join();
  17746. ASSERT_FALSE(svr.is_running());
  17747. });
  17748. svr.wait_until_ready();
  17749. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17750. // request URI limit; this used to be able to crash the process.
  17751. std::string path =
  17752. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17753. std::string req = "GET " + path +
  17754. " HTTP/1.1\r\n"
  17755. "Host: " +
  17756. std::string(HOST) + ":" + std::to_string(port) +
  17757. "\r\n"
  17758. "Connection: close\r\n"
  17759. "\r\n";
  17760. std::string response;
  17761. ASSERT_TRUE(send_request(5, req, &response, port));
  17762. EXPECT_NE(std::string::npos, response.find("404"));
  17763. }
  17764. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17765. Server svr;
  17766. auto handler = [](const Request & /*req*/, Response &res) {
  17767. res.set_content("hit", "text/plain");
  17768. };
  17769. // No regex metacharacter, so this one is compared literally
  17770. svr.Get("/literal/route", handler);
  17771. // '.' is a regex metacharacter, so this one must keep regex semantics
  17772. svr.Get("/a.c", handler);
  17773. auto port = svr.bind_to_any_port(HOST);
  17774. std::thread t([&]() { svr.listen_after_bind(); });
  17775. auto se = detail::scope_exit([&] {
  17776. svr.stop();
  17777. t.join();
  17778. ASSERT_FALSE(svr.is_running());
  17779. });
  17780. svr.wait_until_ready();
  17781. Client cli(HOST, port);
  17782. struct {
  17783. const char *path;
  17784. int status;
  17785. } cases[] = {
  17786. {"/literal/route", StatusCode::OK_200},
  17787. {"/literal/routes", StatusCode::NotFound_404},
  17788. {"/literal/rout", StatusCode::NotFound_404},
  17789. {"/abc", StatusCode::OK_200},
  17790. {"/a.c", StatusCode::OK_200},
  17791. };
  17792. for (const auto &x : cases) {
  17793. auto res = cli.Get(x.path);
  17794. ASSERT_TRUE(res) << x.path;
  17795. EXPECT_EQ(x.status, res->status) << x.path;
  17796. }
  17797. }
  17798. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17799. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17800. // from exhausting the stack, so it must only constrain routes that actually
  17801. // run a regular expression. A literal route is matched by comparison and
  17802. // stays usable at any length.
  17803. Server svr;
  17804. const std::string pattern =
  17805. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17806. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17807. res.set_content("hit", "text/plain");
  17808. });
  17809. auto port = svr.bind_to_any_port(HOST);
  17810. std::thread t([&]() { svr.listen_after_bind(); });
  17811. auto se = detail::scope_exit([&] {
  17812. svr.stop();
  17813. t.join();
  17814. ASSERT_FALSE(svr.is_running());
  17815. });
  17816. svr.wait_until_ready();
  17817. Client cli(HOST, port);
  17818. auto res = cli.Get(pattern);
  17819. ASSERT_TRUE(res);
  17820. EXPECT_EQ(StatusCode::OK_200, res->status);
  17821. }
  17822. TEST(ParseUrlTest, VariousPatterns) {
  17823. {
  17824. detail::UrlComponents uc;
  17825. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17826. EXPECT_EQ("http", uc.scheme);
  17827. EXPECT_EQ("example.com", uc.host);
  17828. EXPECT_EQ("8080", uc.port);
  17829. EXPECT_EQ("/path", uc.path);
  17830. EXPECT_EQ("?q=1", uc.query);
  17831. }
  17832. {
  17833. detail::UrlComponents uc;
  17834. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17835. EXPECT_EQ("https", uc.scheme);
  17836. EXPECT_EQ("example.com", uc.host);
  17837. EXPECT_TRUE(uc.port.empty());
  17838. EXPECT_EQ("/path", uc.path);
  17839. }
  17840. {
  17841. detail::UrlComponents uc;
  17842. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17843. EXPECT_EQ("::1", uc.host);
  17844. EXPECT_EQ("8080", uc.port);
  17845. EXPECT_EQ("/path", uc.path);
  17846. }
  17847. {
  17848. detail::UrlComponents uc;
  17849. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17850. }
  17851. {
  17852. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17853. // the path while the connection still targets the bracketed host.
  17854. detail::UrlComponents uc;
  17855. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17856. }
  17857. {
  17858. detail::UrlComponents uc;
  17859. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17860. }
  17861. {
  17862. detail::UrlComponents uc;
  17863. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17864. EXPECT_EQ("::1", uc.host);
  17865. EXPECT_TRUE(uc.port.empty());
  17866. EXPECT_EQ("/path", uc.path);
  17867. }
  17868. {
  17869. detail::UrlComponents uc;
  17870. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17871. EXPECT_TRUE(uc.scheme.empty());
  17872. EXPECT_EQ("example.com", uc.host);
  17873. EXPECT_EQ("/path", uc.path);
  17874. EXPECT_EQ("?q=1", uc.query);
  17875. }
  17876. {
  17877. detail::UrlComponents uc;
  17878. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17879. EXPECT_TRUE(uc.host.empty());
  17880. EXPECT_EQ("/path", uc.path);
  17881. EXPECT_EQ("?q=1", uc.query);
  17882. }
  17883. {
  17884. detail::UrlComponents uc;
  17885. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17886. EXPECT_EQ("example.com", uc.host);
  17887. EXPECT_EQ("8080", uc.port);
  17888. }
  17889. {
  17890. // Unix socket path — must not be parsed as host
  17891. detail::UrlComponents uc;
  17892. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17893. EXPECT_TRUE(uc.host.empty());
  17894. }
  17895. {
  17896. detail::UrlComponents uc;
  17897. ASSERT_TRUE(detail::parse_url("", uc));
  17898. EXPECT_TRUE(uc.host.empty());
  17899. EXPECT_TRUE(uc.path.empty());
  17900. }
  17901. {
  17902. detail::UrlComponents uc;
  17903. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17904. }
  17905. {
  17906. detail::UrlComponents uc;
  17907. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17908. }
  17909. {
  17910. // Accepted by parse_url; callers restrict to http/https
  17911. detail::UrlComponents uc;
  17912. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17913. EXPECT_EQ("ftp", uc.scheme);
  17914. }
  17915. {
  17916. detail::UrlComponents uc;
  17917. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17918. }
  17919. {
  17920. detail::UrlComponents uc;
  17921. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17922. }
  17923. }
  17924. TEST(ParseUrlTest, FragmentHandling) {
  17925. {
  17926. detail::UrlComponents uc;
  17927. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17928. EXPECT_EQ("/path", uc.path);
  17929. EXPECT_TRUE(uc.query.empty());
  17930. }
  17931. {
  17932. detail::UrlComponents uc;
  17933. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17934. EXPECT_TRUE(uc.path.empty());
  17935. EXPECT_TRUE(uc.query.empty());
  17936. }
  17937. }
  17938. TEST(ParseUrlTest, UserinfoHandling) {
  17939. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17940. // parsers would see evil.com as the host.
  17941. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17942. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17943. for (auto url : urls) {
  17944. detail::UrlComponents uc;
  17945. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17946. }
  17947. }
  17948. TEST(ParseUrlTest, IPv6EdgeCases) {
  17949. {
  17950. detail::UrlComponents uc;
  17951. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17952. EXPECT_TRUE(uc.scheme.empty());
  17953. EXPECT_EQ("::1", uc.host);
  17954. EXPECT_EQ("8080", uc.port);
  17955. }
  17956. {
  17957. // Zone ID '%25' is not in [a-fA-F0-9:]
  17958. detail::UrlComponents uc;
  17959. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17960. }
  17961. }
  17962. TEST(ParseUrlTest, SchemeEdgeCases) {
  17963. {
  17964. detail::UrlComponents uc;
  17965. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17966. }
  17967. {
  17968. detail::UrlComponents uc;
  17969. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17970. }
  17971. {
  17972. detail::UrlComponents uc;
  17973. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17974. }
  17975. }
  17976. TEST(ParseUrlTest, PortEdgeCases) {
  17977. {
  17978. detail::UrlComponents uc;
  17979. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17980. EXPECT_TRUE(uc.port.empty());
  17981. EXPECT_EQ("/path", uc.path);
  17982. }
  17983. {
  17984. // parse_url accepts any port string; validation is done by parse_port
  17985. detail::UrlComponents uc;
  17986. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17987. EXPECT_EQ("abc", uc.port);
  17988. }
  17989. }
  17990. TEST(ParseUrlTest, WebSocketPatterns) {
  17991. {
  17992. detail::UrlComponents uc;
  17993. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17994. EXPECT_EQ("ws", uc.scheme);
  17995. EXPECT_EQ("echo.example.com", uc.host);
  17996. EXPECT_EQ("8080", uc.port);
  17997. EXPECT_EQ("/ws", uc.path);
  17998. }
  17999. {
  18000. detail::UrlComponents uc;
  18001. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18002. EXPECT_EQ("wss", uc.scheme);
  18003. EXPECT_EQ("echo.example.com", uc.host);
  18004. EXPECT_TRUE(uc.port.empty());
  18005. EXPECT_EQ("/ws", uc.path);
  18006. }
  18007. }
  18008. TEST(ParseUrlTest, QueryOnly) {
  18009. detail::UrlComponents uc;
  18010. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18011. EXPECT_TRUE(uc.host.empty());
  18012. EXPECT_TRUE(uc.path.empty());
  18013. EXPECT_EQ("?q=1&r=2", uc.query);
  18014. }
  18015. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18016. detail::UrlComponents uc;
  18017. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18018. EXPECT_TRUE(uc.scheme.empty());
  18019. EXPECT_EQ("example.com", uc.host);
  18020. EXPECT_EQ("443", uc.port);
  18021. EXPECT_EQ("/path", uc.path);
  18022. }
  18023. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18024. // If ipv6 regex working, regex match codepath is taken.
  18025. // else port will default to 80 in Client impl
  18026. int clientImplMagicPort = 80;
  18027. int port = 4321;
  18028. // above ports must be different to avoid false negative
  18029. EXPECT_NE(clientImplMagicPort, port);
  18030. std::string ipV6TestURL = "http://[ff06::c3]";
  18031. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18032. CLIENT_PRIVATE_KEY_FILE);
  18033. EXPECT_EQ(cli.port(), port);
  18034. }
  18035. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18036. auto file_path = "./www/dir/index.html";
  18037. auto dir_path = "./www/dir";
  18038. detail::FileStat stat_file(file_path);
  18039. EXPECT_TRUE(stat_file.is_file());
  18040. EXPECT_FALSE(stat_file.is_dir());
  18041. detail::FileStat stat_dir(dir_path);
  18042. EXPECT_FALSE(stat_dir.is_file());
  18043. EXPECT_TRUE(stat_dir.is_dir());
  18044. }
  18045. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18046. // IPv4 with default HTTP port (80)
  18047. EXPECT_EQ("example.com",
  18048. detail::make_host_and_port_string("example.com", 80, false));
  18049. // IPv4 with default HTTPS port (443)
  18050. EXPECT_EQ("example.com",
  18051. detail::make_host_and_port_string("example.com", 443, true));
  18052. // IPv4 with non-default HTTP port
  18053. EXPECT_EQ("example.com:8080",
  18054. detail::make_host_and_port_string("example.com", 8080, false));
  18055. // IPv4 with non-default HTTPS port
  18056. EXPECT_EQ("example.com:8443",
  18057. detail::make_host_and_port_string("example.com", 8443, true));
  18058. // IPv6 with default HTTP port (80)
  18059. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18060. // IPv6 with default HTTPS port (443)
  18061. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18062. // IPv6 with non-default HTTP port
  18063. EXPECT_EQ("[::1]:8080",
  18064. detail::make_host_and_port_string("::1", 8080, false));
  18065. // IPv6 with non-default HTTPS port
  18066. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18067. // IPv6 full address with default port
  18068. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18069. detail::make_host_and_port_string(
  18070. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18071. // IPv6 full address with non-default port
  18072. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18073. detail::make_host_and_port_string(
  18074. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18075. // IPv6 localhost with non-default port
  18076. EXPECT_EQ("[::1]:3000",
  18077. detail::make_host_and_port_string("::1", 3000, false));
  18078. // IPv6 with zone ID (link-local address) with default port
  18079. EXPECT_EQ("[fe80::1%eth0]",
  18080. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18081. // IPv6 with zone ID (link-local address) with non-default port
  18082. EXPECT_EQ("[fe80::1%eth0]:8080",
  18083. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18084. // Edge case: Port 443 with is_ssl=false (should add port)
  18085. EXPECT_EQ("example.com:443",
  18086. detail::make_host_and_port_string("example.com", 443, false));
  18087. // Edge case: Port 80 with is_ssl=true (should add port)
  18088. EXPECT_EQ("example.com:80",
  18089. detail::make_host_and_port_string("example.com", 80, true));
  18090. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18091. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18092. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18093. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18094. // Security fix: Already bracketed IPv6 should not get double brackets
  18095. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18096. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18097. EXPECT_EQ("[::1]:8080",
  18098. detail::make_host_and_port_string("[::1]", 8080, false));
  18099. EXPECT_EQ("[2001:db8::1]:8080",
  18100. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18101. EXPECT_EQ("[fe80::1%eth0]",
  18102. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18103. EXPECT_EQ("[fe80::1%eth0]:8080",
  18104. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18105. // Edge case: Empty host (should return as-is)
  18106. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18107. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18108. // This is a known limitation but shouldn't crash
  18109. EXPECT_EQ("[host:name]",
  18110. detail::make_host_and_port_string("host:name", 80, false));
  18111. // Port number edge cases (no validation, but should not crash)
  18112. EXPECT_EQ("example.com:0",
  18113. detail::make_host_and_port_string("example.com", 0, false));
  18114. EXPECT_EQ("example.com:-1",
  18115. detail::make_host_and_port_string("example.com", -1, false));
  18116. EXPECT_EQ("example.com:65535",
  18117. detail::make_host_and_port_string("example.com", 65535, false));
  18118. EXPECT_EQ("example.com:65536",
  18119. detail::make_host_and_port_string("example.com", 65536, false));
  18120. }
  18121. #ifdef CPPHTTPLIB_SSL_ENABLED
  18122. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18123. httplib::SSLClient cli("roblox.com", 443);
  18124. cli.set_follow_location(true);
  18125. auto res = cli.Get("/");
  18126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18127. EXPECT_EQ(StatusCode::OK_200, res->status);
  18128. }
  18129. #endif
  18130. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18131. Server svr;
  18132. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18133. EXPECT_EQ(res.status, 400);
  18134. });
  18135. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18136. auto se = detail::scope_exit([&] {
  18137. svr.stop();
  18138. thread.join();
  18139. ASSERT_FALSE(svr.is_running());
  18140. });
  18141. svr.wait_until_ready();
  18142. Client cli(HOST, PORT);
  18143. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18144. }
  18145. TEST(InvalidHeaderCharsTest, is_field_name) {
  18146. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18147. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18148. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18149. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18150. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18151. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18152. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18153. EXPECT_FALSE(detail::fields::is_field_name(""));
  18154. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18155. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18156. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18157. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18158. }
  18159. TEST(InvalidHeaderCharsTest, is_field_value) {
  18160. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18161. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18162. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18163. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18164. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18165. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18166. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18167. EXPECT_TRUE(detail::fields::is_field_value(""));
  18168. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18169. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18170. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18171. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18172. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18173. }
  18174. TEST(InvalidHeaderCharsTest, OnServer) {
  18175. Server svr;
  18176. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18177. std::string header = "Not Set";
  18178. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18179. res.set_header(header, "value");
  18180. res.set_content("Page Content Page Content", "text/plain");
  18181. });
  18182. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18183. std::string header = "Not Set";
  18184. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18185. res.set_header("X-Test", header);
  18186. res.set_content("Page Content Page Content", "text/plain");
  18187. });
  18188. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18189. auto se = detail::scope_exit([&] {
  18190. svr.stop();
  18191. thread.join();
  18192. ASSERT_FALSE(svr.is_running());
  18193. });
  18194. svr.wait_until_ready();
  18195. Client cli(HOST, PORT);
  18196. {
  18197. auto res = cli.Get(
  18198. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18200. EXPECT_EQ("Page Content Page Content", res->body);
  18201. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18202. }
  18203. {
  18204. auto res = cli.Get(
  18205. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18207. EXPECT_EQ("Page Content Page Content", res->body);
  18208. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18209. }
  18210. }
  18211. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18212. auto handled = false;
  18213. Server svr;
  18214. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18215. thread t = thread([&] { svr.listen(HOST, PORT); });
  18216. auto se = detail::scope_exit([&] {
  18217. svr.stop();
  18218. t.join();
  18219. ASSERT_FALSE(svr.is_running());
  18220. ASSERT_FALSE(handled);
  18221. });
  18222. svr.wait_until_ready();
  18223. auto req = "POST /test HTTP/1.1\r\n"
  18224. "Content-Length: x\r\n"
  18225. "\r\n";
  18226. std::string response;
  18227. ASSERT_TRUE(send_request(1, req, &response));
  18228. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18229. response.substr(0, response.find("\r\n")));
  18230. }
  18231. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18232. // case-insensitive, and a server that receives a 100-continue expectation in
  18233. // an HTTP/1.0 request MUST ignore it.
  18234. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18235. std::string response;
  18236. ASSERT_TRUE(send_request(1, req, &response, port));
  18237. *got_100 = response.find("100 Continue") != std::string::npos;
  18238. }
  18239. class ExpectTokenTest : public ::testing::Test {
  18240. protected:
  18241. void SetUp() override {
  18242. svr_.Post("/p", [](const Request &, Response &res) {
  18243. res.set_content("ok", "text/plain");
  18244. });
  18245. port_ = svr_.bind_to_any_port(HOST);
  18246. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18247. svr_.wait_until_ready();
  18248. }
  18249. void TearDown() override {
  18250. svr_.stop();
  18251. if (thread_.joinable()) { thread_.join(); }
  18252. }
  18253. std::string request(const char *version, const char *expect_value) const {
  18254. return std::string("POST /p ") + version +
  18255. "\r\n"
  18256. "Host: localhost\r\n"
  18257. "Content-Length: 2\r\n"
  18258. "Connection: close\r\n"
  18259. "Expect: " +
  18260. expect_value +
  18261. "\r\n"
  18262. "\r\n"
  18263. "hi";
  18264. }
  18265. Server svr_;
  18266. int port_ = 0;
  18267. thread thread_;
  18268. };
  18269. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18270. bool got_100 = false;
  18271. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18272. EXPECT_TRUE(got_100);
  18273. }
  18274. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18275. bool got_100 = true;
  18276. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18277. EXPECT_FALSE(got_100);
  18278. }
  18279. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18280. bool got_100 = false;
  18281. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18282. EXPECT_TRUE(got_100);
  18283. }
  18284. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18285. bool got_100 = false;
  18286. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18287. EXPECT_TRUE(got_100);
  18288. }
  18289. // `100 Continue` is sent only when the server starts reading the body, so a
  18290. // request rejected before that never invites the client to send it. The
  18291. // requests below carry the expectation but withhold the body, as a client
  18292. // waiting for `100 Continue` would.
  18293. // A POST that expects `100 Continue` and withholds its two-byte body.
  18294. static std::string expect_headers_only(const std::string &path) {
  18295. return "POST " + path +
  18296. " HTTP/1.1\r\n"
  18297. "Host: localhost\r\n"
  18298. "Content-Length: 2\r\n"
  18299. "Expect: 100-continue\r\n"
  18300. "\r\n";
  18301. }
  18302. class ExpectLazyContinueTest : public ::testing::Test {
  18303. protected:
  18304. void SetUp() override {
  18305. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18306. if (req.path == "/pre-routing") {
  18307. res.status = StatusCode::Unauthorized_401;
  18308. return Server::HandlerResponse::Handled;
  18309. }
  18310. return Server::HandlerResponse::Unhandled;
  18311. });
  18312. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18313. if (req.matched_route == "/pre-request") {
  18314. res.status = StatusCode::Forbidden_403;
  18315. return Server::HandlerResponse::Handled;
  18316. }
  18317. return Server::HandlerResponse::Unhandled;
  18318. });
  18319. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18320. res.set_content("ok", "text/plain");
  18321. });
  18322. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18323. res.set_content("ok", "text/plain");
  18324. });
  18325. svr_.Post("/reader-used", [](const Request &, Response &res,
  18326. const ContentReader &content_reader) {
  18327. std::string body;
  18328. content_reader([&](const char *data, size_t len) {
  18329. body.append(data, len);
  18330. return true;
  18331. });
  18332. res.set_content(body, "text/plain");
  18333. });
  18334. svr_.Post("/reader-unused",
  18335. [](const Request &, Response &res, const ContentReader &) {
  18336. res.set_content("ignored", "text/plain");
  18337. });
  18338. port_ = svr_.bind_to_any_port(HOST);
  18339. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18340. svr_.wait_until_ready();
  18341. }
  18342. void TearDown() override {
  18343. svr_.stop();
  18344. if (thread_.joinable()) { thread_.join(); }
  18345. }
  18346. // Sends `req` and reads until the server closes the connection. Returns
  18347. // false if the read had to wait for the client-side timeout instead.
  18348. bool send_until_closed(const std::string &req, std::string *resp) const {
  18349. auto start = std::chrono::steady_clock::now();
  18350. if (!send_request(3, req, resp, port_)) { return false; }
  18351. auto elapsed = std::chrono::steady_clock::now() - start;
  18352. return elapsed < std::chrono::seconds(2);
  18353. }
  18354. // The final response comes without `100 Continue`, and the server closes
  18355. // the connection since the body may or may not follow.
  18356. void expect_final_without_interim(const std::string &path,
  18357. const char *status_line) const {
  18358. std::string resp;
  18359. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18360. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18361. EXPECT_EQ(0u, resp.find(status_line));
  18362. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18363. }
  18364. Server svr_;
  18365. int port_ = 0;
  18366. thread thread_;
  18367. };
  18368. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18369. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18370. }
  18371. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18372. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18373. }
  18374. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18375. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18376. }
  18377. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18378. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18379. }
  18380. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18381. // The body follows once `100 Continue` has had time to arrive.
  18382. auto req = expect_headers_only("/reader-used");
  18383. req.insert(req.size() - 2, "Connection: close\r\n");
  18384. std::string resp;
  18385. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18386. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18387. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18388. EXPECT_NE(std::string::npos, resp.find("hi"));
  18389. }
  18390. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18391. // Large enough for the client to add `Expect: 100-continue` itself.
  18392. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18393. std::atomic<bool> body_sent{false};
  18394. Client cli(HOST, port_);
  18395. auto res = cli.Post(
  18396. "/pre-request", length,
  18397. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18398. body_sent = true;
  18399. std::string chunk(len, 'x');
  18400. sink.write(chunk.data(), chunk.size());
  18401. return true;
  18402. },
  18403. "application/octet-stream");
  18404. ASSERT_TRUE(res);
  18405. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18406. EXPECT_FALSE(body_sent);
  18407. }
  18408. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18409. Server svr;
  18410. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18411. return StatusCode::ExpectationFailed_417;
  18412. });
  18413. svr.Post("/p", [](const Request &, Response &res) {
  18414. res.set_content("ok", "text/plain");
  18415. });
  18416. auto port = svr.bind_to_any_port(HOST);
  18417. thread t = thread([&] { svr.listen_after_bind(); });
  18418. auto se = detail::scope_exit([&] {
  18419. svr.stop();
  18420. t.join();
  18421. });
  18422. svr.wait_until_ready();
  18423. std::string resp;
  18424. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18425. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18426. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18427. // Exactly one response: the route handler must not run after the 417.
  18428. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18429. }
  18430. #ifndef _WIN32
  18431. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18432. static constexpr char reject[] = "Unauthorized";
  18433. static constexpr char accept[] = "Upload accepted";
  18434. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18435. Server svr;
  18436. svr.set_expect_100_continue_handler(
  18437. [](const Request & /*req*/, Response &res) {
  18438. res.status = StatusCode::Unauthorized_401;
  18439. res.set_content(reject, "text/plain");
  18440. return res.status;
  18441. });
  18442. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18443. res.set_content(accept, "text/plain");
  18444. });
  18445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18446. auto se = detail::scope_exit([&] {
  18447. svr.stop();
  18448. thread.join();
  18449. ASSERT_FALSE(svr.is_running());
  18450. });
  18451. svr.wait_until_ready();
  18452. {
  18453. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18454. curl_easy_init(), &curl_easy_cleanup};
  18455. ASSERT_NE(curl, nullptr);
  18456. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18457. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18458. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18459. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18460. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18461. &curl_slist_free_all};
  18462. ASSERT_NE(list, nullptr);
  18463. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18464. struct read_data {
  18465. uint64_t read_size;
  18466. uint64_t total_size;
  18467. } data = {0, total_size};
  18468. using read_callback_t =
  18469. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18470. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18471. void *userdata) -> size_t {
  18472. read_data *d = (read_data *)userdata;
  18473. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18474. std::fill_n(ptr, size * nmemb, 'A');
  18475. d->read_size += size * nmemb;
  18476. return size * nmemb;
  18477. };
  18478. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18479. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18480. std::vector<char> buffer;
  18481. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18482. using write_callback_t =
  18483. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18484. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18485. void *userdata) -> size_t {
  18486. std::vector<char> *buf = (std::vector<char> *)userdata;
  18487. buf->reserve(buf->size() + size * nmemb + 1);
  18488. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18489. return size * nmemb;
  18490. };
  18491. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18492. {
  18493. const auto res = curl_easy_perform(curl.get());
  18494. ASSERT_EQ(res, CURLE_OK);
  18495. }
  18496. {
  18497. auto response_code = long{};
  18498. const auto res =
  18499. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18500. ASSERT_EQ(res, CURLE_OK);
  18501. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18502. }
  18503. {
  18504. auto dl = curl_off_t{};
  18505. const auto res =
  18506. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18507. ASSERT_EQ(res, CURLE_OK);
  18508. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18509. }
  18510. {
  18511. buffer.push_back('\0');
  18512. ASSERT_STRCASEEQ(buffer.data(), reject);
  18513. }
  18514. }
  18515. }
  18516. #endif
  18517. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18518. // Regression test for #2458.
  18519. //
  18520. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18521. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18522. // ticket can make the client socket spuriously readable during the
  18523. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18524. // the client withholds the body and then blocks reading a response that never
  18525. // comes, failing with `Failed to read connection`.
  18526. //
  18527. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18528. // within the timeout. This raw OpenSSL server deliberately never sends
  18529. // `100 Continue`; the client must still deliver the body and receive 200.
  18530. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18531. signal(SIGPIPE, SIG_IGN);
  18532. const auto port = PORT + 4;
  18533. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18534. ASSERT_NE(srv, INVALID_SOCKET);
  18535. int opt = 1;
  18536. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18537. sockaddr_in addr{};
  18538. addr.sin_family = AF_INET;
  18539. addr.sin_port = htons(static_cast<uint16_t>(port));
  18540. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18541. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18542. ASSERT_EQ(0, ::listen(srv, 1));
  18543. std::atomic<size_t> server_body_bytes{0};
  18544. auto server_thread = std::thread([&] {
  18545. sockaddr_in cli_addr{};
  18546. socklen_t cli_len = sizeof(cli_addr);
  18547. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18548. if (cli == INVALID_SOCKET) { return; }
  18549. // Bound the lifetime of the server side so a buggy client (which never
  18550. // sends the body) cannot make this thread block forever on join.
  18551. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18552. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18553. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18554. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18555. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18556. SSL *ssl = SSL_new(ctx);
  18557. SSL_set_fd(ssl, static_cast<int>(cli));
  18558. if (SSL_accept(ssl) > 0) {
  18559. // Read the request headers. Reading here also flushes the TLS 1.3
  18560. // session tickets to the client. Deliberately do NOT send
  18561. // `100 Continue`.
  18562. std::string buf;
  18563. char tmp[1024];
  18564. while (buf.find("\r\n\r\n") == std::string::npos) {
  18565. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18566. if (n <= 0) { break; }
  18567. buf.append(tmp, static_cast<size_t>(n));
  18568. }
  18569. // A correct client sends the body now; count what arrives.
  18570. auto pos = buf.find("\r\n\r\n");
  18571. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18572. while (body < 4096) {
  18573. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18574. if (n <= 0) { break; }
  18575. body += static_cast<size_t>(n);
  18576. }
  18577. server_body_bytes = body;
  18578. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18579. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18580. SSL_shutdown(ssl);
  18581. }
  18582. SSL_free(ssl);
  18583. detail::close_socket(cli);
  18584. SSL_CTX_free(ctx);
  18585. });
  18586. auto se = detail::scope_exit([&] {
  18587. server_thread.join();
  18588. detail::close_socket(srv);
  18589. });
  18590. SSLClient cli("127.0.0.1", port);
  18591. cli.enable_server_certificate_verification(false);
  18592. cli.set_connection_timeout(5, 0);
  18593. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18594. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18595. std::string body(4096, 'A');
  18596. auto res = cli.Put("/api/test", body, "application/json");
  18597. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18598. EXPECT_EQ(StatusCode::OK_200, res->status);
  18599. EXPECT_EQ(body.size(), server_body_bytes.load());
  18600. }
  18601. #endif
  18602. template <typename S, typename C>
  18603. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18604. svr.Get("/stream", [&](const Request &, Response &res) {
  18605. auto data = new std::string("01234567890123456789");
  18606. res.set_content_provider(
  18607. data->size(), "text/plain",
  18608. [&, data](size_t offset, size_t length, DataSink &sink) {
  18609. const size_t DATA_CHUNK_SIZE = 4;
  18610. const auto &d = *data;
  18611. std::this_thread::sleep_for(std::chrono::seconds(1));
  18612. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18613. return true;
  18614. },
  18615. [data](bool success) {
  18616. EXPECT_FALSE(success);
  18617. delete data;
  18618. });
  18619. });
  18620. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18621. auto i = new size_t(0);
  18622. res.set_content_provider(
  18623. "text/plain",
  18624. [i](size_t, DataSink &sink) {
  18625. if (*i < 5) {
  18626. std::this_thread::sleep_for(std::chrono::seconds(1));
  18627. sink.write("abcd", 4);
  18628. (*i)++;
  18629. } else {
  18630. sink.done();
  18631. }
  18632. return true;
  18633. },
  18634. [i](bool success) {
  18635. EXPECT_FALSE(success);
  18636. delete i;
  18637. });
  18638. });
  18639. svr.Get("/chunked", [&](const Request &, Response &res) {
  18640. auto i = new size_t(0);
  18641. res.set_chunked_content_provider(
  18642. "text/plain",
  18643. [i](size_t, DataSink &sink) {
  18644. if (*i < 5) {
  18645. std::this_thread::sleep_for(std::chrono::seconds(1));
  18646. sink.os << "abcd";
  18647. (*i)++;
  18648. } else {
  18649. sink.done();
  18650. }
  18651. return true;
  18652. },
  18653. [i](bool success) {
  18654. EXPECT_FALSE(success);
  18655. delete i;
  18656. });
  18657. });
  18658. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18659. auto se = detail::scope_exit([&] {
  18660. svr.stop();
  18661. listen_thread.join();
  18662. ASSERT_FALSE(svr.is_running());
  18663. });
  18664. svr.wait_until_ready();
  18665. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18666. {
  18667. auto start = std::chrono::steady_clock::now();
  18668. auto res = cli.Get("/stream");
  18669. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18670. std::chrono::steady_clock::now() - start)
  18671. .count();
  18672. ASSERT_FALSE(res);
  18673. EXPECT_EQ(Error::Read, res.error());
  18674. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18675. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18676. }
  18677. {
  18678. auto start = std::chrono::steady_clock::now();
  18679. auto res = cli.Get("/stream_without_length");
  18680. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18681. std::chrono::steady_clock::now() - start)
  18682. .count();
  18683. ASSERT_FALSE(res);
  18684. EXPECT_EQ(Error::Read, res.error());
  18685. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18686. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18687. }
  18688. {
  18689. auto start = std::chrono::steady_clock::now();
  18690. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18691. EXPECT_EQ("abcd", string(data, data_length));
  18692. return true;
  18693. });
  18694. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18695. std::chrono::steady_clock::now() - start)
  18696. .count();
  18697. ASSERT_FALSE(res);
  18698. EXPECT_EQ(Error::Read, res.error());
  18699. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18700. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18701. }
  18702. }
  18703. TEST(MaxTimeoutTest, ContentStream) {
  18704. time_t timeout = 2000;
  18705. time_t threshold = 200;
  18706. Server svr;
  18707. Client cli("localhost", PORT);
  18708. max_timeout_test(svr, cli, timeout, threshold);
  18709. }
  18710. #ifdef CPPHTTPLIB_SSL_ENABLED
  18711. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18712. time_t timeout = 2000;
  18713. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18714. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18715. SSLClient cli("localhost", PORT);
  18716. cli.enable_server_certificate_verification(false);
  18717. max_timeout_test(svr, cli, timeout, threshold);
  18718. }
  18719. #endif
  18720. class EventDispatcher {
  18721. public:
  18722. EventDispatcher() {}
  18723. bool wait_event(DataSink *sink) {
  18724. unique_lock<mutex> lk(m_);
  18725. int id = id_;
  18726. // Wait with timeout to prevent hanging if client disconnects
  18727. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18728. [&] { return cid_ == id; })) {
  18729. return false; // Timeout occurred
  18730. }
  18731. sink->write(message_.data(), message_.size());
  18732. return true;
  18733. }
  18734. void send_event(const string &message) {
  18735. lock_guard<mutex> lk(m_);
  18736. cid_ = id_++;
  18737. message_ = message;
  18738. cv_.notify_all();
  18739. }
  18740. private:
  18741. mutex m_;
  18742. condition_variable cv_;
  18743. atomic_int id_{0};
  18744. atomic_int cid_{-1};
  18745. string message_;
  18746. };
  18747. TEST(ClientInThreadTest, Issue2068) {
  18748. EventDispatcher ed;
  18749. Server svr;
  18750. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18751. res.set_chunked_content_provider("text/event-stream",
  18752. [&](size_t /*offset*/, DataSink &sink) {
  18753. return ed.wait_event(&sink);
  18754. });
  18755. });
  18756. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18757. svr.wait_until_ready();
  18758. thread event_thread([&] {
  18759. int id = 0;
  18760. while (svr.is_running()) {
  18761. this_thread::sleep_for(chrono::milliseconds(500));
  18762. std::stringstream ss;
  18763. ss << "data: " << id << "\n\n";
  18764. ed.send_event(ss.str());
  18765. id++;
  18766. }
  18767. });
  18768. auto se = detail::scope_exit([&] {
  18769. svr.stop();
  18770. listen_thread.join();
  18771. event_thread.join();
  18772. ASSERT_FALSE(svr.is_running());
  18773. });
  18774. {
  18775. auto client = detail::make_unique<Client>(HOST, PORT);
  18776. client->set_read_timeout(std::chrono::minutes(10));
  18777. std::atomic<bool> stop{false};
  18778. std::thread t([&] {
  18779. client->Get("/event1",
  18780. [&](const char *, size_t) -> bool { return !stop; });
  18781. });
  18782. std::this_thread::sleep_for(std::chrono::seconds(2));
  18783. stop = true;
  18784. client->stop();
  18785. t.join();
  18786. // Reset client after thread has finished
  18787. client.reset();
  18788. }
  18789. }
  18790. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18791. auto handled = false;
  18792. Server svr;
  18793. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18794. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18795. auto se = detail::scope_exit([&] {
  18796. svr.stop();
  18797. t.join();
  18798. ASSERT_FALSE(svr.is_running());
  18799. ASSERT_FALSE(handled);
  18800. });
  18801. svr.wait_until_ready();
  18802. // Two Content-Length headers with different values — must be rejected
  18803. auto req = "POST /test HTTP/1.1\r\n"
  18804. "Content-Length: 5\r\n"
  18805. "Content-Length: 10\r\n"
  18806. "\r\n"
  18807. "hello";
  18808. std::string response;
  18809. ASSERT_TRUE(send_request(1, req, &response));
  18810. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18811. response.substr(0, response.find("\r\n")));
  18812. }
  18813. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18814. auto handled = false;
  18815. Server svr;
  18816. svr.Post("/test", [&](const Request &, Response &res) {
  18817. handled = true;
  18818. res.set_content("ok", "text/plain");
  18819. });
  18820. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18821. auto se = detail::scope_exit([&] {
  18822. svr.stop();
  18823. t.join();
  18824. ASSERT_FALSE(svr.is_running());
  18825. ASSERT_TRUE(handled);
  18826. });
  18827. svr.wait_until_ready();
  18828. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18829. auto req = "POST /test HTTP/1.1\r\n"
  18830. "Host: localhost\r\n"
  18831. "Content-Length: 5\r\n"
  18832. "Content-Length: 5\r\n"
  18833. "\r\n"
  18834. "hello";
  18835. std::string response;
  18836. ASSERT_TRUE(send_request(1, req, &response));
  18837. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18838. }
  18839. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18840. Server svr;
  18841. svr.Get("/test", [](const Request &, Response &res) {
  18842. res.set_content("ok", "text/plain");
  18843. });
  18844. auto port = svr.bind_to_any_port(HOST);
  18845. thread t = thread([&] { svr.listen_after_bind(); });
  18846. auto se = detail::scope_exit([&] {
  18847. svr.stop();
  18848. t.join();
  18849. ASSERT_FALSE(svr.is_running());
  18850. });
  18851. svr.wait_until_ready();
  18852. auto status_line = [&](const std::string &host_lines) {
  18853. std::string res;
  18854. send_request(
  18855. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18856. &res, port);
  18857. return res.substr(0, res.find("\r\n"));
  18858. };
  18859. const char *accepted[] = {
  18860. "Host: localhost\r\n",
  18861. "Host: a.example:8080\r\n",
  18862. "Host: my_service\r\n",
  18863. "Host: [::1]:8080\r\n",
  18864. "Host: [fe80::1%25eth0]\r\n",
  18865. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18866. };
  18867. for (auto host_lines : accepted) {
  18868. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18869. }
  18870. const char *rejected[] = {
  18871. "Host: a.example\r\nHost: b.example\r\n",
  18872. "Host: a.example\r\nHost: a.example\r\n",
  18873. "Host: a@b.example\r\n",
  18874. "Host: a.example/b\r\n",
  18875. "Host: a.example\\b\r\n",
  18876. "Host: a.example?b\r\n",
  18877. "Host: a.example#b\r\n",
  18878. "Host: a.example b.example\r\n",
  18879. };
  18880. for (auto host_lines : rejected) {
  18881. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18882. << host_lines;
  18883. }
  18884. }
  18885. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18886. Server svr;
  18887. svr.Get("/", [](const Request &req, Response &res) {
  18888. EXPECT_EQ(2U, req.trailers.size());
  18889. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18890. // Denied
  18891. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18892. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18893. // Accepted
  18894. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18895. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18896. EXPECT_TRUE(req.has_trailer("X-World"));
  18897. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18898. res.set_content("ok", "text/plain");
  18899. });
  18900. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18901. auto se = detail::scope_exit([&] {
  18902. svr.stop();
  18903. t.join();
  18904. ASSERT_FALSE(svr.is_running());
  18905. });
  18906. svr.wait_until_ready();
  18907. const std::string req = "GET / HTTP/1.1\r\n"
  18908. "Transfer-Encoding: chunked\r\n"
  18909. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18910. "\r\n"
  18911. "0\r\n"
  18912. "Content-Length: 10\r\n"
  18913. "Host: internal.local\r\n"
  18914. "Content-Type: malicious/content\r\n"
  18915. "Cookie: any\r\n"
  18916. "Set-Cookie: any\r\n"
  18917. "X-Forwarded-For: attacker.com\r\n"
  18918. "X-Real-Ip: 1.1.1.1\r\n"
  18919. "X-Hello: hello\r\n"
  18920. "X-World: world\r\n"
  18921. "\r\n";
  18922. std::string res;
  18923. ASSERT_TRUE(send_request(1, req, &res));
  18924. }
  18925. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18926. // several field lines, and the combined value is what has to be parsed. A
  18927. // Trailer field split across lines therefore declares every name it lists;
  18928. // reading only the first line silently drops the trailers the later lines
  18929. // declare. The prohibited-trailer filter still applies to every line.
  18930. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18931. Server svr;
  18932. size_t observed_trailer_count = 0;
  18933. std::string observed_hello;
  18934. std::string observed_world;
  18935. bool observed_content_length = true;
  18936. svr.Get("/", [&](const Request &req, Response &res) {
  18937. observed_trailer_count = req.trailers.size();
  18938. observed_hello = req.get_trailer_value("X-Hello");
  18939. observed_world = req.get_trailer_value("X-World");
  18940. observed_content_length = req.has_trailer("Content-Length");
  18941. res.set_content("ok", "text/plain");
  18942. });
  18943. auto port = svr.bind_to_any_port(HOST);
  18944. thread t = thread([&]() { svr.listen_after_bind(); });
  18945. auto se = detail::scope_exit([&] {
  18946. svr.stop();
  18947. t.join();
  18948. ASSERT_FALSE(svr.is_running());
  18949. });
  18950. svr.wait_until_ready();
  18951. const std::string req = "GET / HTTP/1.1\r\n"
  18952. "Host: localhost\r\n"
  18953. "Transfer-Encoding: chunked\r\n"
  18954. "Trailer: X-Hello\r\n"
  18955. "Trailer: X-World, Content-Length\r\n"
  18956. "\r\n"
  18957. "0\r\n"
  18958. "X-Hello: hello\r\n"
  18959. "X-World: world\r\n"
  18960. "Content-Length: 10\r\n"
  18961. "\r\n";
  18962. std::string res;
  18963. ASSERT_TRUE(send_request(1, req, &res, port));
  18964. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18965. // Accepted: both field lines contribute to the declared set
  18966. EXPECT_EQ(2U, observed_trailer_count);
  18967. EXPECT_EQ(observed_hello, "hello");
  18968. EXPECT_EQ(observed_world, "world");
  18969. // Denied: a prohibited name stays prohibited on a later field line
  18970. EXPECT_FALSE(observed_content_length);
  18971. }
  18972. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18973. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18974. // unbounded run of fields that are never declared, because the counter would
  18975. // only advance for declared fields.
  18976. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18977. Server svr;
  18978. bool handler_called = false;
  18979. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18980. handler_called = true;
  18981. res.set_content("ok", "text/plain");
  18982. });
  18983. auto port = svr.bind_to_any_port(HOST);
  18984. thread t = thread([&]() { svr.listen_after_bind(); });
  18985. auto se = detail::scope_exit([&] {
  18986. svr.stop();
  18987. t.join();
  18988. ASSERT_FALSE(svr.is_running());
  18989. });
  18990. svr.wait_until_ready();
  18991. // Declare nothing, then send far more undeclared trailer fields than the
  18992. // header-count limit. Parsing must stop and reject the request rather than
  18993. // read every line.
  18994. std::string req = "GET / HTTP/1.1\r\n"
  18995. "Transfer-Encoding: chunked\r\n"
  18996. "\r\n"
  18997. "0\r\n";
  18998. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18999. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19000. }
  19001. req += "\r\n";
  19002. std::string res;
  19003. ASSERT_TRUE(send_request(1, req, &res, port));
  19004. // The request is rejected before the handler runs.
  19005. EXPECT_FALSE(handler_called);
  19006. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19007. }
  19008. // The set of declared trailer names is capped so a peer cannot grow it without
  19009. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19010. // declared past the cap is not honored, even if the field is actually sent.
  19011. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19012. Server svr;
  19013. // One name inside the cap and one past it, so the test tracks the cap rather
  19014. // than a fixed count.
  19015. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19016. const std::string within_cap_name = "X-T-0";
  19017. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19018. bool observed_within_cap = false;
  19019. bool observed_past_cap = false;
  19020. svr.Get("/", [&](const Request &req, Response &res) {
  19021. observed_within_cap = req.has_trailer(within_cap_name);
  19022. observed_past_cap = req.has_trailer(past_cap_name);
  19023. res.set_content("ok", "text/plain");
  19024. });
  19025. auto port = svr.bind_to_any_port(HOST);
  19026. thread t = thread([&]() { svr.listen_after_bind(); });
  19027. auto se = detail::scope_exit([&] {
  19028. svr.stop();
  19029. t.join();
  19030. ASSERT_FALSE(svr.is_running());
  19031. });
  19032. svr.wait_until_ready();
  19033. // Declare more trailer names than the cap in a single Trailer field, then
  19034. // actually send the first (within the cap) and the last (past it).
  19035. std::string trailer_decl = "Trailer: ";
  19036. for (int i = 0; i < declared_count; i++) {
  19037. if (i != 0) { trailer_decl += ", "; }
  19038. trailer_decl += "X-T-" + std::to_string(i);
  19039. }
  19040. trailer_decl += "\r\n";
  19041. const std::string req = "GET / HTTP/1.1\r\n"
  19042. "Host: localhost\r\n"
  19043. "Transfer-Encoding: chunked\r\n" +
  19044. trailer_decl +
  19045. "\r\n"
  19046. "0\r\n" +
  19047. within_cap_name + ": a\r\n" + past_cap_name +
  19048. ": b\r\n"
  19049. "\r\n";
  19050. std::string res;
  19051. ASSERT_TRUE(send_request(1, req, &res, port));
  19052. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19053. // A name within the cap is honored; one declared past the cap is dropped.
  19054. EXPECT_TRUE(observed_within_cap);
  19055. EXPECT_FALSE(observed_past_cap);
  19056. }
  19057. // A direct client that is not listed in trusted_proxies must not be able to
  19058. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19059. // the peer address on the actual TCP connection determines whether the
  19060. // header is honored.
  19061. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19062. Server svr;
  19063. // Deliberately does NOT include the loopback address the test client
  19064. // actually connects from, so the direct connection is not a trusted proxy.
  19065. svr.set_trusted_proxies({"203.0.113.66"});
  19066. std::string observed_remote_addr;
  19067. svr.Get("/ip", [&](const Request &req, Response &res) {
  19068. observed_remote_addr = req.remote_addr;
  19069. res.set_content("ok", "text/plain");
  19070. });
  19071. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19072. auto se = detail::scope_exit([&] {
  19073. svr.stop();
  19074. t.join();
  19075. ASSERT_FALSE(svr.is_running());
  19076. });
  19077. svr.wait_until_ready();
  19078. Client cli(HOST, PORT);
  19079. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19081. EXPECT_EQ(StatusCode::OK_200, res->status);
  19082. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19083. // ignored entirely and the real connection-level address retained.
  19084. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19085. observed_remote_addr == "127.0.0.1");
  19086. }
  19087. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19088. Server svr;
  19089. std::string observed_remote_addr;
  19090. std::string observed_xff;
  19091. svr.Get("/ip", [&](const Request &req, Response &res) {
  19092. observed_remote_addr = req.remote_addr;
  19093. observed_xff = req.get_header_value("X-Forwarded-For");
  19094. res.set_content("ok", "text/plain");
  19095. });
  19096. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19097. auto se = detail::scope_exit([&] {
  19098. svr.stop();
  19099. t.join();
  19100. ASSERT_FALSE(svr.is_running());
  19101. });
  19102. svr.wait_until_ready();
  19103. Client cli(HOST, PORT);
  19104. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19106. EXPECT_EQ(StatusCode::OK_200, res->status);
  19107. EXPECT_EQ(observed_xff, "203.0.113.66");
  19108. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19109. observed_remote_addr == "127.0.0.1");
  19110. }
  19111. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19112. Server svr;
  19113. svr.set_trusted_proxies({"203.0.113.66"});
  19114. std::string observed_remote_addr;
  19115. std::string observed_xff;
  19116. svr.Get("/ip", [&](const Request &req, Response &res) {
  19117. observed_remote_addr = req.remote_addr;
  19118. observed_xff = req.get_header_value("X-Forwarded-For");
  19119. res.set_content("ok", "text/plain");
  19120. });
  19121. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19122. auto se = detail::scope_exit([&] {
  19123. svr.stop();
  19124. t.join();
  19125. ASSERT_FALSE(svr.is_running());
  19126. });
  19127. svr.wait_until_ready();
  19128. Client cli(HOST, PORT);
  19129. auto res = cli.Get("/ip");
  19130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19131. EXPECT_EQ(StatusCode::OK_200, res->status);
  19132. EXPECT_EQ(observed_xff, "");
  19133. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19134. observed_remote_addr == "127.0.0.1");
  19135. }
  19136. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19137. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19138. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19139. Server svr;
  19140. svr.set_trusted_proxies({"127.0.0.1"});
  19141. svr.Get("/ip", [](const Request &req, Response &res) {
  19142. res.set_content(req.remote_addr, "text/plain");
  19143. });
  19144. auto port = svr.bind_to_any_port("::");
  19145. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19146. thread t = thread([&] { svr.listen_after_bind(); });
  19147. auto se = detail::scope_exit([&] {
  19148. svr.stop();
  19149. t.join();
  19150. ASSERT_FALSE(svr.is_running());
  19151. });
  19152. svr.wait_until_ready();
  19153. Client cli("127.0.0.1", port);
  19154. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19156. EXPECT_EQ("198.51.100.23", res->body);
  19157. }
  19158. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19159. Server svr;
  19160. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19161. svr.Get("/ip", [](const Request &req, Response &res) {
  19162. res.set_content(req.remote_addr, "text/plain");
  19163. });
  19164. auto port = svr.bind_to_any_port(HOST);
  19165. ASSERT_GT(port, 0);
  19166. thread t = thread([&] { svr.listen_after_bind(); });
  19167. auto se = detail::scope_exit([&] {
  19168. svr.stop();
  19169. t.join();
  19170. ASSERT_FALSE(svr.is_running());
  19171. });
  19172. svr.wait_until_ready();
  19173. Client cli(HOST, port);
  19174. auto res = cli.Get(
  19175. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19177. EXPECT_EQ("198.51.100.23", res->body);
  19178. }
  19179. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19180. Server svr;
  19181. // Include the loopback address the test client actually connects from, so
  19182. // the direct connection itself is recognized as the trusted proxy hop.
  19183. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19184. std::string observed_remote_addr;
  19185. std::string observed_xff;
  19186. svr.Get("/ip", [&](const Request &req, Response &res) {
  19187. observed_remote_addr = req.remote_addr;
  19188. observed_xff = req.get_header_value("X-Forwarded-For");
  19189. res.set_content("ok", "text/plain");
  19190. });
  19191. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19192. auto se = detail::scope_exit([&] {
  19193. svr.stop();
  19194. t.join();
  19195. ASSERT_FALSE(svr.is_running());
  19196. });
  19197. svr.wait_until_ready();
  19198. Client cli(HOST, PORT);
  19199. auto res = cli.Get(
  19200. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19202. EXPECT_EQ(StatusCode::OK_200, res->status);
  19203. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19204. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19205. }
  19206. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19207. Server svr;
  19208. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19209. std::string observed_remote_addr;
  19210. std::string observed_xff;
  19211. svr.Get("/ip", [&](const Request &req, Response &res) {
  19212. observed_remote_addr = req.remote_addr;
  19213. observed_xff = req.get_header_value("X-Forwarded-For");
  19214. res.set_content("ok", "text/plain");
  19215. });
  19216. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19217. auto se = detail::scope_exit([&] {
  19218. svr.stop();
  19219. t.join();
  19220. ASSERT_FALSE(svr.is_running());
  19221. });
  19222. svr.wait_until_ready();
  19223. Client cli(HOST, PORT);
  19224. auto res = cli.Get(
  19225. "/ip",
  19226. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19228. EXPECT_EQ(StatusCode::OK_200, res->status);
  19229. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19230. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19231. }
  19232. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19233. Server svr;
  19234. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19235. std::string observed_remote_addr;
  19236. std::string observed_xff;
  19237. svr.Get("/ip", [&](const Request &req, Response &res) {
  19238. observed_remote_addr = req.remote_addr;
  19239. observed_xff = req.get_header_value("X-Forwarded-For");
  19240. res.set_content("ok", "text/plain");
  19241. });
  19242. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19243. auto se = detail::scope_exit([&] {
  19244. svr.stop();
  19245. t.join();
  19246. ASSERT_FALSE(svr.is_running());
  19247. });
  19248. svr.wait_until_ready();
  19249. Client cli(HOST, PORT);
  19250. auto res = cli.Get(
  19251. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19253. EXPECT_EQ(StatusCode::OK_200, res->status);
  19254. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19255. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19256. // and must not be selected.
  19257. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19258. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19259. }
  19260. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19261. Server svr;
  19262. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19263. std::string observed_remote_addr;
  19264. svr.Get("/ip", [&](const Request &req, Response &res) {
  19265. observed_remote_addr = req.remote_addr;
  19266. res.set_content("ok", "text/plain");
  19267. });
  19268. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19269. auto se = detail::scope_exit([&] {
  19270. svr.stop();
  19271. t.join();
  19272. ASSERT_FALSE(svr.is_running());
  19273. });
  19274. svr.wait_until_ready();
  19275. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19276. // a forged address and the trusted proxy's own address; the forged value must
  19277. // not win over the address the trusted proxy actually recorded.
  19278. Client cli(HOST, PORT);
  19279. auto res = cli.Get(
  19280. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19282. EXPECT_EQ(StatusCode::OK_200, res->status);
  19283. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19284. }
  19285. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19286. Server svr;
  19287. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19288. std::string observed_remote_addr;
  19289. std::string observed_xff;
  19290. svr.Get("/ip", [&](const Request &req, Response &res) {
  19291. observed_remote_addr = req.remote_addr;
  19292. observed_xff = req.get_header_value("X-Forwarded-For");
  19293. res.set_content("ok", "text/plain");
  19294. });
  19295. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19296. auto se = detail::scope_exit([&] {
  19297. svr.stop();
  19298. t.join();
  19299. ASSERT_FALSE(svr.is_running());
  19300. });
  19301. svr.wait_until_ready();
  19302. Client cli(HOST, PORT);
  19303. auto res = cli.Get(
  19304. "/ip",
  19305. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19307. EXPECT_EQ(StatusCode::OK_200, res->status);
  19308. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19309. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19310. }
  19311. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19312. Server svr;
  19313. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19314. std::string observed_remote_addr;
  19315. std::string observed_xff;
  19316. svr.Get("/ip", [&](const Request &req, Response &res) {
  19317. observed_remote_addr = req.remote_addr;
  19318. observed_xff = req.get_header_value("X-Forwarded-For");
  19319. res.set_content("ok", "text/plain");
  19320. });
  19321. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19322. auto se = detail::scope_exit([&] {
  19323. svr.stop();
  19324. t.join();
  19325. ASSERT_FALSE(svr.is_running());
  19326. });
  19327. svr.wait_until_ready();
  19328. std::string raw_req =
  19329. "GET /ip HTTP/1.1\r\n"
  19330. "Host: localhost\r\n"
  19331. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19332. "Connection: close\r\n"
  19333. "\r\n";
  19334. std::string out;
  19335. ASSERT_TRUE(send_request(5, raw_req, &out));
  19336. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19337. // Header parser trims surrounding whitespace of the header value
  19338. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19339. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19340. }
  19341. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19342. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19343. // their own X-Forwarded-For as a separate field line rather than extending the
  19344. // one the client sent, so every occurrence has to be taken into account.
  19345. // Reading only the first one hands back the address the client chose.
  19346. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19347. Server svr;
  19348. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19349. std::string observed_remote_addr;
  19350. size_t observed_xff_count = 0;
  19351. svr.Get("/ip", [&](const Request &req, Response &res) {
  19352. observed_remote_addr = req.remote_addr;
  19353. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19354. res.set_content("ok", "text/plain");
  19355. });
  19356. auto port = svr.bind_to_any_port(HOST);
  19357. thread t = thread([&]() { svr.listen_after_bind(); });
  19358. auto se = detail::scope_exit([&] {
  19359. svr.stop();
  19360. t.join();
  19361. ASSERT_FALSE(svr.is_running());
  19362. });
  19363. svr.wait_until_ready();
  19364. // The client supplies the first field line; the trusted proxy appends the
  19365. // address it observed as a second one.
  19366. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19367. "Host: localhost\r\n"
  19368. "X-Forwarded-For: 1.2.3.4\r\n"
  19369. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19370. "Connection: close\r\n"
  19371. "\r\n";
  19372. std::string out;
  19373. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19374. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19375. EXPECT_EQ(observed_xff_count, 2U);
  19376. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19377. // The same chain spread over one field line per hop derives the same client
  19378. // address, i.e. the split and the comma-joined representations agree.
  19379. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19380. "Host: localhost\r\n"
  19381. "X-Forwarded-For: 1.2.3.4\r\n"
  19382. "X-Forwarded-For: 198.51.100.23\r\n"
  19383. "X-Forwarded-For: 192.0.2.45\r\n"
  19384. "Connection: close\r\n"
  19385. "\r\n";
  19386. out.clear();
  19387. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19388. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19389. EXPECT_EQ(observed_xff_count, 3U);
  19390. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19391. }
  19392. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19393. // crash the server (it used to call front() on an empty vector inside
  19394. // get_client_ip). The connection-level remote address must be retained instead.
  19395. static void run_malformed_xff_test(const std::string &xff_value) {
  19396. Server svr;
  19397. svr.set_trusted_proxies({"192.0.2.45"});
  19398. std::string observed_remote_addr;
  19399. svr.Get("/ip", [&](const Request &req, Response &res) {
  19400. observed_remote_addr = req.remote_addr;
  19401. res.set_content("ok", "text/plain");
  19402. });
  19403. int port = 0;
  19404. thread t = thread([&]() {
  19405. port = svr.bind_to_any_port(HOST);
  19406. svr.listen_after_bind();
  19407. });
  19408. auto se = detail::scope_exit([&] {
  19409. svr.stop();
  19410. t.join();
  19411. ASSERT_FALSE(svr.is_running());
  19412. });
  19413. svr.wait_until_ready();
  19414. Client cli(HOST, port);
  19415. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19417. EXPECT_EQ(StatusCode::OK_200, res->status);
  19418. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19419. observed_remote_addr == "127.0.0.1");
  19420. }
  19421. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19422. run_malformed_xff_test("");
  19423. }
  19424. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19425. run_malformed_xff_test(",");
  19426. }
  19427. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19428. run_malformed_xff_test(", , ,");
  19429. }
  19430. // The same rule applies to Accept: a request whose acceptable types are spread
  19431. // over several field lines must be negotiated against all of them.
  19432. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19433. // case-insensitive connection options. Comparing the whole field value against
  19434. // one option misses a client that sends several of them, and misses every
  19435. // casing but the one written in the comparison.
  19436. //
  19437. // Sends req, reads the response, then reuses the same socket for a second
  19438. // request to find out whether the server kept the connection.
  19439. static void probe_connection_reuse(int port, const std::string &req,
  19440. bool *announced_close, bool *reusable) {
  19441. auto error = Error::Success;
  19442. auto sock = detail::create_client_socket(
  19443. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19444. /*connection_timeout_sec=*/5, 0,
  19445. /*read_timeout_sec=*/1, 0,
  19446. /*write_timeout_sec=*/5, 0, std::string(), error);
  19447. ASSERT_NE(sock, INVALID_SOCKET);
  19448. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19449. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19450. "Host: localhost\r\n"
  19451. "Connection: close\r\n"
  19452. "\r\n";
  19453. std::string first_response;
  19454. std::string second_response;
  19455. detail::process_client_socket(
  19456. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19457. [&](Stream &strm) {
  19458. if (strm.write(req.data(), req.size()) !=
  19459. static_cast<ssize_t>(req.size())) {
  19460. return false;
  19461. }
  19462. char buf[512];
  19463. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19464. // Headers plus the two-byte body of the handler below
  19465. while (reader.getline()) {
  19466. first_response += reader.ptr();
  19467. if (first_response.find("ok") != std::string::npos) { break; }
  19468. }
  19469. if (strm.write(second.data(), second.size()) !=
  19470. static_cast<ssize_t>(second.size())) {
  19471. return true;
  19472. }
  19473. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19474. while (reader2.getline()) {
  19475. second_response += reader2.ptr();
  19476. if (second_response.find("ok") != std::string::npos) { break; }
  19477. }
  19478. return true;
  19479. });
  19480. *announced_close =
  19481. first_response.find("Connection: close") != std::string::npos;
  19482. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19483. }
  19484. class ConnectionTokenTest : public ::testing::Test {
  19485. protected:
  19486. void SetUp() override {
  19487. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19488. res.set_content("ok", "text/plain");
  19489. });
  19490. port_ = svr_.bind_to_any_port(HOST);
  19491. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19492. svr_.wait_until_ready();
  19493. }
  19494. void TearDown() override {
  19495. svr_.stop();
  19496. if (thread_.joinable()) { thread_.join(); }
  19497. }
  19498. Server svr_;
  19499. int port_ = 0;
  19500. thread thread_;
  19501. };
  19502. // "close" alongside another option still closes the connection, and the
  19503. // response says so rather than leaving the peer to discover it.
  19504. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19505. bool announced_close = false;
  19506. bool reusable = true;
  19507. probe_connection_reuse(port_,
  19508. "GET /keepalive HTTP/1.1\r\n"
  19509. "Host: localhost\r\n"
  19510. "Connection: keep-alive, close\r\n"
  19511. "\r\n",
  19512. &announced_close, &reusable);
  19513. EXPECT_TRUE(announced_close);
  19514. EXPECT_FALSE(reusable);
  19515. }
  19516. // "close" split over two field lines is the same list, so it is honored too.
  19517. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19518. bool announced_close = false;
  19519. bool reusable = true;
  19520. probe_connection_reuse(port_,
  19521. "GET /keepalive HTTP/1.1\r\n"
  19522. "Host: localhost\r\n"
  19523. "Connection: keep-alive\r\n"
  19524. "Connection: close\r\n"
  19525. "\r\n",
  19526. &announced_close, &reusable);
  19527. EXPECT_TRUE(announced_close);
  19528. EXPECT_FALSE(reusable);
  19529. }
  19530. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19531. // keep-alive in the spelling everyone actually sends keeps its connection.
  19532. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19533. bool announced_close = false;
  19534. bool reusable = false;
  19535. probe_connection_reuse(port_,
  19536. "GET /keepalive HTTP/1.0\r\n"
  19537. "Host: localhost\r\n"
  19538. "Connection: keep-alive\r\n"
  19539. "\r\n",
  19540. &announced_close, &reusable);
  19541. EXPECT_FALSE(announced_close);
  19542. EXPECT_TRUE(reusable);
  19543. }
  19544. // A token the value merely contains is not the token itself.
  19545. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19546. bool announced_close = false;
  19547. bool reusable = false;
  19548. probe_connection_reuse(port_,
  19549. "GET /keepalive HTTP/1.1\r\n"
  19550. "Host: localhost\r\n"
  19551. "Connection: notclose\r\n"
  19552. "\r\n",
  19553. &announced_close, &reusable);
  19554. EXPECT_FALSE(announced_close);
  19555. EXPECT_TRUE(reusable);
  19556. }
  19557. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19558. Server svr;
  19559. std::vector<std::string> observed_types;
  19560. svr.Get("/", [&](const Request &req, Response &res) {
  19561. observed_types = req.accept_content_types;
  19562. res.set_content("ok", "text/plain");
  19563. });
  19564. auto port = svr.bind_to_any_port(HOST);
  19565. thread t = thread([&]() { svr.listen_after_bind(); });
  19566. auto se = detail::scope_exit([&] {
  19567. svr.stop();
  19568. t.join();
  19569. ASSERT_FALSE(svr.is_running());
  19570. });
  19571. svr.wait_until_ready();
  19572. Client cli(HOST, port);
  19573. Headers headers;
  19574. headers.emplace("Accept", "text/plain;q=0.5");
  19575. headers.emplace("Accept", "application/json");
  19576. auto res = cli.Get("/", headers);
  19577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19578. EXPECT_EQ(StatusCode::OK_200, res->status);
  19579. // Sorted by q-value, so the second field line's type comes first
  19580. ASSERT_EQ(2U, observed_types.size());
  19581. EXPECT_EQ("application/json", observed_types[0]);
  19582. EXPECT_EQ("text/plain", observed_types[1]);
  19583. }
  19584. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19585. // empty field line must not contribute a bare comma to the combined value.
  19586. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19587. Server svr;
  19588. std::vector<std::string> observed_types;
  19589. svr.Get("/", [&](const Request &req, Response &res) {
  19590. observed_types = req.accept_content_types;
  19591. res.set_content("ok", "text/plain");
  19592. });
  19593. auto port = svr.bind_to_any_port(HOST);
  19594. thread t = thread([&]() { svr.listen_after_bind(); });
  19595. auto se = detail::scope_exit([&] {
  19596. svr.stop();
  19597. t.join();
  19598. ASSERT_FALSE(svr.is_running());
  19599. });
  19600. svr.wait_until_ready();
  19601. // Empty first field line, then a real one
  19602. std::string raw_req = "GET / HTTP/1.1\r\n"
  19603. "Host: localhost\r\n"
  19604. "Accept:\r\n"
  19605. "Accept: application/json\r\n"
  19606. "Connection: close\r\n"
  19607. "\r\n";
  19608. std::string out;
  19609. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19610. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19611. ASSERT_EQ(1U, observed_types.size());
  19612. EXPECT_EQ("application/json", observed_types[0]);
  19613. }
  19614. // The skip in get_combined_header_value() is what keeps an empty field line
  19615. // from contributing a bare comma. Only a trailing empty field line exercises
  19616. // it: a leading one is already covered by the "combined is still empty" check,
  19617. // and parse_accept_header() now ignores the empty element either way, so the
  19618. // request-level test above can no longer tell the two apart.
  19619. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19620. Headers headers;
  19621. headers.emplace("Accept", "text/html");
  19622. headers.emplace("Accept", "");
  19623. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19624. headers.clear();
  19625. headers.emplace("Accept", "");
  19626. headers.emplace("Accept", "application/json");
  19627. EXPECT_EQ("application/json",
  19628. detail::get_combined_header_value(headers, "Accept"));
  19629. }
  19630. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19631. // An encoding offered on a later Accept-Encoding field line is still offered.
  19632. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19633. Server svr;
  19634. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19635. res.set_content(std::string(1024, 'x'), "text/plain");
  19636. });
  19637. auto port = svr.bind_to_any_port(HOST);
  19638. thread t = thread([&]() { svr.listen_after_bind(); });
  19639. auto se = detail::scope_exit([&] {
  19640. svr.stop();
  19641. t.join();
  19642. ASSERT_FALSE(svr.is_running());
  19643. });
  19644. svr.wait_until_ready();
  19645. Client cli(HOST, port);
  19646. cli.set_decompress(false);
  19647. Headers headers;
  19648. headers.emplace("Accept-Encoding", "identity");
  19649. headers.emplace("Accept-Encoding", "gzip");
  19650. auto res = cli.Get("/", headers);
  19651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19652. EXPECT_EQ(StatusCode::OK_200, res->status);
  19653. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19654. }
  19655. #endif
  19656. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19657. // Transfer-Encoding is not its body.
  19658. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19659. Server svr;
  19660. svr.set_payload_max_length(8);
  19661. svr.Post("/test", [](const Request &, Response &res) {
  19662. res.set_content("ok", "text/plain");
  19663. });
  19664. auto port = svr.bind_to_any_port(HOST);
  19665. ASSERT_GT(port, 0);
  19666. thread t = thread([&] { svr.listen_after_bind(); });
  19667. auto se = detail::scope_exit([&] {
  19668. svr.stop();
  19669. t.join();
  19670. ASSERT_FALSE(svr.is_running());
  19671. });
  19672. svr.wait_until_ready();
  19673. std::string resp;
  19674. ASSERT_TRUE(send_request(1,
  19675. "POST /test HTTP/1.1\r\n"
  19676. "Host: localhost\r\n"
  19677. "Connection: close\r\n"
  19678. "\r\n" +
  19679. std::string(16, 'X'),
  19680. &resp, port));
  19681. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19682. }
  19683. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19684. Server svr;
  19685. svr.Post("/post", [&](const Request &req, Response &res) {
  19686. res.set_content(req.body, "text/plain");
  19687. });
  19688. svr.Put("/put", [&](const Request &req, Response &res) {
  19689. res.set_content(req.body, "text/plain");
  19690. });
  19691. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19692. res.set_content(req.body, "text/plain");
  19693. });
  19694. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19695. res.set_content(req.body, "text/plain");
  19696. });
  19697. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19698. auto se = detail::scope_exit([&] {
  19699. svr.stop();
  19700. t.join();
  19701. ASSERT_FALSE(svr.is_running());
  19702. });
  19703. svr.wait_until_ready();
  19704. std::string resp;
  19705. // POST without Content-Length
  19706. ASSERT_TRUE(send_request(5,
  19707. "POST /post HTTP/1.1\r\n"
  19708. "Host: localhost\r\n"
  19709. "Connection: close\r\n"
  19710. "\r\n",
  19711. &resp));
  19712. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19713. // PUT without Content-Length
  19714. resp.clear();
  19715. ASSERT_TRUE(send_request(5,
  19716. "PUT /put HTTP/1.1\r\n"
  19717. "Host: localhost\r\n"
  19718. "Connection: close\r\n"
  19719. "\r\n",
  19720. &resp));
  19721. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19722. // PATCH without Content-Length
  19723. resp.clear();
  19724. ASSERT_TRUE(send_request(5,
  19725. "PATCH /patch HTTP/1.1\r\n"
  19726. "Host: localhost\r\n"
  19727. "Connection: close\r\n"
  19728. "\r\n",
  19729. &resp));
  19730. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19731. // DELETE without Content-Length
  19732. resp.clear();
  19733. ASSERT_TRUE(send_request(5,
  19734. "DELETE /delete HTTP/1.1\r\n"
  19735. "Host: localhost\r\n"
  19736. "Connection: close\r\n"
  19737. "\r\n",
  19738. &resp));
  19739. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19740. }
  19741. //==============================================================================
  19742. // open_stream() Tests
  19743. //==============================================================================
  19744. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19745. std::string result;
  19746. char buf[8192];
  19747. ssize_t n;
  19748. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19749. result.append(buf, static_cast<size_t>(n));
  19750. }
  19751. return result;
  19752. }
  19753. // Mock stream for unit tests
  19754. class MockStream : public Stream {
  19755. public:
  19756. std::string data;
  19757. size_t pos = 0;
  19758. ssize_t error_after = -1; // -1 = no error
  19759. explicit MockStream(const std::string &d, ssize_t err = -1)
  19760. : data(d), error_after(err) {}
  19761. bool is_readable() const override { return true; }
  19762. bool wait_readable() const override { return true; }
  19763. bool wait_writable() const override { return true; }
  19764. ssize_t read(char *ptr, size_t size) override {
  19765. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19766. if (pos >= data.size()) return 0;
  19767. size_t limit =
  19768. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19769. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19770. std::memcpy(ptr, data.data() + pos, to_read);
  19771. pos += to_read;
  19772. return static_cast<ssize_t>(to_read);
  19773. }
  19774. ssize_t write(const char *, size_t) override { return -1; }
  19775. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19776. ip = "127.0.0.1";
  19777. port = 0;
  19778. }
  19779. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19780. ip = "127.0.0.1";
  19781. port = 0;
  19782. }
  19783. socket_t socket() const override { return INVALID_SOCKET; }
  19784. time_t duration() const override { return 0; }
  19785. };
  19786. TEST(StreamHandleTest, Basic) {
  19787. ClientImpl::StreamHandle handle;
  19788. EXPECT_FALSE(handle.is_valid());
  19789. handle.response = detail::make_unique<Response>();
  19790. handle.error = Error::Connection;
  19791. EXPECT_FALSE(handle.is_valid());
  19792. handle.error = Error::Success;
  19793. EXPECT_TRUE(handle.is_valid());
  19794. }
  19795. TEST(BodyReaderTest, Basic) {
  19796. MockStream stream("Hello, World!");
  19797. detail::BodyReader reader;
  19798. reader.stream = &stream;
  19799. reader.content_length = 13;
  19800. char buf[32];
  19801. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19802. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19803. EXPECT_TRUE(reader.eof);
  19804. }
  19805. TEST(BodyReaderTest, NoStream) {
  19806. detail::BodyReader reader;
  19807. char buf[32];
  19808. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19809. EXPECT_EQ(Error::Connection, reader.last_error);
  19810. }
  19811. TEST(BodyReaderTest, Error) {
  19812. MockStream stream("Hello, World!", 5);
  19813. detail::BodyReader reader;
  19814. reader.stream = &stream;
  19815. reader.content_length = 13;
  19816. char buf[32];
  19817. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19818. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19819. EXPECT_EQ(Error::Read, reader.last_error);
  19820. }
  19821. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19822. // Mock-based StreamHandle tests relying on private internals are removed.
  19823. class OpenStreamTest : public ::testing::Test {
  19824. protected:
  19825. void SetUp() override {
  19826. svr_.Get("/hello", [](const Request &, Response &res) {
  19827. res.set_content("Hello World!", "text/plain");
  19828. });
  19829. svr_.Get("/large", [](const Request &, Response &res) {
  19830. res.set_content(std::string(10000, 'X'), "text/plain");
  19831. });
  19832. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19833. res.set_content("Hello World!", "image/jpeg");
  19834. res.set_header("Content-Encoding", "UTF-8");
  19835. });
  19836. svr_.Get("/chunked", [](const Request &, Response &res) {
  19837. res.set_chunked_content_provider("text/plain",
  19838. [](size_t offset, DataSink &sink) {
  19839. if (offset < 15) {
  19840. sink.write("chunk", 5);
  19841. return true;
  19842. }
  19843. sink.done();
  19844. return true;
  19845. });
  19846. });
  19847. svr_.Get("/compressible", [](const Request &, Response &res) {
  19848. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19849. DataSink &sink) {
  19850. if (offset < 100 * 1024) {
  19851. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19852. sink.write(chunk.data(), chunk.size());
  19853. return true;
  19854. }
  19855. sink.done();
  19856. return true;
  19857. });
  19858. });
  19859. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19860. [](const Request & /*req*/, Response &res) {
  19861. auto i = new int(0);
  19862. res.set_header("Trailer", "Content-Length, X-Allowed");
  19863. res.set_chunked_content_provider(
  19864. "text/plain",
  19865. [i](size_t /*offset*/, DataSink &sink) {
  19866. switch (*i) {
  19867. case 0: sink.os << "123"; break;
  19868. case 1: sink.os << "456"; break;
  19869. case 2: sink.os << "789"; break;
  19870. case 3: {
  19871. sink.done_with_trailer(
  19872. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19873. } break;
  19874. }
  19875. (*i)++;
  19876. return true;
  19877. },
  19878. [i](bool success) {
  19879. EXPECT_TRUE(success);
  19880. delete i;
  19881. });
  19882. });
  19883. // Echo headers endpoint for header-related tests
  19884. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19885. std::string body;
  19886. for (const auto &h : req.headers) {
  19887. body.append(h.first);
  19888. body.push_back(':');
  19889. body.append(h.second);
  19890. body.push_back('\n');
  19891. }
  19892. res.set_content(body, "text/plain");
  19893. });
  19894. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19895. std::string body;
  19896. for (const auto &h : req.headers) {
  19897. body.append(h.first);
  19898. body.push_back(':');
  19899. body.append(h.second);
  19900. body.push_back('\n');
  19901. }
  19902. res.set_content(body, "text/plain");
  19903. });
  19904. port_ = svr_.bind_to_any_port("127.0.0.1");
  19905. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19906. svr_.wait_until_ready();
  19907. }
  19908. void TearDown() override {
  19909. svr_.stop();
  19910. if (thread_.joinable()) thread_.join();
  19911. }
  19912. Server svr_;
  19913. std::thread thread_;
  19914. int port_ = 0;
  19915. };
  19916. TEST_F(OpenStreamTest, Basic) {
  19917. Client cli("127.0.0.1", port_);
  19918. auto handle = cli.open_stream("GET", "/hello");
  19919. EXPECT_TRUE(handle.is_valid());
  19920. EXPECT_EQ("Hello World!", read_all(handle));
  19921. }
  19922. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19923. Client cli("127.0.0.1", port_);
  19924. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19925. ASSERT_TRUE(handle.is_valid());
  19926. EXPECT_EQ("Hello World!", read_all(handle));
  19927. }
  19928. TEST_F(OpenStreamTest, SmallBuffer) {
  19929. Client cli("127.0.0.1", port_);
  19930. auto handle = cli.open_stream("GET", "/hello");
  19931. std::string result;
  19932. char buf[4];
  19933. ssize_t n;
  19934. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19935. result.append(buf, static_cast<size_t>(n));
  19936. EXPECT_EQ("Hello World!", result);
  19937. }
  19938. TEST_F(OpenStreamTest, DefaultHeaders) {
  19939. Client cli("127.0.0.1", port_);
  19940. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19941. {
  19942. auto handle = cli.open_stream("GET", "/echo-headers");
  19943. ASSERT_TRUE(handle.is_valid());
  19944. auto body = read_all(handle);
  19945. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19946. std::string::npos);
  19947. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19948. std::string::npos);
  19949. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19950. }
  19951. // open_stream POST with body and no explicit content_type should NOT add
  19952. // text/plain Content-Type (behavior differs from non-streaming path), but
  19953. // should include Content-Length
  19954. {
  19955. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19956. ASSERT_TRUE(handle.is_valid());
  19957. auto body = read_all(handle);
  19958. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19959. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19960. }
  19961. // open_stream POST with explicit Content-Type should preserve it
  19962. {
  19963. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19964. {{"Content-Type", "application/custom"}},
  19965. "{}", "application/custom");
  19966. ASSERT_TRUE(handle.is_valid());
  19967. auto body = read_all(handle);
  19968. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19969. }
  19970. // User-specified User-Agent must not be overwritten for stream API
  19971. {
  19972. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19973. {{"User-Agent", "MyAgent/1.2"}});
  19974. ASSERT_TRUE(handle.is_valid());
  19975. auto body = read_all(handle);
  19976. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19977. }
  19978. }
  19979. TEST_F(OpenStreamTest, Large) {
  19980. Client cli("127.0.0.1", port_);
  19981. auto handle = cli.open_stream("GET", "/large");
  19982. EXPECT_EQ(10000u, read_all(handle).size());
  19983. }
  19984. TEST_F(OpenStreamTest, ConnectionError) {
  19985. Client cli("127.0.0.1", 9999);
  19986. auto handle = cli.open_stream("GET", "/hello");
  19987. EXPECT_FALSE(handle.is_valid());
  19988. }
  19989. TEST_F(OpenStreamTest, Chunked) {
  19990. Client cli("127.0.0.1", port_);
  19991. auto handle = cli.open_stream("GET", "/chunked");
  19992. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19993. "Transfer-Encoding") == "chunked");
  19994. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19995. }
  19996. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19997. Client cli("127.0.0.1", port_);
  19998. auto handle =
  19999. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20000. ASSERT_TRUE(handle.is_valid());
  20001. // Consume body to allow trailers to be received/parsed
  20002. auto body = read_all(handle);
  20003. // Explicitly parse trailers (ensure trailers are available for assertion)
  20004. handle.parse_trailers_if_needed();
  20005. EXPECT_EQ(std::string("123456789"), body);
  20006. // The response should include a Trailer header declaring both names
  20007. ASSERT_TRUE(handle.response);
  20008. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20009. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20010. handle.response->get_header_value("Trailer"));
  20011. // Prohibited trailer must not be present
  20012. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20013. // Allowed trailer should be present
  20014. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20015. EXPECT_EQ(std::string("yes"),
  20016. handle.response->get_trailer_value("X-Allowed"));
  20017. // Verify trailers are NOT present as regular headers
  20018. EXPECT_EQ(std::string(""),
  20019. handle.response->get_header_value("Content-Length"));
  20020. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20021. }
  20022. // Accepts one connection on an OS-assigned port, which it hands over through
  20023. // port_promise, reads the request head and sends back response. after_send,
  20024. // if given, runs on the connection before it is closed.
  20025. static std::thread
  20026. serve_single_response(std::promise<int> &port_promise,
  20027. const std::string &response,
  20028. std::function<void(socket_t)> after_send = nullptr) {
  20029. return std::thread([&port_promise, response, after_send] {
  20030. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20031. default_socket_options(srv);
  20032. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20033. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20034. sockaddr_in addr{};
  20035. addr.sin_family = AF_INET;
  20036. addr.sin_port = htons(0); // Let OS assign a free port
  20037. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20038. int opt = 1;
  20039. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20040. #ifdef _WIN32
  20041. reinterpret_cast<const char *>(&opt),
  20042. #else
  20043. &opt,
  20044. #endif
  20045. sizeof(opt));
  20046. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20047. ::listen(srv, 1) != 0) {
  20048. port_promise.set_value(-1);
  20049. detail::close_socket(srv);
  20050. return;
  20051. }
  20052. socklen_t addr_len = sizeof(addr);
  20053. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20054. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20055. sockaddr_in cli_addr{};
  20056. socklen_t cli_len = sizeof(cli_addr);
  20057. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20058. if (cli != INVALID_SOCKET) {
  20059. // Read the complete HTTP request (until the blank line that terminates
  20060. // headers) before sending the response. If the server closes the socket
  20061. // while the client's request data is still unread in the kernel receive
  20062. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20063. // connection on both sides: it discards the client's receive buffer
  20064. // (which already holds our response) and causes any in-progress write on
  20065. // the client to fail with ECONNRESET. Reading all request data first
  20066. // ensures close() emits a graceful FIN.
  20067. {
  20068. char rbuf[256];
  20069. std::string req;
  20070. while (req.find("\r\n\r\n") == std::string::npos) {
  20071. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20072. if (n <= 0) { break; }
  20073. req.append(rbuf, static_cast<size_t>(n));
  20074. }
  20075. }
  20076. ::send(cli,
  20077. #ifdef _WIN32
  20078. static_cast<const char *>(response.c_str()),
  20079. static_cast<int>(response.size()),
  20080. #else
  20081. response.c_str(), response.size(),
  20082. #endif
  20083. 0);
  20084. if (after_send) { after_send(cli); }
  20085. detail::close_socket(cli);
  20086. }
  20087. detail::close_socket(srv);
  20088. });
  20089. }
  20090. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20091. #ifndef _WIN32
  20092. signal(SIGPIPE, SIG_IGN);
  20093. #endif
  20094. std::promise<int> port_promise;
  20095. auto port_future = port_promise.get_future();
  20096. auto server_thread =
  20097. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20098. "Content-Type: text/plain\r\n"
  20099. "Content-Length: not-a-number\r\n"
  20100. "Connection: close\r\n"
  20101. "\r\n"
  20102. "hello");
  20103. auto port = port_future.get();
  20104. ASSERT_GT(port, 0);
  20105. Client cli("127.0.0.1", port);
  20106. auto handle = cli.open_stream("GET", "/");
  20107. EXPECT_FALSE(handle.is_valid());
  20108. server_thread.join();
  20109. }
  20110. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20111. #ifndef _WIN32
  20112. signal(SIGPIPE, SIG_IGN);
  20113. #endif
  20114. std::promise<int> port_promise;
  20115. auto port_future = port_promise.get_future();
  20116. auto server_thread = serve_single_response(
  20117. port_promise, "HTTP/1.1 200 OK\r\n"
  20118. "Content-Type: text/plain\r\n"
  20119. "Content-Length: 99999999999999999999999999\r\n"
  20120. "Connection: close\r\n"
  20121. "\r\n"
  20122. "hello");
  20123. auto port = port_future.get();
  20124. ASSERT_GT(port, 0);
  20125. // Historically std::stoull would throw std::out_of_range here and crash
  20126. // the process, then parsing silently clamped to a bogus framing length and
  20127. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20128. // so the stream fails to open, matching the not-a-number case above. The
  20129. // process still must NOT terminate.
  20130. Client cli("127.0.0.1", port);
  20131. auto handle = cli.open_stream("GET", "/");
  20132. EXPECT_FALSE(handle.is_valid());
  20133. server_thread.join();
  20134. }
  20135. #ifndef _WIN32
  20136. // As above for the body of a streamed request: a send() cut short by the write
  20137. // timeout must not leave the rest of the body unsent.
  20138. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20139. signal(SIGPIPE, SIG_IGN);
  20140. Server svr;
  20141. svr.set_socket_options([](socket_t sock) {
  20142. int size = 8192;
  20143. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20144. reinterpret_cast<const char *>(&size), sizeof(size));
  20145. });
  20146. svr.Post("/size", [](const Request &, Response &res,
  20147. const ContentReader &content_reader) {
  20148. // Outlast the client's write timeout before reading the body.
  20149. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20150. size_t received = 0;
  20151. content_reader([&](const char *, size_t len) {
  20152. received += len;
  20153. return true;
  20154. });
  20155. res.set_content(std::to_string(received), "text/plain");
  20156. });
  20157. auto port = svr.bind_to_any_port(HOST);
  20158. std::thread t([&]() { svr.listen_after_bind(); });
  20159. auto se = detail::scope_exit([&] {
  20160. svr.stop();
  20161. t.join();
  20162. });
  20163. svr.wait_until_ready();
  20164. Client cli(HOST, port);
  20165. cli.set_write_timeout(0, 500000);
  20166. cli.set_socket_options([](socket_t sock) {
  20167. int size = 8192;
  20168. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20169. reinterpret_cast<const char *>(&size), sizeof(size));
  20170. });
  20171. const std::string body(4 * 1024 * 1024, 'A');
  20172. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20173. "application/octet-stream");
  20174. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20175. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20176. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20177. }
  20178. #endif
  20179. // Serves `response` to the single request `fn` makes with a fresh client.
  20180. template <typename Fn>
  20181. static void with_single_response(const std::string &response, Fn fn) {
  20182. #ifndef _WIN32
  20183. signal(SIGPIPE, SIG_IGN);
  20184. #endif
  20185. std::promise<int> port_promise;
  20186. auto port_future = port_promise.get_future();
  20187. auto server_thread = serve_single_response(port_promise, response);
  20188. auto se = detail::scope_exit([&] { server_thread.join(); });
  20189. auto port = port_future.get();
  20190. ASSERT_GT(port, 0);
  20191. Client cli("127.0.0.1", port);
  20192. fn(cli);
  20193. }
  20194. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20195. // too, also in a build without the decoder for the advertised coding.
  20196. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20197. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20198. const auto response = "HTTP/1.1 200 OK\r\n"
  20199. "Content-Encoding: gzip\r\n"
  20200. "Content-Length: " +
  20201. std::to_string(gzipped.size()) +
  20202. "\r\n"
  20203. "Connection: close\r\n\r\n" +
  20204. gzipped;
  20205. with_single_response(response, [&](Client &cli) {
  20206. cli.set_decompress(false);
  20207. auto handle = cli.open_stream("GET", "/");
  20208. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20209. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20210. EXPECT_EQ(gzipped, read_all(handle));
  20211. EXPECT_FALSE(handle.has_read_error());
  20212. });
  20213. with_single_response(response, [&](Client &cli) {
  20214. cli.set_decompress(false);
  20215. auto res = stream::Get(cli, "/", 7);
  20216. ASSERT_TRUE(res) << to_string(res.error());
  20217. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20218. EXPECT_EQ(gzipped, res.read_all());
  20219. EXPECT_FALSE(res.has_read_error());
  20220. });
  20221. }
  20222. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20223. // Neither Content-Length nor chunked: the body ends at the close
  20224. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20225. "Connection: close\r\n"
  20226. "\r\n"
  20227. "hello";
  20228. with_single_response(close_delimited, [](Client &cli) {
  20229. auto handle = cli.open_stream("GET", "/");
  20230. ASSERT_TRUE(handle.is_valid());
  20231. EXPECT_EQ("hello", read_all(handle));
  20232. EXPECT_FALSE(handle.has_read_error());
  20233. });
  20234. // A close before the end of the Content-Length is still an error
  20235. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20236. "Content-Length: 10\r\n"
  20237. "\r\n"
  20238. "hello";
  20239. with_single_response(short_content_length, [](Client &cli) {
  20240. auto handle = cli.open_stream("GET", "/");
  20241. ASSERT_TRUE(handle.is_valid());
  20242. read_all(handle);
  20243. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20244. });
  20245. // So is a close before the last chunk
  20246. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20247. "Transfer-Encoding: chunked\r\n"
  20248. "\r\n"
  20249. "5\r\nhello\r\n";
  20250. with_single_response(short_chunked, [](Client &cli) {
  20251. auto handle = cli.open_stream("GET", "/");
  20252. ASSERT_TRUE(handle.is_valid());
  20253. read_all(handle);
  20254. EXPECT_TRUE(handle.has_read_error());
  20255. });
  20256. }
  20257. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20258. const char *responses[] = {
  20259. "HTTP/1.1 103 Early Hints\r\n"
  20260. "Link: </style.css>; rel=preload\r\n"
  20261. "\r\n"
  20262. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20263. "HTTP/1.1 100 Continue\r\n"
  20264. "X-Note: interim\r\n"
  20265. "\r\n"
  20266. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20267. };
  20268. for (auto response : responses) {
  20269. with_single_response(response, [](Client &cli) {
  20270. auto res = cli.Get("/");
  20271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20272. EXPECT_EQ(StatusCode::OK_200, res->status);
  20273. EXPECT_EQ("ok", res->body);
  20274. });
  20275. }
  20276. }
  20277. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20278. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20279. const std::string final_response =
  20280. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20281. std::string interims;
  20282. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20283. interims += interim;
  20284. }
  20285. with_single_response(interims + final_response, [](Client &cli) {
  20286. auto res = cli.Get("/");
  20287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20288. EXPECT_EQ("ok", res->body);
  20289. });
  20290. with_single_response(interims + interim + final_response, [](Client &cli) {
  20291. auto res = cli.Get("/");
  20292. ASSERT_FALSE(res);
  20293. EXPECT_EQ(Error::Read, res.error());
  20294. });
  20295. }
  20296. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20297. #ifndef _WIN32
  20298. signal(SIGPIPE, SIG_IGN);
  20299. #endif
  20300. // The server answers the head without asking for the body. Bytes it then
  20301. // reads on the connection would be taken for the body the request declared.
  20302. auto closed_by_client = false;
  20303. std::promise<int> port_promise;
  20304. auto server_thread = serve_single_response(
  20305. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20306. [&](socket_t sock) {
  20307. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20308. char buf[256];
  20309. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20310. });
  20311. Client cli("127.0.0.1", port_promise.get_future().get());
  20312. cli.set_keep_alive(true);
  20313. cli.set_read_timeout(1, 0);
  20314. // Long enough for the client to send Expect: 100-continue.
  20315. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20317. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20318. cli.Get("/second");
  20319. server_thread.join();
  20320. EXPECT_TRUE(closed_by_client);
  20321. }
  20322. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20323. // Long enough for the client to send Expect: 100-continue
  20324. with_single_response(
  20325. "HTTP/1.1 103 Early Hints\r\n"
  20326. "Link: </style.css>; rel=preload\r\n"
  20327. "\r\n"
  20328. "HTTP/1.1 401 Unauthorized\r\n"
  20329. "Content-Length: 0\r\n\r\n",
  20330. [](Client &cli) {
  20331. cli.set_read_timeout(2, 0);
  20332. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20334. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20335. });
  20336. }
  20337. #ifdef CPPHTTPLIB_SSL_ENABLED
  20338. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20339. #ifndef _WIN32
  20340. signal(SIGPIPE, SIG_IGN);
  20341. #endif
  20342. auto reused = false;
  20343. std::promise<int> port_promise;
  20344. auto server_thread = serve_single_response(
  20345. port_promise,
  20346. "HTTP/1.1 401 Unauthorized\r\n"
  20347. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20348. "Content-Length: 0\r\n\r\n",
  20349. [&](socket_t sock) {
  20350. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20351. char buf[256];
  20352. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20353. });
  20354. Client cli("127.0.0.1", port_promise.get_future().get());
  20355. cli.set_keep_alive(true);
  20356. cli.set_digest_auth("user", "pass");
  20357. cli.set_read_timeout(1, 0);
  20358. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20359. server_thread.join();
  20360. EXPECT_FALSE(reused);
  20361. }
  20362. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20363. // Any other answer to CONNECT would read as the origin's response.
  20364. struct {
  20365. const char *response;
  20366. bool passed_on;
  20367. } cases[] = {
  20368. {"HTTP/1.1 201 Created\r\n"
  20369. "Set-Cookie: session=from-proxy\r\n"
  20370. "Content-Length: 0\r\n\r\n",
  20371. false},
  20372. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20373. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20374. "Content-Length: 0\r\n\r\n",
  20375. true},
  20376. };
  20377. for (const auto &c : cases) {
  20378. std::promise<int> port_promise;
  20379. auto server_thread = serve_single_response(port_promise, c.response);
  20380. SSLClient cli("example.com", 443);
  20381. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20382. auto res = cli.Get("/");
  20383. server_thread.join();
  20384. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20385. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20386. if (res) {
  20387. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20388. }
  20389. }
  20390. }
  20391. #endif
  20392. // Records the client's error logger calls as "error METHOD path", or
  20393. // "error null" for a call without a request
  20394. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20395. return [&log](const Error &err, const Request *req) {
  20396. log.push_back(to_string(err) + " " +
  20397. (req ? req->method + " " + req->path : "null"));
  20398. };
  20399. }
  20400. // A failed request is reported once, with the request the caller made
  20401. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20402. Server svr;
  20403. svr.Get("/big", [](const Request &, Response &res) {
  20404. res.set_content(std::string(100000, 'b'), "text/plain");
  20405. });
  20406. auto port = svr.bind_to_any_port(HOST);
  20407. std::thread t([&]() { svr.listen_after_bind(); });
  20408. auto se = detail::scope_exit([&] {
  20409. svr.stop();
  20410. t.join();
  20411. });
  20412. svr.wait_until_ready();
  20413. Client cli(HOST, port);
  20414. std::vector<std::string> log;
  20415. cli.set_error_logger(record_errors(log));
  20416. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20417. cli.Get("/big", [](const char *, size_t) { return false; });
  20418. EXPECT_EQ(expected, log);
  20419. log.clear();
  20420. cli.Get("/big", [](size_t, size_t) { return false; });
  20421. EXPECT_EQ(expected, log);
  20422. }
  20423. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20424. // Fails while the body is read
  20425. auto broken = [](const Request &, Response &res) {
  20426. res.set_content_provider(10, "text/plain",
  20427. [](size_t, size_t, DataSink &) { return false; });
  20428. };
  20429. Server other;
  20430. other.Get("/broken", broken);
  20431. auto other_port = other.bind_to_any_port(HOST);
  20432. std::thread other_t([&]() { other.listen_after_bind(); });
  20433. auto other_se = detail::scope_exit([&] {
  20434. other.stop();
  20435. other_t.join();
  20436. });
  20437. other.wait_until_ready();
  20438. Server svr;
  20439. svr.Get("/broken", broken);
  20440. svr.Get("/same-origin",
  20441. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20442. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20443. res.set_redirect("http://" + std::string(HOST) + ":" +
  20444. std::to_string(other_port) + "/broken");
  20445. });
  20446. auto port = svr.bind_to_any_port(HOST);
  20447. std::thread t([&]() { svr.listen_after_bind(); });
  20448. auto se = detail::scope_exit([&] {
  20449. svr.stop();
  20450. t.join();
  20451. });
  20452. svr.wait_until_ready();
  20453. Client cli(HOST, port);
  20454. cli.set_follow_location(true);
  20455. std::vector<std::string> log;
  20456. cli.set_error_logger(record_errors(log));
  20457. for (auto path : {"/same-origin", "/cross-origin"}) {
  20458. log.clear();
  20459. auto res = cli.Get(path);
  20460. ASSERT_FALSE(res);
  20461. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20462. log);
  20463. }
  20464. }
  20465. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20466. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20467. std::vector<std::string> log;
  20468. cli.set_error_logger(record_errors(log));
  20469. auto handle = cli.open_stream("GET", "/x");
  20470. EXPECT_FALSE(handle.is_valid());
  20471. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20472. log);
  20473. });
  20474. }
  20475. #ifdef CPPHTTPLIB_SSL_ENABLED
  20476. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20477. // Not a TLS server, so the handshake fails. It waits for a request line in
  20478. // the handshake bytes, so a short read timeout lets it close quickly.
  20479. Server svr;
  20480. svr.set_read_timeout(0, 100000);
  20481. svr.Get("/x", [](const Request &, Response &res) {
  20482. res.set_content("x", "text/plain");
  20483. });
  20484. auto port = svr.bind_to_any_port(HOST);
  20485. std::thread t([&]() { svr.listen_after_bind(); });
  20486. auto se = detail::scope_exit([&] {
  20487. svr.stop();
  20488. t.join();
  20489. });
  20490. svr.wait_until_ready();
  20491. std::vector<std::string> log;
  20492. SSLClient cli(HOST, port);
  20493. cli.enable_server_certificate_verification(false);
  20494. cli.set_error_logger(record_errors(log));
  20495. auto res = cli.Get("/x");
  20496. ASSERT_FALSE(res);
  20497. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20498. log.clear();
  20499. auto handle = cli.open_stream("GET", "/x");
  20500. EXPECT_FALSE(handle.is_valid());
  20501. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20502. log.clear();
  20503. SSLClient no_ca(HOST, port);
  20504. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20505. no_ca.set_error_logger(record_errors(log));
  20506. res = no_ca.Get("/x");
  20507. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20508. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20509. }
  20510. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20511. #ifndef _WIN32
  20512. signal(SIGPIPE, SIG_IGN);
  20513. #endif
  20514. // Refused, answered with a challenge, or closed without an answer
  20515. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20516. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20517. "Content-Length: 0\r\n\r\n",
  20518. ""}) {
  20519. std::promise<int> port_promise;
  20520. auto server_thread = serve_single_response(port_promise, response);
  20521. SSLClient cli("example.com", 443);
  20522. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20523. std::vector<std::string> log;
  20524. cli.set_error_logger(record_errors(log));
  20525. auto res = cli.Get("/");
  20526. server_thread.join();
  20527. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20528. << response;
  20529. }
  20530. }
  20531. #endif
  20532. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20533. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20534. // the chunked coding and drop Content-Length, so a front-end that trusts
  20535. // Content-Length would disagree about where the body ends (response
  20536. // smuggling). The client must reject such a response.
  20537. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20538. for (const char *te : {"chunked", "gzip, chunked"}) {
  20539. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20540. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20541. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20542. "5\r\nhello\r\n0\r\n\r\n";
  20543. with_single_response(response, [&](Client &cli) {
  20544. auto res = cli.Get("/");
  20545. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20546. EXPECT_EQ(Error::Read, res.error()) << te;
  20547. });
  20548. with_single_response(response, [&](Client &cli) {
  20549. auto handle = cli.open_stream("GET", "/");
  20550. EXPECT_FALSE(handle.is_valid()) << te;
  20551. EXPECT_EQ(Error::Read, handle.error) << te;
  20552. });
  20553. }
  20554. }
  20555. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20556. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20557. // closing the connection (unlike a request, which must be rejected).
  20558. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20559. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20560. "Transfer-Encoding: chunked\r\n"
  20561. "Connection: close\r\n"
  20562. "\r\n"
  20563. "5\r\nhello\r\n0\r\n\r\n",
  20564. "HTTP/1.1 200 OK\r\n"
  20565. "Transfer-Encoding: gzip\r\n"
  20566. "Connection: close\r\n"
  20567. "\r\n"
  20568. "hello"}) {
  20569. with_single_response(response, [&](Client &cli) {
  20570. auto res = cli.Get("/");
  20571. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20572. EXPECT_EQ("hello", res->body);
  20573. });
  20574. with_single_response(response, [&](Client &cli) {
  20575. auto handle = cli.open_stream("GET", "/");
  20576. ASSERT_TRUE(handle.is_valid()) << response;
  20577. EXPECT_EQ("hello", read_all(handle));
  20578. });
  20579. }
  20580. }
  20581. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20582. // framing headers describe nothing to read and must not be rejected.
  20583. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20584. const std::string framing = "Content-Length: 5\r\n"
  20585. "Transfer-Encoding: chunked\r\n"
  20586. "Connection: close\r\n"
  20587. "\r\n";
  20588. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20589. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20590. });
  20591. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20592. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20593. });
  20594. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20595. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20596. with_single_response(response, [&](Client &cli) {
  20597. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20598. });
  20599. with_single_response(response, [&](Client &cli) {
  20600. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20601. });
  20602. }
  20603. }
  20604. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20605. // header section, so a stream opened on one has nothing to read, whatever
  20606. // framing or coding headers it carries.
  20607. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20608. struct Case {
  20609. const char *method;
  20610. const char *status;
  20611. };
  20612. // A reader of the declared body reports an early close when nothing
  20613. // follows, and hands back what does.
  20614. struct Framing {
  20615. const char *headers;
  20616. const char *after;
  20617. };
  20618. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20619. Case{"GET", "304 Not Modified"}}) {
  20620. for (const auto &f :
  20621. {Framing{"Content-Length: 5\r\n", ""},
  20622. Framing{"Content-Length: 5\r\n", "hello"},
  20623. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20624. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20625. // Not decoded, so a build without Brotli opens it too
  20626. Framing{"Content-Encoding: br\r\n", ""}}) {
  20627. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20628. "Connection: close\r\n"
  20629. "\r\n" +
  20630. f.after;
  20631. with_single_response(response, [&](Client &cli) {
  20632. auto handle = cli.open_stream(c.method, "/");
  20633. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20634. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20635. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20636. });
  20637. }
  20638. }
  20639. }
  20640. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20641. // response, is faulty framing, so the connection is not reused after it.
  20642. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20643. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20644. "Content-Length: 0\r\n"
  20645. "Transfer-Encoding: chunked\r\n"
  20646. "\r\n"
  20647. "5\r\nhello\r\n0\r\n\r\n",
  20648. "HTTP/1.0 200 Connection established\r\n"
  20649. "Connection: keep-alive\r\n"
  20650. "Transfer-Encoding: chunked\r\n"
  20651. "\r\n"
  20652. "5\r\nhello\r\n0\r\n\r\n"}) {
  20653. with_single_response(response, [&](Client &cli) {
  20654. cli.set_keep_alive(true);
  20655. auto res = cli.Get("/");
  20656. ASSERT_TRUE(res) << response;
  20657. EXPECT_EQ("hello", res->body);
  20658. EXPECT_FALSE(cli.is_socket_open()) << response;
  20659. });
  20660. }
  20661. }
  20662. // A payload max length of 0 means no limit, however the body is framed.
  20663. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20664. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20665. "Transfer-Encoding: chunked\r\n"
  20666. "\r\n"
  20667. "5\r\nhello\r\n0\r\n\r\n",
  20668. "HTTP/1.1 200 OK\r\n"
  20669. "Connection: close\r\n"
  20670. "\r\n"
  20671. "hello"}) {
  20672. with_single_response(response, [&](Client &cli) {
  20673. cli.set_payload_max_length(0);
  20674. auto res = cli.Get("/");
  20675. ASSERT_TRUE(res) << response;
  20676. EXPECT_EQ("hello", res->body) << response;
  20677. });
  20678. }
  20679. }
  20680. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20681. Server svr;
  20682. svr.set_payload_max_length(0);
  20683. svr.Post("/echo", [](const Request &req, Response &res) {
  20684. res.set_content(req.body, "text/plain");
  20685. });
  20686. auto port = svr.bind_to_any_port(HOST);
  20687. thread t = thread([&] { svr.listen_after_bind(); });
  20688. auto se = detail::scope_exit([&] {
  20689. svr.stop();
  20690. t.join();
  20691. ASSERT_FALSE(svr.is_running());
  20692. });
  20693. svr.wait_until_ready();
  20694. Client cli(HOST, port);
  20695. auto res = cli.Post(
  20696. "/echo",
  20697. [](size_t /*offset*/, DataSink &sink) {
  20698. sink.write("hello", 5);
  20699. sink.done();
  20700. return true;
  20701. },
  20702. "text/plain");
  20703. ASSERT_TRUE(res);
  20704. EXPECT_EQ(StatusCode::OK_200, res->status);
  20705. EXPECT_EQ("hello", res->body);
  20706. }
  20707. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20708. TEST_F(OpenStreamTest, Gzip) {
  20709. Client cli("127.0.0.1", port_);
  20710. auto handle = cli.open_stream("GET", "/compressible", {},
  20711. {{"Accept-Encoding", "gzip"}});
  20712. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20713. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20714. }
  20715. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20716. Client cli("127.0.0.1", port_);
  20717. auto handle =
  20718. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20719. {{"Accept-Encoding", "gzip"}});
  20720. ASSERT_TRUE(handle.is_valid());
  20721. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20722. EXPECT_EQ("123456789", read_all(handle));
  20723. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20724. }
  20725. #endif
  20726. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20727. TEST_F(OpenStreamTest, Brotli) {
  20728. Client cli("127.0.0.1", port_);
  20729. auto handle =
  20730. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20731. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20732. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20733. }
  20734. #endif
  20735. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20736. TEST_F(OpenStreamTest, Zstd) {
  20737. Client cli("127.0.0.1", port_);
  20738. auto handle = cli.open_stream("GET", "/compressible", {},
  20739. {{"Accept-Encoding", "zstd"}});
  20740. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20741. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20742. }
  20743. #endif
  20744. #ifdef CPPHTTPLIB_SSL_ENABLED
  20745. class SSLOpenStreamTest : public ::testing::Test {
  20746. protected:
  20747. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20748. void SetUp() override {
  20749. svr_.Get("/hello", [](const Request &, Response &res) {
  20750. res.set_content("Hello SSL World!", "text/plain");
  20751. });
  20752. svr_.Get("/chunked", [](const Request &, Response &res) {
  20753. res.set_chunked_content_provider("text/plain",
  20754. [](size_t offset, DataSink &sink) {
  20755. if (offset < 15) {
  20756. sink.write("chunk", 5);
  20757. return true;
  20758. }
  20759. sink.done();
  20760. return true;
  20761. });
  20762. });
  20763. svr_.Post("/echo", [](const Request &req, Response &res) {
  20764. res.set_content(req.body, req.get_header_value("Content-Type"));
  20765. });
  20766. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20767. std::string body = req.body;
  20768. res.set_chunked_content_provider(
  20769. "text/plain", [body](size_t offset, DataSink &sink) {
  20770. if (offset < body.size()) {
  20771. sink.write(body.data() + offset, body.size() - offset);
  20772. }
  20773. sink.done();
  20774. return true;
  20775. });
  20776. });
  20777. port_ = svr_.bind_to_any_port("127.0.0.1");
  20778. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20779. svr_.wait_until_ready();
  20780. }
  20781. void TearDown() override {
  20782. svr_.stop();
  20783. if (thread_.joinable()) thread_.join();
  20784. }
  20785. SSLServer svr_;
  20786. std::thread thread_;
  20787. int port_ = 0;
  20788. };
  20789. TEST_F(SSLOpenStreamTest, Basic) {
  20790. SSLClient cli("127.0.0.1", port_);
  20791. cli.enable_server_certificate_verification(false);
  20792. auto handle = cli.open_stream("GET", "/hello");
  20793. ASSERT_TRUE(handle.is_valid());
  20794. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20795. }
  20796. TEST_F(SSLOpenStreamTest, Chunked) {
  20797. SSLClient cli("127.0.0.1", port_);
  20798. cli.enable_server_certificate_verification(false);
  20799. auto handle = cli.open_stream("GET", "/chunked");
  20800. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20801. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20802. "Transfer-Encoding") == "chunked");
  20803. auto body = read_all(handle);
  20804. EXPECT_EQ("chunkchunkchunk", body);
  20805. }
  20806. TEST_F(SSLOpenStreamTest, Post) {
  20807. SSLClient cli("127.0.0.1", port_);
  20808. cli.enable_server_certificate_verification(false);
  20809. auto handle =
  20810. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20811. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20812. EXPECT_EQ(200, handle.response->status);
  20813. auto body = read_all(handle);
  20814. EXPECT_EQ("Hello SSL POST", body);
  20815. }
  20816. TEST_F(SSLOpenStreamTest, PostChunked) {
  20817. SSLClient cli("127.0.0.1", port_);
  20818. cli.enable_server_certificate_verification(false);
  20819. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20820. "Chunked SSL Data", "text/plain");
  20821. ASSERT_TRUE(handle.is_valid());
  20822. EXPECT_EQ(200, handle.response->status);
  20823. auto body = read_all(handle);
  20824. EXPECT_EQ("Chunked SSL Data", body);
  20825. }
  20826. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20827. // Content-Length is terminated by the server closing the connection. When the
  20828. // SSL peer sends a close_notify after the body, the client must treat it as a
  20829. // clean EOF and return a successful response rather than an error.
  20830. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20832. ASSERT_TRUE(svr.is_valid());
  20833. svr.set_keep_alive_max_count(1);
  20834. const std::string expected_body = "Hello from connection-close response!";
  20835. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20836. res.set_content_provider("text/plain",
  20837. [&](size_t offset, DataSink &sink) -> bool {
  20838. if (offset < expected_body.size()) {
  20839. sink.write(expected_body.data() + offset,
  20840. expected_body.size() - offset);
  20841. }
  20842. sink.done();
  20843. return true;
  20844. });
  20845. });
  20846. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20847. auto se = detail::scope_exit([&] {
  20848. svr.stop();
  20849. listen_thread.join();
  20850. ASSERT_FALSE(svr.is_running());
  20851. });
  20852. svr.wait_until_ready();
  20853. SSLClient cli(HOST, PORT);
  20854. cli.enable_server_certificate_verification(false);
  20855. auto res = cli.Get("/no-content-length");
  20856. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20857. EXPECT_EQ(StatusCode::OK_200, res->status);
  20858. EXPECT_EQ(expected_body, res->body);
  20859. }
  20860. #endif // CPPHTTPLIB_SSL_ENABLED
  20861. //==============================================================================
  20862. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20863. // results for various scenarios.
  20864. //==============================================================================
  20865. TEST(ParityTest, GetVsOpenStream) {
  20866. Server svr;
  20867. const std::string path = "/parity";
  20868. const std::string content = "Parity test content: hello world";
  20869. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20870. res.set_content(content, "text/plain");
  20871. });
  20872. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20873. auto se = detail::scope_exit([&] {
  20874. svr.stop();
  20875. t.join();
  20876. ASSERT_FALSE(svr.is_running());
  20877. });
  20878. svr.wait_until_ready();
  20879. Client cli(HOST, PORT);
  20880. // Non-stream path
  20881. auto r1 = cli.Get(path);
  20882. ASSERT_TRUE(r1);
  20883. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20884. // Stream path
  20885. auto h = cli.open_stream("GET", path);
  20886. ASSERT_TRUE(h.is_valid());
  20887. EXPECT_EQ(r1->body, read_all(h));
  20888. }
  20889. // Helper to compress data with provided compressor type T
  20890. template <typename Compressor>
  20891. static std::string compress_payload_for_parity(const std::string &in) {
  20892. std::string out;
  20893. Compressor compressor;
  20894. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20895. [&](const char *data, size_t n) {
  20896. out.append(data, n);
  20897. return true;
  20898. });
  20899. EXPECT_TRUE(ok);
  20900. return out;
  20901. }
  20902. // Helper function for compression parity tests
  20903. template <typename Compressor>
  20904. static void test_compression_parity(const std::string &original,
  20905. const std::string &path,
  20906. const std::string &encoding) {
  20907. const std::string compressed =
  20908. compress_payload_for_parity<Compressor>(original);
  20909. Server svr;
  20910. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20911. res.set_content(compressed, "application/octet-stream");
  20912. res.set_header("Content-Encoding", encoding);
  20913. });
  20914. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20915. auto se = detail::scope_exit([&] {
  20916. svr.stop();
  20917. t.join();
  20918. ASSERT_FALSE(svr.is_running());
  20919. });
  20920. svr.wait_until_ready();
  20921. Client cli(HOST, PORT);
  20922. // Non-streaming
  20923. {
  20924. auto res = cli.Get(path);
  20925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20926. EXPECT_EQ(StatusCode::OK_200, res->status);
  20927. EXPECT_EQ(original, res->body);
  20928. }
  20929. // Streaming
  20930. {
  20931. auto h = cli.open_stream("GET", path);
  20932. ASSERT_TRUE(h.is_valid());
  20933. EXPECT_EQ(original, read_all(h));
  20934. }
  20935. }
  20936. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20937. TEST(ParityTest, Gzip) {
  20938. test_compression_parity<detail::gzip_compressor>(
  20939. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20940. }
  20941. #endif
  20942. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20943. TEST(ParityTest, Brotli) {
  20944. test_compression_parity<detail::brotli_compressor>(
  20945. "Hello, brotli parity test payload", "/parity-br", "br");
  20946. }
  20947. #endif
  20948. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20949. TEST(ParityTest, Zstd) {
  20950. test_compression_parity<detail::zstd_compressor>(
  20951. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20952. }
  20953. #endif
  20954. //==============================================================================
  20955. // New Stream API Tests
  20956. //==============================================================================
  20957. inline std::string read_body(httplib::stream::Result &result) {
  20958. std::string body;
  20959. while (result.next()) {
  20960. body.append(result.data(), result.size());
  20961. }
  20962. return body;
  20963. }
  20964. TEST(ClientConnectionTest, Basic) {
  20965. httplib::ClientConnection conn;
  20966. EXPECT_FALSE(conn.is_open());
  20967. conn.sock = 1;
  20968. EXPECT_TRUE(conn.is_open());
  20969. httplib::ClientConnection conn2(std::move(conn));
  20970. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20971. conn2.sock = INVALID_SOCKET;
  20972. }
  20973. // Unified test server for all stream::* tests
  20974. class StreamApiTest : public ::testing::Test {
  20975. protected:
  20976. void SetUp() override {
  20977. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20978. res.set_content("Hello World!", "text/plain");
  20979. });
  20980. svr_.Get("/echo-params",
  20981. [](const httplib::Request &req, httplib::Response &res) {
  20982. std::string r;
  20983. for (const auto &p : req.params) {
  20984. if (!r.empty()) r += "&";
  20985. r += p.first + "=" + p.second;
  20986. }
  20987. res.set_content(r, "text/plain");
  20988. });
  20989. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20990. res.set_content(req.body, req.get_header_value("Content-Type"));
  20991. });
  20992. svr_.Post("/echo-headers",
  20993. [](const httplib::Request &req, httplib::Response &res) {
  20994. std::string r;
  20995. for (const auto &h : req.headers)
  20996. r += h.first + ": " + h.second + "\n";
  20997. res.set_content(r, "text/plain");
  20998. });
  20999. svr_.Post("/echo-params",
  21000. [](const httplib::Request &req, httplib::Response &res) {
  21001. std::string r = "params:";
  21002. for (const auto &p : req.params)
  21003. r += p.first + "=" + p.second + ";";
  21004. res.set_content(r + " body:" + req.body, "text/plain");
  21005. });
  21006. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21007. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21008. });
  21009. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21010. res.set_content("PUT:" + req.body, "text/plain");
  21011. });
  21012. svr_.Patch("/echo",
  21013. [](const httplib::Request &req, httplib::Response &res) {
  21014. res.set_content("PATCH:" + req.body, "text/plain");
  21015. });
  21016. svr_.Delete(
  21017. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21018. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21019. "text/plain");
  21020. });
  21021. svr_.Get("/head-test",
  21022. [](const httplib::Request &, httplib::Response &res) {
  21023. res.set_content("body for HEAD", "text/plain");
  21024. });
  21025. svr_.Options("/options",
  21026. [](const httplib::Request &, httplib::Response &res) {
  21027. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21028. });
  21029. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21030. svr_.wait_until_ready();
  21031. }
  21032. void TearDown() override {
  21033. svr_.stop();
  21034. if (thread_.joinable()) thread_.join();
  21035. }
  21036. httplib::Server svr_;
  21037. std::thread thread_;
  21038. };
  21039. // stream::Get tests
  21040. TEST_F(StreamApiTest, GetBasic) {
  21041. httplib::Client cli(HOST, PORT);
  21042. auto result = httplib::stream::Get(cli, "/hello");
  21043. ASSERT_TRUE(result.is_valid());
  21044. EXPECT_EQ(200, result.status());
  21045. EXPECT_EQ("Hello World!", read_body(result));
  21046. }
  21047. TEST_F(StreamApiTest, GetWithParams) {
  21048. httplib::Client cli(HOST, PORT);
  21049. httplib::Params params{{"foo", "bar"}};
  21050. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21051. ASSERT_TRUE(result.is_valid());
  21052. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21053. }
  21054. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21055. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21056. httplib::Client cli(HOST, PORT);
  21057. cli.set_payload_max_length(0);
  21058. auto result = httplib::stream::Get(cli, "/hello");
  21059. ASSERT_TRUE(result.is_valid());
  21060. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21061. EXPECT_EQ("Hello World!", read_body(result));
  21062. }
  21063. #endif
  21064. TEST_F(StreamApiTest, GetConnectionError) {
  21065. httplib::Client cli(HOST, 9999);
  21066. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21067. }
  21068. TEST_F(StreamApiTest, Get404) {
  21069. httplib::Client cli(HOST, PORT);
  21070. auto result = httplib::stream::Get(cli, "/nonexistent");
  21071. EXPECT_TRUE(result.is_valid());
  21072. EXPECT_EQ(404, result.status());
  21073. }
  21074. // stream::Post tests
  21075. TEST_F(StreamApiTest, PostBasic) {
  21076. httplib::Client cli(HOST, PORT);
  21077. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21078. "application/json");
  21079. ASSERT_TRUE(result.is_valid());
  21080. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21081. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21082. }
  21083. TEST_F(StreamApiTest, PostWithHeaders) {
  21084. httplib::Client cli(HOST, PORT);
  21085. httplib::Headers headers{{"X-Custom", "value"}};
  21086. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21087. "text/plain");
  21088. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21089. }
  21090. TEST_F(StreamApiTest, PostWithParams) {
  21091. httplib::Client cli(HOST, PORT);
  21092. httplib::Params params{{"k", "v"}};
  21093. auto result =
  21094. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21095. auto body = read_body(result);
  21096. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21097. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21098. }
  21099. TEST_F(StreamApiTest, PostLarge) {
  21100. httplib::Client cli(HOST, PORT);
  21101. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21102. size_t total = 0;
  21103. while (result.next()) {
  21104. total += result.size();
  21105. }
  21106. EXPECT_EQ(100u * 1024u, total);
  21107. }
  21108. // stream::Put/Patch tests
  21109. TEST_F(StreamApiTest, PutAndPatch) {
  21110. httplib::Client cli(HOST, PORT);
  21111. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21112. EXPECT_EQ("PUT:test", read_body(put));
  21113. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21114. EXPECT_EQ("PATCH:test", read_body(patch));
  21115. }
  21116. // stream::Delete tests
  21117. TEST_F(StreamApiTest, Delete) {
  21118. httplib::Client cli(HOST, PORT);
  21119. auto del1 = httplib::stream::Delete(cli, "/resource");
  21120. EXPECT_EQ("Deleted", read_body(del1));
  21121. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21122. EXPECT_EQ("Deleted:data", read_body(del2));
  21123. }
  21124. // stream::Head/Options tests
  21125. TEST_F(StreamApiTest, HeadAndOptions) {
  21126. httplib::Client cli(HOST, PORT);
  21127. auto head = httplib::stream::Head(cli, "/head-test");
  21128. EXPECT_TRUE(head.is_valid());
  21129. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21130. auto opts = httplib::stream::Options(cli, "/options");
  21131. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21132. }
  21133. // SSL stream::* tests
  21134. #ifdef CPPHTTPLIB_SSL_ENABLED
  21135. class SSLStreamApiTest : public ::testing::Test {
  21136. protected:
  21137. void SetUp() override {
  21138. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21139. res.set_content("Hello SSL!", "text/plain");
  21140. });
  21141. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21142. res.set_content(req.body, "text/plain");
  21143. });
  21144. port_ = svr_.bind_to_any_port("127.0.0.1");
  21145. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21146. svr_.wait_until_ready();
  21147. }
  21148. void TearDown() override {
  21149. svr_.stop();
  21150. if (thread_.joinable()) thread_.join();
  21151. }
  21152. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21153. std::thread thread_;
  21154. int port_ = 0;
  21155. };
  21156. TEST_F(SSLStreamApiTest, GetAndPost) {
  21157. httplib::SSLClient cli("127.0.0.1", port_);
  21158. cli.enable_server_certificate_verification(false);
  21159. auto get = httplib::stream::Get(cli, "/hello");
  21160. EXPECT_EQ("Hello SSL!", read_body(get));
  21161. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21162. EXPECT_EQ("test", read_body(post));
  21163. }
  21164. #endif
  21165. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21166. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21167. // BodyReader
  21168. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21169. // Test that read timeout during streaming is detected
  21170. // Use a large content-length response where server delays mid-stream
  21171. Server svr;
  21172. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21173. // Send a large response with delay in the middle
  21174. res.set_content_provider(
  21175. 1000, // content_length
  21176. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21177. if (offset < 100) {
  21178. // Send first 100 bytes immediately
  21179. std::string data(100, 'A');
  21180. sink.write(data.c_str(), data.size());
  21181. return true;
  21182. }
  21183. // Then delay longer than client timeout
  21184. std::this_thread::sleep_for(std::chrono::seconds(3));
  21185. std::string data(900, 'B');
  21186. sink.write(data.c_str(), data.size());
  21187. return true;
  21188. });
  21189. });
  21190. auto port = 8091;
  21191. std::thread t([&]() { svr.listen("localhost", port); });
  21192. svr.wait_until_ready();
  21193. Client cli("localhost", port);
  21194. cli.set_read_timeout(1, 0); // 1 second timeout
  21195. auto handle = cli.open_stream("GET", "/slow-stream");
  21196. ASSERT_TRUE(handle.is_valid());
  21197. char buf[256];
  21198. ssize_t total = 0;
  21199. ssize_t n;
  21200. bool got_error = false;
  21201. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21202. total += n;
  21203. }
  21204. if (n < 0) {
  21205. got_error = true;
  21206. // Should be timeout or read error
  21207. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21208. handle.get_read_error() == Error::Read)
  21209. << "Actual error: " << to_string(handle.get_read_error());
  21210. }
  21211. // Either we got an error, or we got less data than expected
  21212. EXPECT_TRUE(got_error || total < 1000)
  21213. << "Expected timeout but got all " << total << " bytes";
  21214. svr.stop();
  21215. t.join();
  21216. }
  21217. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21218. // Test connection closed detection via BodyReader
  21219. Server svr;
  21220. std::atomic<bool> close_now{false};
  21221. svr.Get("/will-close", [&](const Request &, Response &res) {
  21222. res.set_content_provider(
  21223. 10000, // Large content_length that we won't fully send
  21224. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21225. if (offset < 100) {
  21226. std::string data(100, 'X');
  21227. sink.write(data.c_str(), data.size());
  21228. return true;
  21229. }
  21230. // Wait for signal then abort
  21231. while (!close_now) {
  21232. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21233. }
  21234. return false; // Abort - server will close connection
  21235. });
  21236. });
  21237. auto port = 8092;
  21238. std::thread t([&]() { svr.listen("localhost", port); });
  21239. svr.wait_until_ready();
  21240. Client cli("localhost", port);
  21241. auto handle = cli.open_stream("GET", "/will-close");
  21242. ASSERT_TRUE(handle.is_valid());
  21243. char buf[256];
  21244. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21245. EXPECT_GT(n, 0) << "First read should succeed";
  21246. // Signal server to close
  21247. close_now = true;
  21248. // Keep reading until error or EOF
  21249. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21250. // Keep reading
  21251. }
  21252. // Should get an error since content_length wasn't satisfied
  21253. if (n < 0) {
  21254. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21255. handle.get_read_error() == Error::Read)
  21256. << "Actual error: " << to_string(handle.get_read_error());
  21257. }
  21258. svr.stop();
  21259. t.join();
  21260. }
  21261. #ifdef CPPHTTPLIB_SSL_ENABLED
  21262. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21263. // Test that read timeout during SSL streaming is detected
  21264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21265. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21266. res.set_content_provider(
  21267. 1000, "text/plain",
  21268. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21269. if (offset < 100) {
  21270. std::string data(100, 'A');
  21271. sink.write(data.c_str(), data.size());
  21272. return true;
  21273. }
  21274. std::this_thread::sleep_for(std::chrono::seconds(3));
  21275. std::string data(900, 'B');
  21276. sink.write(data.c_str(), data.size());
  21277. return true;
  21278. });
  21279. });
  21280. auto port = 8093;
  21281. std::thread t([&]() { svr.listen("localhost", port); });
  21282. svr.wait_until_ready();
  21283. SSLClient cli("localhost", port);
  21284. cli.enable_server_certificate_verification(false);
  21285. cli.set_read_timeout(1, 0); // 1 second timeout
  21286. auto handle = cli.open_stream("GET", "/slow-stream");
  21287. ASSERT_TRUE(handle.is_valid());
  21288. char buf[256];
  21289. ssize_t total = 0;
  21290. ssize_t n;
  21291. bool got_error = false;
  21292. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21293. total += n;
  21294. }
  21295. if (n < 0) {
  21296. got_error = true;
  21297. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21298. handle.get_read_error() == Error::Read)
  21299. << "Actual error: " << to_string(handle.get_read_error());
  21300. }
  21301. EXPECT_TRUE(got_error || total < 1000)
  21302. << "Expected timeout but got all " << total << " bytes";
  21303. svr.stop();
  21304. t.join();
  21305. }
  21306. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21307. // Test SSL connection closed detection
  21308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21309. std::atomic<bool> close_now{false};
  21310. svr.Get("/will-close", [&](const Request &, Response &res) {
  21311. res.set_content_provider(
  21312. 10000, "text/plain",
  21313. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21314. if (offset < 100) {
  21315. std::string data(100, 'X');
  21316. sink.write(data.c_str(), data.size());
  21317. return true;
  21318. }
  21319. while (!close_now) {
  21320. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21321. }
  21322. return false;
  21323. });
  21324. });
  21325. auto port = 8094;
  21326. std::thread t([&]() { svr.listen("localhost", port); });
  21327. svr.wait_until_ready();
  21328. SSLClient cli("localhost", port);
  21329. cli.enable_server_certificate_verification(false);
  21330. auto handle = cli.open_stream("GET", "/will-close");
  21331. ASSERT_TRUE(handle.is_valid());
  21332. char buf[256];
  21333. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21334. EXPECT_GT(n, 0);
  21335. // Signal server to close
  21336. close_now = true;
  21337. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21338. // Keep reading
  21339. }
  21340. if (n < 0) {
  21341. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21342. handle.get_read_error() == Error::Read)
  21343. << "Actual error: " << to_string(handle.get_read_error());
  21344. }
  21345. svr.stop();
  21346. t.join();
  21347. }
  21348. #endif
  21349. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21350. using namespace httplib;
  21351. // Create a test file
  21352. const char *fname = "etag_testfile.txt";
  21353. const char *content = "etag-content";
  21354. {
  21355. std::ofstream ofs(fname);
  21356. ofs << content;
  21357. ASSERT_TRUE(ofs.good());
  21358. }
  21359. Server svr;
  21360. svr.set_mount_point("/static", ".");
  21361. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21362. svr.wait_until_ready();
  21363. Client cli(HOST, PORT);
  21364. // First request: should get 200 with ETag header
  21365. auto res1 = cli.Get("/static/etag_testfile.txt");
  21366. ASSERT_TRUE(res1);
  21367. ASSERT_EQ(200, res1->status);
  21368. ASSERT_TRUE(res1->has_header("ETag"));
  21369. std::string etag = res1->get_header_value("ETag");
  21370. EXPECT_FALSE(etag.empty());
  21371. // Verify ETag format: W/"hex-hex"
  21372. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21373. EXPECT_EQ('W', etag[0]);
  21374. EXPECT_EQ('/', etag[1]);
  21375. EXPECT_EQ('"', etag[2]);
  21376. EXPECT_EQ('"', etag.back());
  21377. // Exact match: expect 304 Not Modified
  21378. Headers h2 = {{"If-None-Match", etag}};
  21379. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21380. ASSERT_TRUE(res2);
  21381. EXPECT_EQ(304, res2->status);
  21382. // Wildcard match: expect 304 Not Modified
  21383. Headers h3 = {{"If-None-Match", "*"}};
  21384. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21385. ASSERT_TRUE(res3);
  21386. EXPECT_EQ(304, res3->status);
  21387. // Non-matching ETag: expect 200
  21388. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21389. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21390. ASSERT_TRUE(res4);
  21391. EXPECT_EQ(200, res4->status);
  21392. // Multiple ETags with one matching: expect 304
  21393. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21394. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21395. ASSERT_TRUE(res5);
  21396. EXPECT_EQ(304, res5->status);
  21397. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21398. // that equivalent to the single comma-separated list above, so the match on
  21399. // the second line must still be found.
  21400. Headers h6;
  21401. h6.emplace("If-None-Match", "W/\"other\"");
  21402. h6.emplace("If-None-Match", etag);
  21403. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21404. ASSERT_TRUE(res6);
  21405. EXPECT_EQ(304, res6->status);
  21406. svr.stop();
  21407. t.join();
  21408. std::remove(fname);
  21409. }
  21410. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21411. using namespace httplib;
  21412. Server svr;
  21413. svr.set_mount_point("/static", ".");
  21414. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21415. svr.wait_until_ready();
  21416. Client cli(HOST, PORT);
  21417. // Send If-None-Match: * to a non-existent file
  21418. Headers h = {{"If-None-Match", "*"}};
  21419. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21421. EXPECT_EQ(404, res->status);
  21422. svr.stop();
  21423. t.join();
  21424. }
  21425. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21426. using namespace httplib;
  21427. // Create a test file
  21428. const char *fname = "etag_boundary_testfile.txt";
  21429. const char *content = "boundary-test";
  21430. {
  21431. std::ofstream ofs(fname);
  21432. ofs << content;
  21433. ASSERT_TRUE(ofs.good());
  21434. }
  21435. Server svr;
  21436. svr.set_mount_point("/static", ".");
  21437. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21438. svr.wait_until_ready();
  21439. Client cli(HOST, PORT);
  21440. // Get the actual ETag
  21441. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21442. ASSERT_TRUE(res1);
  21443. ASSERT_EQ(200, res1->status);
  21444. ASSERT_TRUE(res1->has_header("ETag"));
  21445. std::string etag = res1->get_header_value("ETag");
  21446. // Test 1: Very long ETag value (longer than actual ETag)
  21447. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21448. Headers h1 = {{"If-None-Match", "W/"
  21449. "\"very-long-etag-value-that-is-much-longer-"
  21450. "than-the-actual-etag-value\""}};
  21451. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21452. ASSERT_TRUE(res2);
  21453. EXPECT_EQ(200, res2->status); // Should not match
  21454. // Test 2: Long string followed by wildcard
  21455. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21456. // string)
  21457. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21458. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21459. ASSERT_TRUE(res3);
  21460. EXPECT_EQ(304, res3->status); // Should match on "*"
  21461. // Test 3: Wildcard followed by long string
  21462. // Should match on "*" immediately and return 304
  21463. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21464. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21465. ASSERT_TRUE(res4);
  21466. EXPECT_EQ(304, res4->status); // Should match on "*"
  21467. // Test 4: Multiple long non-matching values
  21468. // Should NOT match and return 200 (test that all comparisons are safe)
  21469. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21470. "W/\"second-long-non-matching-value\", "
  21471. "W/\"third-long-non-matching-value\""}};
  21472. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21473. ASSERT_TRUE(res5);
  21474. EXPECT_EQ(200, res5->status); // Should not match
  21475. // Test 5: Single character that is not "*" (edge case)
  21476. Headers h5 = {{"If-None-Match", "X"}};
  21477. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21478. ASSERT_TRUE(res6);
  21479. EXPECT_EQ(200, res6->status); // Should not match
  21480. svr.stop();
  21481. t.join();
  21482. std::remove(fname);
  21483. }
  21484. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21485. using namespace httplib;
  21486. // Create a test file
  21487. const char *fname = "ims_testfile.txt";
  21488. const char *content = "if-modified-since-test";
  21489. {
  21490. std::ofstream ofs(fname);
  21491. ofs << content;
  21492. ASSERT_TRUE(ofs.good());
  21493. }
  21494. Server svr;
  21495. svr.set_mount_point("/static", ".");
  21496. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21497. svr.wait_until_ready();
  21498. Client cli(HOST, PORT);
  21499. // First request: should get 200 with Last-Modified header
  21500. auto res1 = cli.Get("/static/ims_testfile.txt");
  21501. ASSERT_TRUE(res1);
  21502. ASSERT_EQ(200, res1->status);
  21503. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21504. std::string last_modified = res1->get_header_value("Last-Modified");
  21505. EXPECT_FALSE(last_modified.empty());
  21506. // If-Modified-Since with same time: expect 304
  21507. Headers h2 = {{"If-Modified-Since", last_modified}};
  21508. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21509. ASSERT_TRUE(res2);
  21510. EXPECT_EQ(304, res2->status);
  21511. // If-Modified-Since with future time: expect 304
  21512. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21513. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21514. ASSERT_TRUE(res3);
  21515. EXPECT_EQ(304, res3->status);
  21516. // If-Modified-Since with past time: expect 200
  21517. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21518. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21519. ASSERT_TRUE(res4);
  21520. EXPECT_EQ(200, res4->status);
  21521. // If-None-Match takes precedence over If-Modified-Since
  21522. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21523. ASSERT_TRUE(res1->has_header("ETag"));
  21524. std::string etag = res1->get_header_value("ETag");
  21525. Headers h5 = {{"If-None-Match", etag},
  21526. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21527. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21528. ASSERT_TRUE(res5);
  21529. EXPECT_EQ(304, res5->status);
  21530. svr.stop();
  21531. t.join();
  21532. std::remove(fname);
  21533. }
  21534. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21535. using namespace httplib;
  21536. Server svr;
  21537. // Endpoint that returns compressible content
  21538. svr.Get("/compressible", [](const Request &, Response &res) {
  21539. // Return a large enough body to trigger compression
  21540. std::string body(1000, 'a');
  21541. res.set_content(body, "text/plain");
  21542. });
  21543. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21544. svr.wait_until_ready();
  21545. Client cli(HOST, PORT);
  21546. // Request with gzip support: should get Vary header when compressed
  21547. cli.set_compress(true);
  21548. auto res1 = cli.Get("/compressible");
  21549. ASSERT_TRUE(res1);
  21550. EXPECT_EQ(200, res1->status);
  21551. // If Content-Encoding is set, Vary should also be set
  21552. if (res1->has_header("Content-Encoding")) {
  21553. EXPECT_TRUE(res1->has_header("Vary"));
  21554. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21555. }
  21556. // Request without Accept-Encoding header: should not have compression
  21557. Headers h_no_compress;
  21558. auto res2 = cli.Get("/compressible", h_no_compress);
  21559. ASSERT_TRUE(res2);
  21560. EXPECT_EQ(200, res2->status);
  21561. // Verify Vary header is present when compression is applied
  21562. // (the exact behavior depends on server configuration)
  21563. svr.stop();
  21564. t.join();
  21565. }
  21566. TEST(ETagTest, IfRangeWithETag) {
  21567. using namespace httplib;
  21568. // Create a test file with known content
  21569. const char *fname = "if_range_testfile.txt";
  21570. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21571. {
  21572. std::ofstream ofs(fname);
  21573. ofs << content;
  21574. ASSERT_TRUE(ofs.good());
  21575. }
  21576. Server svr;
  21577. svr.set_mount_point("/static", ".");
  21578. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21579. svr.wait_until_ready();
  21580. Client cli(HOST, PORT);
  21581. // First request: get ETag
  21582. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21583. ASSERT_TRUE(res1);
  21584. ASSERT_EQ(200, res1->status);
  21585. ASSERT_TRUE(res1->has_header("ETag"));
  21586. std::string etag = res1->get_header_value("ETag");
  21587. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21588. // Since our server generates weak ETags (W/"..."), If-Range with our
  21589. // ETag should NOT result in partial content - it should return full content.
  21590. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21591. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21592. ASSERT_TRUE(res2);
  21593. // Weak ETag in If-Range -> full content (200), not partial (206)
  21594. EXPECT_EQ(200, res2->status);
  21595. EXPECT_EQ(content, res2->body);
  21596. EXPECT_FALSE(res2->has_header("Content-Range"));
  21597. // Range request with non-matching If-Range (ETag): should get 200 (full
  21598. // content)
  21599. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21600. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21601. ASSERT_TRUE(res3);
  21602. EXPECT_EQ(200, res3->status);
  21603. EXPECT_EQ(content, res3->body);
  21604. EXPECT_FALSE(res3->has_header("Content-Range"));
  21605. // Range request with strong ETag (hypothetical - our server doesn't generate
  21606. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21607. // should return full content)
  21608. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21609. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21610. ASSERT_TRUE(res4);
  21611. EXPECT_EQ(200, res4->status);
  21612. EXPECT_EQ(content, res4->body);
  21613. EXPECT_FALSE(res4->has_header("Content-Range"));
  21614. svr.stop();
  21615. t.join();
  21616. std::remove(fname);
  21617. }
  21618. TEST(ETagTest, IfRangeWithDate) {
  21619. using namespace httplib;
  21620. // Create a test file
  21621. const char *fname = "if_range_date_testfile.txt";
  21622. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21623. {
  21624. std::ofstream ofs(fname);
  21625. ofs << content;
  21626. ASSERT_TRUE(ofs.good());
  21627. }
  21628. Server svr;
  21629. svr.set_mount_point("/static", ".");
  21630. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21631. svr.wait_until_ready();
  21632. Client cli(HOST, PORT);
  21633. // First request: get Last-Modified
  21634. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21635. ASSERT_TRUE(res1);
  21636. ASSERT_EQ(200, res1->status);
  21637. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21638. std::string last_modified = res1->get_header_value("Last-Modified");
  21639. // Range request with matching If-Range (date): should get 206
  21640. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21641. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21642. ASSERT_TRUE(res2);
  21643. EXPECT_EQ(206, res2->status);
  21644. EXPECT_EQ("FGHIJ", res2->body);
  21645. // Range request with old If-Range date: should get 200 (full content)
  21646. Headers h3 = {{"Range", "bytes=5-9"},
  21647. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21648. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21649. ASSERT_TRUE(res3);
  21650. EXPECT_EQ(200, res3->status);
  21651. EXPECT_EQ(content, res3->body);
  21652. // Range request with future If-Range date: should get 206
  21653. Headers h4 = {{"Range", "bytes=0-4"},
  21654. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21655. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21656. ASSERT_TRUE(res4);
  21657. EXPECT_EQ(206, res4->status);
  21658. EXPECT_EQ("ABCDE", res4->body);
  21659. svr.stop();
  21660. t.join();
  21661. std::remove(fname);
  21662. }
  21663. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21664. using namespace httplib;
  21665. const char *fname = "etag_malformed.txt";
  21666. const char *content = "malformed-etag";
  21667. {
  21668. std::ofstream ofs(fname);
  21669. ofs << content;
  21670. ASSERT_TRUE(ofs.good());
  21671. }
  21672. Server svr;
  21673. svr.set_mount_point("/static", ".");
  21674. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21675. svr.wait_until_ready();
  21676. Client cli(HOST, PORT);
  21677. // baseline: should get 200 and an ETag
  21678. auto res1 = cli.Get("/static/etag_malformed.txt");
  21679. ASSERT_TRUE(res1);
  21680. ASSERT_EQ(200, res1->status);
  21681. ASSERT_TRUE(res1->has_header("ETag"));
  21682. // Malformed ETag value (missing quotes) should be treated as non-matching
  21683. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21684. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21685. ASSERT_TRUE(res_bad);
  21686. EXPECT_EQ(200, res_bad->status);
  21687. // Whitespace-only header value should be considered invalid / non-matching
  21688. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21689. "Host: localhost\r\n"
  21690. "If-None-Match: \r\n"
  21691. "Connection: close\r\n"
  21692. "\r\n";
  21693. std::string out;
  21694. ASSERT_TRUE(send_request(5, raw_req, &out));
  21695. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21696. svr.stop();
  21697. t.join();
  21698. std::remove(fname);
  21699. }
  21700. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21701. using namespace httplib;
  21702. const char *fname = "ims_invalid_format.txt";
  21703. const char *content = "ims-bad-format";
  21704. {
  21705. std::ofstream ofs(fname);
  21706. ofs << content;
  21707. ASSERT_TRUE(ofs.good());
  21708. }
  21709. Server svr;
  21710. svr.set_mount_point("/static", ".");
  21711. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21712. svr.wait_until_ready();
  21713. Client cli(HOST, PORT);
  21714. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21715. ASSERT_TRUE(res1);
  21716. ASSERT_EQ(200, res1->status);
  21717. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21718. // If-Modified-Since with invalid format should not result in 304
  21719. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21720. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21721. ASSERT_TRUE(res_bad);
  21722. EXPECT_EQ(200, res_bad->status);
  21723. // If-Range with invalid date format should be treated as mismatch -> full
  21724. // content (200)
  21725. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21726. {"If-Range", "invalid-date"}};
  21727. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21728. ASSERT_TRUE(res_ifrange);
  21729. EXPECT_EQ(200, res_ifrange->status);
  21730. svr.stop();
  21731. t.join();
  21732. std::remove(fname);
  21733. }
  21734. TEST(ETagTest, IfRangeWithMalformedETag) {
  21735. using namespace httplib;
  21736. const char *fname = "ifrange_malformed.txt";
  21737. const std::string content = "0123456789";
  21738. {
  21739. std::ofstream ofs(fname);
  21740. ofs << content;
  21741. ASSERT_TRUE(ofs.good());
  21742. }
  21743. Server svr;
  21744. svr.set_mount_point("/static", ".");
  21745. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21746. svr.wait_until_ready();
  21747. Client cli(HOST, PORT);
  21748. // First request: get ETag
  21749. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21750. ASSERT_TRUE(res1);
  21751. ASSERT_EQ(200, res1->status);
  21752. ASSERT_TRUE(res1->has_header("ETag"));
  21753. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21754. // full content (200)
  21755. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21756. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21757. ASSERT_TRUE(res2);
  21758. EXPECT_EQ(200, res2->status);
  21759. EXPECT_EQ(content, res2->body);
  21760. svr.stop();
  21761. t.join();
  21762. std::remove(fname);
  21763. }
  21764. TEST(ETagTest, ExtremeLargeDateValues) {
  21765. using namespace httplib;
  21766. const char *fname = "ims_extreme_date.txt";
  21767. const char *content = "ims-extreme-date";
  21768. {
  21769. std::ofstream ofs(fname);
  21770. ofs << content;
  21771. ASSERT_TRUE(ofs.good());
  21772. }
  21773. Server svr;
  21774. svr.set_mount_point("/static", ".");
  21775. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21776. svr.wait_until_ready();
  21777. Client cli(HOST, PORT);
  21778. auto res1 = cli.Get(std::string("/static/") + fname);
  21779. ASSERT_TRUE(res1);
  21780. ASSERT_EQ(200, res1->status);
  21781. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21782. // Extremely large year that may overflow date parsing routines.
  21783. Headers h_large_date = {
  21784. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21785. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21786. ASSERT_TRUE(res_bad);
  21787. // Expect server to treat this as invalid/mismatch and return full content
  21788. EXPECT_EQ(200, res_bad->status);
  21789. // If-Range with extremely large date should be treated as mismatch -> full
  21790. // content (200)
  21791. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21792. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21793. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21794. ASSERT_TRUE(res_ifrange);
  21795. EXPECT_EQ(200, res_ifrange->status);
  21796. svr.stop();
  21797. t.join();
  21798. std::remove(fname);
  21799. }
  21800. TEST(ETagTest, NegativeFileModificationTime) {
  21801. using namespace httplib;
  21802. const char *fname = "ims_negative_mtime.txt";
  21803. const std::string content = "negative-mtime";
  21804. {
  21805. std::ofstream ofs(fname);
  21806. ofs << content;
  21807. ASSERT_TRUE(ofs.good());
  21808. }
  21809. // Try to set file mtime to a negative value. This may fail on some
  21810. // platforms/filesystems; if it fails, the test will still verify server
  21811. // behaves safely by performing a regular conditional request.
  21812. #if defined(__APPLE__) || defined(__linux__)
  21813. bool set_negative = false;
  21814. do {
  21815. struct timeval times[2];
  21816. // access time: now
  21817. times[0].tv_sec = time(nullptr);
  21818. times[0].tv_usec = 0;
  21819. // modification time: negative (e.g., -1)
  21820. times[1].tv_sec = -1;
  21821. times[1].tv_usec = 0;
  21822. if (utimes(fname, times) == 0) { set_negative = true; }
  21823. } while (0);
  21824. #else
  21825. bool set_negative = false;
  21826. #endif
  21827. Server svr;
  21828. svr.set_mount_point("/static", ".");
  21829. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21830. svr.wait_until_ready();
  21831. Client cli(HOST, PORT);
  21832. auto res1 = cli.Get(std::string("/static/") + fname);
  21833. ASSERT_TRUE(res1);
  21834. ASSERT_EQ(200, res1->status);
  21835. bool has_last_modified = res1->has_header("Last-Modified");
  21836. std::string last_modified;
  21837. if (has_last_modified) {
  21838. last_modified = res1->get_header_value("Last-Modified");
  21839. }
  21840. if (set_negative) {
  21841. // If we successfully set a negative mtime, ensure server returns a
  21842. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21843. // with an old date and ensure server handles it without crash.
  21844. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21845. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21846. ASSERT_TRUE(res2);
  21847. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21848. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21849. } else {
  21850. // Could not set negative mtime on this platform; fall back to verifying
  21851. // that normal invalid/malformed dates are treated safely (non-304).
  21852. Headers h_bad_date = {
  21853. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21854. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21855. ASSERT_TRUE(res_bad);
  21856. EXPECT_EQ(200, res_bad->status);
  21857. }
  21858. svr.stop();
  21859. t.join();
  21860. std::remove(fname);
  21861. }
  21862. //==============================================================================
  21863. // Integration Tests with Server
  21864. //==============================================================================
  21865. class SSEIntegrationTest : public ::testing::Test {
  21866. protected:
  21867. void SetUp() override {
  21868. stop_server_.store(false);
  21869. events_.clear();
  21870. server_ = httplib::detail::make_unique<Server>();
  21871. setup_server();
  21872. start_server();
  21873. }
  21874. void TearDown() override {
  21875. stop_server_.store(true);
  21876. event_cv_.notify_all();
  21877. server_->stop();
  21878. if (server_thread_.joinable()) { server_thread_.join(); }
  21879. }
  21880. void setup_server() {
  21881. // Simple SSE endpoint
  21882. server_->Get("/events", [this](const Request &req, Response &res) {
  21883. auto last_id = req.get_header_value("Last-Event-ID");
  21884. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21885. res.set_chunked_content_provider(
  21886. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21887. std::unique_lock<std::mutex> lock(event_mutex_);
  21888. if (event_cv_.wait_for(
  21889. lock, std::chrono::milliseconds(200), [this] {
  21890. return !events_.empty() || stop_server_.load();
  21891. })) {
  21892. if (stop_server_.load()) { return false; }
  21893. if (!events_.empty()) {
  21894. std::string event = events_.front();
  21895. events_.erase(events_.begin());
  21896. sink.write(event.data(), event.size());
  21897. return true;
  21898. }
  21899. }
  21900. return !stop_server_.load();
  21901. });
  21902. });
  21903. // Endpoint that returns error
  21904. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21905. res.status = 500;
  21906. res.set_content("Internal Server Error", "text/plain");
  21907. });
  21908. // Endpoint for custom event types
  21909. server_->Get("/custom-events", [](const Request &, Response &res) {
  21910. res.set_chunked_content_provider(
  21911. "text/event-stream", [](size_t offset, DataSink &sink) {
  21912. if (offset == 0) {
  21913. std::string event = "event: update\ndata: updated\n\n"
  21914. "event: delete\ndata: deleted\n\n";
  21915. sink.write(event.data(), event.size());
  21916. }
  21917. return false; // End stream after sending
  21918. });
  21919. });
  21920. }
  21921. void start_server() {
  21922. port_ = server_->bind_to_any_port(HOST);
  21923. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21924. // Wait for server to start
  21925. while (!server_->is_running()) {
  21926. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21927. }
  21928. }
  21929. int get_port() const { return port_; }
  21930. void send_event(const std::string &event) {
  21931. std::lock_guard<std::mutex> lock(event_mutex_);
  21932. events_.push_back(event);
  21933. event_cv_.notify_all();
  21934. }
  21935. std::unique_ptr<Server> server_;
  21936. std::thread server_thread_;
  21937. std::mutex event_mutex_;
  21938. std::condition_variable event_cv_;
  21939. std::vector<std::string> events_;
  21940. std::atomic<bool> stop_server_{false};
  21941. std::string last_received_event_id_;
  21942. int port_ = 0;
  21943. };
  21944. //==============================================================================
  21945. // SSE Parsing Tests
  21946. //==============================================================================
  21947. class SSEParsingTest : public SSEIntegrationTest {
  21948. protected:
  21949. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21950. // A trailing sentinel event tells when the whole stream has been parsed.
  21951. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21952. auto body = stream + "event: end\ndata: end\n\n";
  21953. server_->Get("/parse", [body](const Request &, Response &res) {
  21954. res.set_content(body, "text/event-stream");
  21955. });
  21956. return collect("/parse");
  21957. }
  21958. // Runs SSEClient against path until an "end" event arrives and returns the
  21959. // messages dispatched before it
  21960. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21961. Client client(HOST, get_port());
  21962. sse::SSEClient sse(client, path);
  21963. std::mutex mutex;
  21964. std::condition_variable cv;
  21965. std::vector<sse::SSEMessage> messages;
  21966. auto done = false;
  21967. sse.on_message([&](const sse::SSEMessage &msg) {
  21968. std::lock_guard<std::mutex> lock(mutex);
  21969. // Ignore a replay from a reconnect that races with stop()
  21970. if (!done) { messages.push_back(msg); }
  21971. });
  21972. sse.on_event("end", [&](const sse::SSEMessage &) {
  21973. std::lock_guard<std::mutex> lock(mutex);
  21974. done = true;
  21975. cv.notify_all();
  21976. });
  21977. sse.set_reconnect_interval(100);
  21978. sse.start_async();
  21979. {
  21980. std::unique_lock<std::mutex> lock(mutex);
  21981. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21982. }
  21983. sse.stop();
  21984. EXPECT_TRUE(done);
  21985. return messages;
  21986. }
  21987. };
  21988. TEST_F(SSEParsingTest, SingleLineData) {
  21989. auto msgs = parse("data: hello\n\n");
  21990. ASSERT_EQ(msgs.size(), 1u);
  21991. EXPECT_EQ(msgs[0].data, "hello");
  21992. EXPECT_EQ(msgs[0].event, "message");
  21993. }
  21994. TEST_F(SSEParsingTest, MultiLineData) {
  21995. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21996. ASSERT_EQ(msgs.size(), 1u);
  21997. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21998. }
  21999. TEST_F(SSEParsingTest, CustomEventType) {
  22000. auto msgs = parse("event: update\ndata: payload\n\n");
  22001. ASSERT_EQ(msgs.size(), 1u);
  22002. EXPECT_EQ(msgs[0].event, "update");
  22003. EXPECT_EQ(msgs[0].data, "payload");
  22004. }
  22005. TEST_F(SSEParsingTest, EventIdHandling) {
  22006. auto msgs = parse("id: 12345\ndata: test\n\n");
  22007. ASSERT_EQ(msgs.size(), 1u);
  22008. EXPECT_EQ(msgs[0].id, "12345");
  22009. }
  22010. TEST_F(SSEParsingTest, EmptyEventId) {
  22011. auto msgs = parse("id:\ndata: test\n\n");
  22012. ASSERT_EQ(msgs.size(), 1u);
  22013. EXPECT_EQ(msgs[0].id, "");
  22014. }
  22015. TEST_F(SSEParsingTest, CommentsIgnored) {
  22016. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  22017. ASSERT_EQ(msgs.size(), 1u);
  22018. EXPECT_EQ(msgs[0].data, "hello");
  22019. EXPECT_EQ(msgs[0].event, "message");
  22020. }
  22021. TEST_F(SSEParsingTest, ColonInValue) {
  22022. auto msgs = parse("data: hello:world:test\n\n");
  22023. ASSERT_EQ(msgs.size(), 1u);
  22024. EXPECT_EQ(msgs[0].data, "hello:world:test");
  22025. }
  22026. TEST_F(SSEParsingTest, FieldNameOnly) {
  22027. // A line without a colon is a field name with an empty value
  22028. auto msgs = parse("data\n\n");
  22029. ASSERT_EQ(msgs.size(), 1u);
  22030. EXPECT_EQ(msgs[0].data, "");
  22031. }
  22032. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  22033. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  22034. ASSERT_EQ(msgs.size(), 1u);
  22035. EXPECT_EQ(msgs[0].event, "update");
  22036. EXPECT_EQ(msgs[0].data, "hello");
  22037. }
  22038. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  22039. auto msgs = parse("data\r\n\r\n");
  22040. ASSERT_EQ(msgs.size(), 1u);
  22041. EXPECT_EQ(msgs[0].data, "");
  22042. }
  22043. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  22044. auto msgs = parse("event: update\rdata: hello\r\r");
  22045. ASSERT_EQ(msgs.size(), 1u);
  22046. EXPECT_EQ(msgs[0].event, "update");
  22047. EXPECT_EQ(msgs[0].data, "hello");
  22048. }
  22049. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  22050. // Chunk boundaries fall inside every \r\n and right before the first one
  22051. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  22052. "\n\r", "\nevent: end\ndata: end\n\n"};
  22053. server_->Get("/split", [chunks](const Request &, Response &res) {
  22054. auto i = std::make_shared<size_t>(0);
  22055. res.set_chunked_content_provider(
  22056. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  22057. if (*i == chunks.size()) {
  22058. sink.done();
  22059. } else {
  22060. sink.write(chunks[*i].data(), chunks[*i].size());
  22061. (*i)++;
  22062. }
  22063. return true;
  22064. });
  22065. });
  22066. auto msgs = collect("/split");
  22067. ASSERT_EQ(msgs.size(), 1u);
  22068. EXPECT_EQ(msgs[0].event, "update");
  22069. EXPECT_EQ(msgs[0].data, "hello");
  22070. }
  22071. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22072. // Only a BOM at the start of the stream is ignored
  22073. auto msgs = parse("\xEF\xBB\xBF"
  22074. "data: first\n\n"
  22075. "\xEF\xBB\xBF"
  22076. "data: second\n\n");
  22077. ASSERT_EQ(msgs.size(), 1u);
  22078. EXPECT_EQ(msgs[0].data, "first");
  22079. }
  22080. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22081. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22082. ASSERT_EQ(msgs.size(), 1u);
  22083. EXPECT_EQ(msgs[0].data, "hello");
  22084. EXPECT_EQ(msgs[0].event, "message");
  22085. }
  22086. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22087. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22088. ASSERT_EQ(msgs.size(), 2u);
  22089. EXPECT_EQ(msgs[0].data, "hello");
  22090. EXPECT_EQ(msgs[1].data, "hello");
  22091. }
  22092. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22093. // An event without data is not dispatched, and its type must not leak
  22094. // into the next event
  22095. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22096. ASSERT_EQ(msgs.size(), 1u);
  22097. EXPECT_EQ(msgs[0].event, "message");
  22098. EXPECT_EQ(msgs[0].data, "hello");
  22099. }
  22100. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22101. // Also when the empty field replaces an earlier type
  22102. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22103. ASSERT_EQ(msgs.size(), 2u);
  22104. EXPECT_EQ(msgs[0].event, "message");
  22105. EXPECT_EQ(msgs[1].event, "message");
  22106. }
  22107. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22108. // The first connection sends only an id; the second echoes back the
  22109. // Last-Event-ID it was reconnected with
  22110. std::atomic<int> connection_count{0};
  22111. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22112. if (connection_count++ == 0) {
  22113. res.set_content("id: 42\n\n", "text/event-stream");
  22114. } else {
  22115. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22116. "\n\nevent: end\ndata: end\n\n",
  22117. "text/event-stream");
  22118. }
  22119. });
  22120. auto msgs = collect("/id-only");
  22121. ASSERT_EQ(msgs.size(), 1u);
  22122. EXPECT_EQ(msgs[0].data, "42");
  22123. }
  22124. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22125. // The first connection sets an id and then clears it with an empty one; the
  22126. // second reports whether it was reconnected with a Last-Event-ID
  22127. std::atomic<int> connection_count{0};
  22128. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22129. if (connection_count++ == 0) {
  22130. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22131. "text/event-stream");
  22132. } else {
  22133. res.set_content(
  22134. std::string("data: ") +
  22135. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22136. "\n\nevent: end\ndata: end\n\n",
  22137. "text/event-stream");
  22138. }
  22139. });
  22140. auto msgs = collect("/id-clear");
  22141. ASSERT_EQ(msgs.size(), 3u);
  22142. EXPECT_EQ(msgs[0].id, "1");
  22143. EXPECT_EQ(msgs[1].id, "");
  22144. EXPECT_EQ(msgs[2].data, "not sent");
  22145. }
  22146. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22147. // The first connection sets an id and then sends ids that cannot be carried
  22148. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22149. // with
  22150. std::atomic<int> connection_count{0};
  22151. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22152. if (connection_count++ == 0) {
  22153. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22154. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22155. "text/event-stream");
  22156. } else {
  22157. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22158. "\n\nevent: end\ndata: end\n\n",
  22159. "text/event-stream");
  22160. }
  22161. });
  22162. auto msgs = collect("/id-unsendable");
  22163. ASSERT_EQ(msgs.size(), 1u);
  22164. EXPECT_EQ(msgs[0].data, "42");
  22165. }
  22166. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22167. auto msgs = parse("event: notification\nid: evt-42\n"
  22168. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22169. ASSERT_EQ(msgs.size(), 1u);
  22170. EXPECT_EQ(msgs[0].event, "notification");
  22171. EXPECT_EQ(msgs[0].id, "evt-42");
  22172. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22173. }
  22174. TEST(SSEMessageTest, Clear) {
  22175. sse::SSEMessage msg;
  22176. msg.event = "custom";
  22177. msg.data = "some data";
  22178. msg.id = "123";
  22179. msg.clear();
  22180. EXPECT_EQ(msg.event, "message");
  22181. EXPECT_EQ(msg.data, "");
  22182. EXPECT_EQ(msg.id, "");
  22183. }
  22184. //==============================================================================
  22185. // SSE Integration Tests
  22186. //==============================================================================
  22187. // Test: Successful connection and on_open callback
  22188. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22189. // Add a simple endpoint that sends one event and closes
  22190. server_->Get("/simple-event", [](const Request &, Response &res) {
  22191. res.set_chunked_content_provider(
  22192. "text/event-stream", [](size_t offset, DataSink &sink) {
  22193. if (offset == 0) {
  22194. std::string event = "data: hello\n\n";
  22195. sink.write(event.data(), event.size());
  22196. }
  22197. return false; // Close stream after sending
  22198. });
  22199. });
  22200. Client client("localhost", get_port());
  22201. sse::SSEClient sse(client, "/simple-event");
  22202. std::atomic<bool> open_called{false};
  22203. std::atomic<bool> message_received{false};
  22204. sse.on_open([&open_called]() { open_called.store(true); });
  22205. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22206. if (msg.data == "hello") { message_received.store(true); }
  22207. });
  22208. sse.set_reconnect_interval(100);
  22209. sse.set_max_reconnect_attempts(1);
  22210. // Start async
  22211. sse.start_async();
  22212. // Wait for message to be processed
  22213. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22214. sse.stop();
  22215. EXPECT_TRUE(open_called.load());
  22216. EXPECT_TRUE(message_received.load());
  22217. }
  22218. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22219. // A data line that never ends.
  22220. server_->Get("/endless-line", [](const Request &, Response &res) {
  22221. res.set_chunked_content_provider(
  22222. "text/event-stream", [](size_t offset, DataSink &sink) {
  22223. if (offset == 0) { sink.write("data: ", 6); }
  22224. std::string chunk(64 * 1024, 'A');
  22225. return sink.write(chunk.data(), chunk.size());
  22226. });
  22227. });
  22228. Client client("localhost", get_port());
  22229. sse::SSEClient sse(client, "/endless-line");
  22230. std::atomic<bool> too_long{false};
  22231. sse.on_error([&](Error err) {
  22232. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22233. });
  22234. sse.set_max_reconnect_attempts(1);
  22235. sse.start_async();
  22236. for (int i = 0; i < 500 && !too_long; i++) {
  22237. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22238. }
  22239. sse.stop();
  22240. EXPECT_TRUE(too_long);
  22241. }
  22242. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22243. // Far more in all than the client's payload limit below.
  22244. server_->Get("/many-events", [](const Request &, Response &res) {
  22245. res.set_chunked_content_provider(
  22246. "text/event-stream", [](size_t offset, DataSink &sink) {
  22247. if (offset == 0) {
  22248. std::string events;
  22249. for (int i = 0; i < 1000; i++) {
  22250. events += "data: message\n\n";
  22251. }
  22252. sink.write(events.data(), events.size());
  22253. }
  22254. return false;
  22255. });
  22256. });
  22257. Client client("localhost", get_port());
  22258. client.set_payload_max_length(1024);
  22259. sse::SSEClient sse(client, "/many-events");
  22260. std::atomic<int> messages{0};
  22261. std::atomic<bool> too_large{false};
  22262. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22263. sse.on_error([&](Error err) {
  22264. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22265. });
  22266. sse.set_max_reconnect_attempts(1);
  22267. sse.start_async();
  22268. for (int i = 0; i < 500 && messages < 1000; i++) {
  22269. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22270. }
  22271. sse.stop();
  22272. EXPECT_GE(messages.load(), 1000);
  22273. EXPECT_FALSE(too_large);
  22274. }
  22275. // Test: on_message callback
  22276. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22277. // Endpoint that sends multiple events then closes
  22278. server_->Get("/multi-event", [](const Request &, Response &res) {
  22279. res.set_chunked_content_provider(
  22280. "text/event-stream", [](size_t offset, DataSink &sink) {
  22281. if (offset == 0) {
  22282. std::string events = "data: message1\n\ndata: message2\n\n";
  22283. sink.write(events.data(), events.size());
  22284. }
  22285. return false;
  22286. });
  22287. });
  22288. Client client("localhost", get_port());
  22289. sse::SSEClient sse(client, "/multi-event");
  22290. std::vector<std::string> received_messages;
  22291. std::mutex messages_mutex;
  22292. sse.on_message([&](const sse::SSEMessage &msg) {
  22293. std::lock_guard<std::mutex> lock(messages_mutex);
  22294. received_messages.push_back(msg.data);
  22295. });
  22296. sse.set_reconnect_interval(100);
  22297. sse.set_max_reconnect_attempts(1);
  22298. sse.start_async();
  22299. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22300. sse.stop();
  22301. std::lock_guard<std::mutex> lock(messages_mutex);
  22302. EXPECT_GE(received_messages.size(), 2u);
  22303. if (received_messages.size() >= 2) {
  22304. EXPECT_EQ(received_messages[0], "message1");
  22305. EXPECT_EQ(received_messages[1], "message2");
  22306. }
  22307. }
  22308. // Test: on_event for specific types
  22309. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22310. Client client("localhost", get_port());
  22311. sse::SSEClient sse(client, "/custom-events");
  22312. std::atomic<bool> update_received{false};
  22313. std::atomic<bool> delete_received{false};
  22314. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22315. if (msg.data == "updated") { update_received.store(true); }
  22316. });
  22317. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22318. if (msg.data == "deleted") { delete_received.store(true); }
  22319. });
  22320. sse.set_max_reconnect_attempts(1);
  22321. sse.start_async();
  22322. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22323. sse.stop();
  22324. EXPECT_TRUE(update_received.load());
  22325. EXPECT_TRUE(delete_received.load());
  22326. }
  22327. // Test: on_error callback on connection failure
  22328. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22329. // Connect to a non-existent port
  22330. Client client("localhost", 59999);
  22331. sse::SSEClient sse(client, "/events");
  22332. std::atomic<bool> error_called{false};
  22333. Error received_error = Error::Success;
  22334. sse.on_error([&](Error err) {
  22335. error_called.store(true);
  22336. received_error = err;
  22337. });
  22338. sse.set_reconnect_interval(50);
  22339. sse.set_max_reconnect_attempts(1);
  22340. sse.start_async();
  22341. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22342. sse.stop();
  22343. EXPECT_TRUE(error_called.load());
  22344. EXPECT_NE(received_error, Error::Success);
  22345. }
  22346. // Test: Last-Event-ID header sent on reconnect
  22347. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22348. // Endpoint that sends event with ID
  22349. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22350. res.set_chunked_content_provider(
  22351. "text/event-stream", [](size_t offset, DataSink &sink) {
  22352. if (offset == 0) {
  22353. std::string event = "id: evt-123\ndata: test\n\n";
  22354. sink.write(event.data(), event.size());
  22355. }
  22356. return false;
  22357. });
  22358. });
  22359. Client client("localhost", get_port());
  22360. sse::SSEClient sse(client, "/event-with-id");
  22361. std::atomic<bool> id_received{false};
  22362. sse.on_message([&](const sse::SSEMessage &msg) {
  22363. if (!msg.id.empty()) { id_received.store(true); }
  22364. });
  22365. sse.set_reconnect_interval(100);
  22366. sse.set_max_reconnect_attempts(1);
  22367. sse.start_async();
  22368. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22369. sse.stop();
  22370. EXPECT_TRUE(id_received.load());
  22371. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22372. }
  22373. // Test: last_event_id() read from another thread while start_async() runs
  22374. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22375. // Ids of every length up to 200, so the stored id keeps changing size
  22376. server_->Get("/many-ids", [](const Request &, Response &res) {
  22377. res.set_chunked_content_provider(
  22378. "text/event-stream", [](size_t offset, DataSink &sink) {
  22379. if (offset == 0) {
  22380. std::string events;
  22381. for (size_t i = 0; i < 2000; i++) {
  22382. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22383. events += "data: x\n\n";
  22384. }
  22385. events += "id: end\ndata: x\n\n";
  22386. sink.write(events.data(), events.size());
  22387. }
  22388. return false;
  22389. });
  22390. });
  22391. Client client("localhost", get_port());
  22392. sse::SSEClient sse(client, "/many-ids");
  22393. // Wait out the rest of the test rather than replay the stream
  22394. sse.set_reconnect_interval(10000);
  22395. sse.set_max_reconnect_attempts(1);
  22396. sse.start_async();
  22397. auto well_formed = true;
  22398. std::string id;
  22399. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22400. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22401. id = sse.last_event_id();
  22402. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22403. well_formed = false;
  22404. }
  22405. }
  22406. sse.stop();
  22407. EXPECT_TRUE(well_formed);
  22408. EXPECT_EQ(sse.last_event_id(), "end");
  22409. }
  22410. // Test: Manual stop
  22411. TEST_F(SSEIntegrationTest, ManualStop) {
  22412. // Endpoint that sends one event and stays open briefly. The server outlives
  22413. // this test body, so the provider uses the fixture's flag, not a local.
  22414. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22415. res.set_chunked_content_provider(
  22416. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22417. if (offset == 0) {
  22418. std::string event = "data: connected\n\n";
  22419. sink.write(event.data(), event.size());
  22420. }
  22421. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22422. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22423. }
  22424. return false;
  22425. });
  22426. });
  22427. Client client("localhost", get_port());
  22428. sse::SSEClient sse(client, "/stay-open");
  22429. std::atomic<bool> connected{false};
  22430. sse.on_open([&connected]() { connected.store(true); });
  22431. sse.set_reconnect_interval(100);
  22432. sse.set_max_reconnect_attempts(1);
  22433. sse.start_async();
  22434. // Wait for connection to establish
  22435. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22436. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22437. }
  22438. EXPECT_TRUE(connected.load());
  22439. EXPECT_TRUE(sse.is_connected());
  22440. // Signal handler to stop
  22441. stop_server_.store(true);
  22442. // Stop SSE client
  22443. sse.stop();
  22444. EXPECT_FALSE(sse.is_connected());
  22445. }
  22446. // Sends one event, then nothing until stop is set
  22447. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22448. return [&stop](const Request &, Response &res) {
  22449. res.set_chunked_content_provider(
  22450. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22451. if (offset == 0) {
  22452. std::string event = "data: hello\n\n";
  22453. sink.write(event.data(), event.size());
  22454. }
  22455. while (!stop.load()) {
  22456. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22457. }
  22458. return false;
  22459. });
  22460. };
  22461. }
  22462. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22463. static void check_stop_interrupts_blocked_read(Client &client) {
  22464. client.set_read_timeout(30, 0);
  22465. for (auto by_destructor : {false, true}) {
  22466. std::atomic<bool> received{false};
  22467. std::chrono::steady_clock::time_point start;
  22468. {
  22469. sse::SSEClient sse(client, "/idle-stream");
  22470. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22471. sse.start_async();
  22472. for (int i = 0; i < 500 && !received.load(); ++i) {
  22473. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22474. }
  22475. ASSERT_TRUE(received.load());
  22476. // Let the client block in the next read
  22477. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22478. start = std::chrono::steady_clock::now();
  22479. if (!by_destructor) { sse.stop(); }
  22480. }
  22481. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22482. std::chrono::seconds(2));
  22483. }
  22484. }
  22485. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22486. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22487. Client client("localhost", get_port());
  22488. check_stop_interrupts_blocked_read(client);
  22489. }
  22490. #ifdef CPPHTTPLIB_SSL_ENABLED
  22491. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22493. std::atomic<bool> done{false};
  22494. svr.Get("/idle-stream", idle_event_stream(done));
  22495. auto port = svr.bind_to_any_port(HOST);
  22496. std::thread t([&] { svr.listen_after_bind(); });
  22497. auto se = detail::scope_exit([&] {
  22498. done.store(true);
  22499. svr.stop();
  22500. t.join();
  22501. });
  22502. svr.wait_until_ready();
  22503. Client client("https://localhost:" + std::to_string(port));
  22504. client.enable_server_certificate_verification(false);
  22505. check_stop_interrupts_blocked_read(client);
  22506. }
  22507. #endif
  22508. // Test: SSEClient with custom headers
  22509. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22510. // Setup a server endpoint that checks for custom header
  22511. std::atomic<bool> header_received{false};
  22512. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22513. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22514. header_received.store(true);
  22515. }
  22516. res.set_chunked_content_provider("text/event-stream",
  22517. [](size_t, DataSink &) { return false; });
  22518. });
  22519. Client client("localhost", get_port());
  22520. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22521. sse::SSEClient sse(client, "/header-check", headers);
  22522. sse.set_max_reconnect_attempts(1);
  22523. sse.start_async();
  22524. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22525. sse.stop();
  22526. EXPECT_TRUE(header_received.load());
  22527. }
  22528. // Test: Reconnect interval configuration
  22529. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22530. Client client("localhost", get_port());
  22531. sse::SSEClient sse(client, "/events");
  22532. auto &result = sse.set_reconnect_interval(500);
  22533. // Builder pattern should return reference to self
  22534. EXPECT_EQ(&result, &sse);
  22535. }
  22536. // Test: Max reconnect attempts
  22537. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22538. // Connect to non-existent port to force reconnects
  22539. Client client("localhost", 59998);
  22540. sse::SSEClient sse(client, "/events");
  22541. std::atomic<int> error_count{0};
  22542. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22543. sse.set_reconnect_interval(50);
  22544. sse.set_max_reconnect_attempts(2);
  22545. auto start = std::chrono::steady_clock::now();
  22546. sse.start(); // Blocking call
  22547. auto end = std::chrono::steady_clock::now();
  22548. // Should have stopped after 2 failed attempts
  22549. EXPECT_GE(error_count.load(), 2);
  22550. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22551. auto duration =
  22552. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22553. #ifdef _WIN32
  22554. // Windows is much slower for socket connection failures
  22555. EXPECT_LT(duration.count(), 7000);
  22556. #else
  22557. EXPECT_LT(duration.count(), 1000);
  22558. #endif
  22559. }
  22560. // Test: Multi-line data in integration
  22561. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22562. // Endpoint with multi-line data
  22563. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22564. res.set_chunked_content_provider(
  22565. "text/event-stream", [](size_t offset, DataSink &sink) {
  22566. if (offset == 0) {
  22567. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22568. sink.write(event.data(), event.size());
  22569. }
  22570. return false;
  22571. });
  22572. });
  22573. Client client("localhost", get_port());
  22574. sse::SSEClient sse(client, "/multiline-data");
  22575. std::string received_data;
  22576. std::mutex data_mutex;
  22577. sse.on_message([&](const sse::SSEMessage &msg) {
  22578. std::lock_guard<std::mutex> lock(data_mutex);
  22579. received_data = msg.data;
  22580. });
  22581. sse.set_reconnect_interval(100);
  22582. sse.set_max_reconnect_attempts(1);
  22583. sse.start_async();
  22584. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22585. sse.stop();
  22586. std::lock_guard<std::mutex> lock(data_mutex);
  22587. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22588. }
  22589. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22590. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22591. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22592. DataSink &sink) {
  22593. if (offset == 0) {
  22594. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22595. sink.write(events.data(), events.size());
  22596. }
  22597. return false;
  22598. });
  22599. });
  22600. Client client("localhost", get_port());
  22601. sse::SSEClient sse(client, "/empty-data-lines");
  22602. std::mutex mutex;
  22603. std::condition_variable cv;
  22604. std::vector<std::string> received;
  22605. sse.on_message([&](const sse::SSEMessage &msg) {
  22606. std::lock_guard<std::mutex> lock(mutex);
  22607. received.push_back(msg.data);
  22608. cv.notify_all();
  22609. });
  22610. sse.set_max_reconnect_attempts(1);
  22611. sse.start_async();
  22612. {
  22613. std::unique_lock<std::mutex> lock(mutex);
  22614. cv.wait_for(lock, std::chrono::seconds(2),
  22615. [&] { return received.size() >= 3; });
  22616. }
  22617. sse.stop();
  22618. ASSERT_GE(received.size(), 3u);
  22619. EXPECT_EQ(received[0], "");
  22620. EXPECT_EQ(received[1], "\nhello");
  22621. EXPECT_EQ(received[2], "");
  22622. }
  22623. // Test: Auto-reconnect after server disconnection
  22624. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22625. std::atomic<int> connection_count{0};
  22626. std::atomic<int> message_count{0};
  22627. // Endpoint that sends one event and closes, forcing reconnect
  22628. server_->Get("/reconnect-test",
  22629. [&connection_count](const Request &, Response &res) {
  22630. connection_count.fetch_add(1);
  22631. res.set_chunked_content_provider(
  22632. "text/event-stream", [](size_t offset, DataSink &sink) {
  22633. if (offset == 0) {
  22634. std::string event = "data: hello\n\n";
  22635. sink.write(event.data(), event.size());
  22636. }
  22637. return false; // Close connection after sending
  22638. });
  22639. });
  22640. Client client("localhost", get_port());
  22641. sse::SSEClient sse(client, "/reconnect-test");
  22642. sse.on_message([&message_count](const sse::SSEMessage &) {
  22643. message_count.fetch_add(1);
  22644. });
  22645. sse.set_reconnect_interval(100);
  22646. sse.set_max_reconnect_attempts(3);
  22647. sse.start_async();
  22648. // Wait long enough for multiple reconnects
  22649. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22650. sse.stop();
  22651. // Should have connected multiple times (initial + reconnects)
  22652. EXPECT_GE(connection_count.load(), 2);
  22653. // Should have received messages from multiple connections
  22654. EXPECT_GE(message_count.load(), 2);
  22655. }
  22656. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22657. std::atomic<int> connection_count{0};
  22658. // Neither Content-Length nor chunked: the close ends the stream
  22659. server_->Get("/close-delimited",
  22660. [&connection_count](const Request &, Response &res) {
  22661. connection_count.fetch_add(1);
  22662. res.set_content_provider(
  22663. "text/event-stream", [](size_t offset, DataSink &sink) {
  22664. if (offset == 0) {
  22665. std::string event = "data: hello\n\n";
  22666. sink.write(event.data(), event.size());
  22667. } else {
  22668. sink.done();
  22669. }
  22670. return true;
  22671. });
  22672. });
  22673. Client client("localhost", get_port());
  22674. sse::SSEClient sse(client, "/close-delimited");
  22675. std::atomic<int> error_count{0};
  22676. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22677. sse.set_reconnect_interval(100);
  22678. sse.start_async();
  22679. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22680. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22681. }
  22682. sse.stop();
  22683. // Reconnects as after any end of the stream, but reports no error
  22684. EXPECT_GE(connection_count.load(), 2);
  22685. EXPECT_EQ(0, error_count.load());
  22686. }
  22687. // Test: A retry field that is not all ASCII digits is ignored
  22688. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22689. std::atomic<int> connection_count{0};
  22690. server_->Get("/bad-retry",
  22691. [&connection_count](const Request &, Response &res) {
  22692. connection_count.fetch_add(1);
  22693. res.set_chunked_content_provider(
  22694. "text/event-stream", [](size_t offset, DataSink &sink) {
  22695. if (offset == 0) {
  22696. std::string event = "retry: -1\ndata: hello\n\n";
  22697. sink.write(event.data(), event.size());
  22698. }
  22699. return false;
  22700. });
  22701. });
  22702. Client client("localhost", get_port());
  22703. sse::SSEClient sse(client, "/bad-retry");
  22704. sse.set_reconnect_interval(10000);
  22705. sse.start_async();
  22706. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22707. sse.stop();
  22708. EXPECT_EQ(connection_count.load(), 1);
  22709. }
  22710. // Test: A retry field of all ASCII digits sets the reconnection time
  22711. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22712. std::mutex mutex;
  22713. std::condition_variable cv;
  22714. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22715. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22716. {
  22717. std::lock_guard<std::mutex> lock(mutex);
  22718. connected_at.push_back(std::chrono::steady_clock::now());
  22719. cv.notify_all();
  22720. }
  22721. res.set_chunked_content_provider(
  22722. "text/event-stream", [](size_t offset, DataSink &sink) {
  22723. if (offset == 0) {
  22724. std::string event = "retry: 0\ndata: hello\n\n";
  22725. sink.write(event.data(), event.size());
  22726. }
  22727. return false;
  22728. });
  22729. });
  22730. Client client("localhost", get_port());
  22731. sse::SSEClient sse(client, "/zero-retry");
  22732. sse.set_reconnect_interval(10000);
  22733. sse.start_async();
  22734. {
  22735. std::unique_lock<std::mutex> lock(mutex);
  22736. cv.wait_for(lock, std::chrono::seconds(5),
  22737. [&] { return connected_at.size() >= 2; });
  22738. }
  22739. sse.stop();
  22740. // The server-supplied interval is applied, but never below 100ms, so
  22741. // "retry: 0" does not cause a busy reconnect loop
  22742. std::lock_guard<std::mutex> lock(mutex);
  22743. ASSERT_GE(connected_at.size(), 2u);
  22744. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22745. connected_at[1] - connected_at[0])
  22746. .count();
  22747. EXPECT_GE(interval_ms, 100);
  22748. }
  22749. // Test: Last-Event-ID sent on reconnect
  22750. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22751. std::atomic<int> connection_count{0};
  22752. std::vector<std::string> received_last_event_ids;
  22753. std::mutex id_mutex;
  22754. // Endpoint that checks Last-Event-ID header and sends event with ID
  22755. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22756. int conn = connection_count.fetch_add(1);
  22757. // Capture the Last-Event-ID header from each connection
  22758. {
  22759. std::lock_guard<std::mutex> lock(id_mutex);
  22760. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22761. }
  22762. res.set_chunked_content_provider(
  22763. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22764. if (offset == 0) {
  22765. std::string event =
  22766. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22767. sink.write(event.data(), event.size());
  22768. }
  22769. return false;
  22770. });
  22771. });
  22772. Client client("localhost", get_port());
  22773. sse::SSEClient sse(client, "/reconnect-with-id");
  22774. sse.set_reconnect_interval(100);
  22775. sse.set_max_reconnect_attempts(3);
  22776. sse.start_async();
  22777. // Wait for at least 2 connections
  22778. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22779. sse.stop();
  22780. // Verify behavior
  22781. std::lock_guard<std::mutex> lock(id_mutex);
  22782. EXPECT_GE(received_last_event_ids.size(), 2u);
  22783. // First connection should have no Last-Event-ID
  22784. if (!received_last_event_ids.empty()) {
  22785. EXPECT_EQ(received_last_event_ids[0], "");
  22786. }
  22787. // Second connection should have Last-Event-ID from first connection
  22788. if (received_last_event_ids.size() >= 2) {
  22789. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22790. }
  22791. }
  22792. // Test: set_headers updates headers used on reconnect
  22793. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22794. std::vector<std::string> received_tokens;
  22795. std::mutex token_mutex;
  22796. // Endpoint that captures Authorization header
  22797. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22798. {
  22799. std::lock_guard<std::mutex> lock(token_mutex);
  22800. received_tokens.push_back(req.get_header_value("Authorization"));
  22801. }
  22802. res.set_chunked_content_provider(
  22803. "text/event-stream", [](size_t offset, DataSink &sink) {
  22804. if (offset == 0) {
  22805. std::string event = "data: hello\n\n";
  22806. sink.write(event.data(), event.size());
  22807. }
  22808. return false; // Close connection to trigger reconnect
  22809. });
  22810. });
  22811. Client client("localhost", get_port());
  22812. Headers headers = {{"Authorization", "Bearer old-token"}};
  22813. sse::SSEClient sse(client, "/auth-check", headers);
  22814. // Update headers on each successful connection
  22815. sse.on_open(
  22816. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22817. sse.set_reconnect_interval(100);
  22818. sse.set_max_reconnect_attempts(3);
  22819. sse.start_async();
  22820. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22821. sse.stop();
  22822. std::lock_guard<std::mutex> lock(token_mutex);
  22823. ASSERT_GE(received_tokens.size(), 2u);
  22824. // First connection uses original header
  22825. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22826. // Second connection uses updated header from set_headers
  22827. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22828. }
  22829. // Test: 401 allows reconnection (so on_error can refresh headers)
  22830. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22831. std::atomic<int> connection_count{0};
  22832. // Endpoint: returns 401 on first attempt, 200 on second
  22833. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22834. int conn = connection_count.fetch_add(1);
  22835. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22836. res.status = StatusCode::Unauthorized_401;
  22837. res.set_content("Unauthorized", "text/plain");
  22838. return;
  22839. }
  22840. res.set_chunked_content_provider(
  22841. "text/event-stream", [](size_t offset, DataSink &sink) {
  22842. if (offset == 0) {
  22843. std::string event = "data: authenticated\n\n";
  22844. sink.write(event.data(), event.size());
  22845. }
  22846. return false;
  22847. });
  22848. });
  22849. Client client("localhost", get_port());
  22850. Headers headers = {{"Authorization", "Bearer expired"}};
  22851. sse::SSEClient sse(client, "/auth-retry", headers);
  22852. std::atomic<bool> message_received{false};
  22853. // Refresh token on error
  22854. sse.on_error(
  22855. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22856. sse.on_message([&](const sse::SSEMessage &msg) {
  22857. if (msg.data == "authenticated") { message_received.store(true); }
  22858. });
  22859. sse.set_reconnect_interval(100);
  22860. sse.set_max_reconnect_attempts(3);
  22861. sse.start_async();
  22862. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22863. sse.stop();
  22864. // Should have reconnected after 401 and succeeded with new token
  22865. EXPECT_GE(connection_count.load(), 2);
  22866. EXPECT_TRUE(message_received.load());
  22867. }
  22868. TEST(Issue2318Test, EmptyHostString) {
  22869. {
  22870. httplib::Client cli_empty("", PORT);
  22871. auto res = cli_empty.Get("/");
  22872. ASSERT_FALSE(res);
  22873. EXPECT_EQ(httplib::Error::Connection, res.error());
  22874. }
  22875. {
  22876. httplib::Client cli(" ", PORT);
  22877. auto res = cli.Get("/");
  22878. ASSERT_FALSE(res);
  22879. EXPECT_EQ(httplib::Error::Connection, res.error());
  22880. }
  22881. }
  22882. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22883. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22884. Server svr;
  22885. // Set a small payload limit (1KB)
  22886. svr.set_payload_max_length(1024);
  22887. svr.Post("/test", [&](const Request &req, Response &res) {
  22888. res.set_content("Body size: " + std::to_string(req.body.size()),
  22889. "text/plain");
  22890. });
  22891. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22892. auto se = detail::scope_exit([&] {
  22893. svr.stop();
  22894. listen_thread.join();
  22895. });
  22896. svr.wait_until_ready();
  22897. // Create data that compresses well but exceeds limit when decompressed
  22898. // 8KB of repeated null bytes compresses to a very small size
  22899. std::string original_data(8 * 1024, '\0');
  22900. // Compress the data using gzip
  22901. std::string compressed_data;
  22902. detail::gzip_compressor compressor;
  22903. compressor.compress(original_data.data(), original_data.size(), true,
  22904. [&](const char *data, size_t size) {
  22905. compressed_data.append(data, size);
  22906. return true;
  22907. });
  22908. // Verify compression worked (compressed should be much smaller)
  22909. ASSERT_LT(compressed_data.size(), original_data.size());
  22910. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22911. // Send compressed data with Content-Encoding: gzip
  22912. Client cli(HOST, PORT);
  22913. Headers headers = {{"Content-Encoding", "gzip"}};
  22914. auto res =
  22915. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22916. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22918. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22919. }
  22920. #endif
  22921. // ============================================================================
  22922. // OpenSSL-Specific Tests
  22923. // ============================================================================
  22924. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22925. X509 *readCertificate(const std::string &strFileName) {
  22926. std::ifstream inStream(strFileName);
  22927. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22928. std::istreambuf_iterator<char>());
  22929. if (strCertPEM.empty()) return (nullptr);
  22930. BIO *pbCert = BIO_new(BIO_s_mem());
  22931. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22932. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22933. BIO_free(pbCert);
  22934. return (pCert);
  22935. }
  22936. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22937. std::ifstream inStream(strFileName);
  22938. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22939. std::istreambuf_iterator<char>());
  22940. if (strPrivateKeyPEM.empty()) return (nullptr);
  22941. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22942. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22943. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22944. BIO_free(pbPrivKey);
  22945. return (pPrivateKey);
  22946. }
  22947. TEST(BindServerTest, UpdateCerts) {
  22948. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22949. int port = svr.bind_to_any_port("0.0.0.0");
  22950. ASSERT_TRUE(svr.is_valid());
  22951. ASSERT_TRUE(port > 0);
  22952. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22953. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22954. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22955. ASSERT_TRUE(cert != nullptr);
  22956. ASSERT_TRUE(ca_cert != nullptr);
  22957. ASSERT_TRUE(key != nullptr);
  22958. X509_STORE *cert_store = X509_STORE_new();
  22959. X509_STORE_add_cert(cert_store, ca_cert);
  22960. // svr.update_certs(cert, key, cert_store); // deprecated
  22961. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22962. CLIENT_CA_CERT_FILE);
  22963. ASSERT_TRUE(svr.is_valid());
  22964. svr.stop();
  22965. X509_STORE_free(cert_store);
  22966. X509_free(cert);
  22967. X509_free(ca_cert);
  22968. EVP_PKEY_free(key);
  22969. }
  22970. // Test that update_certs() updates client CA list correctly
  22971. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22972. // Start with file-based constructor
  22973. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22974. ASSERT_TRUE(svr.is_valid());
  22975. // Initially no client CA list should be set
  22976. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22977. ASSERT_TRUE(ssl_ctx != nullptr);
  22978. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22979. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22980. // Now update with client CA (PEM string)
  22981. std::string cert_pem, key_pem, ca_pem;
  22982. read_file(SERVER_CERT_FILE, cert_pem);
  22983. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22984. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22985. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22986. ASSERT_TRUE(svr.is_valid());
  22987. // Now client CA list should be set
  22988. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22989. ASSERT_TRUE(ca_list_after != nullptr);
  22990. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22991. }
  22992. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22993. // Test that the file-path SSLServer constructor properly sets the client CA
  22994. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22996. ASSERT_TRUE(svr.is_valid());
  22997. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22998. ASSERT_TRUE(ssl_ctx != nullptr);
  22999. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23000. ASSERT_TRUE(ca_list != nullptr);
  23001. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23002. }
  23003. #endif
  23004. // ============================================================================
  23005. // MbedTLS-Specific Tests
  23006. // ============================================================================
  23007. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23008. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23009. using namespace httplib::tls;
  23010. // Track if callback was invoked
  23011. bool callback_invoked = false;
  23012. // The callback receives void* ctx which is actually MbedTlsContext*
  23013. // We can access the mbedtls_ssl_config via the context
  23014. auto setup_callback = [&callback_invoked](void *ctx) {
  23015. callback_invoked = true;
  23016. // Cast to MbedTlsContext* to access the ssl config
  23017. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23018. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23019. // Use static variables to hold certificate data (simplified for test)
  23020. static mbedtls_x509_crt own_cert;
  23021. static mbedtls_pk_context own_key;
  23022. static mbedtls_x509_crt ca_chain;
  23023. static bool initialized = false;
  23024. if (!initialized) {
  23025. mbedtls_x509_crt_init(&own_cert);
  23026. mbedtls_pk_init(&own_key);
  23027. mbedtls_x509_crt_init(&ca_chain);
  23028. // Load server certificate
  23029. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23030. return false;
  23031. }
  23032. // Load server private key.
  23033. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23034. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23035. #if MBEDTLS_VERSION_MAJOR == 3
  23036. ,
  23037. mbedtls_ctr_drbg_random, nullptr
  23038. #endif
  23039. ) != 0) {
  23040. return false;
  23041. }
  23042. // Load CA chain for client verification
  23043. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23044. return false;
  23045. }
  23046. initialized = true;
  23047. }
  23048. // Configure the SSL config
  23049. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23050. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23051. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23052. // Set minimum TLS version using mbedTLS native API
  23053. #if MBEDTLS_VERSION_MAJOR >= 3
  23054. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23055. #else
  23056. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23057. MBEDTLS_SSL_MINOR_VERSION_3);
  23058. #endif
  23059. return true;
  23060. };
  23061. SSLServer svr(setup_callback);
  23062. ASSERT_TRUE(svr.is_valid());
  23063. ASSERT_TRUE(callback_invoked);
  23064. svr.Get("/test", [&](const Request &req, Response &res) {
  23065. res.set_content("test", "text/plain");
  23066. auto cert = req.peer_cert();
  23067. ASSERT_TRUE(static_cast<bool>(cert));
  23068. auto common_name = cert.subject_cn();
  23069. EXPECT_EQ("Common Name", common_name);
  23070. });
  23071. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23072. auto se = detail::scope_exit([&] {
  23073. svr.stop();
  23074. t.join();
  23075. ASSERT_FALSE(svr.is_running());
  23076. });
  23077. svr.wait_until_ready();
  23078. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23079. cli.enable_server_certificate_verification(false);
  23080. cli.set_connection_timeout(30);
  23081. auto res = cli.Get("/test");
  23082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23083. ASSERT_EQ(StatusCode::OK_200, res->status);
  23084. }
  23085. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23086. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23087. // keep-alive SSL session, which reads through that config in
  23088. // mbedtls_ssl_close_notify.
  23089. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23090. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23091. ASSERT_TRUE(svr.is_valid());
  23092. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23093. res.set_content("test", "text/plain");
  23094. });
  23095. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23096. auto se = detail::scope_exit([&] {
  23097. svr.stop();
  23098. t.join();
  23099. ASSERT_FALSE(svr.is_running());
  23100. });
  23101. svr.wait_until_ready();
  23102. {
  23103. SSLClient cli(HOST, PORT);
  23104. cli.enable_server_certificate_verification(false);
  23105. cli.set_keep_alive(true);
  23106. auto res = cli.Get("/test");
  23107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23108. ASSERT_EQ(StatusCode::OK_200, res->status);
  23109. // cli is destructed here with the keep-alive SSL session still open.
  23110. }
  23111. }
  23112. #endif
  23113. // WebSocket Tests
  23114. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23115. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23116. // defining the meaning of these bits has been negotiated.
  23117. auto make_frame = [](uint8_t first_byte) {
  23118. std::string frame;
  23119. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23120. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23121. frame += "Hello";
  23122. return frame;
  23123. };
  23124. // RSV1 set (0x40)
  23125. {
  23126. detail::BufferStream strm;
  23127. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  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::Fail);
  23134. }
  23135. // RSV2 set (0x20)
  23136. {
  23137. detail::BufferStream strm;
  23138. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23139. ws::Opcode opcode;
  23140. std::string payload;
  23141. bool fin;
  23142. EXPECT_EQ(
  23143. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23144. ws::impl::FrameRead::Fail);
  23145. }
  23146. // RSV3 set (0x10)
  23147. {
  23148. detail::BufferStream strm;
  23149. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23150. ws::Opcode opcode;
  23151. std::string payload;
  23152. bool fin;
  23153. EXPECT_EQ(
  23154. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23155. ws::impl::FrameRead::Fail);
  23156. }
  23157. // No RSV bits set - should succeed
  23158. {
  23159. detail::BufferStream strm;
  23160. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23161. ws::Opcode opcode;
  23162. std::string payload;
  23163. bool fin;
  23164. EXPECT_EQ(
  23165. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23166. ws::impl::FrameRead::Ok);
  23167. EXPECT_EQ(ws::Opcode::Text, opcode);
  23168. EXPECT_EQ("Hello", payload);
  23169. EXPECT_TRUE(fin);
  23170. }
  23171. }
  23172. TEST(WebSocketTest, ControlFrameValidation) {
  23173. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23174. // payload length <= 125.
  23175. // Ping with FIN=0 - must be rejected
  23176. {
  23177. detail::BufferStream strm;
  23178. std::string frame;
  23179. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23180. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23181. strm.write(frame.data(), frame.size());
  23182. ws::Opcode opcode;
  23183. std::string payload;
  23184. bool fin;
  23185. EXPECT_EQ(
  23186. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23187. ws::impl::FrameRead::Fail);
  23188. }
  23189. // Close with FIN=0 - must be rejected
  23190. {
  23191. detail::BufferStream strm;
  23192. std::string frame;
  23193. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23194. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23195. strm.write(frame.data(), frame.size());
  23196. ws::Opcode opcode;
  23197. std::string payload;
  23198. bool fin;
  23199. EXPECT_EQ(
  23200. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23201. ws::impl::FrameRead::Fail);
  23202. }
  23203. // Ping with payload_len=126 (extended length) - must be rejected
  23204. {
  23205. detail::BufferStream strm;
  23206. std::string frame;
  23207. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23208. frame += static_cast<char>(126); // payload_len=126 (>125)
  23209. frame += static_cast<char>(0x00); // extended length high byte
  23210. frame += static_cast<char>(126); // extended length low byte
  23211. frame += std::string(126, 'x');
  23212. strm.write(frame.data(), frame.size());
  23213. ws::Opcode opcode;
  23214. std::string payload;
  23215. bool fin;
  23216. EXPECT_EQ(
  23217. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23218. ws::impl::FrameRead::Fail);
  23219. }
  23220. // Ping with FIN=1 and payload_len=125 - should succeed
  23221. {
  23222. detail::BufferStream strm;
  23223. std::string frame;
  23224. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23225. frame += static_cast<char>(125); // payload_len=125
  23226. frame += std::string(125, 'x');
  23227. strm.write(frame.data(), frame.size());
  23228. ws::Opcode opcode;
  23229. std::string payload;
  23230. bool fin;
  23231. EXPECT_EQ(
  23232. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23233. ws::impl::FrameRead::Ok);
  23234. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23235. EXPECT_EQ(125u, payload.size());
  23236. EXPECT_TRUE(fin);
  23237. }
  23238. }
  23239. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23240. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23241. // length MUST be 0.
  23242. // MSB set - must be rejected
  23243. {
  23244. detail::BufferStream strm;
  23245. std::string frame;
  23246. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23247. frame += static_cast<char>(127); // 64-bit extended length
  23248. frame += static_cast<char>(0x80); // MSB set (invalid)
  23249. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23250. strm.write(frame.data(), frame.size());
  23251. ws::Opcode opcode;
  23252. std::string payload;
  23253. bool fin;
  23254. EXPECT_EQ(
  23255. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23256. ws::impl::FrameRead::Fail);
  23257. }
  23258. // MSB clear - should pass length parsing (will be rejected by max_len,
  23259. // but that's a different check; use a small length to verify)
  23260. {
  23261. detail::BufferStream strm;
  23262. std::string frame;
  23263. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23264. frame += static_cast<char>(127); // 64-bit extended length
  23265. frame += std::string(7, '\0'); // high bytes = 0
  23266. frame += static_cast<char>(0x03); // length = 3
  23267. frame += "abc";
  23268. strm.write(frame.data(), frame.size());
  23269. ws::Opcode opcode;
  23270. std::string payload;
  23271. bool fin;
  23272. EXPECT_EQ(
  23273. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23274. ws::impl::FrameRead::Ok);
  23275. EXPECT_EQ(ws::Opcode::Text, opcode);
  23276. EXPECT_EQ("abc", payload);
  23277. }
  23278. }
  23279. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23280. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23281. // Valid UTF-8
  23282. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23283. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23284. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23285. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23286. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23287. // Invalid UTF-8
  23288. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23289. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23290. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23291. EXPECT_FALSE(
  23292. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23293. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23294. }
  23295. TEST(WebSocketTest, ConnectAndDisconnect) {
  23296. Server svr;
  23297. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23298. std::string msg;
  23299. while (ws.read(msg)) {}
  23300. });
  23301. auto port = svr.bind_to_any_port(HOST);
  23302. std::thread t([&]() { svr.listen_after_bind(); });
  23303. svr.wait_until_ready();
  23304. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23305. auto res = client.connect();
  23306. ASSERT_TRUE(res);
  23307. EXPECT_EQ(Error::Success, res.error());
  23308. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23309. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23310. EXPECT_TRUE(client.is_open());
  23311. client.close();
  23312. EXPECT_FALSE(client.is_open());
  23313. svr.stop();
  23314. t.join();
  23315. }
  23316. TEST(WebSocketTest, ValidURL) {
  23317. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23318. EXPECT_TRUE(ws1.is_valid());
  23319. ws::WebSocketClient ws2("ws://example.com/path");
  23320. EXPECT_TRUE(ws2.is_valid());
  23321. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23322. EXPECT_TRUE(ws3.is_valid());
  23323. #ifdef CPPHTTPLIB_SSL_ENABLED
  23324. ws::WebSocketClient wss1("wss://example.com/path");
  23325. EXPECT_TRUE(wss1.is_valid());
  23326. ws::WebSocketClient wss2("wss://example.com:443/path");
  23327. EXPECT_TRUE(wss2.is_valid());
  23328. #endif
  23329. }
  23330. TEST(WebSocketTest, InvalidURL) {
  23331. // No scheme
  23332. ws::WebSocketClient ws1("localhost:8080/path");
  23333. EXPECT_FALSE(ws1.is_valid());
  23334. // No path
  23335. ws::WebSocketClient ws2("ws://localhost:8080");
  23336. EXPECT_FALSE(ws2.is_valid());
  23337. // Empty string
  23338. ws::WebSocketClient ws3("");
  23339. EXPECT_FALSE(ws3.is_valid());
  23340. // Missing host
  23341. ws::WebSocketClient ws4("ws://:8080/path");
  23342. EXPECT_FALSE(ws4.is_valid());
  23343. // Port number overflow — should not crash
  23344. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23345. EXPECT_FALSE(ws5.is_valid());
  23346. // Port out of range
  23347. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23348. EXPECT_FALSE(ws6.is_valid());
  23349. }
  23350. TEST(WebSocketTest, UnsupportedScheme) {
  23351. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23352. ws::WebSocketClient ws1("http://localhost:8080/path");
  23353. EXPECT_FALSE(ws1.is_valid());
  23354. ws::WebSocketClient ws2("https://localhost:8080/path");
  23355. EXPECT_FALSE(ws2.is_valid());
  23356. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23357. EXPECT_FALSE(ws3.is_valid());
  23358. #else
  23359. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23360. std::invalid_argument);
  23361. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23362. std::invalid_argument);
  23363. #endif
  23364. }
  23365. TEST(WebSocketTest, ConnectWhenInvalid) {
  23366. ws::WebSocketClient ws("not a valid url");
  23367. EXPECT_FALSE(ws.is_valid());
  23368. auto res = ws.connect();
  23369. EXPECT_FALSE(res);
  23370. EXPECT_EQ(Error::Connection, res.error());
  23371. EXPECT_EQ(-1, res.status());
  23372. }
  23373. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23374. // Grab a port that is free, then close it again so nothing listens there
  23375. Server svr;
  23376. auto port = svr.bind_to_any_port(HOST);
  23377. svr.stop();
  23378. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23379. auto res = client.connect();
  23380. ASSERT_FALSE(res);
  23381. EXPECT_EQ(Error::Connection, res.error());
  23382. EXPECT_EQ(-1, res.status());
  23383. }
  23384. TEST(WebSocketTest, DefaultPort) {
  23385. ws::WebSocketClient ws1("ws://example.com/path");
  23386. EXPECT_TRUE(ws1.is_valid());
  23387. // ws:// defaults to port 80 (verified by successful parse)
  23388. #ifdef CPPHTTPLIB_SSL_ENABLED
  23389. ws::WebSocketClient ws2("wss://example.com/path");
  23390. EXPECT_TRUE(ws2.is_valid());
  23391. // wss:// defaults to port 443 (verified by successful parse)
  23392. #endif
  23393. }
  23394. TEST(WebSocketTest, IPv6LiteralAddress) {
  23395. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23396. EXPECT_TRUE(ws1.is_valid());
  23397. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23398. EXPECT_TRUE(ws2.is_valid());
  23399. }
  23400. TEST(WebSocketTest, ComplexPath) {
  23401. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23402. EXPECT_TRUE(ws1.is_valid());
  23403. ws::WebSocketClient ws2("ws://localhost:8080/");
  23404. EXPECT_TRUE(ws2.is_valid());
  23405. }
  23406. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23407. Server svr;
  23408. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23409. std::string msg;
  23410. while (ws.read(msg)) {}
  23411. });
  23412. auto port = svr.bind_to_any_port(HOST);
  23413. std::thread t([&]() { svr.listen_after_bind(); });
  23414. svr.wait_until_ready();
  23415. auto another_host = "example.com";
  23416. auto wrong_ip = "192.0.2.1";
  23417. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23418. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23419. ASSERT_TRUE(client.connect());
  23420. EXPECT_TRUE(client.is_open());
  23421. client.close();
  23422. svr.stop();
  23423. t.join();
  23424. }
  23425. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23426. Server svr;
  23427. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23428. std::string msg;
  23429. while (ws.read(msg)) {}
  23430. });
  23431. auto port = svr.bind_to_any_port(HOST);
  23432. std::thread t([&]() { svr.listen_after_bind(); });
  23433. svr.wait_until_ready();
  23434. auto wrong_ip = "192.0.2.1";
  23435. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23436. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23437. client.set_connection_timeout(1);
  23438. client.set_read_timeout(1);
  23439. client.set_write_timeout(1);
  23440. EXPECT_FALSE(client.connect());
  23441. EXPECT_FALSE(client.is_open());
  23442. svr.stop();
  23443. t.join();
  23444. }
  23445. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23446. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23447. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23448. // (RFC 6761) is only a map key and the Host header value.
  23449. auto host = "target.invalid";
  23450. Server svr;
  23451. std::string received_host;
  23452. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23453. received_host = req.get_header_value("Host");
  23454. std::string msg;
  23455. while (ws.read(msg)) {}
  23456. });
  23457. auto port = svr.bind_to_any_port(HOST);
  23458. std::thread t([&]() { svr.listen_after_bind(); });
  23459. // ASSERT_* below returns from the test body, which would leave t joinable
  23460. // and make ~thread call std::terminate.
  23461. auto se = detail::scope_exit([&] {
  23462. svr.stop();
  23463. if (t.joinable()) { t.join(); }
  23464. });
  23465. svr.wait_until_ready();
  23466. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23467. std::to_string(port) + "/ws");
  23468. client.set_hostname_addr_map({{host, HOST}});
  23469. ASSERT_TRUE(client.connect());
  23470. EXPECT_TRUE(client.is_open());
  23471. client.close();
  23472. svr.stop();
  23473. t.join();
  23474. // The mapping only redirects the connection; the identity stays host_.
  23475. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23476. }
  23477. class WebSocketIntegrationTest : public ::testing::Test {
  23478. protected:
  23479. void SetUp() override {
  23480. server_ = httplib::detail::make_unique<Server>();
  23481. setup_server();
  23482. start_server();
  23483. }
  23484. void TearDown() override {
  23485. server_->stop();
  23486. if (server_thread_.joinable()) { server_thread_.join(); }
  23487. }
  23488. void setup_server() {
  23489. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23490. std::string msg;
  23491. ws::ReadResult ret;
  23492. while ((ret = ws.read(msg))) {
  23493. if (ret == ws::Binary) {
  23494. ws.send(msg.data(), msg.size());
  23495. } else {
  23496. ws.send(msg);
  23497. }
  23498. }
  23499. });
  23500. server_->WebSocket("/ws-echo-string",
  23501. [](const Request &, ws::WebSocket &ws) {
  23502. std::string msg;
  23503. while (ws.read(msg)) {
  23504. ws.send("echo: " + msg);
  23505. }
  23506. });
  23507. server_->WebSocket(
  23508. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23509. // Echo back request metadata
  23510. ws.send("path:" + req.path);
  23511. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23512. std::string msg;
  23513. while (ws.read(msg)) {}
  23514. });
  23515. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23516. std::string msg;
  23517. ws.read(msg); // wait for a message
  23518. ws.close();
  23519. });
  23520. server_->WebSocket("/ws-close-status",
  23521. [](const Request &, ws::WebSocket &ws) {
  23522. std::string msg;
  23523. ws.read(msg); // wait for a message
  23524. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23525. });
  23526. server_->WebSocket(
  23527. "/ws-subprotocol",
  23528. [](const Request &, ws::WebSocket &ws) {
  23529. std::string msg;
  23530. while (ws.read(msg)) {
  23531. ws.send(msg);
  23532. }
  23533. },
  23534. [](const std::vector<std::string> &protocols) -> std::string {
  23535. for (const auto &p : protocols) {
  23536. if (p == "graphql-ws") { return p; }
  23537. }
  23538. return "";
  23539. });
  23540. server_->WebSocket(
  23541. "/ws-subprotocol-unoffered",
  23542. [](const Request &, ws::WebSocket &ws) {
  23543. std::string msg;
  23544. while (ws.read(msg)) {
  23545. ws.send(msg);
  23546. }
  23547. },
  23548. [](const std::vector<std::string> &) -> std::string {
  23549. return "admin";
  23550. });
  23551. }
  23552. void start_server() {
  23553. port_ = server_->bind_to_any_port(HOST);
  23554. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23555. server_->wait_until_ready();
  23556. }
  23557. std::unique_ptr<Server> server_;
  23558. std::thread server_thread_;
  23559. int port_ = 0;
  23560. };
  23561. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23562. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23563. "/ws-echo");
  23564. ASSERT_TRUE(client.connect());
  23565. ASSERT_TRUE(client.is_open());
  23566. ASSERT_TRUE(client.send("Hello WebSocket"));
  23567. std::string msg;
  23568. EXPECT_EQ(ws::Text, client.read(msg));
  23569. EXPECT_EQ("Hello WebSocket", msg);
  23570. client.close();
  23571. }
  23572. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23573. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23574. "/ws-echo");
  23575. ASSERT_TRUE(client.connect());
  23576. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23577. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23578. std::string msg;
  23579. EXPECT_EQ(ws::Binary, client.read(msg));
  23580. EXPECT_EQ(binary_data, msg);
  23581. client.close();
  23582. }
  23583. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23584. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23585. "/ws-echo");
  23586. ASSERT_TRUE(client.connect());
  23587. for (int i = 0; i < 10; i++) {
  23588. auto text = "message " + std::to_string(i);
  23589. ASSERT_TRUE(client.send(text));
  23590. std::string msg;
  23591. ASSERT_TRUE(client.read(msg));
  23592. EXPECT_EQ(text, msg);
  23593. }
  23594. client.close();
  23595. }
  23596. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23597. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23598. "/ws-close");
  23599. ASSERT_TRUE(client.connect());
  23600. // Send a message to trigger the server to close
  23601. ASSERT_TRUE(client.send("trigger close"));
  23602. // The server will close, so read should return false
  23603. std::string msg;
  23604. EXPECT_FALSE(client.read(msg));
  23605. EXPECT_FALSE(client.is_open());
  23606. }
  23607. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23608. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23609. "/ws-echo");
  23610. ASSERT_TRUE(client.connect());
  23611. // 128KB message
  23612. std::string large_data(128 * 1024, 'X');
  23613. ASSERT_TRUE(client.send(large_data));
  23614. std::string msg;
  23615. ASSERT_TRUE(client.read(msg));
  23616. EXPECT_EQ(large_data, msg);
  23617. client.close();
  23618. }
  23619. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23620. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23621. "/ws-echo");
  23622. ASSERT_TRUE(client.connect());
  23623. const int num_threads = 4;
  23624. std::vector<std::thread> threads;
  23625. std::atomic<int> send_count{0};
  23626. for (int t = 0; t < num_threads; t++) {
  23627. threads.emplace_back([&client, &send_count, t]() {
  23628. for (int i = 0; i < 5; i++) {
  23629. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23630. if (client.send(text)) { send_count++; }
  23631. }
  23632. });
  23633. }
  23634. for (auto &th : threads) {
  23635. th.join();
  23636. }
  23637. int received = 0;
  23638. std::string msg;
  23639. while (received < send_count.load()) {
  23640. if (!client.read(msg)) { break; }
  23641. received++;
  23642. }
  23643. EXPECT_EQ(send_count.load(), received);
  23644. client.close();
  23645. }
  23646. TEST_F(WebSocketIntegrationTest, ReadString) {
  23647. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23648. "/ws-echo-string");
  23649. ASSERT_TRUE(client.connect());
  23650. ASSERT_TRUE(client.send("hello"));
  23651. std::string msg;
  23652. ASSERT_TRUE(client.read(msg));
  23653. EXPECT_EQ("echo: hello", msg);
  23654. ASSERT_TRUE(client.send("world"));
  23655. ASSERT_TRUE(client.read(msg));
  23656. EXPECT_EQ("echo: world", msg);
  23657. client.close();
  23658. }
  23659. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23660. Headers headers = {{"X-Test-Header", "test-value"}};
  23661. ws::WebSocketClient client(
  23662. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23663. ASSERT_TRUE(client.connect());
  23664. std::string msg;
  23665. ASSERT_TRUE(client.read(msg));
  23666. EXPECT_EQ("path:/ws-request-info", msg);
  23667. ASSERT_TRUE(client.read(msg));
  23668. EXPECT_EQ("header:test-value", msg);
  23669. client.close();
  23670. }
  23671. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23672. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23673. "/ws-echo");
  23674. client.set_read_timeout(1, 0); // 1 second
  23675. ASSERT_TRUE(client.connect());
  23676. // Don't send anything — server echo handler waits for a message, so read()
  23677. // should time out. The connection survives it: nothing was consumed.
  23678. std::string msg;
  23679. EXPECT_EQ(client.read(msg), ws::Timeout);
  23680. EXPECT_TRUE(client.is_open());
  23681. // And it is still usable afterwards.
  23682. EXPECT_TRUE(client.send("after timeout"));
  23683. EXPECT_EQ(client.read(msg), ws::Text);
  23684. EXPECT_EQ(msg, "after timeout");
  23685. }
  23686. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23687. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23688. "/ws-echo");
  23689. client.set_read_timeout(1, 0);
  23690. ASSERT_TRUE(client.connect());
  23691. ASSERT_TRUE(client.send("first"));
  23692. std::string msg;
  23693. ASSERT_EQ(client.read(msg), ws::Text);
  23694. ASSERT_EQ(msg, "first");
  23695. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23696. // not be used with a read timeout: it would reprocess the previous message.
  23697. EXPECT_EQ(client.read(msg), ws::Timeout);
  23698. EXPECT_EQ(msg, "first");
  23699. }
  23700. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23701. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23702. "/ws-echo");
  23703. ASSERT_TRUE(client.connect());
  23704. // Setting it once the connection is open reaches the live stream, not just
  23705. // the seed for the next connect().
  23706. client.set_read_timeout(1, 0);
  23707. std::string msg;
  23708. EXPECT_EQ(client.read(msg), ws::Timeout);
  23709. EXPECT_TRUE(client.is_open());
  23710. }
  23711. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23712. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23713. "/ws-echo");
  23714. client.set_read_timeout(5, 0);
  23715. ASSERT_TRUE(client.connect());
  23716. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23717. // The server should reject it and close the connection.
  23718. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23719. client.send(oversized);
  23720. // The server's read() should have failed due to payload limit,
  23721. // so our read() should return false (connection closed).
  23722. std::string msg;
  23723. EXPECT_FALSE(client.read(msg));
  23724. }
  23725. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23726. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23727. "/ws-echo");
  23728. client.set_read_timeout(10, 0);
  23729. ASSERT_TRUE(client.connect());
  23730. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23731. // This should succeed.
  23732. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23733. ASSERT_TRUE(client.send(at_limit));
  23734. std::string msg;
  23735. ASSERT_TRUE(client.read(msg));
  23736. EXPECT_EQ(at_limit.size(), msg.size());
  23737. client.close();
  23738. }
  23739. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23740. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23741. "/nonexistent");
  23742. auto res = client.connect();
  23743. EXPECT_FALSE(res);
  23744. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23745. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23746. EXPECT_FALSE(client.is_open());
  23747. }
  23748. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23749. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23750. "/ws-echo");
  23751. ASSERT_TRUE(client.connect());
  23752. ASSERT_TRUE(client.send(""));
  23753. std::string msg;
  23754. EXPECT_EQ(ws::Text, client.read(msg));
  23755. EXPECT_EQ("", msg);
  23756. client.close();
  23757. }
  23758. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23760. "/ws-echo");
  23761. // First connection
  23762. ASSERT_TRUE(client.connect());
  23763. ASSERT_TRUE(client.send("first"));
  23764. std::string msg;
  23765. ASSERT_TRUE(client.read(msg));
  23766. EXPECT_EQ("first", msg);
  23767. client.close();
  23768. EXPECT_FALSE(client.is_open());
  23769. // Reconnect using the same client object
  23770. ASSERT_TRUE(client.connect());
  23771. ASSERT_TRUE(client.is_open());
  23772. ASSERT_TRUE(client.send("second"));
  23773. ASSERT_TRUE(client.read(msg));
  23774. EXPECT_EQ("second", msg);
  23775. client.close();
  23776. }
  23777. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23778. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23779. "/ws-close-status");
  23780. ASSERT_TRUE(client.connect());
  23781. // Trigger the server to close with GoingAway status
  23782. ASSERT_TRUE(client.send("trigger"));
  23783. // read() should return false after receiving the close frame
  23784. std::string msg;
  23785. EXPECT_FALSE(client.read(msg));
  23786. EXPECT_FALSE(client.is_open());
  23787. }
  23788. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23789. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23790. "/ws-echo");
  23791. ASSERT_TRUE(client.connect());
  23792. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23793. EXPECT_FALSE(client.is_open());
  23794. }
  23795. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23796. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23797. ws::WebSocketClient client(
  23798. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23799. ASSERT_TRUE(client.connect());
  23800. // Server should have selected graphql-ws
  23801. EXPECT_EQ("graphql-ws", client.subprotocol());
  23802. client.close();
  23803. }
  23804. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23805. Headers headers;
  23806. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23807. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23808. ws::WebSocketClient client(
  23809. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23810. ASSERT_TRUE(client.connect());
  23811. // The offer on the second field line counts too, so graphql-ws is selected
  23812. EXPECT_EQ("graphql-ws", client.subprotocol());
  23813. client.close();
  23814. }
  23815. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23816. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23817. ws::WebSocketClient client(
  23818. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23819. ASSERT_TRUE(client.connect());
  23820. // Server should not have selected any subprotocol
  23821. EXPECT_TRUE(client.subprotocol().empty());
  23822. client.close();
  23823. }
  23824. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23825. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23826. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23827. "/ws-subprotocol-unoffered",
  23828. headers);
  23829. ASSERT_TRUE(client.connect());
  23830. EXPECT_TRUE(client.subprotocol().empty());
  23831. client.close();
  23832. }
  23833. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23834. // Connect without requesting any subprotocol
  23835. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23836. "/ws-subprotocol");
  23837. ASSERT_TRUE(client.connect());
  23838. EXPECT_TRUE(client.subprotocol().empty());
  23839. client.close();
  23840. }
  23841. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23842. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23843. "/ws-echo");
  23844. client.set_tcp_nodelay(true);
  23845. client.set_connection_timeout(3, 0);
  23846. bool socket_options_called = false;
  23847. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23848. ASSERT_TRUE(client.connect());
  23849. ASSERT_TRUE(client.is_open());
  23850. EXPECT_TRUE(socket_options_called);
  23851. ASSERT_TRUE(client.send("hello"));
  23852. std::string msg;
  23853. auto result = client.read(msg);
  23854. EXPECT_EQ(result, ws::ReadResult::Text);
  23855. EXPECT_EQ(msg, "hello");
  23856. client.close();
  23857. }
  23858. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23859. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23860. "/ws-echo");
  23861. client.set_connection_timeout(std::chrono::seconds(3));
  23862. client.set_write_timeout(std::chrono::seconds(3));
  23863. // A sub-second remainder exercises the seconds/microseconds split.
  23864. client.set_read_timeout(std::chrono::milliseconds(1500));
  23865. ASSERT_TRUE(client.connect());
  23866. auto start = std::chrono::steady_clock::now();
  23867. std::string msg;
  23868. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23869. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23870. std::chrono::steady_clock::now() - start)
  23871. .count();
  23872. // Above 1s so that dropping the microseconds half of the split fails here.
  23873. // Ignoring the setter altogether would not reach this line at all: a client
  23874. // waits forever by default.
  23875. EXPECT_GE(elapsed, 1400);
  23876. EXPECT_LT(elapsed, 30000);
  23877. }
  23878. #ifndef _WIN32
  23879. // A send() that times out after part of the data went out returns the count
  23880. // written so far. Every byte of the frame must still be sent, or the peer reads
  23881. // the next frame's header and payload as the rest of this one.
  23882. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  23883. signal(SIGPIPE, SIG_IGN);
  23884. const std::string large(4 * 1024 * 1024, 'A');
  23885. std::atomic<bool> large_sent{false};
  23886. std::atomic<bool> small_sent{false};
  23887. Server svr;
  23888. svr.set_write_timeout(0, 500000);
  23889. svr.set_socket_options([](socket_t sock) {
  23890. int size = 8192;
  23891. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  23892. reinterpret_cast<const char *>(&size), sizeof(size));
  23893. });
  23894. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23895. large_sent = ws.send(large.data(), large.size());
  23896. small_sent = ws.send("after");
  23897. std::string msg;
  23898. while (ws.read(msg)) {}
  23899. });
  23900. auto port = svr.bind_to_any_port(HOST);
  23901. std::thread t([&]() { svr.listen_after_bind(); });
  23902. auto se = detail::scope_exit([&] {
  23903. svr.stop();
  23904. t.join();
  23905. });
  23906. svr.wait_until_ready();
  23907. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  23908. std::to_string(port) + "/ws");
  23909. client.set_read_timeout(5);
  23910. client.set_socket_options([](socket_t sock) {
  23911. int size = 8192;
  23912. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  23913. reinterpret_cast<const char *>(&size), sizeof(size));
  23914. });
  23915. ASSERT_TRUE(client.connect());
  23916. // Outlast the server's write timeout, then drain.
  23917. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  23918. std::string msg;
  23919. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  23920. EXPECT_TRUE(msg == large);
  23921. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  23922. EXPECT_EQ("after", msg);
  23923. EXPECT_TRUE(large_sent);
  23924. EXPECT_TRUE(small_sent);
  23925. client.close();
  23926. }
  23927. #endif
  23928. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23929. Server svr;
  23930. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23931. if (!req.has_header("Authorization")) {
  23932. res.status = StatusCode::Unauthorized_401;
  23933. res.set_content("Unauthorized", "text/plain");
  23934. return Server::HandlerResponse::Handled;
  23935. }
  23936. return Server::HandlerResponse::Unhandled;
  23937. });
  23938. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23939. std::string msg;
  23940. while (ws.read(msg)) {
  23941. ws.send(msg);
  23942. }
  23943. });
  23944. auto port = svr.bind_to_any_port("localhost");
  23945. std::thread t([&]() { svr.listen_after_bind(); });
  23946. svr.wait_until_ready();
  23947. // Without Authorization header - should be rejected before upgrade
  23948. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23949. EXPECT_FALSE(client1.connect());
  23950. // The rejection is framed like any other HTTP response
  23951. {
  23952. Client cli("localhost", port);
  23953. Headers headers = {{"Upgrade", "websocket"},
  23954. {"Connection", "Upgrade"},
  23955. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23956. {"Sec-WebSocket-Version", "13"}};
  23957. auto res = cli.Get("/ws", headers);
  23958. ASSERT_TRUE(res);
  23959. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23960. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23961. EXPECT_EQ("Unauthorized", res->body);
  23962. }
  23963. // With Authorization header - should succeed
  23964. Headers headers = {{"Authorization", "Bearer token123"}};
  23965. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23966. headers);
  23967. ASSERT_TRUE(client2.connect());
  23968. ASSERT_TRUE(client2.send("hello"));
  23969. std::string msg;
  23970. ASSERT_TRUE(client2.read(msg));
  23971. EXPECT_EQ("hello", msg);
  23972. client2.close();
  23973. svr.stop();
  23974. t.join();
  23975. }
  23976. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23977. Server svr;
  23978. std::atomic<int> pre_routing_calls{0};
  23979. std::atomic<int> pre_request_calls{0};
  23980. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23981. pre_routing_calls++;
  23982. if (req.path == "/handled") {
  23983. res.set_content("handled", "text/plain");
  23984. return Server::HandlerResponse::Handled;
  23985. }
  23986. return Server::HandlerResponse::Unhandled;
  23987. });
  23988. svr.set_pre_request_handler([&](const Request &, Response &) {
  23989. pre_request_calls++;
  23990. return Server::HandlerResponse::Unhandled;
  23991. });
  23992. svr.Get("/http", [](const Request &, Response &res) {
  23993. res.set_content("http", "text/plain");
  23994. });
  23995. svr.WebSocket("/ws",
  23996. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23997. auto port = svr.bind_to_any_port("localhost");
  23998. std::thread t([&]() { svr.listen_after_bind(); });
  23999. auto se = detail::scope_exit([&] {
  24000. svr.stop();
  24001. t.join();
  24002. });
  24003. svr.wait_until_ready();
  24004. Headers upgrade = {{"Upgrade", "websocket"},
  24005. {"Connection", "Upgrade"},
  24006. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24007. {"Sec-WebSocket-Version", "13"}};
  24008. auto get = [&](const char *path) {
  24009. pre_routing_calls = 0;
  24010. return Client("localhost", port).Get(path, upgrade);
  24011. };
  24012. // No WebSocket route, but an HTTP one
  24013. auto res = get("/http");
  24014. ASSERT_TRUE(res);
  24015. EXPECT_EQ(StatusCode::OK_200, res->status);
  24016. EXPECT_EQ("http", res->body);
  24017. EXPECT_EQ(1, pre_routing_calls);
  24018. EXPECT_EQ(1, pre_request_calls);
  24019. // No route at all
  24020. res = get("/none");
  24021. ASSERT_TRUE(res);
  24022. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24023. EXPECT_EQ(1, pre_routing_calls);
  24024. // Answered by the pre-routing handler
  24025. res = get("/handled");
  24026. ASSERT_TRUE(res);
  24027. EXPECT_EQ(StatusCode::OK_200, res->status);
  24028. EXPECT_EQ("handled", res->body);
  24029. EXPECT_EQ(1, pre_routing_calls);
  24030. // A WebSocket route
  24031. pre_routing_calls = 0;
  24032. pre_request_calls = 0;
  24033. {
  24034. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24035. "/ws");
  24036. ASSERT_TRUE(client.connect());
  24037. std::string msg;
  24038. ASSERT_TRUE(client.read(msg));
  24039. EXPECT_EQ("ws", msg);
  24040. client.close();
  24041. }
  24042. EXPECT_EQ(1, pre_routing_calls);
  24043. EXPECT_EQ(1, pre_request_calls);
  24044. }
  24045. // An upgrade request answered by a hook leaves its body unread, so that body
  24046. // must not be served as the next request on the connection.
  24047. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24048. Server svr;
  24049. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24050. if (req.path == "/pre-routing") {
  24051. res.set_content("pre-routing", "text/plain");
  24052. return Server::HandlerResponse::Handled;
  24053. }
  24054. return Server::HandlerResponse::Unhandled;
  24055. });
  24056. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24057. if (req.matched_route == "/pre-request") {
  24058. res.set_content("pre-request", "text/plain");
  24059. return Server::HandlerResponse::Handled;
  24060. }
  24061. return Server::HandlerResponse::Unhandled;
  24062. });
  24063. svr.Get("/smuggled", [](const Request &, Response &res) {
  24064. res.set_content("smuggled", "text/plain");
  24065. });
  24066. svr.WebSocket("/pre-request",
  24067. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24068. auto port = svr.bind_to_any_port(HOST);
  24069. std::thread t([&]() { svr.listen_after_bind(); });
  24070. auto se = detail::scope_exit([&] {
  24071. svr.stop();
  24072. t.join();
  24073. });
  24074. svr.wait_until_ready();
  24075. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24076. for (auto path : {"/pre-routing", "/pre-request"}) {
  24077. std::string req = std::string("GET ") + path +
  24078. " HTTP/1.1\r\n"
  24079. "Host: localhost\r\n"
  24080. "Upgrade: websocket\r\n"
  24081. "Connection: Upgrade\r\n"
  24082. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24083. "Sec-WebSocket-Version: 13\r\n"
  24084. "Content-Length: " +
  24085. std::to_string(body.size()) + "\r\n\r\n" + body;
  24086. std::string res;
  24087. ASSERT_TRUE(send_request(5, req, &res, port));
  24088. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24089. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24090. // Only one response, and the body was not served as a request
  24091. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24092. }
  24093. }
  24094. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24095. Server svr;
  24096. std::atomic<int> pre_request_calls{0};
  24097. std::atomic<bool> route_matched{false};
  24098. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24099. pre_request_calls++;
  24100. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24101. if (req.get_header_value("Authorization") != "Bearer token123") {
  24102. res.status = StatusCode::Unauthorized_401;
  24103. res.set_content("Unauthorized", "text/plain");
  24104. return Server::HandlerResponse::Handled;
  24105. }
  24106. return Server::HandlerResponse::Unhandled;
  24107. });
  24108. std::atomic<bool> handler_called{false};
  24109. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24110. handler_called = true;
  24111. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24112. });
  24113. auto port = svr.bind_to_any_port("localhost");
  24114. std::thread t([&]() { svr.listen_after_bind(); });
  24115. svr.wait_until_ready();
  24116. // Without Authorization header - should be rejected before upgrade
  24117. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24118. "/ws/1");
  24119. EXPECT_FALSE(client1.connect());
  24120. EXPECT_FALSE(handler_called);
  24121. EXPECT_EQ(1, pre_request_calls);
  24122. EXPECT_TRUE(route_matched);
  24123. // The rejection is an ordinary HTTP response, not a protocol switch
  24124. {
  24125. Client cli("localhost", port);
  24126. Headers headers = {{"Upgrade", "websocket"},
  24127. {"Connection", "Upgrade"},
  24128. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24129. {"Sec-WebSocket-Version", "13"}};
  24130. auto res = cli.Get("/ws/1", headers);
  24131. ASSERT_TRUE(res);
  24132. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24133. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24134. EXPECT_EQ("Unauthorized", res->body);
  24135. }
  24136. EXPECT_FALSE(handler_called);
  24137. // With Authorization header - should succeed
  24138. Headers headers = {{"Authorization", "Bearer token123"}};
  24139. ws::WebSocketClient client2(
  24140. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24141. ASSERT_TRUE(client2.connect());
  24142. std::string msg;
  24143. ASSERT_TRUE(client2.read(msg));
  24144. EXPECT_EQ("/ws/:id 2", msg);
  24145. EXPECT_TRUE(handler_called);
  24146. client2.close();
  24147. svr.stop();
  24148. t.join();
  24149. }
  24150. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24151. static Headers websocket_upgrade_headers() {
  24152. return {{"Upgrade", "websocket"},
  24153. {"Connection", "Upgrade"},
  24154. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24155. {"Sec-WebSocket-Version", "13"},
  24156. {"Sec-WebSocket-Protocol", "chat"}};
  24157. }
  24158. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24159. Server svr;
  24160. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24161. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24162. return Server::HandlerResponse::Unhandled;
  24163. });
  24164. svr.set_pre_request_handler([](const Request &req, Response &) {
  24165. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24166. return Server::HandlerResponse::Unhandled;
  24167. });
  24168. svr.set_exception_handler(
  24169. [](const Request &, Response &res, std::exception_ptr ep) {
  24170. try {
  24171. std::rethrow_exception(ep);
  24172. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24173. });
  24174. auto handler = [](const Request &, ws::WebSocket &) {};
  24175. svr.WebSocket("/pre-routing", handler);
  24176. svr.WebSocket("/pre-request", handler);
  24177. svr.WebSocket("/sub-protocol", handler,
  24178. [](const std::vector<std::string> &) -> std::string {
  24179. throw std::runtime_error("/sub-protocol");
  24180. });
  24181. auto port = svr.bind_to_any_port(HOST);
  24182. ASSERT_GT(port, 0);
  24183. thread t = thread([&] { svr.listen_after_bind(); });
  24184. auto se = detail::scope_exit([&] {
  24185. svr.stop();
  24186. t.join();
  24187. ASSERT_FALSE(svr.is_running());
  24188. });
  24189. svr.wait_until_ready();
  24190. Client cli(HOST, port);
  24191. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24192. auto res = cli.Get(path, websocket_upgrade_headers());
  24193. if (!res) {
  24194. ADD_FAILURE() << path << ": " << to_string(res.error());
  24195. continue;
  24196. }
  24197. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24198. EXPECT_EQ(path, res->body);
  24199. }
  24200. }
  24201. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24202. Server svr;
  24203. svr.set_pre_routing_handler(
  24204. [](const Request &, Response &) -> Server::HandlerResponse {
  24205. throw std::runtime_error("pre-routing");
  24206. });
  24207. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24208. auto port = svr.bind_to_any_port(HOST);
  24209. ASSERT_GT(port, 0);
  24210. thread t = thread([&] { svr.listen_after_bind(); });
  24211. auto se = detail::scope_exit([&] {
  24212. svr.stop();
  24213. t.join();
  24214. ASSERT_FALSE(svr.is_running());
  24215. });
  24216. svr.wait_until_ready();
  24217. Client cli(HOST, port);
  24218. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24219. ASSERT_TRUE(res) << to_string(res.error());
  24220. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24221. }
  24222. #endif
  24223. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24224. Server svr;
  24225. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24226. // A read timeout is how a handler gets control back. Without it, a handler
  24227. // parked in read() can never write on the connection it is reading.
  24228. ws.set_read_timeout(std::chrono::milliseconds(100));
  24229. std::string msg;
  24230. while (ws.is_open()) {
  24231. auto r = ws.read(msg);
  24232. if (r == httplib::ws::Timeout) {
  24233. ws.send("tick");
  24234. continue;
  24235. }
  24236. if (r == httplib::ws::Fail) { break; }
  24237. ws.send(msg);
  24238. }
  24239. });
  24240. auto port = svr.bind_to_any_port("localhost");
  24241. std::thread t([&]() { svr.listen_after_bind(); });
  24242. svr.wait_until_ready();
  24243. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24244. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24245. ASSERT_TRUE(client.connect());
  24246. // The client sends nothing, so anything it receives came out of the
  24247. // handler's timeout path.
  24248. std::string msg;
  24249. ASSERT_EQ(client.read(msg), ws::Text);
  24250. EXPECT_EQ("tick", msg);
  24251. client.close();
  24252. svr.stop();
  24253. t.join();
  24254. }
  24255. // Stream::read may return fewer bytes than asked for. This is that contract at
  24256. // its worst -- one byte per call -- which is what a frame header straddling a
  24257. // read buffer's boundary looks like to the frame parser.
  24258. class WsByteAtATimeStream : public Stream {
  24259. public:
  24260. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24261. bool is_readable() const override { return true; }
  24262. bool wait_readable() const override { return true; }
  24263. bool wait_writable() const override { return true; }
  24264. ssize_t read(char *ptr, size_t size) override {
  24265. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24266. *ptr = data_[pos_++];
  24267. return 1;
  24268. }
  24269. ssize_t write(const char *, size_t size) override {
  24270. return static_cast<ssize_t>(size);
  24271. }
  24272. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24273. ip = "127.0.0.1";
  24274. port = 0;
  24275. }
  24276. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24277. ip = "127.0.0.1";
  24278. port = 0;
  24279. }
  24280. socket_t socket() const override { return INVALID_SOCKET; }
  24281. time_t duration() const override { return 0; }
  24282. private:
  24283. std::string data_;
  24284. size_t pos_ = 0;
  24285. };
  24286. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24287. // The payload uses the 16-bit extended length, so the header, the length
  24288. // and the mask key are all multi-byte fields here. Each used to be read
  24289. // with a single read() call, which fails as soon as one is split. The
  24290. // payload is also a little over one read chunk, so it is read in two.
  24291. std::string body;
  24292. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24293. body += static_cast<char>(i % 251);
  24294. }
  24295. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24296. std::string frame;
  24297. frame += static_cast<char>(0x81); // FIN + Text
  24298. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24299. frame += static_cast<char>(body.size() >> 8);
  24300. frame += static_cast<char>(body.size() & 0xff);
  24301. for (size_t i = 0; i < 4; i++) {
  24302. frame += static_cast<char>(mask[i]);
  24303. }
  24304. for (size_t i = 0; i < body.size(); i++) {
  24305. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24306. }
  24307. WsByteAtATimeStream strm(frame);
  24308. ws::Opcode opcode;
  24309. std::string payload;
  24310. bool fin = false;
  24311. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24312. /*expect_masked=*/true, body.size()),
  24313. ws::impl::FrameRead::Ok);
  24314. EXPECT_TRUE(fin);
  24315. EXPECT_EQ(opcode, ws::Opcode::Text);
  24316. EXPECT_EQ(payload, body);
  24317. }
  24318. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24319. std::string body(2000, 'x');
  24320. std::string frame;
  24321. frame += static_cast<char>(0x82); // FIN + Binary
  24322. frame += static_cast<char>(126); // 16-bit length follows
  24323. frame += static_cast<char>(body.size() >> 8);
  24324. frame += static_cast<char>(body.size() & 0xff);
  24325. frame += body;
  24326. detail::BufferStream strm;
  24327. strm.write(frame.data(), frame.size());
  24328. ws::Opcode opcode;
  24329. std::string payload;
  24330. bool fin;
  24331. EXPECT_EQ(
  24332. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24333. ws::impl::FrameRead::Ok);
  24334. EXPECT_EQ(body, payload);
  24335. }
  24336. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24337. // The header announces the largest payload allowed, and only 3 bytes of it
  24338. // ever arrive.
  24339. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24340. std::string frame;
  24341. frame += static_cast<char>(0x82); // FIN + Binary
  24342. frame += static_cast<char>(127); // 64-bit length follows
  24343. for (int shift = 56; shift >= 0; shift -= 8) {
  24344. frame += static_cast<char>((len >> shift) & 0xff);
  24345. }
  24346. frame += "abc";
  24347. detail::BufferStream strm;
  24348. strm.write(frame.data(), frame.size());
  24349. ws::Opcode opcode;
  24350. std::string payload;
  24351. bool fin;
  24352. EXPECT_EQ(
  24353. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24354. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24355. ws::impl::FrameRead::Fail);
  24356. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24357. }
  24358. TEST(WebSocketTest, QueryStringInHandshake) {
  24359. Server svr;
  24360. std::mutex mtx;
  24361. std::string received_target;
  24362. std::string received_token;
  24363. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24364. {
  24365. std::lock_guard<std::mutex> lock(mtx);
  24366. received_target = req.target;
  24367. if (req.has_param("token")) {
  24368. received_token = req.get_param_value("token");
  24369. }
  24370. }
  24371. std::string msg;
  24372. while (ws.read(msg)) {
  24373. ws.send(msg);
  24374. }
  24375. });
  24376. auto port = svr.bind_to_any_port("localhost");
  24377. std::thread t([&]() { svr.listen_after_bind(); });
  24378. svr.wait_until_ready();
  24379. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24380. "/ws?token=ABC&session=123");
  24381. ASSERT_TRUE(client.connect());
  24382. // Round-trip ensures the handler has run and captured the request.
  24383. ASSERT_TRUE(client.send("hello"));
  24384. std::string msg;
  24385. ASSERT_TRUE(client.read(msg));
  24386. EXPECT_EQ("hello", msg);
  24387. client.close();
  24388. {
  24389. std::lock_guard<std::mutex> lock(mtx);
  24390. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24391. EXPECT_EQ("ABC", received_token);
  24392. }
  24393. svr.stop();
  24394. t.join();
  24395. }
  24396. // Run a handshake against a throwaway server and hand the request the server
  24397. // received back to the caller, so tests can assert on the headers the client
  24398. // actually put on the wire.
  24399. static void capture_websocket_handshake_request(
  24400. const Headers &client_headers,
  24401. std::function<void(const Request &, int port)> verify) {
  24402. Server svr;
  24403. std::mutex mtx;
  24404. Request received;
  24405. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24406. {
  24407. std::lock_guard<std::mutex> lock(mtx);
  24408. received = req;
  24409. }
  24410. std::string msg;
  24411. while (ws.read(msg)) {
  24412. ws.send(msg);
  24413. }
  24414. });
  24415. auto port = svr.bind_to_any_port("localhost");
  24416. std::thread t([&]() { svr.listen_after_bind(); });
  24417. auto se = detail::scope_exit([&] {
  24418. svr.stop();
  24419. t.join();
  24420. });
  24421. svr.wait_until_ready();
  24422. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24423. client_headers);
  24424. ASSERT_TRUE(client.connect());
  24425. ASSERT_TRUE(client.send("hello"));
  24426. std::string msg;
  24427. ASSERT_TRUE(client.read(msg));
  24428. client.close();
  24429. {
  24430. std::lock_guard<std::mutex> lock(mtx);
  24431. verify(received, port);
  24432. }
  24433. }
  24434. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24435. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24436. // Non-default port must be present in the Host header. Default ports
  24437. // (80/443) are omitted; that logic is covered by
  24438. // MakeHostAndPortStringTest.
  24439. EXPECT_EQ("localhost:" + std::to_string(port),
  24440. req.get_header_value("Host"));
  24441. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24442. req.get_header_value("User-Agent"));
  24443. EXPECT_FALSE(req.has_header("Accept"));
  24444. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24445. EXPECT_FALSE(req.has_header("Content-Length"));
  24446. });
  24447. }
  24448. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24449. capture_websocket_handshake_request(
  24450. {{"Host", "example.com"},
  24451. {"User-Agent", "custom-agent"},
  24452. {"X-Custom", "value"}},
  24453. [](const Request &req, int) {
  24454. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24455. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24456. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24457. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24458. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24459. });
  24460. }
  24461. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24462. capture_websocket_handshake_request(
  24463. {{"Upgrade", "bogus"},
  24464. {"Connection", "close"},
  24465. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24466. {"Sec-WebSocket-Version", "8"}},
  24467. [](const Request &req, int) {
  24468. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24469. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24470. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24471. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24472. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24473. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24474. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24475. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24476. req.get_header_value("Sec-WebSocket-Key"));
  24477. });
  24478. }
  24479. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24480. // A header the client refuses to send must abort the handshake before any
  24481. // part of it reaches the wire; a lone request line would otherwise sit in
  24482. // the peer's buffer as a truncated request.
  24483. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24484. ASSERT_NE(INVALID_SOCKET, srv);
  24485. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24486. sockaddr_in addr{};
  24487. addr.sin_family = AF_INET;
  24488. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24489. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24490. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24491. ASSERT_EQ(0, ::listen(srv, 1));
  24492. sockaddr_in bound{};
  24493. socklen_t bound_len = sizeof(bound);
  24494. ASSERT_EQ(
  24495. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24496. auto port = ntohs(bound.sin_port);
  24497. ssize_t received = -1;
  24498. std::thread t([&] {
  24499. // Bound every blocking call so a regression fails the test with a bad
  24500. // value instead of hanging the suite.
  24501. fd_set rfds;
  24502. FD_ZERO(&rfds);
  24503. FD_SET(srv, &rfds);
  24504. timeval tv{5, 0};
  24505. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24506. 0) {
  24507. return;
  24508. }
  24509. sockaddr_in cli_addr{};
  24510. socklen_t cli_len = sizeof(cli_addr);
  24511. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24512. if (cli == INVALID_SOCKET) { return; }
  24513. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24514. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24515. char buf[4096];
  24516. received = ::recv(cli, buf, sizeof(buf), 0);
  24517. });
  24518. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24519. // connect() has already shut the socket down by the time it returns false,
  24520. // so the peer sees EOF without waiting for the client to be destroyed.
  24521. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24522. {{"X-Bad", "a\r\nInjected: 1"}});
  24523. EXPECT_FALSE(client.connect());
  24524. t.join();
  24525. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24526. EXPECT_EQ(0, received);
  24527. }
  24528. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24529. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24530. // contains "upgrade" as a substring is a different token and must not
  24531. // start a WebSocket handshake.
  24532. auto make_request = [](const std::vector<std::string> &connection_values) {
  24533. Request req;
  24534. req.method = "GET";
  24535. req.headers.emplace("Upgrade", "websocket");
  24536. for (const auto &value : connection_values) {
  24537. req.headers.emplace("Connection", value);
  24538. }
  24539. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24540. req.headers.emplace("Sec-WebSocket-Version", "13");
  24541. return req;
  24542. };
  24543. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24544. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24545. EXPECT_TRUE(
  24546. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24547. EXPECT_TRUE(
  24548. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24549. EXPECT_TRUE(
  24550. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24551. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24552. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24553. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24554. EXPECT_FALSE(
  24555. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24556. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24557. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24558. }
  24559. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24560. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24561. // asks recipients to match each protocol-name case-insensitively, and RFC
  24562. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24563. // client naming websocket alongside another protocol, or on a second field
  24564. // line, is offering websocket; a value that merely contains "websocket" as a
  24565. // substring is a different protocol name and is not.
  24566. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24567. Request req;
  24568. req.method = "GET";
  24569. for (const auto &value : upgrade_values) {
  24570. req.headers.emplace("Upgrade", value);
  24571. }
  24572. req.headers.emplace("Connection", "Upgrade");
  24573. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24574. req.headers.emplace("Sec-WebSocket-Version", "13");
  24575. return req;
  24576. };
  24577. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24578. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24579. EXPECT_TRUE(
  24580. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24581. EXPECT_TRUE(
  24582. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24583. EXPECT_TRUE(
  24584. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24585. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24586. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24587. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24588. EXPECT_FALSE(
  24589. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24590. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24591. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24592. }
  24593. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24594. Server svr;
  24595. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24596. auto port = svr.bind_to_any_port("localhost");
  24597. std::thread t([&]() { svr.listen_after_bind(); });
  24598. auto se = detail::scope_exit([&] {
  24599. svr.stop();
  24600. t.join();
  24601. });
  24602. svr.wait_until_ready();
  24603. Headers headers = {{"Upgrade", "websocket"},
  24604. {"Connection", "notupgrade"},
  24605. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24606. {"Sec-WebSocket-Version", "13"}};
  24607. Client cli("localhost", port);
  24608. auto res = cli.Get("/ws", headers);
  24609. // The route exists only as a WebSocket route, so a request that fails the
  24610. // handshake check falls through to ordinary routing.
  24611. ASSERT_TRUE(res);
  24612. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24613. }
  24614. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24615. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24616. // Connection value is the only thing left for the client to reject.
  24617. Server svr;
  24618. svr.Get("/ws", [](const Request &req, Response &res) {
  24619. res.status = StatusCode::SwitchingProtocol_101;
  24620. res.set_header("Upgrade", "websocket");
  24621. res.set_header("Connection", "notupgrade");
  24622. res.set_header("Sec-WebSocket-Accept",
  24623. detail::websocket_accept_key(
  24624. req.get_header_value("Sec-WebSocket-Key")));
  24625. });
  24626. auto port = svr.bind_to_any_port("localhost");
  24627. std::thread t([&]() { svr.listen_after_bind(); });
  24628. auto se = detail::scope_exit([&] {
  24629. svr.stop();
  24630. t.join();
  24631. });
  24632. svr.wait_until_ready();
  24633. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24634. auto res = client.connect();
  24635. EXPECT_FALSE(res);
  24636. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24637. EXPECT_FALSE(client.is_open());
  24638. }
  24639. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24640. Server svr;
  24641. svr.Get("/ws", [](const Request &req, Response &res) {
  24642. res.status = StatusCode::SwitchingProtocol_101;
  24643. res.set_header("Upgrade", "websocket");
  24644. res.set_header("Connection", "Upgrade");
  24645. res.set_header("Sec-WebSocket-Accept",
  24646. detail::websocket_accept_key(
  24647. req.get_header_value("Sec-WebSocket-Key")));
  24648. res.set_header("Sec-WebSocket-Protocol", "admin");
  24649. });
  24650. auto port = svr.bind_to_any_port("localhost");
  24651. std::thread t([&]() { svr.listen_after_bind(); });
  24652. auto se = detail::scope_exit([&] {
  24653. svr.stop();
  24654. t.join();
  24655. });
  24656. svr.wait_until_ready();
  24657. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24658. // Server selects a subprotocol the client never offered
  24659. {
  24660. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24661. ws::WebSocketClient client(url, headers);
  24662. auto res = client.connect();
  24663. EXPECT_FALSE(res);
  24664. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24665. EXPECT_FALSE(client.is_open());
  24666. EXPECT_TRUE(client.subprotocol().empty());
  24667. }
  24668. // Client offered none but the server named one anyway
  24669. {
  24670. ws::WebSocketClient client(url);
  24671. auto res = client.connect();
  24672. EXPECT_FALSE(res);
  24673. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24674. EXPECT_FALSE(client.is_open());
  24675. EXPECT_TRUE(client.subprotocol().empty());
  24676. }
  24677. }
  24678. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24679. // The socket path doubles as the URL host, so it must not contain '/'.
  24680. const char *shard = getenv("GTEST_SHARD_INDEX");
  24681. const std::string sock_path =
  24682. shard ? std::string("httplib-ws-") + shard + ".sock"
  24683. : std::string("httplib-ws.sock");
  24684. std::remove(sock_path.c_str());
  24685. Server svr;
  24686. std::mutex mtx;
  24687. std::string received_host;
  24688. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24689. {
  24690. std::lock_guard<std::mutex> lock(mtx);
  24691. received_host = req.get_header_value("Host");
  24692. }
  24693. std::string msg;
  24694. while (ws.read(msg)) {
  24695. ws.send(msg);
  24696. }
  24697. });
  24698. svr.set_address_family(AF_UNIX);
  24699. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24700. auto se = detail::scope_exit([&] {
  24701. svr.stop();
  24702. t.join();
  24703. std::remove(sock_path.c_str());
  24704. });
  24705. svr.wait_until_ready();
  24706. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24707. client.set_address_family(AF_UNIX);
  24708. ASSERT_TRUE(client.connect());
  24709. ASSERT_TRUE(client.send("hello"));
  24710. std::string msg;
  24711. ASSERT_TRUE(client.read(msg));
  24712. client.close();
  24713. {
  24714. std::lock_guard<std::mutex> lock(mtx);
  24715. // There is no host:port for a Unix socket, so the same "localhost"
  24716. // placeholder the HTTP client uses is expected.
  24717. EXPECT_EQ("localhost", received_host);
  24718. }
  24719. }
  24720. // Two threads must never parse WebSocket frames from the same stream.
  24721. // close() used to read the peer's Close reply with its own frame read, so it
  24722. // raced a reader thread that was in the middle of a payload: the payload loop
  24723. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24724. // so bytes taken by close() were replaced with bytes from further along the
  24725. // stream. The message kept its length and silently changed content.
  24726. //
  24727. // The raw peer below sends a frame header plus part of the payload, waits for
  24728. // the handler to call close(), and only then sends the rest. Whichever thread
  24729. // would win the race for those bytes, the message must arrive intact, because
  24730. // close() must not touch the stream while read() owns it.
  24731. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24732. #ifndef _WIN32
  24733. signal(SIGPIPE, SIG_IGN);
  24734. #endif
  24735. const size_t payload_len = 120; // fits the 7-bit length field
  24736. const size_t prefix_len = 8;
  24737. const int attempts = 8;
  24738. std::string expected(payload_len, '\0');
  24739. for (size_t i = 0; i < payload_len; i++) {
  24740. expected[i] = static_cast<char>('a' + i % 26);
  24741. }
  24742. std::atomic<bool> peer_stalled{false};
  24743. std::atomic<bool> handler_done{false};
  24744. std::mutex received_mutex;
  24745. std::vector<std::string> received;
  24746. // Bound every wait, so a regression fails the test instead of hanging the
  24747. // suite.
  24748. auto wait_for = [](const std::atomic<bool> &flag) {
  24749. for (int i = 0; i < 500 && !flag; i++) {
  24750. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24751. }
  24752. };
  24753. Server svr;
  24754. svr.set_websocket_ping_interval(0);
  24755. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24756. std::thread reader([&]() {
  24757. std::string msg;
  24758. while (ws.read(msg)) {
  24759. std::lock_guard<std::mutex> guard(received_mutex);
  24760. received.push_back(msg);
  24761. }
  24762. });
  24763. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24764. // inside read_websocket_frame() when close() runs.
  24765. wait_for(peer_stalled);
  24766. ws.close();
  24767. reader.join();
  24768. handler_done = true;
  24769. });
  24770. auto port = svr.bind_to_any_port("127.0.0.1");
  24771. std::thread t([&]() { svr.listen_after_bind(); });
  24772. auto se = detail::scope_exit([&] {
  24773. svr.stop();
  24774. t.join();
  24775. });
  24776. svr.wait_until_ready();
  24777. auto send_bytes = [](socket_t s, const std::string &data) {
  24778. #ifdef _WIN32
  24779. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24780. #else
  24781. auto n = ::send(s, data.data(), data.size(), 0);
  24782. #endif
  24783. return n == static_cast<decltype(n)>(data.size());
  24784. };
  24785. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24786. // Every length used here fits the 7-bit length field.
  24787. auto masked_header = [](uint8_t first_byte, size_t len) {
  24788. std::string h;
  24789. h += static_cast<char>(first_byte);
  24790. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24791. h.append(4, '\0'); // mask key
  24792. return h;
  24793. };
  24794. for (int attempt = 0; attempt < attempts; attempt++) {
  24795. peer_stalled = false;
  24796. handler_done = false;
  24797. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24798. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24799. auto se_sock = detail::scope_exit([&] {
  24800. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24801. });
  24802. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24803. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24804. sockaddr_in addr{};
  24805. addr.sin_family = AF_INET;
  24806. addr.sin_port = htons(static_cast<uint16_t>(port));
  24807. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24808. ASSERT_EQ(
  24809. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24810. << "attempt " << attempt;
  24811. ASSERT_TRUE(send_bytes(sock,
  24812. "GET /ws HTTP/1.1\r\n"
  24813. "Host: 127.0.0.1\r\n"
  24814. "Upgrade: websocket\r\n"
  24815. "Connection: Upgrade\r\n"
  24816. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24817. "Sec-WebSocket-Version: 13\r\n"
  24818. "\r\n"))
  24819. << "attempt " << attempt;
  24820. std::string response;
  24821. while (response.find("\r\n\r\n") == std::string::npos) {
  24822. char buf[512];
  24823. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24824. if (n <= 0) { break; }
  24825. response.append(buf, static_cast<size_t>(n));
  24826. }
  24827. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24828. << "attempt " << attempt;
  24829. // Send the header of a Binary message but only the first prefix_len bytes
  24830. // of its payload, leaving the reader thread stalled inside the payload.
  24831. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24832. expected.substr(0, prefix_len)))
  24833. << "attempt " << attempt;
  24834. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24835. peer_stalled = true;
  24836. // Let close() send its Close frame and park in its own read before the
  24837. // rest of the payload arrives, so both threads are waiting for it.
  24838. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24839. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24840. close_frame += static_cast<char>(0x03); // status 1000
  24841. close_frame += static_cast<char>(0xE8);
  24842. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24843. << "attempt " << attempt;
  24844. // Closing the peer releases the reader thread even on the buggy path,
  24845. // where it waits for bytes another thread already consumed.
  24846. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24847. detail::close_socket(sock);
  24848. sock = INVALID_SOCKET;
  24849. wait_for(handler_done);
  24850. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24851. }
  24852. std::lock_guard<std::mutex> guard(received_mutex);
  24853. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24854. << "a message in flight when close() ran was dropped";
  24855. for (size_t i = 0; i < received.size(); i++) {
  24856. EXPECT_EQ(expected, received[i]) << "message " << i;
  24857. }
  24858. }
  24859. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24860. // returning the socket, or INVALID_SOCKET.
  24861. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24862. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24863. if (sock == INVALID_SOCKET) { return sock; }
  24864. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24865. sockaddr_in addr{};
  24866. addr.sin_family = AF_INET;
  24867. addr.sin_port = htons(static_cast<uint16_t>(port));
  24868. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24869. std::string req = "GET " + path +
  24870. " HTTP/1.1\r\n"
  24871. "Host: 127.0.0.1\r\n"
  24872. "Upgrade: websocket\r\n"
  24873. "Connection: Upgrade\r\n"
  24874. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24875. "Sec-WebSocket-Version: 13\r\n"
  24876. "\r\n";
  24877. std::string res;
  24878. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24879. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24880. static_cast<ssize_t>(req.size())) {
  24881. char c;
  24882. while (res.find("\r\n\r\n") == std::string::npos &&
  24883. ::recv(sock, &c, 1, 0) == 1) {
  24884. res += c;
  24885. }
  24886. }
  24887. if (res.find(" 101 ") == std::string::npos) {
  24888. detail::close_socket(sock);
  24889. return INVALID_SOCKET;
  24890. }
  24891. return sock;
  24892. }
  24893. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24894. // The payload must fit the 7-bit length field.
  24895. static std::string masked_frame(uint8_t first_byte,
  24896. const std::string &payload) {
  24897. std::string f;
  24898. f += static_cast<char>(first_byte);
  24899. f += static_cast<char>(0x80 | payload.size());
  24900. f.append(4, '\0');
  24901. return f + payload;
  24902. }
  24903. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24904. std::atomic<bool> done{false};
  24905. std::string received;
  24906. Server svr;
  24907. svr.set_websocket_ping_interval(0);
  24908. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24909. std::string msg;
  24910. if (ws.read(msg) == ws::Binary) { received = msg; }
  24911. done = true;
  24912. });
  24913. auto port = svr.bind_to_any_port("127.0.0.1");
  24914. std::thread t([&]() { svr.listen_after_bind(); });
  24915. auto se = detail::scope_exit([&] {
  24916. svr.stop();
  24917. t.join();
  24918. });
  24919. svr.wait_until_ready();
  24920. auto sock = connect_raw_websocket(port, "/ws");
  24921. ASSERT_NE(INVALID_SOCKET, sock);
  24922. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24923. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24924. masked_frame(0x89, "p") + // FIN + Ping
  24925. masked_frame(0x80, "lo"); // FIN + Continuation
  24926. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24927. for (int i = 0; i < 500 && !done; i++) {
  24928. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24929. }
  24930. ASSERT_TRUE(done);
  24931. EXPECT_EQ("Hello", received);
  24932. // The Ping between the fragments is answered with a Pong.
  24933. char pong[3];
  24934. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24935. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24936. }
  24937. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24938. Server svr;
  24939. svr.set_websocket_ping_interval(-1);
  24940. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24941. std::string msg;
  24942. while (ws.read(msg)) {}
  24943. });
  24944. auto port = svr.bind_to_any_port("127.0.0.1");
  24945. std::thread t([&]() { svr.listen_after_bind(); });
  24946. auto se = detail::scope_exit([&] {
  24947. svr.stop();
  24948. t.join();
  24949. });
  24950. svr.wait_until_ready();
  24951. auto sock = connect_raw_websocket(port, "/ws");
  24952. ASSERT_NE(INVALID_SOCKET, sock);
  24953. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24954. // Nothing comes while the client stays quiet.
  24955. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24956. char c;
  24957. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24958. }
  24959. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24960. // and that has to end a read() already waiting on the peer, on every platform.
  24961. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24962. // The peer sends no pings, and its handler never calls read(), which is
  24963. // where pongs are written.
  24964. std::mutex mutex;
  24965. std::condition_variable cv;
  24966. auto release = false;
  24967. svr.set_websocket_ping_interval(0);
  24968. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24969. std::unique_lock<std::mutex> lock(mutex);
  24970. cv.wait(lock, [&] { return release; });
  24971. });
  24972. auto port = svr.bind_to_any_port(HOST);
  24973. std::thread t([&]() { svr.listen_after_bind(); });
  24974. auto se = detail::scope_exit([&] {
  24975. {
  24976. std::lock_guard<std::mutex> lock(mutex);
  24977. release = true;
  24978. }
  24979. cv.notify_all();
  24980. svr.stop();
  24981. t.join();
  24982. });
  24983. svr.wait_until_ready();
  24984. ws::WebSocketClient client(std::string(scheme) +
  24985. "://localhost:" + std::to_string(port) + "/ws");
  24986. #ifdef CPPHTTPLIB_SSL_ENABLED
  24987. client.enable_server_certificate_verification(false);
  24988. #endif
  24989. // A ping a second, given up on after two go unanswered: about 3s
  24990. client.set_websocket_ping_interval(1);
  24991. client.set_websocket_max_missed_pongs(2);
  24992. // Well past that, so that a read the timeout ends instead stands out
  24993. client.set_read_timeout(10);
  24994. ASSERT_TRUE(client.connect());
  24995. auto start = std::chrono::steady_clock::now();
  24996. std::string msg;
  24997. EXPECT_EQ(ws::Fail, client.read(msg));
  24998. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24999. std::chrono::steady_clock::now() - start)
  25000. .count(),
  25001. 6000);
  25002. EXPECT_FALSE(client.is_open());
  25003. }
  25004. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25005. Server svr;
  25006. check_pong_timeout_ends_read(svr, "ws");
  25007. }
  25008. #ifdef CPPHTTPLIB_SSL_ENABLED
  25009. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25011. ASSERT_TRUE(svr.is_valid());
  25012. check_pong_timeout_ends_read(svr, "wss");
  25013. }
  25014. #endif
  25015. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25016. Server svr;
  25017. svr.set_websocket_ping_interval(0);
  25018. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25019. std::string msg;
  25020. while (ws.read(msg)) {}
  25021. });
  25022. auto port = svr.bind_to_any_port("127.0.0.1");
  25023. std::thread t([&]() { svr.listen_after_bind(); });
  25024. auto se = detail::scope_exit([&] {
  25025. svr.stop();
  25026. t.join();
  25027. });
  25028. svr.wait_until_ready();
  25029. // Each Close payload and the reply it should get: an echo when valid, 1002
  25030. // otherwise.
  25031. std::vector<std::pair<std::string, std::string>> cases = {
  25032. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25033. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25034. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25035. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25036. };
  25037. // Also between the fragments of a message.
  25038. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25039. for (const auto &c : cases) {
  25040. auto sock = connect_raw_websocket(port, "/ws");
  25041. ASSERT_NE(INVALID_SOCKET, sock);
  25042. auto frames = prefix + masked_frame(0x88, c.first);
  25043. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25044. std::string reply;
  25045. char buf[256];
  25046. while (reply.size() < 2 + c.second.size()) {
  25047. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25048. if (n <= 0) { break; }
  25049. reply.append(buf, static_cast<size_t>(n));
  25050. }
  25051. detail::close_socket(sock);
  25052. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25053. c.second,
  25054. reply);
  25055. }
  25056. }
  25057. }
  25058. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25059. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25060. protected:
  25061. void SetUp() override {
  25062. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25063. SERVER_PRIVATE_KEY_FILE);
  25064. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25065. std::string msg;
  25066. ws::ReadResult ret;
  25067. while ((ret = ws.read(msg))) {
  25068. if (ret == ws::Binary) {
  25069. ws.send(msg.data(), msg.size());
  25070. } else {
  25071. ws.send(msg);
  25072. }
  25073. }
  25074. });
  25075. port_ = server_->bind_to_any_port(HOST);
  25076. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25077. server_->wait_until_ready();
  25078. }
  25079. void TearDown() override {
  25080. server_->stop();
  25081. if (server_thread_.joinable()) { server_thread_.join(); }
  25082. }
  25083. std::unique_ptr<SSLServer> server_;
  25084. std::thread server_thread_;
  25085. int port_ = 0;
  25086. };
  25087. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25088. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25089. {
  25090. ws::WebSocketClient client(url);
  25091. client.enable_server_certificate_verification(false);
  25092. auto calls = 0;
  25093. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25094. calls++;
  25095. return false;
  25096. });
  25097. EXPECT_FALSE(client.connect());
  25098. EXPECT_GT(calls, 0);
  25099. }
  25100. {
  25101. ws::WebSocketClient client(url);
  25102. client.enable_server_certificate_verification(false);
  25103. client.set_session_verifier([](tls::session_t) {
  25104. return SSLVerifierResponse::CertificateRejected;
  25105. });
  25106. EXPECT_FALSE(client.connect());
  25107. }
  25108. {
  25109. ws::WebSocketClient client(url);
  25110. client.enable_server_certificate_verification(false);
  25111. client.set_session_verifier([](tls::session_t) {
  25112. return SSLVerifierResponse::CertificateAccepted;
  25113. });
  25114. EXPECT_TRUE(client.connect());
  25115. }
  25116. }
  25117. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25118. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25119. "/ws-echo");
  25120. client.enable_server_certificate_verification(false);
  25121. ASSERT_TRUE(client.connect());
  25122. ASSERT_TRUE(client.is_open());
  25123. ASSERT_TRUE(client.send("Hello WSS"));
  25124. std::string msg;
  25125. EXPECT_EQ(ws::Text, client.read(msg));
  25126. EXPECT_EQ("Hello WSS", msg);
  25127. client.close();
  25128. }
  25129. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25130. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25131. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25132. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25133. // client (without calling close() first) is the only path that runs
  25134. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25135. // bug exactly.
  25136. //
  25137. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25138. // when linked against an instrumented libssl; run under Valgrind to catch it
  25139. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25140. // suite (the freed session otherwise stalls on the close handshake) — this test
  25141. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25142. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25143. {
  25144. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25145. "/ws-echo");
  25146. client.enable_server_certificate_verification(false);
  25147. client.set_read_timeout(2, 0);
  25148. client.set_write_timeout(2, 0);
  25149. ASSERT_TRUE(client.connect());
  25150. ASSERT_TRUE(client.is_open());
  25151. ASSERT_TRUE(client.send("still open"));
  25152. // Intentionally do NOT call client.close(): leaving scope runs
  25153. // shutdown_and_close() with the WebSocket still open, which must send the
  25154. // close frame while the TLS session is still alive.
  25155. }
  25156. }
  25157. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25158. // shutdown_and_close() at the start of connect(), reproducing the same
  25159. // use-after-free within the test body rather than at scope exit. The second
  25160. // connect must succeed and echo, proving the close handshake ran over a live
  25161. // session. See the note above about memory-tool requirements.
  25162. TEST_F(WebSocketSSLIntegrationTest,
  25163. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25164. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25165. "/ws-echo");
  25166. client.enable_server_certificate_verification(false);
  25167. client.set_read_timeout(2, 0);
  25168. client.set_write_timeout(2, 0);
  25169. ASSERT_TRUE(client.connect());
  25170. ASSERT_TRUE(client.is_open());
  25171. ASSERT_TRUE(client.send("still open"));
  25172. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25173. // the still-open connection, which must not touch a freed TLS session.
  25174. ASSERT_TRUE(client.connect());
  25175. ASSERT_TRUE(client.is_open());
  25176. ASSERT_TRUE(client.send("after reconnect"));
  25177. std::string msg;
  25178. EXPECT_EQ(ws::Text, client.read(msg));
  25179. EXPECT_EQ("after reconnect", msg);
  25180. client.close();
  25181. }
  25182. #endif
  25183. #ifdef CPPHTTPLIB_SSL_ENABLED
  25184. class WebSocketSSLCATest : public ::testing::Test {
  25185. protected:
  25186. void SetUp() override {
  25187. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25188. SERVER_PRIVATE_KEY_FILE);
  25189. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25190. std::string msg;
  25191. while (ws.read(msg)) {
  25192. ws.send(msg);
  25193. }
  25194. });
  25195. port_ = server_->bind_to_any_port("127.0.0.1");
  25196. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25197. server_->wait_until_ready();
  25198. }
  25199. void TearDown() override {
  25200. server_->stop();
  25201. if (server_thread_.joinable()) { server_thread_.join(); }
  25202. }
  25203. std::string url() const {
  25204. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25205. }
  25206. std::unique_ptr<SSLServer> server_;
  25207. std::thread server_thread_;
  25208. int port_ = 0;
  25209. };
  25210. // A custom CA loaded as PEM verifies the server with full certificate
  25211. // verification enabled
  25212. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25213. ws::WebSocketClient client(url());
  25214. std::string cert;
  25215. read_file(SERVER_CERT2_FILE, cert);
  25216. client.load_ca_cert_store(cert.c_str(), cert.size());
  25217. ASSERT_TRUE(client.connect());
  25218. ASSERT_TRUE(client.send("hello"));
  25219. std::string msg;
  25220. EXPECT_EQ(ws::Text, client.read(msg));
  25221. EXPECT_EQ("hello", msg);
  25222. client.close();
  25223. }
  25224. // A custom CA that does not cover the server must fail verification (the
  25225. // custom CA is exclusive; system certs are not loaded alongside it)
  25226. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25227. ws::WebSocketClient client(url());
  25228. std::string cert;
  25229. read_file(CLIENT_CA_CERT_FILE, cert);
  25230. client.load_ca_cert_store(cert.c_str(), cert.size());
  25231. auto res = client.connect();
  25232. ASSERT_FALSE(res);
  25233. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25234. EXPECT_EQ(-1, res.status());
  25235. EXPECT_NE(0u, res.ssl_backend_error());
  25236. }
  25237. // The same CA as a file path rather than PEM in memory
  25238. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25239. ws::WebSocketClient client(url());
  25240. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25241. ASSERT_TRUE(client.connect());
  25242. ASSERT_TRUE(client.send("hello"));
  25243. std::string msg;
  25244. EXPECT_EQ(ws::Text, client.read(msg));
  25245. EXPECT_EQ("hello", msg);
  25246. client.close();
  25247. }
  25248. // ...and a CA file that does not cover the server still fails, so it is the
  25249. // path above that decides the outcome
  25250. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25251. ws::WebSocketClient client(url());
  25252. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25253. ASSERT_FALSE(client.connect());
  25254. }
  25255. // Regression test: reconnecting with a native custom CA store used to reuse
  25256. // a store handle the previous TLS context had already freed (use-after-free
  25257. // under the OpenSSL backend). The context now lives as long as the client.
  25258. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25259. ws::WebSocketClient client(url());
  25260. std::string cert;
  25261. read_file(SERVER_CERT2_FILE, cert);
  25262. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25263. ASSERT_TRUE(client.connect());
  25264. client.close();
  25265. ASSERT_TRUE(client.connect());
  25266. ASSERT_TRUE(client.send("again"));
  25267. std::string msg;
  25268. EXPECT_EQ(ws::Text, client.read(msg));
  25269. EXPECT_EQ("again", msg);
  25270. client.close();
  25271. }
  25272. // Regression test: a certificate with a trusted chain but no identity match
  25273. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25274. // verification entirely for IP hosts, so this connection succeeded there.
  25275. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25276. // chain verification while the identity check must still fail.
  25277. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25279. ASSERT_TRUE(svr.is_valid());
  25280. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25281. std::string msg;
  25282. while (ws.read(msg)) {
  25283. ws.send(msg);
  25284. }
  25285. });
  25286. auto port = svr.bind_to_any_port("127.0.0.1");
  25287. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25288. auto se = detail::scope_exit([&] {
  25289. svr.stop();
  25290. t.join();
  25291. });
  25292. svr.wait_until_ready();
  25293. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25294. "/echo");
  25295. std::string cert;
  25296. read_file(SERVER_CERT_FILE, cert);
  25297. client.load_ca_cert_store(cert.c_str(), cert.size());
  25298. ASSERT_FALSE(client.connect());
  25299. }
  25300. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25301. // SNI, so nothing binds the host name to the TLS session. These bind the
  25302. // server to "localhost" instead, the only shape that exercises the SNI and
  25303. // hostname-verification path with certificate verification left enabled.
  25304. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25305. protected:
  25306. void Start(const char *cert_file) {
  25307. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25308. SERVER_PRIVATE_KEY_FILE);
  25309. ASSERT_TRUE(server_->is_valid());
  25310. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25311. std::string msg;
  25312. while (ws.read(msg)) {
  25313. ws.send(msg);
  25314. }
  25315. });
  25316. port_ = server_->bind_to_any_port("localhost");
  25317. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25318. server_->wait_until_ready();
  25319. }
  25320. void TearDown() override {
  25321. if (server_) { server_->stop(); }
  25322. if (server_thread_.joinable()) { server_thread_.join(); }
  25323. }
  25324. std::string url() const {
  25325. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25326. }
  25327. std::unique_ptr<SSLServer> server_;
  25328. std::thread server_thread_;
  25329. int port_ = 0;
  25330. };
  25331. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25332. // out and the connection is usable
  25333. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25334. Start(SERVER_CERT2_FILE);
  25335. ws::WebSocketClient client(url());
  25336. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25337. ASSERT_TRUE(client.connect());
  25338. ASSERT_TRUE(client.send("hello"));
  25339. std::string msg;
  25340. EXPECT_EQ(ws::Text, client.read(msg));
  25341. EXPECT_EQ("hello", msg);
  25342. client.close();
  25343. }
  25344. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25345. // while the identity check must still reject "localhost"
  25346. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25347. Start(SERVER_CERT_FILE);
  25348. ws::WebSocketClient client(url());
  25349. client.set_ca_cert_path(SERVER_CERT_FILE);
  25350. auto res = client.connect();
  25351. ASSERT_FALSE(res);
  25352. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25353. EXPECT_EQ(-1, res.status());
  25354. }
  25355. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25356. // disabled: the chain is still checked, only the identity check is skipped
  25357. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25358. Start(SERVER_CERT_FILE);
  25359. ws::WebSocketClient client(url());
  25360. client.set_ca_cert_path(SERVER_CERT_FILE);
  25361. client.enable_server_hostname_verification(false);
  25362. ASSERT_TRUE(client.connect());
  25363. ASSERT_TRUE(client.send("hello"));
  25364. std::string msg;
  25365. EXPECT_EQ(ws::Text, client.read(msg));
  25366. EXPECT_EQ("hello", msg);
  25367. client.close();
  25368. }
  25369. // A CA that did not sign the server certificate fails the chain, even though
  25370. // the name would match
  25371. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25372. Start(SERVER_CERT2_FILE);
  25373. ws::WebSocketClient client(url());
  25374. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25375. ASSERT_FALSE(client.connect());
  25376. }
  25377. // With verification disabled, neither the chain nor the name is checked
  25378. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25379. Start(SERVER_CERT_FILE);
  25380. ws::WebSocketClient client(url());
  25381. client.enable_server_certificate_verification(false);
  25382. ASSERT_TRUE(client.connect());
  25383. ASSERT_TRUE(client.send("hello"));
  25384. std::string msg;
  25385. EXPECT_EQ(ws::Text, client.read(msg));
  25386. EXPECT_EQ("hello", msg);
  25387. client.close();
  25388. }
  25389. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25390. protected:
  25391. void SetUp() override {
  25392. server_ = httplib::detail::make_unique<SSLServer>(
  25393. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25394. ASSERT_TRUE(server_->is_valid());
  25395. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25396. std::string msg;
  25397. while (ws.read(msg)) {
  25398. ws.send(msg);
  25399. }
  25400. });
  25401. port_ = server_->bind_to_any_port("localhost");
  25402. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25403. server_->wait_until_ready();
  25404. }
  25405. void TearDown() override {
  25406. server_->stop();
  25407. if (server_thread_.joinable()) { server_thread_.join(); }
  25408. }
  25409. std::string url() const {
  25410. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25411. }
  25412. void ConnectWithClientCert(const std::string &client_cert_file,
  25413. const std::string &client_private_key_file,
  25414. const char *private_key_password) {
  25415. std::string cert_pem, key_pem;
  25416. read_file(client_cert_file, cert_pem);
  25417. read_file(client_private_key_file, key_pem);
  25418. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25419. key_pem.c_str(), key_pem.size(),
  25420. private_key_password};
  25421. ConnectWithPem(pem);
  25422. }
  25423. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25424. ws::WebSocketClient client(url(), pem);
  25425. ASSERT_TRUE(client.is_valid());
  25426. client.enable_server_certificate_verification(false);
  25427. ASSERT_TRUE(client.connect());
  25428. ASSERT_TRUE(client.send("hello"));
  25429. std::string msg;
  25430. EXPECT_EQ(ws::Text, client.read(msg));
  25431. EXPECT_EQ("hello", msg);
  25432. client.close();
  25433. }
  25434. std::unique_ptr<SSLServer> server_;
  25435. std::thread server_thread_;
  25436. int port_ = 0;
  25437. };
  25438. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25439. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25440. }
  25441. // Control for the tests above: the fixture's server really does require a
  25442. // client certificate, so it is the PEM the constructor installed that decides
  25443. // the outcome.
  25444. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25445. ws::WebSocketClient client(url());
  25446. ASSERT_TRUE(client.is_valid());
  25447. client.enable_server_certificate_verification(false);
  25448. EXPECT_FALSE(client.connect());
  25449. }
  25450. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25451. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25452. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25453. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25454. }
  25455. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25456. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25457. std::string cert_pem, key_pem;
  25458. read_file(CLIENT_CERT_FILE, cert_pem);
  25459. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25460. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25461. std::vector<char> key(key_pem.begin(), key_pem.end());
  25462. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25463. key.size(), nullptr};
  25464. ConnectWithPem(pem);
  25465. }
  25466. #endif
  25467. #if !defined(_WIN32)
  25468. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25469. auto secret_dir = std::string("./symlink_test_secret");
  25470. auto served_dir = std::string("./symlink_test_served");
  25471. auto secret_file = secret_dir + "/secret.txt";
  25472. auto symlink_path = served_dir + "/escape";
  25473. // Setup: create directories and files
  25474. mkdir(secret_dir.c_str(), 0755);
  25475. mkdir(served_dir.c_str(), 0755);
  25476. {
  25477. std::ofstream ofs(secret_file);
  25478. ofs << "SECRET_DATA";
  25479. }
  25480. // Create symlink using absolute path so it resolves correctly
  25481. #ifdef PATH_MAX
  25482. char abs_secret[PATH_MAX];
  25483. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25484. #else
  25485. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25486. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25487. ASSERT_NE(nullptr, abs_secret);
  25488. #endif
  25489. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25490. auto se = detail::scope_exit([&] {
  25491. unlink(symlink_path.c_str());
  25492. unlink(secret_file.c_str());
  25493. rmdir(served_dir.c_str());
  25494. rmdir(secret_dir.c_str());
  25495. });
  25496. Server svr;
  25497. svr.set_mount_point("/", served_dir);
  25498. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25499. auto se2 = detail::scope_exit([&] {
  25500. svr.stop();
  25501. listen_thread.join();
  25502. });
  25503. svr.wait_until_ready();
  25504. Client cli("localhost", PORT);
  25505. // Symlink pointing outside base dir should be blocked
  25506. auto res = cli.Get("/escape/secret.txt");
  25507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25508. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25509. }
  25510. #endif
  25511. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25512. // "GET /smuggled" request), reads the first response, and only then sends the
  25513. // embedded request as the body. Returns how many times /smuggled ran.
  25514. //
  25515. // The body is sent AFTER receiving the first response (as in the original
  25516. // PoC) so that the stream_line_reader cannot buffer it together with the
  25517. // headers of the first request.
  25518. static int count_smuggled_requests(const std::string &outer_head,
  25519. std::string &first_response) {
  25520. Server svr;
  25521. svr.set_mount_point("/", "./www");
  25522. std::atomic<int> smuggled_count(0);
  25523. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25524. smuggled_count++;
  25525. res.set_content("oops", "text/plain");
  25526. });
  25527. svr.Post("/post", [&](const Request &req, Response &res) {
  25528. res.set_content(req.body, "text/plain");
  25529. });
  25530. auto port = svr.bind_to_any_port("localhost");
  25531. thread t = thread([&] { svr.listen_after_bind(); });
  25532. auto se = detail::scope_exit([&] {
  25533. svr.stop();
  25534. t.join();
  25535. });
  25536. svr.wait_until_ready();
  25537. auto error = Error::Success;
  25538. auto sock = detail::create_client_socket(
  25539. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25540. /*connection_timeout_sec=*/2, 0,
  25541. /*read_timeout_sec=*/2, 0,
  25542. /*write_timeout_sec=*/2, 0, std::string(), error);
  25543. EXPECT_NE(INVALID_SOCKET, sock);
  25544. if (sock == INVALID_SOCKET) { return -1; }
  25545. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25546. // The "smuggled" request will be sent as the body of the outer request
  25547. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25548. "Host: localhost\r\n"
  25549. "Connection: close\r\n"
  25550. "\r\n";
  25551. auto head = outer_head;
  25552. auto len = std::to_string(smuggled.size());
  25553. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25554. pos = head.find("{len}", pos + len.size())) {
  25555. head.replace(pos, 5, len);
  25556. }
  25557. // Step 1: Send only the outer request headers (no body yet)
  25558. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25559. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25560. // Step 2: Read the first response
  25561. char buf[4096];
  25562. for (;;) {
  25563. auto n = recv(sock, buf, sizeof(buf), 0);
  25564. if (n <= 0) break;
  25565. first_response.append(buf, static_cast<size_t>(n));
  25566. // Stop once we have a complete response (headers + body)
  25567. auto hdr_end = first_response.find("\r\n\r\n");
  25568. if (hdr_end != std::string::npos) {
  25569. // Check for Content-Length to know when the body is complete
  25570. auto cl_pos = first_response.find("Content-Length:");
  25571. if (cl_pos != std::string::npos) {
  25572. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25573. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25574. auto cl = std::stoul(
  25575. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25576. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25577. } else {
  25578. break; // No Content-Length, assume headers-only response
  25579. }
  25580. }
  25581. }
  25582. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25583. // vulnerable server the keep-alive loop reads this as a second request. The
  25584. // server may already have closed the connection, so the result is ignored.
  25585. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25586. // Half-close so that a server which drained the body sees EOF and closes,
  25587. // instead of the read below waiting for the read timeout.
  25588. #ifdef _WIN32
  25589. ::shutdown(sock, SD_SEND);
  25590. #else
  25591. ::shutdown(sock, SHUT_WR);
  25592. #endif
  25593. // Step 4: Read until the server closes the connection
  25594. for (;;) {
  25595. auto n = recv(sock, buf, sizeof(buf), 0);
  25596. if (n <= 0) break;
  25597. }
  25598. return smuggled_count.load();
  25599. }
  25600. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25601. // A GET request with Content-Length to a static file handler must have its
  25602. // body drained before the keep-alive connection is reused. Otherwise the
  25603. // unread body bytes are interpreted as the next HTTP request.
  25604. std::string first_response;
  25605. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25606. "Host: localhost\r\n"
  25607. "Content-Length: {len}\r\n"
  25608. "\r\n",
  25609. first_response));
  25610. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25611. }
  25612. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25613. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25614. // be answered with 400 and the connection closed. Treating it as "no body"
  25615. // leaves the body to be parsed as the next request.
  25616. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25617. const char *targets[] = {
  25618. "GET /file", // handler that never reads the body
  25619. "GET /not-found", // no handler matches (404)
  25620. "POST /post", // handler that reads the body
  25621. };
  25622. for (auto target : targets) {
  25623. for (auto value : values) {
  25624. std::string first_response;
  25625. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25626. " HTTP/1.1\r\n"
  25627. "Host: localhost\r\n"
  25628. "Content-Length: " +
  25629. value + "\r\n\r\n",
  25630. first_response))
  25631. << target << " with Content-Length: " << value;
  25632. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25633. << target << " with Content-Length: " << value;
  25634. }
  25635. }
  25636. }
  25637. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25638. // A 400 for an unparseable request line leaves the rest of the message
  25639. // unread, so the connection must be closed rather than reused.
  25640. std::string first_response;
  25641. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25642. "Host: localhost\r\n"
  25643. "Content-Length: {len}\r\n"
  25644. "\r\n",
  25645. first_response));
  25646. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25647. }
  25648. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25649. // Same as above for a header block that fails to parse.
  25650. std::string first_response;
  25651. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25652. "Host: localhost\r\n"
  25653. "Bad Header\r\n"
  25654. "Content-Length: {len}\r\n"
  25655. "\r\n",
  25656. first_response));
  25657. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25658. }
  25659. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25660. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25661. // server must not read another request on that connection, even when the
  25662. // request had no body to drain.
  25663. std::string first_response;
  25664. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25665. "Host: localhost\r\n"
  25666. "\r\n",
  25667. first_response));
  25668. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25669. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25670. }
  25671. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25672. // A content reader that stops early leaves the stream inside the body.
  25673. // Draining the whole Content-Length from there, or reading the body again,
  25674. // reads into the next request, and whatever follows is parsed as a request
  25675. // of its own.
  25676. Server svr;
  25677. std::atomic<int> smuggled_count(0);
  25678. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25679. svr.Post("/upload", [](const Request &req, Response &res,
  25680. const ContentReader &content_reader) {
  25681. // Stop at the last chunk, so the whole body has been read however it
  25682. // arrives.
  25683. auto length = req.get_header_value_u64("Content-Length");
  25684. size_t total = 0;
  25685. auto consumed = content_reader([&](const char *, size_t n) {
  25686. total += n;
  25687. return total < length;
  25688. });
  25689. EXPECT_FALSE(consumed);
  25690. if (req.has_param("retry")) {
  25691. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25692. }
  25693. // Replace the 400 the aborted read set, which would close the connection.
  25694. res.set_redirect("/done");
  25695. });
  25696. auto port = svr.bind_to_any_port(HOST);
  25697. thread t = thread([&] { svr.listen_after_bind(); });
  25698. auto se = detail::scope_exit([&] {
  25699. svr.stop();
  25700. t.join();
  25701. });
  25702. svr.wait_until_ready();
  25703. // A front end sees the second request as a POST whose body is the GET. The
  25704. // first body is as long as the POST's headers, so draining it again reads
  25705. // exactly those and leaves the GET to be parsed next.
  25706. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25707. "Host: localhost\r\n"
  25708. "\r\n";
  25709. std::string second_head = "POST /post HTTP/1.1\r\n"
  25710. "Host: localhost\r\n"
  25711. "Content-Length: " +
  25712. std::to_string(inner.size()) +
  25713. "\r\n"
  25714. "\r\n";
  25715. for (auto target : {"/upload", "/upload?retry"}) {
  25716. smuggled_count = 0;
  25717. std::string request = "POST " + std::string(target) +
  25718. " HTTP/1.1\r\n"
  25719. "Host: localhost\r\n"
  25720. "Content-Length: " +
  25721. std::to_string(second_head.size()) +
  25722. "\r\n"
  25723. "\r\n" +
  25724. std::string(second_head.size(), 'A') + second_head +
  25725. inner;
  25726. std::string response;
  25727. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25728. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25729. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25730. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25731. EXPECT_EQ(0, smuggled_count.load()) << target;
  25732. }
  25733. }
  25734. // An error response closes the connection anyway, so the body is left unread
  25735. // with a redirect, such as one to a login page.
  25736. static void serve_redirects(Server &svr,
  25737. const std::function<void(int)> &client) {
  25738. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25739. res.set_redirect("/login");
  25740. return Server::HandlerResponse::Handled;
  25741. });
  25742. auto port = svr.bind_to_any_port(HOST);
  25743. ASSERT_GT(port, 0);
  25744. thread t = thread([&] { svr.listen_after_bind(); });
  25745. auto se = detail::scope_exit([&] {
  25746. svr.stop();
  25747. t.join();
  25748. ASSERT_FALSE(svr.is_running());
  25749. });
  25750. svr.wait_until_ready();
  25751. client(port);
  25752. }
  25753. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25754. Server svr;
  25755. serve_redirects(svr, [](int port) {
  25756. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25757. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25758. std::to_string(body.size()) + "\r\n\r\n" + body +
  25759. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25760. std::string resp;
  25761. ASSERT_TRUE(send_request(1, req, &resp, port));
  25762. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25763. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25764. });
  25765. }
  25766. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25767. Server svr;
  25768. svr.set_read_timeout(0, 200000);
  25769. serve_redirects(svr, [](int port) {
  25770. // A byte every 100 ms keeps each read within the read timeout, but not the
  25771. // body as a whole, so the server closes and the bytes sent after that fail.
  25772. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25773. "Content-Length: 10\r\n\r\n"};
  25774. parts.resize(11, "x");
  25775. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25776. });
  25777. }
  25778. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25779. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25780. // must be rejected with 400 Bad Request.
  25781. Server svr;
  25782. svr.Post("/test", [&](const Request &, Response &res) {
  25783. res.set_content("ok", "text/plain");
  25784. });
  25785. thread t = thread([&] { svr.listen(HOST, PORT); });
  25786. auto se = detail::scope_exit([&] {
  25787. svr.stop();
  25788. t.join();
  25789. ASSERT_FALSE(svr.is_running());
  25790. });
  25791. svr.wait_until_ready();
  25792. // Exact "chunked"
  25793. {
  25794. auto req = "POST /test HTTP/1.1\r\n"
  25795. "Host: localhost\r\n"
  25796. "Content-Length: 5\r\n"
  25797. "Transfer-Encoding: chunked\r\n"
  25798. "Connection: close\r\n"
  25799. "\r\n"
  25800. "hello";
  25801. std::string response;
  25802. ASSERT_TRUE(send_request(1, req, &response));
  25803. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25804. response.substr(0, response.find("\r\n")));
  25805. }
  25806. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25807. {
  25808. auto req = "POST /test HTTP/1.1\r\n"
  25809. "Host: localhost\r\n"
  25810. "Content-Length: 5\r\n"
  25811. "Transfer-Encoding: gzip, chunked\r\n"
  25812. "Connection: close\r\n"
  25813. "\r\n"
  25814. "hello";
  25815. std::string response;
  25816. ASSERT_TRUE(send_request(1, req, &response));
  25817. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25818. response.substr(0, response.find("\r\n")));
  25819. }
  25820. }
  25821. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25822. Server svr;
  25823. svr.Post("/test", [&](const Request &, Response &res) {
  25824. res.set_content("ok", "text/plain");
  25825. });
  25826. thread t = thread([&] { svr.listen(HOST, PORT); });
  25827. auto se = detail::scope_exit([&] {
  25828. svr.stop();
  25829. t.join();
  25830. ASSERT_FALSE(svr.is_running());
  25831. });
  25832. svr.wait_until_ready();
  25833. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25834. // length cannot be determined, so the server must answer 400 and close
  25835. // rather than treat the request as bodyless and leave the body in the
  25836. // socket for the next request to pick up.
  25837. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25838. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25839. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25840. std::string response;
  25841. ASSERT_TRUE(send_request(1, req, &response));
  25842. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25843. response.substr(0, response.find("\r\n")))
  25844. << transfer_encoding;
  25845. }
  25846. // RFC 9110 5.3: the codings may also be split across several
  25847. // Transfer-Encoding lines, which combine in the order they were received.
  25848. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25849. // just like the single-line "chunked, gzip" above.
  25850. {
  25851. auto req = "POST /test HTTP/1.1\r\n"
  25852. "Host: localhost\r\n"
  25853. "Transfer-Encoding: chunked\r\n"
  25854. "Transfer-Encoding: gzip\r\n"
  25855. "\r\n"
  25856. "0\r\n\r\n";
  25857. std::string response;
  25858. ASSERT_TRUE(send_request(1, req, &response));
  25859. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25860. response.substr(0, response.find("\r\n")));
  25861. }
  25862. }
  25863. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25864. Server svr;
  25865. svr.Post("/test", [&](const Request &, Response &res) {
  25866. res.set_content("ok", "text/plain");
  25867. });
  25868. auto port = svr.bind_to_any_port(HOST);
  25869. ASSERT_GT(port, 0);
  25870. thread t = thread([&] { svr.listen_after_bind(); });
  25871. auto se = detail::scope_exit([&] {
  25872. svr.stop();
  25873. t.join();
  25874. ASSERT_FALSE(svr.is_running());
  25875. });
  25876. svr.wait_until_ready();
  25877. for (auto transfer_encoding :
  25878. {"Transfer-Encoding: gzip, chunked\r\n",
  25879. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25880. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25881. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25882. transfer_encoding + "\r\n0\r\n\r\n";
  25883. std::string response;
  25884. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25885. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25886. response.substr(0, response.find("\r\n")))
  25887. << transfer_encoding;
  25888. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25889. << transfer_encoding;
  25890. }
  25891. }
  25892. // Regression for issue #2450: a DELETE without Content-Length on a
  25893. // keep-alive connection must not let the post-response drain consume the
  25894. // next request's bytes.
  25895. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25896. Server svr;
  25897. std::atomic<int> delete_count(0);
  25898. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25899. delete_count++;
  25900. res.status = StatusCode::NoContent_204;
  25901. });
  25902. auto port = svr.bind_to_any_port(HOST);
  25903. thread t = thread([&] { svr.listen_after_bind(); });
  25904. auto se = detail::scope_exit([&] {
  25905. svr.stop();
  25906. t.join();
  25907. });
  25908. svr.wait_until_ready();
  25909. auto error = Error::Success;
  25910. auto sock = detail::create_client_socket(
  25911. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25912. /*connection_timeout_sec=*/2, 0,
  25913. /*read_timeout_sec=*/2, 0,
  25914. /*write_timeout_sec=*/2, 0, std::string(), error);
  25915. ASSERT_NE(INVALID_SOCKET, sock);
  25916. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25917. auto send_request_and_read_response = [&](const std::string &req,
  25918. std::string &out) -> bool {
  25919. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25920. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25921. char buf[4096];
  25922. for (;;) {
  25923. auto n = recv(sock, buf, sizeof(buf), 0);
  25924. if (n <= 0) { return !out.empty(); }
  25925. out.append(buf, static_cast<size_t>(n));
  25926. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25927. }
  25928. };
  25929. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25930. "Host: localhost\r\n"
  25931. "\r\n";
  25932. std::string resp1;
  25933. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25934. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25935. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25936. "Host: localhost\r\n"
  25937. "Connection: close\r\n"
  25938. "\r\n";
  25939. std::string resp2;
  25940. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25941. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25942. EXPECT_EQ(2, delete_count.load());
  25943. }
  25944. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25945. Server svr;
  25946. svr.Post("/ingest", [&](const Request &, Response &res,
  25947. const ContentReader &content_reader) {
  25948. auto consumed = content_reader([](const char *, size_t) { return false; });
  25949. EXPECT_FALSE(consumed);
  25950. res.status = StatusCode::Conflict_409;
  25951. res.set_header("Connection", "close");
  25952. });
  25953. auto port = svr.bind_to_any_port(HOST);
  25954. thread t = thread([&] { svr.listen_after_bind(); });
  25955. auto se = detail::scope_exit([&] {
  25956. svr.stop();
  25957. t.join();
  25958. });
  25959. svr.wait_until_ready();
  25960. auto error = Error::Success;
  25961. auto sock = detail::create_client_socket(
  25962. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25963. /*connection_timeout_sec=*/2, 0,
  25964. /*read_timeout_sec=*/1, 0,
  25965. /*write_timeout_sec=*/2, 0, std::string(), error);
  25966. ASSERT_NE(INVALID_SOCKET, sock);
  25967. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25968. std::string request = "POST /ingest HTTP/1.1\r\n"
  25969. "Host: localhost\r\n"
  25970. "Transfer-Encoding: chunked\r\n"
  25971. "\r\n"
  25972. "4\r\n"
  25973. "data\r\n";
  25974. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25975. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25976. std::string response;
  25977. ssize_t received = 0;
  25978. do {
  25979. char buf[4096];
  25980. received = recv(sock, buf, sizeof(buf), 0);
  25981. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25982. } while (received > 0);
  25983. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25984. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25985. EXPECT_EQ(0, received);
  25986. }
  25987. namespace no_proxy_test {
  25988. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25989. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25990. // calling listen().
  25991. class ScopedServer {
  25992. public:
  25993. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25994. ~ScopedServer() {
  25995. svr_.stop();
  25996. if (th_.joinable()) { th_.join(); }
  25997. }
  25998. Server &svr() { return svr_; }
  25999. int port() const { return port_; }
  26000. void listen() {
  26001. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26002. svr_.wait_until_ready();
  26003. }
  26004. private:
  26005. Server svr_;
  26006. std::thread th_;
  26007. int port_ = 0;
  26008. };
  26009. class ProxyAndTargetServers {
  26010. public:
  26011. ProxyAndTargetServers() {
  26012. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26013. proxy_hits_++;
  26014. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26015. res.set_content("via-proxy", "text/plain");
  26016. });
  26017. target_.Get(".*", [this](const Request &req, Response &res) {
  26018. target_hits_++;
  26019. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26020. res.set_content("direct", "text/plain");
  26021. });
  26022. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26023. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26024. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26025. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26026. proxy_mock_.wait_until_ready();
  26027. target_.wait_until_ready();
  26028. }
  26029. ~ProxyAndTargetServers() {
  26030. proxy_mock_.stop();
  26031. target_.stop();
  26032. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26033. if (target_thread_.joinable()) { target_thread_.join(); }
  26034. }
  26035. Server &proxy_mock() { return proxy_mock_; }
  26036. Server &target() { return target_; }
  26037. int proxy_port() const { return proxy_port_; }
  26038. int target_port() const { return target_port_; }
  26039. int proxy_hits() const { return proxy_hits_.load(); }
  26040. int target_hits() const { return target_hits_.load(); }
  26041. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26042. void reset_counters() {
  26043. proxy_hits_ = 0;
  26044. target_hits_ = 0;
  26045. last_had_proxy_authz_ = false;
  26046. }
  26047. private:
  26048. Server proxy_mock_;
  26049. Server target_;
  26050. std::thread proxy_thread_;
  26051. std::thread target_thread_;
  26052. int proxy_port_ = 0;
  26053. int target_port_ = 0;
  26054. std::atomic<int> proxy_hits_{0};
  26055. std::atomic<int> target_hits_{0};
  26056. std::atomic<bool> last_had_proxy_authz_{false};
  26057. };
  26058. inline std::unique_ptr<Client> make_client(const std::string &host,
  26059. ProxyAndTargetServers &s) {
  26060. auto cli = detail::make_unique<Client>(host, s.target_port());
  26061. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  26062. cli->set_proxy("127.0.0.1", s.proxy_port());
  26063. return cli;
  26064. }
  26065. } // namespace no_proxy_test
  26066. using no_proxy_test::make_client;
  26067. using no_proxy_test::ProxyAndTargetServers;
  26068. // A stream request carries the credentials a buffered request does
  26069. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26070. no_proxy_test::ScopedServer origin;
  26071. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26072. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26073. });
  26074. origin.listen();
  26075. Client cli("127.0.0.1", origin.port());
  26076. cli.set_basic_auth("user", "pass");
  26077. auto handle = cli.open_stream("GET", "/x");
  26078. ASSERT_TRUE(handle.is_valid());
  26079. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26080. Client bearer("127.0.0.1", origin.port());
  26081. bearer.set_bearer_token_auth("tok");
  26082. auto handle2 = bearer.open_stream("GET", "/x");
  26083. ASSERT_TRUE(handle2.is_valid());
  26084. EXPECT_EQ("Bearer tok", read_all(handle2));
  26085. }
  26086. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26087. // takes its own credentials, as for a buffered request
  26088. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26089. std::string target, authz, proxy_authz;
  26090. no_proxy_test::ScopedServer proxy;
  26091. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26092. target = req.target;
  26093. authz = req.get_header_value("Authorization");
  26094. proxy_authz = req.get_header_value("Proxy-Authorization");
  26095. res.set_content("ok", "text/plain");
  26096. });
  26097. proxy.listen();
  26098. Client cli("origin.example", 8080);
  26099. cli.set_proxy("127.0.0.1", proxy.port());
  26100. cli.set_proxy_basic_auth("puser", "ppass");
  26101. cli.set_basic_auth("user", "pass");
  26102. auto handle = cli.open_stream("GET", "/x");
  26103. ASSERT_TRUE(handle.is_valid());
  26104. EXPECT_EQ("ok", read_all(handle));
  26105. EXPECT_EQ("http://origin.example:8080/x", target);
  26106. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26107. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26108. }
  26109. // In absolute-form the path follows the authority, so a path that does not
  26110. // begin with '/' would make the proxy connect to another host
  26111. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26112. std::vector<std::string> targets;
  26113. no_proxy_test::ScopedServer proxy;
  26114. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26115. targets.push_back(req.target);
  26116. res.set_content("ok", "text/plain");
  26117. });
  26118. proxy.listen();
  26119. Client cli("origin.example", 8080);
  26120. cli.set_proxy("127.0.0.1", proxy.port());
  26121. cli.set_basic_auth("user", "pass");
  26122. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26123. auto res = cli.Get(path);
  26124. EXPECT_FALSE(res) << path;
  26125. auto handle = cli.open_stream("GET", path);
  26126. EXPECT_FALSE(handle.is_valid()) << path;
  26127. }
  26128. EXPECT_TRUE(targets.empty());
  26129. auto res = cli.Get("/x");
  26130. ASSERT_TRUE(res);
  26131. ASSERT_EQ(1u, targets.size());
  26132. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26133. }
  26134. TEST(NoProxyTest, ExactHostnameBypasses) {
  26135. ProxyAndTargetServers s;
  26136. auto cli = make_client("example.com", s);
  26137. cli->set_no_proxy({"example.com"});
  26138. auto res = cli->Get("/");
  26139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26140. EXPECT_EQ(0, s.proxy_hits());
  26141. EXPECT_EQ(1, s.target_hits());
  26142. }
  26143. TEST(NoProxyTest, SubdomainBypasses) {
  26144. ProxyAndTargetServers s;
  26145. auto cli = make_client("foo.example.com", s);
  26146. cli->set_no_proxy({"example.com"});
  26147. auto res = cli->Get("/");
  26148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26149. EXPECT_EQ(0, s.proxy_hits());
  26150. EXPECT_EQ(1, s.target_hits());
  26151. }
  26152. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26153. // Regression guard: "evilexample.com" must not be considered a subdomain
  26154. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26155. // check would let traffic bypass the proxy and leak credentials direct
  26156. // to the attacker host.
  26157. ProxyAndTargetServers s;
  26158. auto cli = make_client("evilexample.com", s);
  26159. cli->set_no_proxy({"example.com"});
  26160. auto res = cli->Get("/");
  26161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26162. EXPECT_GE(s.proxy_hits(), 1);
  26163. EXPECT_EQ(0, s.target_hits());
  26164. }
  26165. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26166. ProxyAndTargetServers s;
  26167. auto cli = make_client("example.com.evil.com", s);
  26168. cli->set_no_proxy({"example.com"});
  26169. auto res = cli->Get("/");
  26170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26171. EXPECT_GE(s.proxy_hits(), 1);
  26172. EXPECT_EQ(0, s.target_hits());
  26173. }
  26174. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26175. ProxyAndTargetServers s;
  26176. auto cli = make_client("example.com", s);
  26177. cli->set_no_proxy({".example.com"});
  26178. auto res = cli->Get("/");
  26179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26180. EXPECT_EQ(0, s.proxy_hits());
  26181. EXPECT_EQ(1, s.target_hits());
  26182. }
  26183. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26184. ProxyAndTargetServers s;
  26185. auto cli = make_client("Example.COM", s);
  26186. cli->set_no_proxy({"EXAMPLE.com"});
  26187. auto res = cli->Get("/");
  26188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26189. EXPECT_EQ(0, s.proxy_hits());
  26190. EXPECT_EQ(1, s.target_hits());
  26191. }
  26192. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26193. ProxyAndTargetServers s;
  26194. auto cli = make_client("example.com.", s);
  26195. cli->set_no_proxy({"example.com"});
  26196. auto res = cli->Get("/");
  26197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26198. EXPECT_EQ(0, s.proxy_hits());
  26199. EXPECT_EQ(1, s.target_hits());
  26200. }
  26201. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26202. // Trailing dots must be normalized on BOTH sides — host and entry.
  26203. // An implementation that only strips the host-side trailing dot would
  26204. // fail to match host "example.com" against entry "example.com." because
  26205. // a literal substring search would compare 11 chars against 12.
  26206. ProxyAndTargetServers s;
  26207. auto cli = make_client("example.com", s);
  26208. cli->set_no_proxy({"example.com."});
  26209. auto res = cli->Get("/");
  26210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26211. EXPECT_EQ(0, s.proxy_hits());
  26212. EXPECT_EQ(1, s.target_hits());
  26213. }
  26214. TEST(NoProxyTest, WildcardBypassesEverything) {
  26215. ProxyAndTargetServers s;
  26216. auto cli = make_client("anything.invalid.test", s);
  26217. cli->set_no_proxy({"*"});
  26218. auto res = cli->Get("/");
  26219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26220. EXPECT_EQ(0, s.proxy_hits());
  26221. EXPECT_EQ(1, s.target_hits());
  26222. }
  26223. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26224. ProxyAndTargetServers s;
  26225. Client cli("127.0.0.1", s.target_port());
  26226. cli.set_proxy("127.0.0.1", s.proxy_port());
  26227. cli.set_no_proxy({"127.0.0.1"});
  26228. auto res = cli.Get("/");
  26229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26230. EXPECT_EQ(0, s.proxy_hits());
  26231. EXPECT_EQ(1, s.target_hits());
  26232. }
  26233. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26234. ProxyAndTargetServers s;
  26235. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26236. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26237. cli.set_proxy("127.0.0.1", s.proxy_port());
  26238. cli.set_no_proxy({"::1"});
  26239. auto res = cli.Get("/");
  26240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26241. EXPECT_EQ(0, s.proxy_hits());
  26242. EXPECT_EQ(1, s.target_hits());
  26243. }
  26244. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26245. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26246. // must still be recognized as IPv6 for CIDR matching. Implementations
  26247. // that detect IPv6 only when the host begins with '[' would parse the
  26248. // host as a hostname and miss the match.
  26249. ProxyAndTargetServers s;
  26250. Client cli("fe80::1", s.target_port());
  26251. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26252. cli.set_proxy("127.0.0.1", s.proxy_port());
  26253. cli.set_no_proxy({"fe80::/10"});
  26254. auto res = cli.Get("/");
  26255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26256. EXPECT_EQ(0, s.proxy_hits());
  26257. EXPECT_EQ(1, s.target_hits());
  26258. }
  26259. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26260. ProxyAndTargetServers s;
  26261. Client cli("::1", s.target_port());
  26262. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  26263. cli.set_proxy("127.0.0.1", s.proxy_port());
  26264. cli.set_no_proxy({"[::1]"});
  26265. auto res = cli.Get("/");
  26266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26267. EXPECT_EQ(0, s.proxy_hits());
  26268. EXPECT_EQ(1, s.target_hits());
  26269. }
  26270. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26271. ProxyAndTargetServers s;
  26272. Client cli("fe80::1", s.target_port());
  26273. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26274. cli.set_proxy("127.0.0.1", s.proxy_port());
  26275. cli.set_no_proxy({"[fe80::]/10"});
  26276. auto res = cli.Get("/");
  26277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26278. EXPECT_EQ(0, s.proxy_hits());
  26279. EXPECT_EQ(1, s.target_hits());
  26280. }
  26281. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26282. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26283. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26284. // tricks via address-family conversion.
  26285. ProxyAndTargetServers s;
  26286. Client cli("::ffff:127.0.0.1", s.target_port());
  26287. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26288. cli.set_proxy("127.0.0.1", s.proxy_port());
  26289. cli.set_no_proxy({"127.0.0.1"});
  26290. auto res = cli.Get("/");
  26291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26292. EXPECT_GE(s.proxy_hits(), 1);
  26293. EXPECT_EQ(0, s.target_hits());
  26294. }
  26295. TEST(NoProxyTest, IPv4CidrMatch) {
  26296. ProxyAndTargetServers s;
  26297. Client cli("127.0.0.1", s.target_port());
  26298. cli.set_proxy("127.0.0.1", s.proxy_port());
  26299. cli.set_no_proxy({"127.0.0.0/8"});
  26300. auto res = cli.Get("/");
  26301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26302. EXPECT_EQ(0, s.proxy_hits());
  26303. EXPECT_EQ(1, s.target_hits());
  26304. }
  26305. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26306. ProxyAndTargetServers s;
  26307. Client cli("127.0.0.1", s.target_port());
  26308. cli.set_proxy("127.0.0.1", s.proxy_port());
  26309. cli.set_no_proxy({"10.0.0.0/8"});
  26310. auto res = cli.Get("/");
  26311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26312. EXPECT_GE(s.proxy_hits(), 1);
  26313. EXPECT_EQ(0, s.target_hits());
  26314. }
  26315. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26316. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26317. // IPv4 target matches.
  26318. ProxyAndTargetServers s;
  26319. Client cli("127.0.0.1", s.target_port());
  26320. cli.set_proxy("127.0.0.1", s.proxy_port());
  26321. cli.set_no_proxy({"0.0.0.0/0"});
  26322. auto res = cli.Get("/");
  26323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26324. EXPECT_EQ(0, s.proxy_hits());
  26325. EXPECT_EQ(1, s.target_hits());
  26326. }
  26327. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26328. ProxyAndTargetServers s;
  26329. Client cli("127.0.0.1", s.target_port());
  26330. cli.set_proxy("127.0.0.1", s.proxy_port());
  26331. cli.set_no_proxy({"127.0.0.1"});
  26332. auto res = cli.Get("/");
  26333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26334. EXPECT_EQ(0, s.proxy_hits());
  26335. EXPECT_EQ(1, s.target_hits());
  26336. }
  26337. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26338. ProxyAndTargetServers s;
  26339. Client cli("127.0.0.1", s.target_port());
  26340. cli.set_proxy("127.0.0.1", s.proxy_port());
  26341. cli.set_no_proxy({"127.0.0.0/33"});
  26342. auto res = cli.Get("/");
  26343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26344. EXPECT_GE(s.proxy_hits(), 1);
  26345. EXPECT_EQ(0, s.target_hits());
  26346. }
  26347. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26348. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26349. ProxyAndTargetServers s;
  26350. Client cli("127.0.0.1", s.target_port());
  26351. cli.set_proxy("127.0.0.1", s.proxy_port());
  26352. cli.set_no_proxy({"127.0.0.1/"});
  26353. auto res = cli.Get("/");
  26354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26355. EXPECT_GE(s.proxy_hits(), 1);
  26356. EXPECT_EQ(0, s.target_hits());
  26357. }
  26358. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26359. ProxyAndTargetServers s;
  26360. auto cli = make_client("internal.corp", s);
  26361. cli->set_proxy_basic_auth("u", "p");
  26362. cli->set_no_proxy({"internal.corp"});
  26363. auto res = cli->Get("/");
  26364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26365. EXPECT_EQ(1, s.target_hits());
  26366. EXPECT_EQ(0, s.proxy_hits());
  26367. EXPECT_FALSE(s.last_had_proxy_authz())
  26368. << "Proxy-Authorization must not be sent direct to the target";
  26369. }
  26370. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26371. ProxyAndTargetServers s;
  26372. auto cli = make_client("public.example", s);
  26373. cli->set_proxy_basic_auth("u", "p");
  26374. cli->set_no_proxy({"internal.corp"}); // does not match
  26375. auto res = cli->Get("/");
  26376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26377. EXPECT_GE(s.proxy_hits(), 1);
  26378. EXPECT_TRUE(s.last_had_proxy_authz());
  26379. }
  26380. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26381. std::atomic<int> hits{0};
  26382. std::atomic<int> hits_with_authz{0};
  26383. no_proxy_test::ScopedServer proxy_mock;
  26384. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26385. hits++;
  26386. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26387. if (req.target.find("/redir") != std::string::npos) {
  26388. res.set_redirect("http://other.example/landed");
  26389. } else {
  26390. res.set_content("via-proxy", "text/plain");
  26391. }
  26392. });
  26393. proxy_mock.listen();
  26394. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26395. hits = 0;
  26396. hits_with_authz = 0;
  26397. Client cli("public.example", 80);
  26398. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26399. cli.set_proxy_basic_auth(c.first, c.second);
  26400. cli.set_follow_location(true);
  26401. // The redirect to another host goes through the proxy as well
  26402. auto res = cli.Get("/redir");
  26403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26404. EXPECT_EQ(2, hits.load());
  26405. EXPECT_EQ(2, hits_with_authz.load());
  26406. }
  26407. }
  26408. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26409. ProxyAndTargetServers s;
  26410. auto cli = make_client("anything.test", s);
  26411. auto res = cli->Get("/");
  26412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26413. EXPECT_GE(s.proxy_hits(), 1);
  26414. EXPECT_EQ(0, s.target_hits());
  26415. }
  26416. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26417. ProxyAndTargetServers s;
  26418. auto cli = make_client("example.com", s);
  26419. cli->set_no_proxy({"example.com:8080"});
  26420. auto res = cli->Get("/");
  26421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26422. EXPECT_GE(s.proxy_hits(), 1);
  26423. EXPECT_EQ(0, s.target_hits());
  26424. }
  26425. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26426. ProxyAndTargetServers s;
  26427. auto cli = make_client("anything.test", s);
  26428. cli->set_no_proxy({"", " ", "\t"});
  26429. auto res = cli->Get("/");
  26430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26431. EXPECT_GE(s.proxy_hits(), 1);
  26432. EXPECT_EQ(0, s.target_hits());
  26433. }
  26434. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26435. // An entry with leading/trailing whitespace must still match — env-style
  26436. // values are commonly pasted with stray spaces and an implementation
  26437. // that feeds the raw token directly to inet_pton would fail to match
  26438. // valid CIDRs because of the spaces.
  26439. ProxyAndTargetServers s;
  26440. Client cli("127.0.0.1", s.target_port());
  26441. cli.set_proxy("127.0.0.1", s.proxy_port());
  26442. cli.set_no_proxy({" 127.0.0.0/8 "});
  26443. auto res = cli.Get("/");
  26444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26445. EXPECT_EQ(0, s.proxy_hits());
  26446. EXPECT_EQ(1, s.target_hits());
  26447. }
  26448. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26449. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26450. // go direct and must NOT carry Proxy-Authorization.
  26451. std::atomic<int> proxy_hits{0};
  26452. std::atomic<int> target_hits{0};
  26453. std::atomic<bool> target_saw_authz{false};
  26454. no_proxy_test::ScopedServer proxy_mock, target;
  26455. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26456. proxy_hits++;
  26457. res.status = 302;
  26458. res.set_header("Location", "http://127.0.0.1:" +
  26459. std::to_string(target.port()) + "/landed");
  26460. });
  26461. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26462. target_hits++;
  26463. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26464. res.set_content("direct", "text/plain");
  26465. });
  26466. proxy_mock.listen();
  26467. target.listen();
  26468. Client cli("public.example", target.port());
  26469. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26470. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26471. cli.set_proxy_basic_auth("u", "p");
  26472. cli.set_no_proxy({"127.0.0.1"});
  26473. cli.set_follow_location(true);
  26474. auto res = cli.Get("/redir");
  26475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26476. EXPECT_GE(proxy_hits.load(), 1);
  26477. EXPECT_GE(target_hits.load(), 1);
  26478. EXPECT_FALSE(target_saw_authz.load());
  26479. }
  26480. #ifdef CPPHTTPLIB_SSL_ENABLED
  26481. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26482. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26483. // proxy creds would be sent to the (possibly hostile) origin.
  26484. std::atomic<int> target_hits{0};
  26485. std::atomic<bool> target_saw_proxy_authz{false};
  26486. no_proxy_test::ScopedServer target;
  26487. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26488. target_hits++;
  26489. if (req.has_header("Proxy-Authorization")) {
  26490. target_saw_proxy_authz = true;
  26491. }
  26492. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26493. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26494. "nonce=\"abc\", algorithm=MD5");
  26495. });
  26496. target.listen();
  26497. // The proxy address is set to the target's port: the bypass MUST kick in;
  26498. // if it doesn't, the test still routes "via proxy" to the same server and
  26499. // the Proxy-Authorization assertion below catches the leak.
  26500. Client cli("evil.example", target.port());
  26501. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26502. cli.set_proxy("127.0.0.1", target.port());
  26503. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26504. cli.set_no_proxy({"evil.example"});
  26505. auto res = cli.Get("/x");
  26506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26507. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26508. EXPECT_EQ(1, target_hits.load());
  26509. EXPECT_FALSE(target_saw_proxy_authz.load());
  26510. }
  26511. #endif
  26512. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26513. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26514. std::atomic<int> proxy_hits{0};
  26515. std::atomic<int> bypass_hits{0};
  26516. std::atomic<bool> proxy_saw_c_url{false};
  26517. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26518. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26519. proxy_hits++;
  26520. if (req.path.find("/start") != std::string::npos) {
  26521. res.status = 302;
  26522. res.set_header("Location", "http://127.0.0.1:" +
  26523. std::to_string(bypass_server.port()) +
  26524. "/middle");
  26525. return;
  26526. }
  26527. if (req.path.find("/end") != std::string::npos) {
  26528. proxy_saw_c_url = true;
  26529. res.set_content("c-via-proxy", "text/plain");
  26530. return;
  26531. }
  26532. res.set_content("unexpected", "text/plain");
  26533. });
  26534. // public.example's "advertised" port is arbitrary (the request never lands
  26535. // there — it goes through the proxy), but use a dynamic value to stay
  26536. // friendly with sharded parallel runs.
  26537. int public_port = bypass_server.port();
  26538. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26539. bypass_hits++;
  26540. res.status = 302;
  26541. res.set_header("Location", "http://public.example:" +
  26542. std::to_string(public_port) + "/end");
  26543. });
  26544. proxy_mock.listen();
  26545. bypass_server.listen();
  26546. Client cli("public.example", public_port);
  26547. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26548. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26549. cli.set_no_proxy({"127.0.0.1"});
  26550. cli.set_follow_location(true);
  26551. auto res = cli.Get("/start");
  26552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26553. EXPECT_EQ(StatusCode::OK_200, res->status);
  26554. EXPECT_EQ("c-via-proxy", res->body);
  26555. EXPECT_GE(proxy_hits.load(), 2);
  26556. EXPECT_GE(bypass_hits.load(), 1);
  26557. EXPECT_TRUE(proxy_saw_c_url.load());
  26558. }
  26559. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26560. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26561. // request reconnects to the correct endpoint.
  26562. std::atomic<int> proxy_hits{0};
  26563. std::atomic<int> target_hits{0};
  26564. no_proxy_test::ScopedServer proxy_mock, target;
  26565. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26566. proxy_hits++;
  26567. res.set_content("via-proxy", "text/plain");
  26568. });
  26569. target.svr().Get(".*", [&](const Request &, Response &res) {
  26570. target_hits++;
  26571. res.set_content("direct", "text/plain");
  26572. });
  26573. proxy_mock.listen();
  26574. target.listen();
  26575. Client cli("public.example", target.port());
  26576. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26577. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26578. cli.set_keep_alive(true);
  26579. auto res1 = cli.Get("/a");
  26580. ASSERT_TRUE(res1);
  26581. EXPECT_EQ("via-proxy", res1->body);
  26582. EXPECT_EQ(1, proxy_hits.load());
  26583. EXPECT_EQ(0, target_hits.load());
  26584. cli.set_no_proxy({"public.example"});
  26585. auto res2 = cli.Get("/b");
  26586. ASSERT_TRUE(res2);
  26587. EXPECT_EQ("direct", res2->body);
  26588. EXPECT_EQ(1, proxy_hits.load());
  26589. EXPECT_EQ(1, target_hits.load());
  26590. }
  26591. // Forward declarations (see the base64_encode note).
  26592. namespace httplib {
  26593. namespace detail {
  26594. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26595. int shutdown_socket(socket_t sock) noexcept;
  26596. } // namespace detail
  26597. } // namespace httplib
  26598. namespace proxy_tunnel_test {
  26599. const char *const kTunnelEstablished =
  26600. "HTTP/1.1 200 Connection established\r\n\r\n";
  26601. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26602. using ConnectReply = std::function<std::string(const std::string &head)>;
  26603. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26604. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26605. class ScopedConnectProxy {
  26606. public:
  26607. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26608. : forward_port_(forward_port), reply_(std::move(reply)) {
  26609. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26610. if (listen_sock_ == INVALID_SOCKET) { return; }
  26611. auto a = loopback(0);
  26612. auto addr = reinterpret_cast<sockaddr *>(&a);
  26613. socklen_t alen = sizeof(a);
  26614. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26615. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26616. ::listen(listen_sock_, 4) != 0) {
  26617. return;
  26618. }
  26619. port_ = ntohs(a.sin_port);
  26620. th_ = std::thread([this] { run(); });
  26621. }
  26622. ~ScopedConnectProxy() {
  26623. if (th_.joinable()) {
  26624. stop_ = true;
  26625. auto wake = connect_to(port_);
  26626. th_.join();
  26627. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26628. }
  26629. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26630. }
  26631. int port() const { return port_; }
  26632. int connect_hits() const { return connect_hits_.load(); }
  26633. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26634. std::string connect_request() const {
  26635. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26636. return connect_request_;
  26637. }
  26638. private:
  26639. static sockaddr_in loopback(int port) {
  26640. sockaddr_in a{};
  26641. a.sin_family = AF_INET;
  26642. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26643. a.sin_port = htons(static_cast<unsigned short>(port));
  26644. return a;
  26645. }
  26646. static socket_t connect_to(int port) {
  26647. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26648. if (sock == INVALID_SOCKET) { return sock; }
  26649. auto a = loopback(port);
  26650. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26651. detail::close_socket(sock);
  26652. return INVALID_SOCKET;
  26653. }
  26654. return sock;
  26655. }
  26656. static bool send_all(socket_t sock, const char *data, size_t size) {
  26657. while (size > 0) {
  26658. auto n = detail::send_socket(sock, data, size, 0);
  26659. if (n <= 0) { return false; }
  26660. data += n;
  26661. size -= static_cast<size_t>(n);
  26662. }
  26663. return true;
  26664. }
  26665. void run() {
  26666. for (;;) {
  26667. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26668. if (stop_) {
  26669. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26670. return;
  26671. }
  26672. if (client == INVALID_SOCKET) { continue; }
  26673. serve(client);
  26674. detail::close_socket(client);
  26675. }
  26676. }
  26677. void serve(socket_t client) {
  26678. std::string head;
  26679. char buf[2048];
  26680. while (head.find("\r\n\r\n") == std::string::npos) {
  26681. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26682. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26683. if (n <= 0) { return; }
  26684. head.append(buf, static_cast<size_t>(n));
  26685. }
  26686. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26687. connect_hits_++;
  26688. {
  26689. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26690. connect_request_ = head;
  26691. }
  26692. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26693. if (!send_all(client, res.data(), res.size()) ||
  26694. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26695. return;
  26696. }
  26697. auto origin = connect_to(forward_port_);
  26698. if (origin == INVALID_SOCKET) { return; }
  26699. // When either side stops, shut both down so the other pump returns too.
  26700. auto pump = [&](socket_t from, socket_t to) {
  26701. char b[8192];
  26702. for (;;) {
  26703. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26704. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26705. }
  26706. detail::shutdown_socket(client);
  26707. detail::shutdown_socket(origin);
  26708. };
  26709. std::thread up([&] { pump(client, origin); });
  26710. pump(origin, client);
  26711. up.join();
  26712. detail::close_socket(origin);
  26713. }
  26714. int forward_port_;
  26715. ConnectReply reply_;
  26716. socket_t listen_sock_ = INVALID_SOCKET;
  26717. int port_ = 0;
  26718. std::thread th_;
  26719. std::atomic<bool> stop_{false};
  26720. std::atomic<int> connect_hits_{0};
  26721. mutable std::mutex connect_request_mutex_;
  26722. std::string connect_request_;
  26723. };
  26724. } // namespace proxy_tunnel_test
  26725. #ifdef CPPHTTPLIB_SSL_ENABLED
  26726. namespace proxy_tunnel_test {
  26727. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26728. class ScopedSSLServer {
  26729. public:
  26730. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26731. port_ = svr_.bind_to_any_port("127.0.0.1");
  26732. }
  26733. ~ScopedSSLServer() {
  26734. svr_.stop();
  26735. if (th_.joinable()) { th_.join(); }
  26736. }
  26737. SSLServer &svr() { return svr_; }
  26738. int port() const { return port_; }
  26739. void listen() {
  26740. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26741. svr_.wait_until_ready();
  26742. }
  26743. private:
  26744. SSLServer svr_;
  26745. std::thread th_;
  26746. int port_ = 0;
  26747. };
  26748. // Sends one request through the CONNECT proxy to the TLS origin with a
  26749. // credential configured for each hop, and checks that each credential reaches
  26750. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26751. // origin's (every header in origin_headers) on the tunnelled request.
  26752. void CredentialsStayWithTheirHop(
  26753. const std::function<void(SSLClient &)> &set_credentials,
  26754. const std::string &scheme,
  26755. const std::vector<std::string> &origin_headers = {"Authorization"},
  26756. bool stream = false) {
  26757. std::atomic<int> origin_hits{0};
  26758. std::atomic<bool> origin_saw_proxy_authz{false};
  26759. std::atomic<bool> origin_saw_headers{false};
  26760. ScopedSSLServer origin;
  26761. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26762. origin_hits++;
  26763. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26764. origin_saw_headers =
  26765. std::all_of(origin_headers.begin(), origin_headers.end(),
  26766. [&](const std::string &h) { return req.has_header(h); });
  26767. res.set_content("ok", "text/plain");
  26768. });
  26769. origin.listen();
  26770. ScopedConnectProxy proxy(origin.port());
  26771. ASSERT_NE(0, proxy.port());
  26772. // Pinned to 127.0.0.1 for the same reason as the test below.
  26773. SSLClient cli("127.0.0.1", origin.port());
  26774. cli.enable_server_certificate_verification(false);
  26775. cli.set_proxy("127.0.0.1", proxy.port());
  26776. set_credentials(cli);
  26777. if (stream) {
  26778. auto handle = cli.open_stream("GET", "/x");
  26779. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26780. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26781. } else {
  26782. auto res = cli.Get("/x");
  26783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26784. EXPECT_EQ(StatusCode::OK_200, res->status);
  26785. }
  26786. EXPECT_EQ(1, origin_hits.load());
  26787. EXPECT_EQ(1, proxy.connect_hits());
  26788. EXPECT_TRUE(origin_saw_headers.load());
  26789. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26790. << "Proxy-Authorization must not be sent inside the tunnel";
  26791. auto connect_req = proxy.connect_request();
  26792. EXPECT_NE(std::string::npos,
  26793. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26794. for (const auto &h : origin_headers) {
  26795. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26796. << h << " must not be sent to the proxy on CONNECT";
  26797. }
  26798. }
  26799. } // namespace proxy_tunnel_test
  26800. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26801. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26802. [](SSLClient &cli) {
  26803. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26804. cli.set_basic_auth("origin-user", "origin-pass");
  26805. },
  26806. "Basic");
  26807. }
  26808. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26809. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26810. [](SSLClient &cli) {
  26811. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26812. cli.set_basic_auth("origin-user", "origin-pass");
  26813. },
  26814. "Basic", {"Authorization"}, true);
  26815. }
  26816. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26817. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26818. [](SSLClient &cli) {
  26819. cli.set_proxy_bearer_token_auth("proxy-token");
  26820. cli.set_bearer_token_auth("origin-token");
  26821. },
  26822. "Bearer");
  26823. }
  26824. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26825. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26826. [](SSLClient &cli) {
  26827. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26828. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26829. {"Cookie", "sid=origin-session"},
  26830. {"X-Api-Key", "origin-key"}});
  26831. },
  26832. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26833. }
  26834. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26835. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26836. // retry; otherwise proxy creds would be sent to the origin.
  26837. std::atomic<int> origin_hits{0};
  26838. std::atomic<bool> origin_saw_proxy_authz{false};
  26839. proxy_tunnel_test::ScopedSSLServer origin;
  26840. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26841. origin_hits++;
  26842. if (req.has_header("Proxy-Authorization")) {
  26843. origin_saw_proxy_authz = true;
  26844. }
  26845. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26846. res.set_header("Proxy-Authenticate",
  26847. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26848. "algorithm=MD5");
  26849. });
  26850. origin.listen();
  26851. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26852. ASSERT_NE(0, proxy.port());
  26853. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26854. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26855. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26856. // and answer with its own status, making this test flaky.
  26857. SSLClient cli("127.0.0.1", origin.port());
  26858. cli.enable_server_certificate_verification(false);
  26859. cli.set_proxy("127.0.0.1", proxy.port());
  26860. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26861. auto res = cli.Get("/x");
  26862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26863. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26864. EXPECT_EQ(1, origin_hits.load());
  26865. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26866. EXPECT_EQ(1, proxy.connect_hits());
  26867. }
  26868. #endif
  26869. namespace proxy_tunnel_test {
  26870. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26871. // anything else gets a 407 with `challenge`.
  26872. ConnectReply require_proxy_auth(const std::string &expected,
  26873. const std::string &challenge) {
  26874. return [=](const std::string &head) -> std::string {
  26875. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26876. std::string::npos) {
  26877. return kTunnelEstablished;
  26878. }
  26879. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26880. "Proxy-Authenticate: " +
  26881. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26882. };
  26883. }
  26884. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26885. // request, then echoes.
  26886. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26887. ws.send(
  26888. "authorization:" + req.get_header_value("Authorization") +
  26889. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26890. std::string msg;
  26891. while (ws.read(msg)) {
  26892. ws.send(msg);
  26893. }
  26894. }
  26895. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26896. class ScopedWebSocketOrigin {
  26897. public:
  26898. ScopedWebSocketOrigin() {
  26899. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26900. server_.listen();
  26901. }
  26902. int port() const { return server_.port(); }
  26903. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26904. std::string url() const {
  26905. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26906. }
  26907. private:
  26908. no_proxy_test::ScopedServer server_;
  26909. };
  26910. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26911. // passed as a constructor header, and checks that each reaches only its hop.
  26912. void WebSocketCredentialsStayWithTheirHop(
  26913. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26914. const std::string &proxy_authz, const std::string &origin_authz) {
  26915. ScopedWebSocketOrigin origin;
  26916. ScopedConnectProxy proxy(
  26917. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26918. ASSERT_NE(0, proxy.port());
  26919. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26920. client.set_proxy("127.0.0.1", proxy.port());
  26921. set_proxy_credentials(client);
  26922. auto res = client.connect();
  26923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26924. std::string msg;
  26925. ASSERT_TRUE(client.read(msg));
  26926. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26927. client.close();
  26928. EXPECT_EQ(1, proxy.connect_hits());
  26929. EXPECT_EQ(std::string::npos,
  26930. proxy.connect_request().find("\r\nAuthorization: "))
  26931. << "origin credentials must not be sent to the proxy";
  26932. }
  26933. } // namespace proxy_tunnel_test
  26934. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26935. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26936. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26937. ASSERT_NE(0, proxy.port());
  26938. ws::WebSocketClient client(origin.url());
  26939. client.set_proxy("127.0.0.1", proxy.port());
  26940. auto res = client.connect();
  26941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26942. std::string msg;
  26943. ASSERT_TRUE(client.read(msg));
  26944. ASSERT_TRUE(client.send("hello"));
  26945. ASSERT_TRUE(client.read(msg));
  26946. EXPECT_EQ("hello", msg);
  26947. client.close();
  26948. EXPECT_EQ(1, proxy.connect_hits());
  26949. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26950. auto connect_req = proxy.connect_request();
  26951. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26952. EXPECT_NE(std::string::npos,
  26953. connect_req.find("\r\nHost: " + target + "\r\n"));
  26954. }
  26955. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26956. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26957. [](ws::WebSocketClient &cli) {
  26958. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26959. },
  26960. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26961. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26962. }
  26963. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26964. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26965. [](ws::WebSocketClient &cli) {
  26966. cli.set_proxy_bearer_token_auth("proxy-token");
  26967. },
  26968. "Bearer proxy-token", "Bearer origin-token");
  26969. }
  26970. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26971. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26972. proxy_tunnel_test::ScopedConnectProxy proxy(
  26973. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26974. "Basic " + detail::base64_encode("proxy-user:"),
  26975. "Basic realm=\"proxy\""));
  26976. ASSERT_NE(0, proxy.port());
  26977. ws::WebSocketClient client(origin.url());
  26978. client.set_proxy("127.0.0.1", proxy.port());
  26979. client.set_proxy_basic_auth("proxy-user", "");
  26980. auto res = client.connect();
  26981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26982. client.close();
  26983. EXPECT_EQ(1, proxy.connect_hits());
  26984. }
  26985. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26986. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26987. proxy_tunnel_test::ScopedConnectProxy proxy(
  26988. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26989. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26990. ASSERT_NE(0, proxy.port());
  26991. ws::WebSocketClient client(origin.url());
  26992. client.set_proxy("127.0.0.1", proxy.port());
  26993. auto res = client.connect();
  26994. EXPECT_FALSE(res);
  26995. EXPECT_EQ(Error::ProxyConnection, res.error());
  26996. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26997. EXPECT_EQ("Basic realm=\"proxy\"",
  26998. res.get_header_value("Proxy-Authenticate"));
  26999. EXPECT_FALSE(client.is_open());
  27000. }
  27001. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  27002. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27003. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27004. ASSERT_NE(0, proxy.port());
  27005. ws::WebSocketClient client(origin.url());
  27006. client.set_proxy("127.0.0.1", proxy.port());
  27007. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27008. client.set_no_proxy({"127.0.0.1"});
  27009. auto res = client.connect();
  27010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27011. std::string msg;
  27012. ASSERT_TRUE(client.read(msg));
  27013. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27014. << "proxy credentials must not reach a bypassed origin";
  27015. client.close();
  27016. EXPECT_EQ(0, proxy.connect_hits());
  27017. }
  27018. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27019. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27020. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27021. ASSERT_NE(0, proxy.port());
  27022. ws::WebSocketClient client(origin.url());
  27023. client.set_proxy("127.0.0.1", proxy.port());
  27024. ASSERT_TRUE(client.connect());
  27025. ASSERT_TRUE(client.connect());
  27026. client.close();
  27027. EXPECT_EQ(2, proxy.connect_hits());
  27028. }
  27029. #ifdef CPPHTTPLIB_SSL_ENABLED
  27030. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27031. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27032. proxy_tunnel_test::ScopedConnectProxy proxy(
  27033. origin.port(), [](const std::string &head) -> std::string {
  27034. if (head.find(
  27035. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27036. std::string::npos) {
  27037. return proxy_tunnel_test::kTunnelEstablished;
  27038. }
  27039. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27040. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27041. "nonce=\"abc\", algorithm=MD5\r\n"
  27042. "Content-Length: 0\r\n\r\n";
  27043. });
  27044. ASSERT_NE(0, proxy.port());
  27045. ws::WebSocketClient client(origin.url());
  27046. client.set_proxy("127.0.0.1", proxy.port());
  27047. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27048. auto res = client.connect();
  27049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27050. std::string msg;
  27051. ASSERT_TRUE(client.read(msg));
  27052. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27053. client.close();
  27054. EXPECT_EQ(2, proxy.connect_hits());
  27055. }
  27056. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27057. proxy_tunnel_test::ScopedSSLServer origin;
  27058. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27059. origin.listen();
  27060. proxy_tunnel_test::ScopedConnectProxy proxy(
  27061. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27062. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27063. ASSERT_NE(0, proxy.port());
  27064. ws::WebSocketClient client(
  27065. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27066. client.enable_server_certificate_verification(false);
  27067. client.set_proxy("127.0.0.1", proxy.port());
  27068. client.set_proxy_bearer_token_auth("proxy-token");
  27069. auto res = client.connect();
  27070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27071. std::string msg;
  27072. ASSERT_TRUE(client.read(msg));
  27073. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27074. << "Proxy-Authorization must not be sent inside the tunnel";
  27075. client.close();
  27076. EXPECT_EQ(1, proxy.connect_hits());
  27077. }
  27078. #endif